This repository has been archived by the owner on Dec 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
96 lines (91 loc) · 2.33 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { getContext, hasContext, setContext } from "svelte";
/**
* Options for the `createContext` function.
*/
interface Options<value> {
/**
* The default value for the context.
*
* @default null
*/
defaultValue?: value;
/**
* Function that is called when context has not been set but is trying to be gotten.
*
* @default () => {}
*/
onError?: (...args: unknown[]) => unknown;
}
/**
* Return type of the `createContext` function.
*/
interface Context<SetValue, GetValue = SetValue> {
/**
* A unique symbol used to identify the context.
*/
key: symbol;
/**
* A function that retrieves the current value of the context.
* If a `defaultValue` was provided and the context has not been set, it will return the `defaultValue`.
* If an `onError` function is provided and the context has not been set, it will be called.
*
* @returns {GetValue} The value of the context
*/
get: () => GetValue;
/**
* A function that sets the value of the context.
*
* @param {SetValue} value - The value to set
* @returns {SetValue} The value that was set
*/
set: (value: SetValue) => SetValue;
/**
* A function that checks if the context has been set.
*
* @returns {boolean} Whether the context has been set
*/
has: () => boolean;
}
/**
* All the overloads for the `createContext` function.
*/
interface CreateContext {
<Value>(options: {
defaultValue: Value;
onError: (...args: unknown[]) => unknown;
}): Context<Value>;
<Value>(options: {
defaultValue: Value;
}): Context<Value>;
<Value>(options: {
onError: (...args: unknown[]) => unknown;
}): Context<Value, Value | null>;
<Value>(): Context<Value, Value | null>;
}
/**
* Creates a context object.
*
* @param {Options<Value>} options - Options
* @return {Context<Value>} The created context object
*/
const createContext: CreateContext = <Value>(
options: Options<Value> = {},
): Context<Value, Value | null> => {
const { defaultValue = null, onError = () => {} } = options;
const key = Symbol();
const get = () => {
if (!hasContext(key)) {
onError();
}
return getContext<Value>(key) ?? defaultValue;
};
const set = (value: Value) => {
return setContext<Value>(key, value);
};
const has = () => {
return hasContext(key);
};
return { key, get, set, has };
};
export { createContext };
export type { Options, Context, CreateContext };