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