-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathcontext.ts
More file actions
70 lines (63 loc) · 2.31 KB
/
context.ts
File metadata and controls
70 lines (63 loc) · 2.31 KB
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
/*
* Copyright (c) 2023, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import { createContextProviderWithRegister } from '@lwc/engine-core';
import { addEventListener, dispatchEvent } from './index';
import type {
WireAdapterConstructor,
WireContextValue,
WireContextSubscriptionPayload,
WireContextSubscriptionCallback,
} from '@lwc/engine-core';
export class WireContextSubscriptionEvent extends CustomEvent<undefined> {
// These are initialized on the constructor via defineProperties.
public readonly setNewContext!: (newContext: WireContextValue) => boolean;
public readonly setDisconnectedCallback?: (disconnectCallback: () => void) => void;
constructor(
adapterToken: string,
{ setNewContext, setDisconnectedCallback }: WireContextSubscriptionPayload
) {
super(adapterToken, {
bubbles: true,
composed: true,
});
this.setNewContext = setNewContext;
this.setDisconnectedCallback = setDisconnectedCallback;
}
}
/**
* Creates a context provider, given a wire adapter constructor.
* @param adapter The wire adapter to create a context provider for.
* @returns A new context provider.
*/
export function createContextProvider(adapter: WireAdapterConstructor) {
return createContextProviderWithRegister(adapter, registerContextProvider);
}
export function registerContextConsumer(
elm: Node,
adapterContextToken: string,
subscriptionPayload: WireContextSubscriptionPayload
) {
dispatchEvent(elm, new WireContextSubscriptionEvent(adapterContextToken, subscriptionPayload));
}
export function registerContextProvider(
elm: Node,
adapterContextToken: string,
onContextSubscription: WireContextSubscriptionCallback
) {
addEventListener(elm, adapterContextToken, ((evt: WireContextSubscriptionEvent) => {
const { setNewContext, setDisconnectedCallback } = evt;
// If context subscription is successful, stop event propagation
if (
onContextSubscription({
setNewContext,
setDisconnectedCallback,
})
) {
evt.stopImmediatePropagation();
}
}) as EventListener);
}