|
| 1 | +type OnChange<T> = (value: T) => void |
| 2 | + |
| 3 | +type OffChange = () => void |
| 4 | + |
| 5 | +interface Ref <T> { |
| 6 | + value: T, |
| 7 | + change: (fn: OnChange<T>) => OffChange, |
| 8 | + toBe: (expect: T) => Promise<void>, |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Reactive variable |
| 13 | + * |
| 14 | + * @param initialValue initial value |
| 15 | + * @example |
| 16 | + * |
| 17 | + * const isBusy = useRef(false) |
| 18 | + * |
| 19 | + * function onClick () { |
| 20 | + * // Wait other tobe done |
| 21 | + * if (isBusy.value) |
| 22 | + * await isBusy.toBe(false) |
| 23 | + * |
| 24 | + * isBusy.value = true |
| 25 | + * |
| 26 | + * // Heavy async function |
| 27 | + * setTimeout(() => { |
| 28 | + * isBusy.value = false |
| 29 | + * },5000) |
| 30 | + * } |
| 31 | + */ |
| 32 | +export function useRef<T = any> (): Ref<T | undefined> |
| 33 | +export function useRef<T = any> (initialValue: T): Ref<T> |
| 34 | +export function useRef<T> (initialValue?: T): Ref<T | undefined> { |
| 35 | + let value: T | undefined = initialValue |
| 36 | + |
| 37 | + const watcher = new Set<OnChange<T>>() |
| 38 | + |
| 39 | + return { |
| 40 | + /** |
| 41 | + * Get value |
| 42 | + */ |
| 43 | + get value (): T | undefined { |
| 44 | + return value |
| 45 | + }, |
| 46 | + |
| 47 | + /** |
| 48 | + * Set value |
| 49 | + */ |
| 50 | + set value (newValue: T) { |
| 51 | + value = newValue |
| 52 | + |
| 53 | + // emit on-change |
| 54 | + for (const emit of watcher) |
| 55 | + emit(newValue) |
| 56 | + }, |
| 57 | + |
| 58 | + /** |
| 59 | + * Add on change listener |
| 60 | + * @param fn on change handler |
| 61 | + */ |
| 62 | + change (fn: OnChange<T>): OffChange { |
| 63 | + watcher.add(fn) |
| 64 | + |
| 65 | + return () => { |
| 66 | + watcher.delete(fn) |
| 67 | + } |
| 68 | + }, |
| 69 | + |
| 70 | + /** |
| 71 | + * Wait until |
| 72 | + * @param expect expected value |
| 73 | + */ |
| 74 | + // eslint-disable-next-line @typescript-eslint/promise-function-async |
| 75 | + toBe (expect: T | undefined) { |
| 76 | + return new Promise<void>((resolve) => { |
| 77 | + const stop = this.change((value) => { |
| 78 | + if (value === expect) { |
| 79 | + stop() |
| 80 | + resolve() |
| 81 | + } |
| 82 | + }) |
| 83 | + }) |
| 84 | + }, |
| 85 | + } |
| 86 | +} |
0 commit comments