-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathsignal-like.ts
More file actions
60 lines (52 loc) · 1.9 KB
/
signal-like.ts
File metadata and controls
60 lines (52 loc) · 1.9 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
createComputed,
createLinkedSignal,
createSignal,
linkedSignalSetFn,
linkedSignalUpdateFn,
SIGNAL,
untracked as primitiveUntracked,
} from '@angular/core/primitives/signals';
export {primitiveUntracked as untracked};
export type SignalLike<T> = () => T;
export interface WritableSignalLike<T> extends SignalLike<T> {
set(value: T): void;
update(updateFn: (value: T) => T): void;
asReadonly(): SignalLike<T>;
}
/** Converts a getter setter style signal to a WritableSignalLike. */
export function convertGetterSetterToWritableSignalLike<T>(
getter: () => T,
setter: (v: T) => void,
): WritableSignalLike<T> {
// tslint:disable-next-line:ban Have to use `Object.assign` to preserve the getter function.
return Object.assign(getter, {
set: setter,
update: (updateCallback: (v: T) => T) => setter(updateCallback(getter())),
asReadonly: () => getter,
});
}
export function computed<T>(computation: () => T): SignalLike<T> {
return createComputed(computation);
}
export function signal<T>(initialValue: T): WritableSignalLike<T> {
const [get, set, update] = createSignal(initialValue);
// tslint:disable-next-line:ban Have to use `Object.assign` to preserve the getter function.
return Object.assign(get, {set, update, asReadonly: () => get});
}
export function linkedSignal<T>(sourceFn: () => T): WritableSignalLike<T> {
const getter = createLinkedSignal(sourceFn, s => s);
// tslint:disable-next-line:ban Have to use `Object.assign` to preserve the getter function.
return Object.assign(getter, {
set: (v: T) => linkedSignalSetFn(getter[SIGNAL], v),
update: (updater: (v: T) => T) => linkedSignalUpdateFn(getter[SIGNAL], updater),
asReadonly: () => getter,
});
}