-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathcontext.ts
More file actions
30 lines (27 loc) · 848 Bytes
/
context.ts
File metadata and controls
30 lines (27 loc) · 848 Bytes
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
import { ContextRoot, createContext, type Context } from '@lit/context';
import { isServer } from 'lit';
let root: ContextRoot;
function makeContextRoot() {
const root = new ContextRoot();
if (!isServer) {
root.attach(document.body);
} else {
root.attach(
// @ts-expect-error: enable context root in ssr
globalThis.litServerRoot,
);
}
return root;
}
/**
* In order to prevent late-upgrading-context-consumers from 'missing'
* their rightful context providers, we must set up a `ContextRoot` on the body.
* Always use this function when creating contexts that are shared with child elements.
* @param args createContext args
*/
export function createContextWithRoot<T>(
...args: Parameters<typeof createContext>
): Context<unknown, T> {
root ??= makeContextRoot();
return createContext<T>(...args);
}