Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 5x 1x 1x 1x 1x 4x 4x 4x 5x 1x 1x 5x 5x 5x 6x 6x 6x 1x 7x 7x 5x 7x 7x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 20x 20x 20x 20x 20x 12x 12x 1x 1x 1x 1x 10x 10x 10x 18x 8x 8x 18x 10x 10x 20x 20x 20x 1x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 1x 1x 1x 1x 8x 6x 6x 8x 5x 1x 1x 1x 1x 4x 4x 4x 4x 6x 2x 2x 2x 2x 2x 2x 2x 6x 4x 4x 4x 4x 4x 3x 4x 4x 8x 8x 8x 1x 3x 3x 3x 3x 3x 3x 4x 3x 3x 3x 3x 1x 1x 3x 1x 1x 1x 3x 3x | import { type RefObject, useEffect, useMemo, useRef, useState } from 'react';
import { anchor, captureStack, type Linkable, type State, subscribe } from '@anchorlib/core';
import type { TransformFn } from './types.js';
import { CLEANUP_DEBOUNCE_TIME, RENDERER_INIT_VERSION } from './constant.js';
import { depsChanged, isMutationOf } from './utils.js';
import { useMicrotask } from './hooks.js';
/**
* React hook that allows you to derive a computed value from a reactive state.
* It automatically re-computes the value whenever the dependent state change.
*
* @param state - The reactive state to derive from.
* @param recursive - Whether to recursively derive the computed value.
*/
export function useDerived<T extends Linkable>(state: T, recursive?: boolean): T;
/**
* React hook that allows you to derive a computed value from a reactive state.
* It automatically re-computes the value whenever the dependent state change.
*
* @param state - The reactive state to derive from.
* @param transform - A function that receives the current value, and returns the computed value.
*/
export function useDerived<T extends Linkable, R>(state: T, transform: TransformFn<T, R>): R;
export function useDerived<T extends Linkable, R>(state: T, transformRecursive?: TransformFn<T, R> | boolean): T | R {
const [version, setVersion] = useState(RENDERER_INIT_VERSION);
const value = useMemo(() => {
const current = anchor.has(state) ? anchor.get(state) : state;
return typeof transformRecursive === 'function' ? transformRecursive(current) : current;
}, [state, version]);
useEffect(() => {
if (!anchor.has(state)) {
const error = new Error('State is not reactive.');
captureStack.violation.derivation('Attempted to derive from a non-reactive state.', error);
return;
}
return subscribe(
state,
(_, event) => {
if (event.type !== 'init') {
setVersion((c) => c + 1);
}
},
typeof transformRecursive === 'boolean' ? transformRecursive : false
);
}, [state]);
return value as T | R;
}
/**
* React hook that creates a derivation pipe between a source and target reactive state.
* Changes from the source state are automatically piped to the target state.
* An optional transform function can be used to modify the data during the pipe operation.
*
* @template T - The type of the source reactive state.
* @template R - The type of the target reactive state.
* @param {T} source - The source reactive state to pipe from.
* @param {R} target - The target reactive state to pipe to.
* @param {TransformFn<T, R>} [transform] - Optional function to transform the data during piping.
* @returns {void}
*/
export function usePipe<T extends State, R extends State>(source: T, target: R, transform?: TransformFn<T, R>): void {
useEffect(() => {
if (!source || !target) return;
return subscribe.pipe(source, target, transform);
}, [source, target]);
}
/**
* React hook that creates a bidirectional binding between two reactive states.
* Changes from either state are automatically synchronized to the other state.
* Optional transform functions can be used to modify the data during the synchronization.
*
* @template T - The type of the left reactive state.
* @template R - The type of the right reactive state.
* @param {T} left - The left reactive state to bind.
* @param {R} right - The right reactive state to bind.
* @param {TransformFn<T, R>} [transformLeft] - Optional function to transform data from left to right.
* @param {TransformFn<R, T>} [transformRight] - Optional function to transform data from right to left.
* @returns {void}
*/
export function useBind<T extends State, R extends State>(
left: T,
right: R,
transformLeft?: TransformFn<T, R>,
transformRight?: TransformFn<R, T>
) {
useEffect(() => {
return subscribe.bind(left, right, transformLeft, transformRight);
}, [left, right]);
}
/**
* React hook that derives a specific property value from a reactive state object.
* It automatically re-computes the value whenever the dependent state property changes.
*
* @template T - The type of the reactive state object.
* @template K - The type of the key being derived.
* @param {T} state - The reactive state object to derive from.
* @param {K} key - The key of the property to derive from the state object.
* @returns {T[K]} - The derived value of the specified property.
*/
export function useValue<T extends State, K extends keyof T>(state: T, key: K): T[K] {
const [version, setVersion] = useState(RENDERER_INIT_VERSION);
const current = useMemo(() => {
return state?.[key];
}, [state, key, version]);
useEffect(() => {
if (typeof state === 'undefined') return;
if (!anchor.has(state)) {
const error = new Error('State is not reactive.');
captureStack.violation.derivation('Attempted to derive value from a non-reactive state.', error);
return;
}
return subscribe(
state,
(next, event) => {
if (isMutationOf(event, key)) {
setVersion((c) => c + 1);
}
},
false
);
}, [state, key]);
return current;
}
/**
* React hook that checks if a specific property of a reactive state equals an expected value.
* It automatically re-evaluates the comparison whenever the dependent state changes.
*
* @template T - The type of the reactive state object.
* @template K - The type of the key being checked.
* @param {T} state - The reactive state object to check.
* @param {K} key - The key of the property to check in the state object.
* @param {unknown} expect - The expected value to compare against.
* @returns {boolean} - Returns true if the property value equals the expected value, false otherwise.
*/
export function useValueIs<T extends State, K extends keyof T>(state: T, key: K, expect: unknown): boolean {
const ref = useRef({
deps: new Set([state, key, expect]),
matched: state?.[key] === expect,
checkDeps: false,
}).current;
const [cleanup, cancelCleanup] = useMicrotask(CLEANUP_DEBOUNCE_TIME);
const [, setVersion] = useState(RENDERER_INIT_VERSION);
if (ref.checkDeps) {
const updatedDeps = depsChanged(ref.deps, [state, key, expect]);
if (updatedDeps) {
ref.deps.clear(); // Cleanup the previous deps to allow for garbage collection.
ref.deps = updatedDeps;
ref.matched = state?.[key] === expect;
}
} else {
ref.checkDeps = true;
}
useEffect(() => {
if (!anchor.has(state)) {
const error = new Error('State is not reactive.');
captureStack.violation.derivation('Attempted to compare value from a non-reactive state.', error);
return;
}
cancelCleanup();
const unsubscribe = subscribe(
state,
(_, event) => {
if (isMutationOf(event, key)) {
const next = state[key] === expect;
if (next !== ref.matched) {
ref.matched = next;
ref.checkDeps = false;
setVersion((c) => c + 1);
}
}
},
false
);
return () => {
unsubscribe();
cleanup(() => {
ref.deps.clear();
});
};
}, [state, key, expect]);
return ref.matched;
}
/**
* React hook that creates a derived reference from a reactive state.
* The handle function is called whenever the state changes, receiving the current state and the current ref value.
* The hook returns a RefObject that can be used to get or set the current ref value.
* When the ref value is set, the handle function is called with the current state and the new ref value.
*
* @template S - The type of the reactive state.
* @template R - The type of the ref value.
* @param {S} state - The reactive state to derive from.
* @param {(current: S, ref: R | null) => void} handle - The function to call when the state changes or the ref value is set.
* @returns {RefObject<R | null>} - A RefObject that can be used to get or set the current ref value.
*/
export function useDerivedRef<S extends State, R>(
state: S,
handle: (current: S, ref: R | null) => void
): RefObject<R | null> {
const valueRef = useRef<R>(null);
useEffect(() => {
return subscribe(state, () => {
handle(anchor.read(state) as S, valueRef.current);
});
}, [state]);
return {
get current() {
return valueRef.current;
},
set current(next) {
valueRef.current = next;
handle(anchor.read(state) as S, valueRef.current);
},
};
}
|