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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | 5x 5x 5x 5x 5x 5x 78x 23x 5x 7x 7x 5x 18x 18x 5x 4x 4x 1x 5x 37x 5x 37x 37x 5x 37x 37x 37x 5x 28x 28x 5x 9x 9x 5x 16x 16x 16x 5x 4x 5x 2x 5x 2x 5x 2x | import {useState, useMemo, useCallback, useSyncExternalStore, useEffect} from 'react';
import {useCtxModelStrict, useCtxNodeStrict} from './context';
import type {FanOutUnsubscribe} from 'thingies/lib/fanout';
import type {SyncStore} from 'json-joy/lib/util/events/sync-store';
import type {Model, JsonNodeView, ArrApi, ObjApi, StrApi} from 'json-joy/lib/json-crdt';
import type {ChangeEvent} from 'json-joy/lib/json-crdt/model/api/events';
import type {ApiPath} from 'json-joy/lib/json-crdt/model/api/types';
import type {CrdtNodeApi} from './types';
// ------------------------------------------------------------------ SyncStore
export const useStore = <T>(store: SyncStore<T>): T => useSyncExternalStore(store.subscribe, store.getSnapshot);
const emptySyncStore: SyncStore<undefined> = {
getSnapshot: () => undefined,
subscribe: () => () => {},
};
export const useStoreOpt = <T>(store: SyncStore<T | undefined> = emptySyncStore): T | undefined =>
useSyncExternalStore(store.subscribe, store.getSnapshot);
// ---------------------------------------------------------------- Model hooks
/**
* Hook to subscribe to a model's *tick* and get the current tick value. Useful
* for re-rendering on every *tick* of the model, this will re-render on every
* change of the model, even if the change results in not view-relevant updates.
*
* @param model The JSON CRDT model. If not provided, it will be retrieved from
* the context using `useCtxModelStrict()`.
* @returns The current tick value (volatile change counter) of the model.
*/
export const useModelTick = <M extends Model<any>>(model: M = useCtxModelStrict() as M): number => {
const getSnapshot = useCallback(() => model.tick, [model]);
return useSyncExternalStore(model.api.subscribe, getSnapshot);
};
/**
* Hook to subscribe to a model's view and get the current view value.
* Re-renders the component whenever the view changes. Does not re-render if the
* identity of the view object does not change, for example, if `{foo: 'bar'}`
* changes to `{foo: 'bar'}`, the JSON CRDT model will preserve the same view
* object, so this hook will not trigger a re-render.
*
* @returns The view of the model.
* @param model The JSON CRDT model. If not provided, it will be retrieved from
* the context using `useCtxModelStrict()`.
*/
export const useModelView = <M extends Model<any>>(model: M = useCtxModelStrict() as M): JsonNodeView<M['root']> => {
const api = model.api;
return useSyncExternalStore(api.subscribe, api.getSnapshot) as any;
};
/**
* Hook to subscribe to a model and get a derived value from the model using a
* selector function. Re-renders the component whenever the model changes, even
* if the view does not change.
*
* @param selector A function that maps JSON CRDT `Model` to some value.
* @param model The JSON CRDT model. If not provided, it will be retrieved from
* the context using `useCtxModelStrict()`.
* @returns The value returned by the `selector` function.
*/
export const useModel = <M extends Model<any>, R = unknown>(
selector: (model: M) => R,
model: M = useCtxModelStrict() as M,
): R => {
const tick = useModelTick(model);
// biome-ignore lint: manual dependency list
return useMemo(() => selector(model), [tick, model]);
};
/**
* A safe version of `useModel` that returns `undefined` if the selector function
* throws an error. This can be useful if the selector function may throw an error
* during the initial render, for example, if it tries to access a part of the
* model that is not yet initialized.
*
* @param selector A function that maps JSON CRDT `Model` to some value.
* @param model The JSON CRDT model. If not provided, it will be retrieved from
* the context using `useCtxModelStrict()`.
* @returns The value returned by the `selector` function, or `undefined` if the selector throws an error.
*/
export const useModelTry = <M extends Model<any>, R = unknown>(selector: (model: M) => R, model?: M): R | undefined => {
try {
// biome-ignore lint/correctness/useHookAtTopLevel: intentional pattern to catch errors from useModel in a try-catch
return useModel(selector, model);
} catch {
return;
}
};
// ----------------------------------------------------------------- Node hooks
/**
* Hook to subscribe to change events on a JSON CRDT node. Returns a function
* to unsubscribe from the events. If the `node` parameter is
* not provided, the node will be retrieved from the context using
* `useCtxNodeStrict()`.
*
* @see useNodeEffect for a more convenient hook that automatically handles un-subscription.
*
* @param event The type of change event to subscribe to.
* Defaults to 'subtree', which will trigger whenever the top `node` or
* any of its descendants change. 'self' will only trigger when the `node`
* itself changes, and 'child' will trigger when direct children change.
* @param listener The callback function to be invoked when the specified change
* event occurs.
* @param node The JSON CRDT node to subscribe to. If not provided, it will be
* retrieved from the context using `useCtxNodeStrict()`.
* @returns A function to unsubscribe from the change events.
*/
export const useNodeEvents = <N extends CrdtNodeApi = CrdtNodeApi>(
event: 'self' | 'child' | 'subtree',
listener: (event: ChangeEvent) => void,
node: N = useCtxNodeStrict() as N,
// biome-ignore lint/correctness/useExhaustiveDependencies: listener is intentionally excluded to avoid stale closure re-subscriptions
): FanOutUnsubscribe => useMemo(() => node.onNodeChange(event, listener), [node, event]);
/**
* Same as `useNodeEvents`, but automatically unsubscribes when the component
* unmounts.
*
* @see useNodeEvents for a more low-level hook that returns the un-subscription
* function for manual control over subscription lifecycle.
*
* @param event The type of change event to subscribe to.
* Defaults to 'subtree', which will trigger whenever the top `node` or
* any of its descendants change. 'self' will only trigger when the `node`
* itself changes, and 'child' will trigger when direct children change.
* @param listener The callback function to be invoked when the specified change
* event occurs.
* @param node The JSON CRDT node to subscribe to. If not provided, it will be
* retrieved from the context using `useCtxNodeStrict()`.
* @returns A function to unsubscribe from the change events.
*/
export const useNodeEffect = <N extends CrdtNodeApi = CrdtNodeApi>(
event: 'self' | 'child' | 'subtree',
listener: (event: ChangeEvent) => void,
node?: N,
): void => {
const unsubscribe = useNodeEvents(event, listener, node);
useEffect(() => unsubscribe, [unsubscribe]);
};
/**
* Re-renders the component whenever the specified type of change event occurs
* on the given node. Returns the latest change event object, or `undefined` if
* no change has occurred yet. If the `node` parameter is not provided, the node
* will be retrieved from the context using `useCtxNodeStrict()`.
*
* @see useNodeEffect for a more low-level hook that listen for change events
* without causing re-renders.
*
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @param node The JSON CRDT node to subscribe to. If not provided, it will be
* retrieved from the context using `useCtxNodeStrict()`.
* @returns The latest change event object, or `undefined` if no change has
* occurred yet.
*/
export const useNodeChange = <N extends CrdtNodeApi = CrdtNodeApi>(
event: 'self' | 'child' | 'subtree',
node?: N,
): ChangeEvent | undefined => {
const [change, setChange] = useState<ChangeEvent>();
useNodeEffect(event, setChange, node);
return change;
};
/**
* Re-renders the component whenever the specified type of change event occurs
* on the given node, and returns the node itself. If the `node` parameter is not
* provided, the node will be retrieved from the context using `useCtxNodeStrict()`.
*
* @see useNodeEvents
* @see useNodeEffect
* @see useNodeChange
* @see useNodeView
*
* @param node The JSON CRDT node to subscribe to. If not provided, it will be
* retrieved from the context using `useCtxNodeStrict()`.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns The JSON CRDT node that the component is subscribed to.
*/
export const useNode = <N extends CrdtNodeApi = CrdtNodeApi>(
node: N = useCtxNodeStrict() as N,
event: 'self' | 'child' | 'subtree' = 'subtree',
): N => {
useNodeChange(event, node);
return node;
};
/**
* Re-renders the component whenever the specified type of change event occurs
* on the given node, and returns the node view. If the `node` parameter is not
* provided, the node will be retrieved from the context using `useCtxNodeStrict()`.
*
* @see useNodeEvents
* @see useNodeEffect
* @see useNodeChange
* @see useNode
*
* @param node The JSON CRDT node to subscribe to. If not provided, it will be
* retrieved from the context using `useCtxNodeStrict()`.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns The view of the JSON CRDT node that the component is subscribed to.
*/
export const useNodeView = <N extends CrdtNodeApi = CrdtNodeApi>(
node: N = useCtxNodeStrict() as N,
event: 'self' | 'child' | 'subtree' = 'subtree',
): ReturnType<N['view']> => {
useNodeChange(event, node);
return node.view() as ReturnType<N['view']>;
};
// ----------------------------------------------------------------- Path hooks
/**
* React hook to access a nested JSON CRDT node at a specified path. Subscribes
* to changes on the parent node (or context node if not provided) and
* re-renders when the specified type of change event occurs. Returns
* `undefined` if the path does not exist or cannot be resolved to a node.
*
* @param path Path at which to find a nested JSON CRDT node.
* @param node The parent (or node taken from React context, if not provided)
* from which to start search of the nested node.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns The nested JSON CRDT node at the specified path, or `undefined` if
* the path does not exist.
*/
export const usePath = <N extends CrdtNodeApi = CrdtNodeApi>(
path: ApiPath,
node: N = useCtxNodeStrict() as N,
event: 'self' | 'child' | 'subtree' = 'subtree',
): CrdtNodeApi | undefined => {
useNode(node, event);
try {
return node.in(path);
} catch {
return;
}
};
/**
* React hook to access the view of a nested JSON CRDT node at a specified path.
* Same as `usePath`, but returns the view of the node at the path instead of
* the node itself.
*
* @param path Path at which to find a nested JSON CRDT node.
* @param node The parent (or node taken from React context, if not provided)
* from which to start search of the nested node.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns The view of the nested JSON CRDT node at the specified path,
* or `undefined` if the path does not exist.
*/
export const usePathView = <N extends CrdtNodeApi = CrdtNodeApi>(
path: ApiPath,
node: N = useCtxNodeStrict() as N,
event?: 'self' | 'child' | 'subtree',
) => usePath(path, node, event)?.view();
/**
* React hook to access "obj" node at a specified path. Same as `usePath`, but
* returns the node casted to an `ObjApi` using `asObj()`. Returns `undefined`
* if the path does not exist or if the node at the path is not an object node.
* Subscribes to changes on the parent node (or context node if not provided)
* and re-renders when the specified type of change event occurs.
*
* @param path Path at which to find a nested JSON CRDT node.
* @param node The parent (or node taken from React context, if not provided)
* from which to start search of the nested node.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns An instance of `ObjApi` at the specified path, or `undefined` if
* the path does not exist, or if the node is of a different type.
*/
export const useObj = <N extends CrdtNodeApi = CrdtNodeApi>(
path: ApiPath = [],
node?: N,
event?: 'self' | 'child' | 'subtree',
): ObjApi<any> | undefined => usePath(path, node, event)?.asObj(true);
/**
* React hook to access "arr" node at a specified path. Same as `usePath`, but
* returns the node casted to an `ArrApi` using `asArr()`. Returns `undefined`
* if the path does not exist or if the node at the path is not an array node.
* Subscribes to changes on the parent node (or context node if not provided)
* and re-renders when the specified type of change event occurs.
*
* @param path Path at which to find a nested JSON CRDT node.
* @param node The parent (or node taken from React context, if not provided)
* from which to start search of the nested node.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns An instance of `ArrApi` at the specified path, or `undefined` if
* the path does not exist, or if the node is of a different type.
*/
export const useArr = <N extends CrdtNodeApi = CrdtNodeApi>(
path: ApiPath = [],
node?: N,
event?: 'self' | 'child' | 'subtree',
): ArrApi<any> | undefined => usePath(path, node, event)?.asArr(true);
/**
* React hook to access "str" node at a specified path. Same as `usePath`, but
* returns the node casted to an `StrApi` using `asStr()`. Returns `undefined`
* if the path does not exist or if the node at the path is not a string node.
* Subscribes to changes on the parent node (or context node if not provided)
* and re-renders when the specified type of change event occurs.
*
* @param path Path at which to find a nested JSON CRDT node.
* @param node The parent (or node taken from React context, if not provided)
* from which to start search of the nested node.
* @param event The type of change event to subscribe to for re-rendering.
* Defaults to 'subtree', which will re-render whenever the top `node` or
* any of its descendants change. 'self' will only re-render when the `node`
* itself changes, and 'child' will re-render when direct children change.
* @returns An instance of `StrApi` at the specified path, or `undefined` if
* the path does not exist, or if the node is of a different type.
*/
export const useStr = <N extends CrdtNodeApi = CrdtNodeApi>(
path: ApiPath = [],
node?: N,
event?: 'self' | 'child' | 'subtree',
): StrApi | undefined => usePath(path, node, event)?.asStr(true);
|