Open History to see the last commit
1/**
2 * A value that can be passed directly or read from a zero-argument getter.
3 *
4 * Lit Query APIs read function accessors during host updates, so the getter can
5 * depend on reactive host state.
6 *
7 * @example
8 * ```ts
9 * const staticKey: Accessor<readonly unknown[]> = ['todos']
10 * const reactiveKey: Accessor<readonly unknown[]> = () => ['todos', this.userId]
11 * ```
12 */
13export type Accessor<T> = T | (() => T)
14β
15export function readAccessor<T>(value: Accessor<T>): T {
16 return typeof value === 'function' ? (value as () => T)() : value
17}
18β
19/**
20 * A callable accessor with a `current` property for reading the latest
21 * controller result.
22 *
23 * Controller creators and cache state helpers return this shape so render code
24 * can use either `result()` or `result.current`.
25 *
26 * @example
27 * ```ts
28 * const query = this.todos()
29 * const sameQuery = this.todos.current
30 * ```
31 */
32export type ValueAccessor<T> = (() => T) & {
33 readonly current: T
34}
35β
36export function createValueAccessor<T>(getter: () => T): ValueAccessor<T> {
37 const accessor = (() => getter()) as ValueAccessor<T>
38 Object.defineProperty(accessor, 'current', {
39 get: getter,
40 enumerable: true,
41 })
42 return accessor
43}