|
| 1 | +import { type Context, ContextConsumer, type ContextType } from '@lit/context'; |
| 2 | +import type { |
| 3 | + LitElement, |
| 4 | + ReactiveController, |
| 5 | + ReactiveControllerHost, |
| 6 | +} from 'lit'; |
| 7 | + |
| 8 | +type AsyncContextOptions<T extends Context<unknown, unknown>> = { |
| 9 | + context: T; |
| 10 | + callback?: (value: ContextType<T>, dispose?: () => void) => void; |
| 11 | + subscribe?: boolean; |
| 12 | +}; |
| 13 | + |
| 14 | +/* blazorSuppress */ |
| 15 | +export class AsyncContextConsumer< |
| 16 | + T extends Context<unknown, unknown>, |
| 17 | + Host extends ReactiveControllerHost & HTMLElement, |
| 18 | +> implements ReactiveController |
| 19 | +{ |
| 20 | + protected _host: Host; |
| 21 | + protected _options: AsyncContextOptions<T>; |
| 22 | + protected _consumer?: ContextConsumer<T, Host>; |
| 23 | + |
| 24 | + constructor(host: Host, options: AsyncContextOptions<T>) { |
| 25 | + this._host = host; |
| 26 | + this._options = options; |
| 27 | + |
| 28 | + this._host.addController(this); |
| 29 | + } |
| 30 | + |
| 31 | + public get value(): ContextType<T> | undefined { |
| 32 | + return this._consumer?.value; |
| 33 | + } |
| 34 | + |
| 35 | + public async hostConnected(): Promise<void> { |
| 36 | + await this._host.updateComplete; |
| 37 | + |
| 38 | + // If there is already an instance of a consumer (because of an attach/detach cycle), |
| 39 | + // skip creating a new instance for this host. |
| 40 | + if (!this._consumer) { |
| 41 | + this._consumer = new ContextConsumer(this._host, { |
| 42 | + context: this._options.context, |
| 43 | + callback: this._options.callback, |
| 44 | + subscribe: this._options.subscribe, |
| 45 | + }); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +export function createAsyncContext< |
| 51 | + T extends Context<unknown, unknown>, |
| 52 | + Host extends ReactiveControllerHost & LitElement, |
| 53 | +>( |
| 54 | + host: Host, |
| 55 | + context: T, |
| 56 | + callback?: (value: ContextType<T>, dispose?: () => void) => void |
| 57 | +): AsyncContextConsumer<T, Host> { |
| 58 | + return new AsyncContextConsumer(host, { |
| 59 | + context, |
| 60 | + callback, |
| 61 | + subscribe: true, |
| 62 | + }) as AsyncContextConsumer<T, Host>; |
| 63 | +} |
0 commit comments