forked from open-wc/context-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context-protocol.ts
78 lines (71 loc) · 2.37 KB
/
context-protocol.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
// From: https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md#definitions
/**
* A Context object defines an optional initial value for a Context, as well as a name identifier for debugging purposes.
*/
export type Context<T> = {
name: string;
initialValue?: T;
};
/**
* An unknown context type
*/
export type UnknownContext = Context<unknown>;
/**
* A helper type which can extract a Context value type from a Context type
*/
export type ContextType<T extends UnknownContext> =
T extends Context<infer Y> ? Y : never;
/**
* A function which creates a Context value object
*/
export function createContext<T>(
name: string,
initialValue?: T,
): Readonly<Context<T>> {
return {
name,
initialValue,
};
}
/**
* A callback which is provided by a context requester and is called with the value satisfying the request.
* This callback can be called multiple times by context providers as the requested value is changed.
*/
export type ContextCallback<ValueType> = (
value: ValueType,
unsubscribe?: () => void,
) => void;
/**
* An event fired by a context requester to signal it desires a named context.
*
* A provider should inspect the `context` property of the event to determine if it has a value that can
* satisfy the request, calling the `callback` with the requested value if so.
*
* If the requested context event contains a truthy `subscribe` value, then a provider can call the callback
* multiple times if the value is changed, if this is the case the provider should pass an `unsubscribe`
* function to the callback which requesters can invoke to indicate they no longer wish to receive these updates.
*/
export class ContextEvent<T extends UnknownContext> extends Event {
public constructor(
public readonly context: T,
public readonly callback: ContextCallback<ContextType<T>>,
public readonly subscribe?: boolean,
) {
super("context-request", { bubbles: true, composed: true });
}
}
/**
* A 'context-request' event can be emitted by any element which desires
* a context value to be injected by an external provider.
*/
declare global {
interface WindowEventMap {
"context-request": ContextEvent<UnknownContext>;
}
interface ElementEventMap {
"context-request": ContextEvent<UnknownContext>;
}
interface HTMLElementEventMap {
"context-request": ContextEvent<UnknownContext>;
}
}