(
initial: T,
options: ControlledRefOptions<T> = {},
)
| 22 | * Fine-grained controls over ref and its reactivity. |
| 23 | */ |
| 24 | export function refWithControl<T>( |
| 25 | initial: T, |
| 26 | options: ControlledRefOptions<T> = {}, |
| 27 | ) { |
| 28 | let source = initial |
| 29 | let track: Fn |
| 30 | let trigger: Fn |
| 31 | |
| 32 | const ref = customRef<T>((_track, _trigger) => { |
| 33 | track = _track |
| 34 | trigger = _trigger |
| 35 | |
| 36 | return { |
| 37 | get() { |
| 38 | return get() |
| 39 | }, |
| 40 | set(v) { |
| 41 | set(v) |
| 42 | }, |
| 43 | } |
| 44 | }) |
| 45 | |
| 46 | function get(tracking = true) { |
| 47 | if (tracking) |
| 48 | track() |
| 49 | return source |
| 50 | } |
| 51 | |
| 52 | function set(value: T, triggering = true) { |
| 53 | if (value === source) |
| 54 | return |
| 55 | |
| 56 | const old = source |
| 57 | if (options.onBeforeChange?.(value, old) === false) |
| 58 | return // dismissed |
| 59 | |
| 60 | source = value |
| 61 | |
| 62 | options.onChanged?.(value, old) |
| 63 | |
| 64 | if (triggering) |
| 65 | trigger() |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Get the value without tracked in the reactivity system |
| 70 | */ |
| 71 | const untrackedGet = () => get(false) |
| 72 | /** |
| 73 | * Set the value without triggering the reactivity system |
| 74 | */ |
| 75 | const silentSet = (v: T) => set(v, false) |
| 76 | |
| 77 | /** |
| 78 | * Get the value without tracked in the reactivity system. |
| 79 | * |
| 80 | * Alias for `untrackedGet()` |
| 81 | */ |
no test coverage detected