1
1
// From: https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md#definitions
2
2
3
3
/**
4
- * A Context object defines an optional initial value for a Context, as well as a name identifier for debugging purposes.
4
+ * A context key.
5
+ *
6
+ * A context key can be any type of object, including strings and symbols. The
7
+ * Context type brands the key type with the `__context__` property that
8
+ * carries the type of the value the context references.
5
9
*/
6
- export type Context < T > = {
7
- name : string ;
8
- initialValue ?: T ;
9
- } ;
10
+ export type Context < KeyType , ValueType > = KeyType & { __context__ : ValueType } ;
10
11
11
12
/**
12
13
* An unknown context type
13
14
*/
14
- export type UnknownContext = Context < unknown > ;
15
+ export type UnknownContext = Context < unknown , unknown > ;
15
16
16
17
/**
17
18
* A helper type which can extract a Context value type from a Context type
18
19
*/
19
20
export type ContextType < T extends UnknownContext > =
20
- T extends Context < infer Y > ? Y : never ;
21
+ T extends Context < infer _ , infer V > ? V : never ;
21
22
22
23
/**
23
24
* A function which creates a Context value object
24
25
*/
25
- export function createContext < T > (
26
- name : string ,
27
- initialValue ?: T ,
28
- ) : Readonly < Context < T > > {
29
- return {
30
- name,
31
- initialValue,
32
- } ;
33
- }
26
+ export const createContext = < ValueType > ( key : unknown ) =>
27
+ key as Context < typeof key , ValueType > ;
34
28
35
29
/**
36
30
* A callback which is provided by a context requester and is called with the value satisfying the request.
@@ -51,7 +45,7 @@ export type ContextCallback<ValueType> = (
51
45
* multiple times if the value is changed, if this is the case the provider should pass an `unsubscribe`
52
46
* function to the callback which requesters can invoke to indicate they no longer wish to receive these updates.
53
47
*/
54
- export class ContextEvent < T extends UnknownContext > extends Event {
48
+ export class ContextRequestEvent < T extends UnknownContext > extends Event {
55
49
public constructor (
56
50
public readonly context : T ,
57
51
public readonly callback : ContextCallback < ContextType < T > > ,
@@ -67,12 +61,12 @@ export class ContextEvent<T extends UnknownContext> extends Event {
67
61
*/
68
62
declare global {
69
63
interface WindowEventMap {
70
- "context-request" : ContextEvent < UnknownContext > ;
64
+ "context-request" : ContextRequestEvent < UnknownContext > ;
71
65
}
72
66
interface ElementEventMap {
73
- "context-request" : ContextEvent < UnknownContext > ;
67
+ "context-request" : ContextRequestEvent < UnknownContext > ;
74
68
}
75
69
interface HTMLElementEventMap {
76
- "context-request" : ContextEvent < UnknownContext > ;
70
+ "context-request" : ContextRequestEvent < UnknownContext > ;
77
71
}
78
72
}
0 commit comments