From df75f711973a58580aac7d2b6798edcec00f368a Mon Sep 17 00:00:00 2001 From: Jay Meistrich Date: Tue, 16 Jul 2024 14:44:55 -0700 Subject: [PATCH] refactor rename type NodeValue to NodeInfo because it was confusing to be named Value --- src/ObservableObject.ts | 88 +++++++++++++++---------------- src/ObservablePrimitive.ts | 10 ++-- src/batching.ts | 24 ++++----- src/config.ts | 6 +-- src/config/enableReactTracking.ts | 4 +- src/config/enableReactUse.ts | 4 +- src/createObservable.ts | 4 +- src/globals.ts | 36 ++++++------- src/is.ts | 4 +- src/observableInterfaces.ts | 34 ++++++------ src/onChange.ts | 12 ++--- src/setupTracking.ts | 4 +- src/sync/activateSyncedNode.ts | 6 +-- src/sync/syncObservable.ts | 8 +-- src/sync/syncTypes.ts | 6 +-- src/trace/traceHelpers.ts | 4 +- src/trace/useTraceListeners.ts | 4 +- src/trace/useVerifyNotTracking.ts | 4 +- src/tracking.ts | 4 +- tests/tests.test.ts | 4 +- 20 files changed, 135 insertions(+), 135 deletions(-) diff --git a/src/ObservableObject.ts b/src/ObservableObject.ts index 6ef34a1e5..209572a20 100644 --- a/src/ObservableObject.ts +++ b/src/ObservableObject.ts @@ -22,7 +22,7 @@ import { hasOwnProperty, isArray, isBoolean, - isChildNodeValue, + isChildNode, isEmpty, isFunction, isMap, @@ -35,11 +35,11 @@ import { import { linked } from './linked'; import type { Change, - ChildNodeValue, + ChildNodeInfo, GetOptions, LinkedOptions, ListenerParams, - NodeValue, + NodeInfo, ObservableState, TrackingType, UpdateFn, @@ -76,9 +76,9 @@ const ArrayLoopers = new Set>([ const ArrayLoopersReturn = new Set>(['filter', 'find']); export const observableProperties = new Map< string, - { get: (node: NodeValue, ...args: any[]) => any; set: (node: NodeValue, value: any) => any } + { get: (node: NodeInfo, ...args: any[]) => any; set: (node: NodeInfo, value: any) => any } >(); -export const observableFns = new Map any>([ +export const observableFns = new Map any>([ ['get', get], ['set', set], ['peek', peek], @@ -92,7 +92,7 @@ if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') { // eslint-disable-next-line no-var var __devUpdateNodes = new Set(); } -function collectionSetter(node: NodeValue, target: any[], prop: keyof Array, ...args: any[]) { +function collectionSetter(node: NodeInfo, target: any[], prop: keyof Array, ...args: any[]) { if (prop === 'push' && args.length === 1) { // Fast path for push to just append to the end setKey(node, target.length + '', args[0]); @@ -102,7 +102,7 @@ function collectionSetter(node: NodeValue, target: any[], prop: keyof Array const ret = (target[prop] as Function).apply(target, args); if (node) { - const hasParent = isChildNodeValue(node); + const hasParent = isChildNode(node); const key: string = hasParent ? node.key : '_'; const parentValue = hasParent ? getNodeValue(node.parent) : node.root; @@ -122,7 +122,7 @@ function getKeys(obj: Record | Array | undefined, isArr: boolean, return isArr ? (undefined as any) : obj ? (isMap ? Array.from(obj.keys()) : Object.keys(obj)) : []; } -function updateNodes(parent: NodeValue, obj: Record | Array | undefined, prevValue: any): boolean { +function updateNodes(parent: NodeInfo, obj: Record | Array | undefined, prevValue: any): boolean { if ( (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') && typeof __devUpdateNodes !== 'undefined' && @@ -156,8 +156,8 @@ function updateNodes(parent: NodeValue, obj: Record | Array | und const isArr = isArray(obj); - let prevChildrenById: Map | undefined; - let moved: [string, ChildNodeValue][] | undefined; + let prevChildrenById: Map | undefined; + let moved: [string, ChildNodeInfo][] | undefined; const isCurMap = isMap(obj); const isPrevMap = isMap(prevValue); @@ -357,7 +357,7 @@ function updateNodes(parent: NodeValue, obj: Record | Array | und return retValue ?? false; } -function handleDeletedChild(child: NodeValue, p: any) { +function handleDeletedChild(child: NodeInfo, p: any) { // If the previous value is not in the new array and it // is an activated, disable its listeners child.linkedToNodeDispose?.(); @@ -372,12 +372,12 @@ function handleDeletedChild(child: NodeValue, p: any) { } } -export function getProxy(node: NodeValue, p?: string, asFunction?: Function): Observable { +export function getProxy(node: NodeInfo, p?: string, asFunction?: Function): Observable { // Get the child node if p prop if (p !== undefined) node = getChildNode(node, p, asFunction); // Create a proxy if not already cached and return it - return (node.proxy || (node.proxy = new Proxy(node, proxyHandler))) as Observable; + return (node.proxy || (node.proxy = new Proxy(node, proxyHandler))) as Observable; } export function flushPending() { @@ -391,7 +391,7 @@ export function flushPending() { } const proxyHandler: ProxyHandler = { - get(node: NodeValue, p: any, receiver: any) { + get(node: NodeInfo, p: any, receiver: any) { if (p === symbolToPrimitive) { throw new Error( process.env.NODE_ENV === 'development' @@ -558,11 +558,11 @@ const proxyHandler: ProxyHandler = { return getProxy(node, p); }, // Forward all proxy properties to the target's value - getPrototypeOf(node: NodeValue) { + getPrototypeOf(node: NodeInfo) { const value = getNodeValue(node); return value !== null && typeof value === 'object' ? Reflect.getPrototypeOf(value) : null; }, - ownKeys(node: NodeValue) { + ownKeys(node: NodeInfo) { // TODO: Temporary workaround to fix a bug - the first peek may not return the correct value // if the value is a cached. This fixes the test "cache with initial ownKeys" peekInternal(node); @@ -584,14 +584,14 @@ const proxyHandler: ProxyHandler = { } return keys; }, - getOwnPropertyDescriptor(node: NodeValue, prop: string) { + getOwnPropertyDescriptor(node: NodeInfo, prop: string) { if (prop === 'caller' || prop === 'arguments' || prop === 'prototype') { return { configurable: false, enumerable: false }; } const value = getNodeValue(node); return isPrimitive(value) ? undefined : Reflect.getOwnPropertyDescriptor(value, prop); }, - set(node: NodeValue, prop: string, value: any) { + set(node: NodeInfo, prop: string, value: any) { // If this assignment comes from within an observable function it's allowed if (node.isSetting) { return Reflect.set(node, prop, value); @@ -612,7 +612,7 @@ const proxyHandler: ProxyHandler = { } return false; }, - deleteProperty(node: NodeValue, prop: string) { + deleteProperty(node: NodeInfo, prop: string) { // If this delete comes from within an observable function it's allowed if (node.isSetting) { return Reflect.deleteProperty(node, prop); @@ -623,7 +623,7 @@ const proxyHandler: ProxyHandler = { return false; } }, - has(node: NodeValue, prop: string) { + has(node: NodeInfo, prop: string) { const value = getNodeValue(node); return Reflect.has(value, prop); }, @@ -636,14 +636,14 @@ const proxyHandler: ProxyHandler = { }, }; -export function set(node: NodeValue, newValue?: any) { +export function set(node: NodeInfo, newValue?: any) { if (node.parent) { setKey(node.parent, node.key, newValue); } else { setKey(node, '_', newValue); } } -function toggle(node: NodeValue) { +function toggle(node: NodeInfo) { const value = getNodeValue(node); if (value === undefined || value === null || isBoolean(value)) { set(node, !value); @@ -652,7 +652,7 @@ function toggle(node: NodeValue) { } } -function setKey(node: NodeValue, key: string, newValue?: any, level?: number) { +function setKey(node: NodeInfo, key: string, newValue?: any, level?: number) { if (process.env.NODE_ENV === 'development') { if (typeof HTMLElement !== 'undefined' && newValue instanceof HTMLElement) { console.warn(`[legend-state] Set an HTMLElement into state. You probably don't want to do that.`); @@ -666,7 +666,7 @@ function setKey(node: NodeValue, key: string, newValue?: any, level?: number) { } // Get the child node for updating and notifying - const childNode: NodeValue = isRoot ? node : getChildNode(node, key, newValue); + const childNode: NodeInfo = isRoot ? node : getChildNode(node, key, newValue); if (isObservable(newValue)) { setToObservable(childNode, newValue); @@ -695,7 +695,7 @@ function setKey(node: NodeValue, key: string, newValue?: any, level?: number) { } } -function assign(node: NodeValue, value: any) { +function assign(node: NodeInfo, value: any) { const proxy = getProxy(node); beginBatch(); @@ -727,9 +727,9 @@ function assign(node: NodeValue, value: any) { return proxy; } -function deleteFn(node: NodeValue, key?: string) { +function deleteFn(node: NodeInfo, key?: string) { // If called without a key, delete by key from the parent node - if (key === undefined && isChildNodeValue(node)) { + if (key === undefined && isChildNode(node)) { key = node.key; node = node.parent; } @@ -741,7 +741,7 @@ function deleteFn(node: NodeValue, key?: string) { } } -function handlerMapSet(node: NodeValue, p: any, value: Map | WeakMap | Set | WeakSet) { +function handlerMapSet(node: NodeInfo, p: any, value: Map | WeakMap | Set | WeakSet) { const vProp = (value as any)?.[p]; if (p === 'size') { updateTracking(node, true); @@ -812,10 +812,10 @@ function handlerMapSet(node: NodeValue, p: any, value: Map | WeakMap, setter?: (params: { value: any }) => void) { +export function extractPromise(node: NodeInfo, value: Promise, setter?: (params: { value: any }) => void) { const numGets = (node.numGets = (node.numGets || 0) + 1); if (!node.state) { @@ -891,7 +891,7 @@ export function extractPromise(node: NodeValue, value: Promise, setter?: (p }); } -function extractFunctionOrComputed(node: NodeValue, k: string, v: any) { +function extractFunctionOrComputed(node: NodeInfo, k: string, v: any) { // We want to extract these types of values from the observable's raw value so that // the raw value does not contain Promises, Observables or functions if (isPromise(v)) { @@ -915,7 +915,7 @@ function extractFunctionOrComputed(node: NodeValue, k: string, v: any) { } } -export function get(node: NodeValue, options?: TrackingType | GetOptions) { +export function get(node: NodeInfo, options?: TrackingType | GetOptions) { const track = options ? (isObject(options) ? (options.shallow as TrackingType) : options) : undefined; // Track by default updateTracking(node, track); @@ -923,13 +923,13 @@ export function get(node: NodeValue, options?: TrackingType | GetOptions) { return peek(node); } -export function peek(node: NodeValue) { +export function peek(node: NodeInfo) { return peekInternal(node, true); } let isFlushing = false; -export function peekInternal(node: NodeValue, activateRecursive?: boolean) { +export function peekInternal(node: NodeInfo, activateRecursive?: boolean) { isFlushing = true; // Need to refresh all dirty children when getting if (activateRecursive && node.dirtyChildren?.size) { @@ -956,7 +956,7 @@ export function peekInternal(node: NodeValue, activateRecursive?: boolean) { return value; } -function checkLazy(node: NodeValue, value: any, activateRecursive: boolean) { +function checkLazy(node: NodeInfo, value: any, activateRecursive: boolean) { const origValue = value; // If node is not yet lazily computed go do that const lazy = node.lazy; @@ -1016,7 +1016,7 @@ function checkProperty(value: any, key: string) { } } -function reactivateNode(node: NodeValue, lazyFn: Function) { +function reactivateNode(node: NodeInfo, lazyFn: Function) { node.activatedObserveDispose?.(); node.linkedToNodeDispose?.(); node.activatedObserveDispose = node.linkedToNodeDispose = node.linkedToNode = undefined; @@ -1024,7 +1024,7 @@ function reactivateNode(node: NodeValue, lazyFn: Function) { node.lazy = true; } -export function isObserved(node: NodeValue) { +export function isObserved(node: NodeInfo) { let parent = node; let hasListeners = node.numListenersRecursive > 0; while (parent && !hasListeners) { @@ -1036,7 +1036,7 @@ export function isObserved(node: NodeValue) { return hasListeners; } -export function shouldIgnoreUnobserved(node: NodeValue, refreshFn: () => void) { +export function shouldIgnoreUnobserved(node: NodeInfo, refreshFn: () => void) { if (!isFlushing) { const hasListeners = isObserved(node); if (!hasListeners) { @@ -1057,7 +1057,7 @@ export function shouldIgnoreUnobserved(node: NodeValue, refreshFn: () => void) { } } -function activateNodeFunction(node: NodeValue, lazyFn: Function) { +function activateNodeFunction(node: NodeInfo, lazyFn: Function) { // let prevTarget$: Observable; // let curTarget$: Observable; let update: UpdateFn; @@ -1203,7 +1203,7 @@ function activateNodeFunction(node: NodeValue, lazyFn: Function) { return activatedValue; } -function activateNodeBase(node: NodeValue, value: any) { +function activateNodeBase(node: NodeInfo, value: any) { if (!node.state) { node.state = createObservable( { @@ -1306,7 +1306,7 @@ function activateNodeBase(node: NodeValue, value: any) { return { update, value }; } -function setToObservable(node: NodeValue, value: any) { +function setToObservable(node: NodeInfo, value: any) { // If the computed is a proxy to another observable // link it to the target observable const linkedNode = value ? getNode(value) : undefined; @@ -1333,7 +1333,7 @@ function setToObservable(node: NodeValue, value: any) { return value; } -function recursivelyAutoActivate(obj: Record, node: NodeValue) { +function recursivelyAutoActivate(obj: Record, node: NodeInfo) { if (!node.recursivelyAutoActivated && (isObject(obj) || isArray(obj)) && !isOpaqueObject(obj)) { node.recursivelyAutoActivated = true; const pathStack: { key: string; value: any }[] = []; // Maintain a stack for path tracking @@ -1355,7 +1355,7 @@ function recursivelyAutoActivate(obj: Record, node: NodeValue) { function recursivelyAutoActivateInner( obj: Record, pathStack: { key: string; value: any }[], - getNodeAtPath: () => NodeValue, + getNodeAtPath: () => NodeInfo, ) { if ((isObject(obj) || isArray(obj)) && !isOpaqueObject(obj)) { for (const key in obj) { diff --git a/src/ObservablePrimitive.ts b/src/ObservablePrimitive.ts index d3acaf174..78b9d1732 100644 --- a/src/ObservablePrimitive.ts +++ b/src/ObservablePrimitive.ts @@ -1,18 +1,18 @@ import { set, get, peek, flushPending } from './ObservableObject'; import { symbolGetNode } from './globals'; import { isBoolean } from './is'; -import type { NodeValue, TrackingType } from './observableInterfaces'; +import type { NodeInfo, TrackingType } from './observableInterfaces'; import type { ObservablePrimitive, ObservableBoolean } from './observableTypes'; import { onChange } from './onChange'; interface ObservablePrimitiveState { - _node: NodeValue; + _node: NodeInfo; toggle: () => void; } const fns: (keyof ObservableBoolean)[] = ['get', 'set', 'peek', 'onChange', 'toggle']; -export function ObservablePrimitiveClass(this: ObservablePrimitive & ObservablePrimitiveState, node: NodeValue) { +export function ObservablePrimitiveClass(this: ObservablePrimitive & ObservablePrimitiveState, node: NodeInfo) { this._node = node; // Bind to this @@ -28,11 +28,11 @@ function proto(key: string, fn: Function) { return fn.call(this, this._node, ...args); }; } -proto('peek', (node: NodeValue) => { +proto('peek', (node: NodeInfo) => { flushPending(); return peek(node); }); -proto('get', (node: NodeValue, options?: TrackingType) => { +proto('get', (node: NodeInfo, options?: TrackingType) => { flushPending(); return get(node, options); }); diff --git a/src/batching.ts b/src/batching.ts index 3fe5fce6b..a6d71db1e 100644 --- a/src/batching.ts +++ b/src/batching.ts @@ -1,6 +1,6 @@ import { clone, getChildNode, getNodeValue, getPathType, globalState, optimized } from './globals'; import { applyChanges } from './helpers'; -import type { Change, ListenerFn, ListenerParams, NodeValue, TypeAtPath } from './observableInterfaces'; +import type { Change, ListenerFn, ListenerParams, NodeInfo, TypeAtPath } from './observableInterfaces'; interface BatchItem { value: any; @@ -22,7 +22,7 @@ let timeout: ReturnType | undefined; let numInBatch = 0; let isRunningBatch = false; let didDelayEndBatch = false; -let _batchMap = new Map(); +let _batchMap = new Map(); function onActionTimeout() { if (_batchMap.size > 0) { @@ -63,9 +63,9 @@ export function createPreviousHandler(value: any, changes: Change[]) { }; } -export function notify(node: NodeValue, value: any, prev: any, level: number, whenOptimizedOnlyIf?: boolean) { +export function notify(node: NodeInfo, value: any, prev: any, level: number, whenOptimizedOnlyIf?: boolean) { // Run immediate listeners if there are any - const changesInBatch = new Map(); + const changesInBatch = new Map(); computeChangesRecursive( changesInBatch, node, @@ -114,8 +114,8 @@ export function notify(node: NodeValue, value: any, prev: any, level: number, wh } function computeChangesAtNode( - changesInBatch: Map, - node: NodeValue, + changesInBatch: Map, + node: NodeInfo, isFromPersist: boolean, isFromSync: boolean, value: any, @@ -159,8 +159,8 @@ function computeChangesAtNode( } function computeChangesRecursive( - changesInBatch: Map, - node: NodeValue, + changesInBatch: Map, + node: NodeInfo, loading: boolean, remote: boolean, value: any, @@ -229,7 +229,7 @@ function computeChangesRecursive( } } -function batchNotifyChanges(changesInBatch: Map, immediate: boolean) { +function batchNotifyChanges(changesInBatch: Map, immediate: boolean) { const listenersNotified = new Set(); // For each change in the batch, notify all of the listeners changesInBatch.forEach(({ changes, level, value, isFromPersist, isFromSync, whenOptimizedOnlyIf }, node) => { @@ -284,7 +284,7 @@ export function runBatch() { // This can happen with computeds for example. const map = _batchMap; _batchMap = new Map(); - const changesInBatch = new Map(); + const changesInBatch = new Map(); // First compute all of the changes at each node. It's important to do this first before // running all the notifications because createPreviousHandler depends on knowing // all of the changes happening at the node. @@ -355,8 +355,8 @@ export function endBatch(force?: boolean) { } } -function getNodeAtPath(obj: NodeValue, path: string[]): NodeValue { - let o: NodeValue = obj; +function getNodeAtPath(obj: NodeInfo, path: string[]): NodeInfo { + let o: NodeInfo = obj; for (let i = 0; i < path.length; i++) { const p = path[i]; o = getChildNode(o, p); diff --git a/src/config.ts b/src/config.ts index 769aab2fb..951d21273 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,7 +1,7 @@ import { globalState } from './globals'; import { observableProperties as _observableProperties, observableFns } from './ObservableObject'; import { ObservablePrimitiveClass } from './ObservablePrimitive'; -import type { NodeValue } from './observableInterfaces'; +import type { NodeInfo } from './observableInterfaces'; export function configureLegendState({ observableFunctions, @@ -9,8 +9,8 @@ export function configureLegendState({ jsonReplacer, jsonReviver, }: { - observableFunctions?: Record any>; - observableProperties?: Record any; set: (node: NodeValue, value: any) => any }>; + observableFunctions?: Record any>; + observableProperties?: Record any; set: (node: NodeInfo, value: any) => any }>; jsonReplacer?: (this: any, key: string, value: any) => any; jsonReviver?: (this: any, key: string, value: any) => any; }) { diff --git a/src/config/enableReactTracking.ts b/src/config/enableReactTracking.ts index 576383468..14924e99a 100644 --- a/src/config/enableReactTracking.ts +++ b/src/config/enableReactTracking.ts @@ -4,7 +4,7 @@ import { internal, isObject, tracking, - type NodeValue, + type NodeInfo, type TrackingType, } from '@legendapp/state'; import { UseSelectorOptions, useSelector } from '@legendapp/state/react'; @@ -44,7 +44,7 @@ export function enableReactTracking({ auto, warnUnobserved }: ReactTrackingOptio configureLegendState({ observableFunctions: { - get: (node: NodeValue, options?: TrackingType | (GetOptions & UseSelectorOptions)) => { + get: (node: NodeInfo, options?: TrackingType | (GetOptions & UseSelectorOptions)) => { if (needsSelector()) { if (auto) { return useSelector(() => get(node, options), isObject(options) ? options : undefined); diff --git a/src/config/enableReactUse.ts b/src/config/enableReactUse.ts index 6ba99c436..48772eb67 100644 --- a/src/config/enableReactUse.ts +++ b/src/config/enableReactUse.ts @@ -1,4 +1,4 @@ -import { configureLegendState, internal, NodeValue } from '@legendapp/state'; +import { configureLegendState, internal, NodeInfo } from '@legendapp/state'; import { useSelector, UseSelectorOptions } from '@legendapp/state/react'; // TODO: Deprecated, remove in v4 @@ -7,7 +7,7 @@ let didWarn = false; export function enableReactUse() { configureLegendState({ observableFunctions: { - use: (node: NodeValue, options?: UseSelectorOptions) => { + use: (node: NodeInfo, options?: UseSelectorOptions) => { if (process.env.NODE_ENV === 'development' && !didWarn) { didWarn = true; console.warn( diff --git a/src/createObservable.ts b/src/createObservable.ts index 8d7c6fb45..ea94f69f6 100644 --- a/src/createObservable.ts +++ b/src/createObservable.ts @@ -1,7 +1,7 @@ import { isObservable, setNodeValue } from './globals'; import { isActualPrimitive, isFunction, isPromise } from './is'; import type { ClassConstructor, ObservableRoot } from './observableInterfaces'; -import { NodeValue } from './observableInterfaces'; +import { NodeInfo } from './observableInterfaces'; import { Observable, ObservablePrimitive } from './observableTypes'; export function createObservable( @@ -21,7 +21,7 @@ export function createObservable( _: value, }; - let node: NodeValue = { + let node: NodeInfo = { root, lazy: true, numListenersRecursive: 0, diff --git a/src/globals.ts b/src/globals.ts index 8594b43cb..0dc6a5783 100644 --- a/src/globals.ts +++ b/src/globals.ts @@ -1,5 +1,5 @@ -import { isArray, isChildNodeValue, isDate, isFunction, isMap, isObject, isSet } from './is'; -import type { NodeValue, ObservableEvent, TypeAtPath, UpdateFn } from './observableInterfaces'; +import { isArray, isChildNode, isDate, isFunction, isMap, isObject, isSet } from './is'; +import type { NodeInfo, ObservableEvent, TypeAtPath, UpdateFn } from './observableInterfaces'; import type { Observable, ObservableParam } from './observableTypes'; export const symbolToPrimitive = Symbol.toPrimitive; @@ -13,9 +13,9 @@ export const symbolLinked = Symbol('linked'); export const globalState = { isLoadingLocal: false, isLoadingRemote: false, - activateSyncedNode: undefined as unknown as (node: NodeValue, newValue: any) => { update: UpdateFn; value: any }, - pendingNodes: new Map void>(), - dirtyNodes: new Set(), + activateSyncedNode: undefined as unknown as (node: NodeInfo, newValue: any) => { update: UpdateFn; value: any }, + pendingNodes: new Map void>(), + dirtyNodes: new Set(), replacer: undefined as undefined | ((this: any, key: string, value: any) => any), reviver: undefined as undefined | ((this: any, key: string, value: any) => any), }; @@ -80,15 +80,15 @@ export function isObservable(value$: any): value$ is Observable { return !!value$ && !!value$[symbolGetNode as any]; } -export function getNode(value$: ObservableParam): NodeValue { +export function getNode(value$: ObservableParam): NodeInfo { return value$ && (value$ as any)[symbolGetNode]; } export function isEvent(value$: any): value$ is ObservableEvent { - return value$ && (value$[symbolGetNode as any] as NodeValue)?.isEvent; + return value$ && (value$[symbolGetNode as any] as NodeInfo)?.isEvent; } -export function setNodeValue(node: NodeValue, newValue: any) { +export function setNodeValue(node: NodeInfo, newValue: any) { const parentNode = node.parent ?? node; const key = node.parent ? node.key : '_'; @@ -138,10 +138,10 @@ export function setNodeValue(node: NodeValue, newValue: any) { } const arrNodeKeys: string[] = []; -export function getNodeValue(node: NodeValue): any { +export function getNodeValue(node: NodeInfo): any { let count = 0; - let n: NodeValue = node; - while (isChildNodeValue(n)) { + let n: NodeInfo = node; + while (isChildNode(n)) { arrNodeKeys[count++] = n.key; n = n.parent; } @@ -153,7 +153,7 @@ export function getNodeValue(node: NodeValue): any { return child; } -export function getChildNode(node: NodeValue, key: string, asFunction?: Function): NodeValue { +export function getChildNode(node: NodeInfo, key: string, asFunction?: Function): NodeInfo { // Get the child by key let child = node.children?.get(key); @@ -183,10 +183,10 @@ export function getChildNode(node: NodeValue, key: string, asFunction?: Function return child; } -export function ensureNodeValue(node: NodeValue) { +export function ensureNodeValue(node: NodeInfo) { let value = getNodeValue(node); if (!value || isFunction(value)) { - if (isChildNodeValue(node)) { + if (isChildNode(node)) { const parent = ensureNodeValue(node.parent); value = parent[node.key] = {}; } else { @@ -196,7 +196,7 @@ export function ensureNodeValue(node: NodeValue) { return value; } -export function findIDKey(obj: unknown | undefined, node: NodeValue): string | ((value: any) => string) | undefined { +export function findIDKey(obj: unknown | undefined, node: NodeInfo): string | ((value: any) => string) | undefined { let idKey: string | ((value: any) => string) | undefined = isObservable(obj) ? undefined : isObject(obj) @@ -224,9 +224,9 @@ export function findIDKey(obj: unknown | undefined, node: NodeValue): string | ( return idKey; } -export function extractFunction(node: NodeValue, key: string, fnOrComputed: Function): void; -export function extractFunction(node: NodeValue, key: string, fnOrComputed: Observable): void; -export function extractFunction(node: NodeValue, key: string, fnOrComputed: Function | Observable): void { +export function extractFunction(node: NodeInfo, key: string, fnOrComputed: Function): void; +export function extractFunction(node: NodeInfo, key: string, fnOrComputed: Observable): void; +export function extractFunction(node: NodeInfo, key: string, fnOrComputed: Function | Observable): void { if (!node.functions) { node.functions = new Map(); } diff --git a/src/is.ts b/src/is.ts index dce6deb46..0ca063435 100644 --- a/src/is.ts +++ b/src/is.ts @@ -1,4 +1,4 @@ -import type { ChildNodeValue, NodeValue } from './observableInterfaces'; +import type { ChildNodeInfo, NodeInfo } from './observableInterfaces'; export const hasOwnProperty = Object.prototype.hasOwnProperty; @@ -62,6 +62,6 @@ export function isActualPrimitive(arg: unknown): arg is boolean | string | numbe return setPrimitives.has(typeof arg); } /** @internal */ -export function isChildNodeValue(node: NodeValue): node is ChildNodeValue { +export function isChildNode(node: NodeInfo): node is ChildNodeInfo { return !!node.parent; } diff --git a/src/observableInterfaces.ts b/src/observableInterfaces.ts index 2ebc4df15..9aadaecae 100644 --- a/src/observableInterfaces.ts +++ b/src/observableInterfaces.ts @@ -51,32 +51,32 @@ export interface ObservableRoot { export type Primitive = boolean | string | number | Date; export type NotPrimitive = T extends Primitive ? never : T; -export interface NodeValueListener { +export interface NodeListener { track: TrackingType; noArgs?: boolean; listener: ListenerFn; } export interface TrackingState { - nodes?: Map; - traceListeners?: (nodes: Map) => void; + nodes?: Map; + traceListeners?: (nodes: Map) => void; traceUpdates?: (fn: Function) => Function; } -interface BaseNodeValue { - children?: Map; +interface BaseNodeInfo { + children?: Map; proxy?: object; root: ObservableRoot; - listeners?: Set; - listenersImmediate?: Set; + listeners?: Set; + listenersImmediate?: Set; isEvent?: boolean; - linkedToNode?: NodeValue; + linkedToNode?: NodeInfo; linkedToNodeDispose?: () => void; activatedObserveDispose?: () => void; - linkedFromNodes?: Set; + linkedFromNodes?: Set; isSetting?: number; isAssigning?: number; isComputing?: boolean; - parentOther?: NodeValue; + parentOther?: NodeInfo; functions?: Map>; lazy?: boolean; lazyFn?: Function; @@ -90,25 +90,25 @@ interface BaseNodeValue { onChange: (params: UpdateFnParams) => void | Promise; }; dirtyFn?: () => void; - dirtyChildren?: Set; + dirtyChildren?: Set; numGets?: number; getNumResolved?: number; } -export interface RootNodeValue extends BaseNodeValue { +export interface RootNodeInfo extends BaseNodeInfo { parent?: undefined; key?: undefined; } -export interface ChildNodeValue extends BaseNodeValue { - parent: NodeValue; +export interface ChildNodeInfo extends BaseNodeInfo { + parent: NodeInfo; key: string; } -export type NodeValue = RootNodeValue | ChildNodeValue; +export type NodeInfo = RootNodeInfo | ChildNodeInfo; export interface TrackingNode { - node: NodeValue; + node: NodeInfo; track: TrackingType; num: number; } @@ -123,7 +123,7 @@ export interface ObserveEventCallback { previous?: T | undefined; value?: T; cancel: boolean; - nodes: Map | undefined; + nodes: Map | undefined; refresh: () => void; onCleanup?: () => void; onCleanupReaction?: () => void; diff --git a/src/onChange.ts b/src/onChange.ts index 8ca2dd463..d89bb57d0 100644 --- a/src/onChange.ts +++ b/src/onChange.ts @@ -1,12 +1,12 @@ import { getNodeValue } from './globals'; import { isArray } from './is'; -import type { ListenerFn, ListenerParams, NodeValue, NodeValueListener, TrackingType } from './observableInterfaces'; +import type { ListenerFn, ListenerParams, NodeInfo, NodeListener, TrackingType } from './observableInterfaces'; export function onChange( - node: NodeValue, + node: NodeInfo, callback: ListenerFn, options: { trackingType?: TrackingType; initial?: boolean; immediate?: boolean; noArgs?: boolean } = {}, - fromLinks?: Set, + fromLinks?: Set, ): () => void { const { initial, immediate, noArgs } = options; const { trackingType } = options; @@ -21,7 +21,7 @@ export function onChange( } } - const listener: NodeValueListener = { + const listener: NodeListener = { listener: callback, track: trackingType, noArgs, @@ -49,7 +49,7 @@ export function onChange( let extraDisposes: (() => void)[]; - function addLinkedNodeListeners(childNode: NodeValue, cb: ListenerFn = callback, from?: NodeValue) { + function addLinkedNodeListeners(childNode: NodeInfo, cb: ListenerFn = callback, from?: NodeInfo) { // Don't add listeners for the same node more than once if (!fromLinks?.has(childNode)) { fromLinks ||= new Set(); @@ -104,7 +104,7 @@ export function onChange( }; } -function createCb(linkedFromNode: NodeValue, path: string[], callback: ListenerFn) { +function createCb(linkedFromNode: NodeInfo, path: string[], callback: ListenerFn) { // Create a callback for a path that calls it with the current value at the path let { valueAtPath: prevAtPath } = getValueAtPath(getNodeValue(linkedFromNode), path); diff --git a/src/setupTracking.ts b/src/setupTracking.ts index 0213fde7c..d99ac013a 100644 --- a/src/setupTracking.ts +++ b/src/setupTracking.ts @@ -1,8 +1,8 @@ -import type { ListenerFn, NodeValue, TrackingNode } from './observableInterfaces'; +import type { ListenerFn, NodeInfo, TrackingNode } from './observableInterfaces'; import { onChange } from './onChange'; export function setupTracking( - nodes: Map | undefined, + nodes: Map | undefined, update: ListenerFn, noArgs?: boolean, immediate?: boolean, diff --git a/src/sync/activateSyncedNode.ts b/src/sync/activateSyncedNode.ts index af7e58db1..518009245 100644 --- a/src/sync/activateSyncedNode.ts +++ b/src/sync/activateSyncedNode.ts @@ -1,11 +1,11 @@ -import type { NodeValue, UpdateFn } from '@legendapp/state'; +import type { NodeInfo, UpdateFn } from '@legendapp/state'; import { internal, isFunction, isPromise } from '@legendapp/state'; import { syncObservable } from './syncObservable'; import type { SyncedGetParams, SyncedOptions } from './syncTypes'; const { getProxy, globalState, setNodeValue, getNodeValue } = internal; export function enableActivateSyncedNode() { - globalState.activateSyncedNode = function activateSyncedNode(node: NodeValue, newValue: any) { + globalState.activateSyncedNode = function activateSyncedNode(node: NodeInfo, newValue: any) { const obs$ = getProxy(node); if (node.activationState) { // If it is a Synced @@ -14,7 +14,7 @@ export function enableActivateSyncedNode() { initial, set, onChange, - } = node.activationState! as NodeValue['activationState'] & SyncedOptions; + } = node.activationState! as NodeInfo['activationState'] & SyncedOptions; let promiseReturn: any = undefined; diff --git a/src/sync/syncObservable.ts b/src/sync/syncObservable.ts index 952cb047a..4578637be 100644 --- a/src/sync/syncObservable.ts +++ b/src/sync/syncObservable.ts @@ -3,7 +3,7 @@ import type { ClassConstructor, GetMode, ListenerParams, - NodeValue, + NodeInfo, Observable, ObservableObject, ObservableParam, @@ -67,7 +67,7 @@ export const mapSyncPlugins: WeakMap< } > = new WeakMap(); -const allSyncStates = new Map, NodeValue>(); +const allSyncStates = new Map, NodeInfo>(); const metadatas = new WeakMap, PersistMetadata>(); const promisesLocalSaves = new Set>(); @@ -1212,7 +1212,7 @@ export function syncObservable( // Wait for this node and all parent nodes up the hierarchy to be loaded const onAllPersistLoaded = () => { - let parentNode: NodeValue | undefined = node; + let parentNode: NodeInfo | undefined = node; while (parentNode) { if (parentNode.state?.isPersistLoaded?.get() === false) { return false; @@ -1238,6 +1238,6 @@ export function syncObservable( return syncState$; } -export function getAllSyncStates(): readonly [Observable, NodeValue][] { +export function getAllSyncStates(): readonly [Observable, NodeInfo][] { return Array.from(allSyncStates.entries()); } diff --git a/src/sync/syncTypes.ts b/src/sync/syncTypes.ts index e2ca01bd7..071ecf682 100644 --- a/src/sync/syncTypes.ts +++ b/src/sync/syncTypes.ts @@ -9,7 +9,7 @@ import type { ClassConstructor, GetMode, LinkedOptions, - NodeValue, + NodeInfo, Observable, ObservableParam, ObservableSyncState, @@ -34,7 +34,7 @@ export interface PersistOptions { } export interface SyncedGetSetSubscribeBaseParams { - node: NodeValue; + node: NodeInfo; value$: ObservableParam; refresh: () => void; } @@ -149,7 +149,7 @@ export interface ObservableSyncFunctions { } export interface SubscribeOptions { - node: NodeValue; + node: NodeInfo; update: UpdateFn; refresh: () => void; } diff --git a/src/trace/traceHelpers.ts b/src/trace/traceHelpers.ts index a10656c4e..1cc88b7c7 100644 --- a/src/trace/traceHelpers.ts +++ b/src/trace/traceHelpers.ts @@ -1,6 +1,6 @@ -import type { NodeValue } from '@legendapp/state'; +import type { NodeInfo } from '@legendapp/state'; -export function getNodePath(node: NodeValue) { +export function getNodePath(node: NodeInfo) { const arr: (string | number)[] = []; let n = node; while (n?.key !== undefined) { diff --git a/src/trace/useTraceListeners.ts b/src/trace/useTraceListeners.ts index 8974ca7e7..24f8b4e40 100644 --- a/src/trace/useTraceListeners.ts +++ b/src/trace/useTraceListeners.ts @@ -1,4 +1,4 @@ -import { NodeValue, internal, TrackingNode } from '@legendapp/state'; +import { NodeInfo, internal, TrackingNode } from '@legendapp/state'; import { getNodePath } from './traceHelpers'; const { optimized, tracking } = internal; @@ -8,7 +8,7 @@ export function useTraceListeners(this: any, name?: string) { } } -function traceNodes(name: string | undefined, nodes: Map) { +function traceNodes(name: string | undefined, nodes: Map) { if (process.env.NODE_ENV === 'development' && tracking.current) { tracking.current.traceListeners = undefined; const arr: string[] = []; diff --git a/src/trace/useVerifyNotTracking.ts b/src/trace/useVerifyNotTracking.ts index 460dc9deb..4364424b9 100644 --- a/src/trace/useVerifyNotTracking.ts +++ b/src/trace/useVerifyNotTracking.ts @@ -1,4 +1,4 @@ -import { internal, NodeValue, TrackingNode } from '@legendapp/state'; +import { internal, NodeInfo, TrackingNode } from '@legendapp/state'; import { getNodePath } from './traceHelpers'; const { optimized, tracking } = internal; @@ -8,7 +8,7 @@ export function useVerifyNotTracking(this: any, name?: string) { } } -function traceNodes(name: string | undefined, nodes: Map) { +function traceNodes(name: string | undefined, nodes: Map) { if (process.env.NODE_ENV === 'development') { tracking.current!.traceListeners = undefined; const arr: string[] = []; diff --git a/src/tracking.ts b/src/tracking.ts index f16141d84..0e484c8c6 100644 --- a/src/tracking.ts +++ b/src/tracking.ts @@ -1,4 +1,4 @@ -import type { NodeValue, TrackingState, TrackingType } from './observableInterfaces'; +import type { NodeInfo, TrackingState, TrackingType } from './observableInterfaces'; let trackCount = 0; const trackingQueue: (TrackingState | undefined)[] = []; @@ -23,7 +23,7 @@ export function endTracking() { tracking.current = trackingQueue.pop(); } -export function updateTracking(node: NodeValue, track?: TrackingType) { +export function updateTracking(node: NodeInfo, track?: TrackingType) { if (trackCount) { const tracker = tracking.current; if (tracker) { diff --git a/tests/tests.test.ts b/tests/tests.test.ts index b8f950373..73f1a7141 100644 --- a/tests/tests.test.ts +++ b/tests/tests.test.ts @@ -8,7 +8,7 @@ import { clone, getNodeValue, isEvent, isObservable, optimized, symbolGetNode } import { setAtPath } from '../src/helpers'; import { linked } from '../src/linked'; import { observable, observablePrimitive } from '../src/observable'; -import { NodeValue } from '../src/observableInterfaces'; +import { NodeInfo } from '../src/observableInterfaces'; import { observe } from '../src/observe'; import { syncState } from '../src/syncState'; import { when, whenReady } from '../src/when'; @@ -3223,7 +3223,7 @@ describe('Extend observableFunctions', () => { test('Extend observableFunctions works', () => { configureLegendState({ observableFunctions: { - testfn: (node: NodeValue, arg1, arg2) => getNodeValue(node) + arg2, + testfn: (node: NodeInfo, arg1, arg2) => getNodeValue(node) + arg2, }, });