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 * @example
7 * ```ts
8 * const staticKey: Accessor<readonly unknown[]> = ['todos']
9 * const reactiveKey: Accessor<readonly unknown[]> = () => ['todos', this.userId]
10 * ```
11 */
12export type Accessor<T> = T | (() => T)
13β
14/**
15 * Reads an {@link Accessor}: calls it if it is a function, otherwise returns it as is.
16 * @param value - The value, or a getter that returns it.
17 * @returns The value.
18 */
19export function readAccessor<T>(value: Accessor<T>): T {
20 return typeof value === 'function' ? (value as () => T)() : value
21}
22β
23/**
24 * A callable accessor with a `current` property for reading the latest
25 * controller result.
26 *
27 * Controller creators and cache state helpers return this shape so render code
28 * can use either `result()` or `result.current`.
29 * @example
30 * ```ts
31 * const query = this.todos()
32 * const sameQuery = this.todos.current
33 * ```
34 */
35export type ValueAccessor<T> = (() => T) & {
36 readonly current: T
37}
38β
39/**
40 * Creates a {@link ValueAccessor} that reads its value from `getter`, both when called and through
41 * its `current` property.
42 * @param getter - Returns the latest value.
43 * @returns A function that returns the latest value, which is also available on `current`.
44 */
45export function createValueAccessor<T>(getter: () => T): ValueAccessor<T> {
46 const accessor = (() => getter()) as ValueAccessor<T>
47 Object.defineProperty(accessor, 'current', {
48 get: getter,
49 enumerable: true,
50 })
51 return accessor
52}