cogsbox-state 0.5.293 → 0.5.295

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport {\r\n createElement,\r\n startTransition,\r\n useCallback,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type CSSProperties,\r\n type ReactNode,\r\n type RefObject,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\r\nimport useMeasure from \"react-use-measure\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type VirtualViewOptions = {\r\n itemHeight?: number;\r\n overscan?: number;\r\n stickToBottom?: boolean;\r\n};\r\n\r\n// The result now returns a real StateObject\r\nexport type VirtualStateObjectResult<T extends any[]> = {\r\n /**\r\n * A new, fully-functional StateObject that represents the virtualized slice.\r\n * You can use `.get()`, `.stateMap()`, `.insert()`, `.cut()` etc. on this object.\r\n */\r\n virtualState: StateObject<T>;\r\n /**\r\n * Props to be spread onto your DOM elements to enable virtualization.\r\n */\r\n virtualizerProps: {\r\n outer: { ref: RefObject<HTMLDivElement>; style: CSSProperties };\r\n inner: { style: CSSProperties };\r\n list: { style: CSSProperties };\r\n };\r\n scrollToBottom: (behavior?: ScrollBehavior) => void;\r\n scrollToIndex: (index: number, behavior?: ScrollBehavior) => void;\r\n};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n useVirtualView: (\r\n options: VirtualViewOptions\r\n ) => VirtualStateObjectResult<InferArrayElement<TShape>[]>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateList: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n applyJsonPatch: (patches: any[]) => void;\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {});\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n getDifferences: () => string[];\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: z.ZodTypeAny;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[];\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n }\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n getGlobalStore.getState().setCreatedState(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n\r\n if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n // Parse the json part back normally\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\r\n }\r\n};\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n getGlobalStore.getState().initializeShadowState(thisKey, initialState);\r\n // Update the global state\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(dependencies || []),\r\n ]);\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(componentKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n const store = getGlobalStore.getState();\r\n\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = store.signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = store.signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n\r\n console.log(\"shadowState\", store.shadowStateStore);\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const stateEntry = store.stateComponents.get(thisKey);\r\n console.log(\"stateEntry >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\", stateEntry);\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n console.log(\"component\", component);\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\r\n );\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n switch (updateObj.updateType) {\r\n case \"update\":\r\n // For updates, just mirror the structure at the path\r\n store.updateShadowAtPath(thisKey, path, payload);\r\n break;\r\n\r\n case \"insert\":\r\n // For array insert, add empty element to shadow array\r\n\r\n const parentPath = path.slice(0, -1);\r\n store.insertShadowArrayElement(thisKey, parentPath, newValue);\r\n break;\r\n\r\n case \"cut\":\r\n // For array cut, remove element from shadow array\r\n const arrayPath = path.slice(0, -1);\r\n const index = parseInt(path[path.length - 1]!);\r\n store.removeShadowArrayElement(thisKey, arrayPath, index);\r\n break;\r\n }\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = store.serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey, sessionId]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n getGlobalStore.getState().initializeShadowState(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n \"_componentId\",\r\n \"_stateKey\",\r\n \"getComponents\",\r\n ]);\r\n\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\" &&\r\n !mutationMethods.has(prop)\r\n ) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n // console.log(\"adding path\", fullComponentId, path, prop);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Mark as initialized immediately to prevent re-processing\r\n\r\n // Now do the path tracking logic ONCE\r\n if (!component.paths.has(\"\")) {\r\n const currentPath = path.join(\".\");\r\n let needsAdd = true;\r\n for (const existingPath of component.paths) {\r\n if (\r\n currentPath.startsWith(existingPath) &&\r\n (currentPath === existingPath ||\r\n currentPath[existingPath.length] === \".\")\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n }\r\n\r\n // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\r\n }\r\n };\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n\r\n if (prop === \"useVirtualView\") {\r\n return (\r\n options: VirtualViewOptions\r\n ): VirtualStateObjectResult<any[]> => {\r\n const {\r\n itemHeight = 50, // Default/estimated height\r\n overscan = 5,\r\n stickToBottom = false,\r\n } = options;\r\n\r\n const containerRef = useRef<HTMLDivElement | null>(null);\r\n const [range, setRange] = useState({\r\n startIndex: 0,\r\n endIndex: 10,\r\n });\r\n\r\n // --- State Tracking Refs for Stability ---\r\n const isAtBottomRef = useRef(stickToBottom);\r\n // Store the scroll position before a new item is added\r\n const scrollOffsetRef = useRef(0);\r\n // Ref to track if the list has grown, to trigger scroll correction\r\n const listGrewRef = useRef(false);\r\n\r\n const sourceArray = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n ) as any[];\r\n const totalCount = sourceArray.length;\r\n\r\n // Helper to get measured heights or the default\r\n const getItemHeight = useCallback(\r\n (index: number): number => {\r\n const metadata = getGlobalStore\r\n .getState()\r\n .getShadowMetadata(stateKey, [...path, index.toString()]);\r\n return metadata?.virtualizer?.itemHeight || itemHeight;\r\n },\r\n [itemHeight, stateKey, path]\r\n );\r\n\r\n // Pre-calculate total height and the top offset of each item\r\n const { totalHeight, positions } = useMemo(() => {\r\n let currentHeight = 0;\r\n const pos: number[] = [];\r\n for (let i = 0; i < totalCount; i++) {\r\n pos[i] = currentHeight;\r\n currentHeight += getItemHeight(i);\r\n }\r\n\r\n console.log(\"totalHeight\", totalHeight);\r\n return { totalHeight: currentHeight, positions: pos };\r\n }, [totalCount, getItemHeight]);\r\n\r\n // This is identical to your original code\r\n const virtualState = useMemo(() => {\r\n const start = Math.max(0, range.startIndex);\r\n const end = Math.min(totalCount, range.endIndex);\r\n const validIndices = Array.from(\r\n { length: end - start },\r\n (_, i) => start + i\r\n );\r\n const slicedArray = validIndices.map((idx) => sourceArray[idx]);\r\n return rebuildStateShape(slicedArray as any, path, {\r\n ...meta,\r\n validIndices,\r\n });\r\n }, [range.startIndex, range.endIndex, sourceArray, totalCount]);\r\n\r\n // --- STABLE SCROLL LOGIC ---\r\n // useLayoutEffect runs after DOM mutations but before the browser paints.\r\n // This is the perfect place to correct scroll positions.\r\n useLayoutEffect(() => {\r\n const container = containerRef.current;\r\n if (!container) return;\r\n\r\n // If the list grew, we need to adjust the scroll position\r\n // to prevent the content from jumping.\r\n if (listGrewRef.current) {\r\n listGrewRef.current = false; // Reset the flag\r\n\r\n if (isAtBottomRef.current) {\r\n // If we were at the bottom, stay at the bottom.\r\n // This is the fix for the auto-scroll issue.\r\n container.scrollTop = container.scrollHeight;\r\n } else {\r\n // If we were in the middle, restore the previous scroll position\r\n // plus the height of the content that was added above us.\r\n // This is an advanced case, but for now, let's keep it simple\r\n // as most use-cases are for chat-like views. For a simple list,\r\n // just staying at the bottom is the main goal.\r\n }\r\n }\r\n }, [totalHeight]); // This effect runs whenever the total height changes\r\n\r\n useEffect(() => {\r\n const container = containerRef.current;\r\n if (!container) return;\r\n\r\n // Track the previous total count to detect when new items are added\r\n let previousTotalCount = totalCount;\r\n\r\n const handleScroll = () => {\r\n if (!container) return;\r\n const { scrollTop, clientHeight, scrollHeight } = container;\r\n // Update \"is at bottom\" status on every scroll\r\n isAtBottomRef.current =\r\n scrollHeight - scrollTop - clientHeight < 10;\r\n scrollOffsetRef.current = scrollTop;\r\n\r\n // Find start/end indices based on positions\r\n let startIndex = 0;\r\n for (let i = 0; i < positions.length; i++) {\r\n if (positions[i]! >= scrollTop) {\r\n startIndex = i;\r\n break;\r\n }\r\n }\r\n\r\n let endIndex = startIndex;\r\n while (\r\n endIndex < totalCount &&\r\n positions[endIndex]! < scrollTop + clientHeight\r\n ) {\r\n endIndex++;\r\n }\r\n\r\n startIndex = Math.max(0, startIndex - overscan);\r\n endIndex = Math.min(totalCount, endIndex + overscan);\r\n\r\n setRange((prevRange) => {\r\n if (\r\n prevRange.startIndex !== startIndex ||\r\n prevRange.endIndex !== endIndex\r\n ) {\r\n return { startIndex, endIndex };\r\n }\r\n return prevRange;\r\n });\r\n };\r\n\r\n // Check if the list has grown *before* the next render cycle\r\n if (totalCount > previousTotalCount) {\r\n listGrewRef.current = true;\r\n }\r\n previousTotalCount = totalCount;\r\n\r\n container.addEventListener(\"scroll\", handleScroll, {\r\n passive: true,\r\n });\r\n handleScroll(); // Initial calculation\r\n\r\n return () =>\r\n container.removeEventListener(\"scroll\", handleScroll);\r\n }, [totalCount, overscan, positions]); // Depend on positions to re-run scroll logic\r\n\r\n const scrollToBottom = useCallback(\r\n (behavior: ScrollBehavior = \"smooth\") => {\r\n if (containerRef.current) {\r\n containerRef.current.scrollTo({\r\n top: containerRef.current.scrollHeight,\r\n behavior,\r\n });\r\n }\r\n },\r\n []\r\n );\r\n\r\n const scrollToIndex = useCallback(\r\n (index: number, behavior: ScrollBehavior = \"smooth\") => {\r\n if (containerRef.current && positions[index] !== undefined) {\r\n containerRef.current.scrollTo({\r\n top: positions[index],\r\n behavior,\r\n });\r\n }\r\n },\r\n [positions]\r\n );\r\n\r\n const virtualizerProps = {\r\n outer: {\r\n ref: containerRef,\r\n style: { overflowY: \"auto\", height: \"100%\" },\r\n },\r\n inner: {\r\n style: { height: `${totalHeight}px`, position: \"relative\" },\r\n },\r\n list: {\r\n style: {\r\n transform: `translateY(${positions[range.startIndex] || 0}px)`,\r\n },\r\n },\r\n };\r\n\r\n return {\r\n virtualState,\r\n virtualizerProps: virtualizerProps as any,\r\n scrollToBottom,\r\n scrollToIndex,\r\n };\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n info: {\r\n register: () => void;\r\n index: number;\r\n originalIndex: number;\r\n }\r\n ) => any\r\n ) => {\r\n const arrayToMap = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Defensive check to make sure we are mapping over an array\r\n if (!Array.isArray(arrayToMap)) {\r\n console.warn(\r\n `stateMap called on a non-array value at path: ${path.join(\".\")}. The current value is:`,\r\n arrayToMap\r\n );\r\n return null;\r\n }\r\n\r\n // If we have validIndices, only map those items\r\n const indicesToMap =\r\n meta?.validIndices ||\r\n Array.from({ length: arrayToMap.length }, (_, i) => i);\r\n\r\n return indicesToMap.map((originalIndex, localIndex) => {\r\n const item = arrayToMap[originalIndex];\r\n const finalPath = [...path, originalIndex.toString()];\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n\r\n // Create the register function right here. It closes over the necessary variables.\r\n const register = () => {\r\n const [, forceUpdate] = useState({});\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([finalPath.join(\".\")]),\r\n });\r\n\r\n getGlobalStore\r\n .getState()\r\n .stateComponents.set(stateKey, stateEntry);\r\n\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId]);\r\n };\r\n\r\n return callbackfn(item, setter, {\r\n register,\r\n index: localIndex,\r\n originalIndex,\r\n });\r\n });\r\n };\r\n }\r\n if (prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateList\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n if (!Array.isArray(arrayToMap)) {\r\n console.warn(\r\n `stateList called on a non-array value at path: ${path.join(\".\")}.`\r\n );\r\n return null;\r\n }\r\n\r\n const indicesToMap =\r\n meta?.validIndices ||\r\n Array.from({ length: arrayToMap.length }, (_, i) => i);\r\n\r\n return indicesToMap.map((originalIndex, localIndex) => {\r\n const item = arrayToMap[originalIndex];\r\n const finalPath = [...path, originalIndex.toString()];\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n return createElement(CogsItemWrapper, {\r\n key: originalIndex,\r\n stateKey,\r\n itemComponentId,\r\n itemPath: finalPath,\r\n children: callbackfn(\r\n item,\r\n setter,\r\n localIndex,\r\n arrayToMap as any,\r\n rebuildStateShape(arrayToMap as any, path, meta)\r\n ),\r\n });\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\r\n };\r\n }\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => {\r\n if (meta?.validIndices && Array.isArray(currentState)) {\r\n // For filtered arrays, return only the items at validIndices\r\n const fullArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return meta.validIndices.map((index) => fullArray[index]);\r\n }\r\n return getGlobalStore.getState().getNestedState(stateKey, path);\r\n };\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (prop === \"toggleSelected\") {\r\n return () => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\r\n );\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n\r\nfunction CogsItemWrapper({\r\n stateKey,\r\n itemComponentId,\r\n itemPath,\r\n children,\r\n}: {\r\n stateKey: string;\r\n itemComponentId: string;\r\n itemPath: string[];\r\n children: React.ReactNode;\r\n}) {\r\n const [, forceUpdate] = useState({});\r\n const [ref, bounds] = useMeasure();\r\n\r\n useEffect(() => {\r\n if (bounds.height > 0) {\r\n getGlobalStore.getState().setShadowMetadata(stateKey, itemPath, {\r\n virtualizer: {\r\n itemHeight: bounds.height,\r\n },\r\n });\r\n }\r\n }, [bounds.height]);\r\n\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([itemPath.join(\".\")]),\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(stateKey, stateEntry);\r\n\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId, itemPath.join(\".\")]);\r\n\r\n return <div ref={ref}>{children}</div>;\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","store","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","index","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","selectedIndex","itemHeight","overscan","stickToBottom","containerRef","range","setRange","isAtBottomRef","scrollOffsetRef","listGrewRef","sourceArray","totalCount","getItemHeight","useCallback","totalHeight","positions","currentHeight","pos","virtualState","start","end","validIndices","_","slicedArray","idx","container","previousTotalCount","handleScroll","scrollTop","clientHeight","scrollHeight","startIndex","endIndex","prevRange","scrollToBottom","behavior","scrollToIndex","virtualizerProps","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","arrayToMap","localIndex","finalPath","setter","itemComponentId","currentEntry","createElement","SignalMapRenderer","CogsItemWrapper","fieldName","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fullArray","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify","itemPath","ref","bounds","useMeasure"],"mappings":";;;;;;;;;;;;AA6eA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;AAEjE,EAAAI,EAAuBJ,GAAoB;AAAA,IACzC,GAAGK;AAAA,IACH,GAAGJ;AAAA,EAAA,CACJ;AACH;AAGA,SAASK,GAA0B;AAAA,EACjC,UAAAN;AAAA,EACA,SAAAO;AAAA,EACA,oBAAAC;AACF,GAIG;AACD,QAAMH,IAAiBH,GAAkBF,CAAkB,KAAK,CAAC,GAC3DS,IAA0BD,EAAmBR,CAAkB,KAAK,CAAC,GACrEI,IACJD,EAAe,SAAA,EAAW,wBACtBO,IAAgB,EAAE,GAAGD,GAAyB,GAAGJ,EAAe;AAEtE,MAAIM,IAAY;AAChB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,IAAI,CAAC4N,EAAS,KAAK,GAAG,CAAC,CAAC;AAAA,IAAA,CACpC,GAEDjT,EAAe,SAAS,EAAE,gBAAgB,IAAIH,GAAUoE,CAAU,GAE3D,MAAM;AACX,YAAM4K,IAAe7O,EAClB,SACA,EAAA,gBAAgB,IAAIH,CAAQ;AAC/B,MAAIgP,KACWA,EAAA,WAAW,OAAOxK,CAAe;AAAA,IAElD;AAAA,EAAA,GACC,CAACxE,GAAU+O,GAAiBqE,EAAS,KAAK,GAAG,CAAC,CAAC,GAE3C,gBAAAtB,GAAC,OAAI,EAAA,KAAAuB,GAAW,UAAAzB,EAAS,CAAA;AAClC;"}
1
+ {"version":3,"file":"CogsState.jsx","sources":["../src/CogsState.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport {\r\n createElement,\r\n startTransition,\r\n useCallback,\r\n useEffect,\r\n useLayoutEffect,\r\n useMemo,\r\n useRef,\r\n useState,\r\n useSyncExternalStore,\r\n type CSSProperties,\r\n type ReactNode,\r\n type RefObject,\r\n} from \"react\";\r\n\r\nimport {\r\n debounce,\r\n getDifferences,\r\n getNestedValue,\r\n isFunction,\r\n type GenericObject,\r\n} from \"./utility.js\";\r\nimport {\r\n cutFunc,\r\n FormControlComponent,\r\n pushFunc,\r\n updateFn,\r\n ValidationWrapper,\r\n} from \"./Functions.js\";\r\nimport { isDeepEqual, transformStateFunc } from \"./utility.js\";\r\nimport superjson from \"superjson\";\r\nimport { v4 as uuidv4 } from \"uuid\";\r\nimport { z } from \"zod\";\r\n\r\nimport { formRefStore, getGlobalStore, type ComponentsType } from \"./store.js\";\r\nimport { useCogsConfig } from \"./CogsStateClient.js\";\r\nimport { applyPatch } from \"fast-json-patch\";\r\nimport useMeasure from \"react-use-measure\";\r\n\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\nexport type VirtualViewOptions = {\r\n itemHeight?: number;\r\n overscan?: number;\r\n stickToBottom?: boolean;\r\n};\r\n\r\n// The result now returns a real StateObject\r\nexport type VirtualStateObjectResult<T extends any[]> = {\r\n /**\r\n * A new, fully-functional StateObject that represents the virtualized slice.\r\n * You can use `.get()`, `.stateMap()`, `.insert()`, `.cut()` etc. on this object.\r\n */\r\n virtualState: StateObject<T>;\r\n /**\r\n * Props to be spread onto your DOM elements to enable virtualization.\r\n */\r\n virtualizerProps: {\r\n outer: { ref: RefObject<HTMLDivElement>; style: CSSProperties };\r\n inner: { style: CSSProperties };\r\n list: { style: CSSProperties };\r\n };\r\n scrollToBottom: (behavior?: ScrollBehavior) => void;\r\n scrollToIndex: (index: number, behavior?: ScrollBehavior) => void;\r\n};\r\n\r\nexport type ServerSyncStatus = {\r\n isFresh: boolean;\r\n isFreshTime: number;\r\n isStale: boolean;\r\n isStaleTime: number;\r\n isSyncing: boolean;\r\n isSyncingTime: number;\r\n};\r\n\r\nexport type SyncInfo = {\r\n timeStamp: number;\r\n userId: number;\r\n};\r\n\r\nexport type FormElementParams<T> = {\r\n get: () => T;\r\n\r\n set: UpdateType<T>;\r\n syncStatus: (SyncInfo & { date: Date }) | null;\r\n path: string[];\r\n validationErrors: () => string[];\r\n addValidationError: (message?: string) => void;\r\n\r\n inputProps: {\r\n ref?: React.RefObject<any>;\r\n value?: T extends boolean ? never : T;\r\n onChange?: (\r\n event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>\r\n ) => void;\r\n onBlur?: () => void;\r\n };\r\n};\r\n\r\nexport type StateKeys = string;\r\n\r\ntype findWithFuncType<U> = (\r\n thisKey: keyof U,\r\n thisValue: U[keyof U]\r\n) => EndType<U> & StateObject<U>;\r\nexport type PushArgs<U, T> = (\r\n update:\r\n | Prettify<U>\r\n | ((prevState: NonNullable<Prettify<U>>[]) => NonNullable<Prettify<U>>),\r\n opts?: UpdateOpts<U>\r\n) => StateObject<T>;\r\n\r\ntype CutFunctionType<T> = (\r\n index?: number,\r\n options?: { waitForSync?: boolean }\r\n) => StateObject<T>;\r\n\r\nexport type InferArrayElement<T> = T extends (infer U)[] ? U : never;\r\ntype ArraySpecificPrototypeKeys =\r\n | \"concat\"\r\n | \"copyWithin\"\r\n | \"fill\"\r\n | \"find\"\r\n | \"findIndex\"\r\n | \"flat\"\r\n | \"flatMap\"\r\n | \"includes\"\r\n | \"indexOf\"\r\n | \"join\"\r\n | \"keys\"\r\n | \"lastIndexOf\"\r\n | \"map\"\r\n | \"pop\"\r\n | \"push\"\r\n | \"reduce\"\r\n | \"reduceRight\"\r\n | \"reverse\"\r\n | \"shift\"\r\n | \"slice\"\r\n | \"some\"\r\n | \"sort\"\r\n | \"splice\"\r\n | \"unshift\"\r\n | \"values\"\r\n | \"entries\"\r\n | \"every\"\r\n | \"filter\"\r\n | \"forEach\"\r\n | \"with\";\r\n\r\nexport type ArrayEndType<TShape extends unknown> = {\r\n findWith: findWithFuncType<InferArrayElement<TShape>>;\r\n index: (index: number) => StateObject<InferArrayElement<TShape>> & {\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n _index: number;\r\n } & EndType<InferArrayElement<TShape>>;\r\n insert: PushArgs<InferArrayElement<TShape>, TShape>;\r\n cut: CutFunctionType<TShape>;\r\n cutByValue: (value: string | number | boolean) => void;\r\n toggleByValue: (value: string | number | boolean) => void;\r\n stateSort: (\r\n compareFn: (\r\n a: InferArrayElement<TShape>,\r\n b: InferArrayElement<TShape>\r\n ) => number\r\n ) => ArrayEndType<TShape>;\r\n useVirtualView: (\r\n options: VirtualViewOptions\r\n ) => VirtualStateObjectResult<InferArrayElement<TShape>[]>;\r\n\r\n stateMapNoRender: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateList: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n $stateMap: (\r\n callbackfn: (\r\n value: InferArrayElement<TShape>,\r\n setter: StateObject<InferArrayElement<TShape>>,\r\n index: number,\r\n array: TShape,\r\n arraySetter: StateObject<TShape>\r\n ) => void\r\n ) => any;\r\n stateFlattenOn: <K extends keyof InferArrayElement<TShape>>(\r\n field: K\r\n ) => StateObject<InferArrayElement<InferArrayElement<TShape>[K]>[]>;\r\n uniqueInsert: (\r\n payload: UpdateArg<InferArrayElement<TShape>>,\r\n fields?: (keyof InferArrayElement<TShape>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => void;\r\n stateFind: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => boolean\r\n ) => StateObject<InferArrayElement<TShape>> | undefined;\r\n stateFilter: (\r\n callbackfn: (value: InferArrayElement<TShape>, index: number) => void\r\n ) => ArrayEndType<TShape>;\r\n getSelected: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n clearSelected: () => void;\r\n getSelectedIndex: () => number;\r\n last: () => StateObject<InferArrayElement<TShape>> | undefined;\r\n} & EndType<TShape>;\r\n\r\nexport type FormOptsType = {\r\n key?: string;\r\n validation?: {\r\n hideMessage?: boolean;\r\n message?: string;\r\n stretch?: boolean;\r\n props?: GenericObject;\r\n disable?: boolean;\r\n };\r\n formElements?: boolean;\r\n debounceTime?: number;\r\n stateServerDifferences?: string[][];\r\n};\r\n\r\nexport type FormControl<T> = (obj: FormElementParams<T>) => JSX.Element;\r\n\r\nexport type UpdateArg<S> = S | ((prevState: S) => S);\r\n\r\nexport type UpdateType<T> = (\r\n payload: UpdateArg<T>,\r\n opts?: UpdateOpts<T>\r\n) => void;\r\n\r\nexport type UpdateOpts<T> = {\r\n afterUpdate?: (state: T) => void;\r\n debounce?: number;\r\n};\r\nexport type ObjectEndType<T> = EndType<T> & {\r\n [K in keyof T]-?: ObjectEndType<T[K]>;\r\n} & {\r\n stateObject: (callbackfn: (value: T, setter: StateObject<T>) => void) => any;\r\n delete: () => void;\r\n};\r\ntype EffectFunction<T, R> = (state: T) => R;\r\nexport type EndType<T, IsArrayElement = false> = {\r\n applyJsonPatch: (patches: any[]) => void;\r\n update: UpdateType<T>;\r\n _path: string[];\r\n _stateKey: string;\r\n formElement: (control: FormControl<T>, opts?: FormOptsType) => JSX.Element;\r\n get: () => T;\r\n $get: () => T;\r\n $derive: <R>(fn: EffectFunction<T, R>) => R;\r\n _status: \"fresh\" | \"stale\" | \"synced\";\r\n getStatus: () => \"fresh\" | \"stale\";\r\n\r\n showValidationErrors: () => string[];\r\n setValidation: (ctx: string) => void;\r\n removeValidation: (ctx: string) => void;\r\n ignoreFields: (fields: string[]) => StateObject<T>;\r\n _selected: boolean;\r\n setSelected: (value: boolean) => void;\r\n toggleSelected: () => void;\r\n getFormRef: () => React.RefObject<any> | undefined;\r\n removeStorage: () => void;\r\n sync: () => void;\r\n validationWrapper: ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => JSX.Element;\r\n lastSynced?: SyncInfo;\r\n} & (IsArrayElement extends true ? { cut: () => void } : {});\r\n\r\nexport type StateObject<T> = (T extends any[]\r\n ? ArrayEndType<T>\r\n : T extends Record<string, unknown> | object\r\n ? { [K in keyof T]-?: StateObject<T[K]> } & ObjectEndType<T>\r\n : T extends string | number | boolean | null\r\n ? T\r\n : never) &\r\n EndType<T, true> & {\r\n getAllFormRefs: () => Map<string, React.RefObject<any>>;\r\n _componentId: string | null;\r\n getComponents: () => ComponentsType;\r\n validateZodSchema: () => void;\r\n _initialState: T;\r\n updateInitialState: (newState: T | null) => {\r\n fetchId: (field: keyof T) => string | number;\r\n };\r\n _isLoading: boolean;\r\n _serverState: T;\r\n revertToInitialState: (obj?: { validationKey?: string }) => T;\r\n getDifferences: () => string[];\r\n middleware: (\r\n middles: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void\r\n ) => void;\r\n _isServerSynced: () => boolean;\r\n getLocalStorage: (key: string) => LocalStorageData<T> | null;\r\n };\r\n\r\nexport type CogsUpdate<T extends unknown> = UpdateType<T>;\r\n\r\nexport type EffectiveSetState<TStateObject> = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"update\" | \"insert\" | \"cut\" },\r\n validationKey?: string,\r\n opts?: UpdateOpts<TStateObject>\r\n) => void;\r\n\r\nexport type UpdateTypeDetail = {\r\n timeStamp: number;\r\n stateKey: string;\r\n updateType: \"update\" | \"insert\" | \"cut\";\r\n path: string[];\r\n status: \"new\" | \"sent\" | \"synced\";\r\n oldValue: any;\r\n newValue: any;\r\n userId?: number;\r\n};\r\n\r\nexport type ActionsType<T> = {\r\n type: \"onChange\";\r\n action: ({ state, actionType }: { state: T; actionType: string }) => void;\r\n debounce?: number;\r\n}[];\r\n\r\ntype ArrayToObject<T extends string[]> = Record<T[number], string>;\r\ntype CookieType<T> = {\r\n timeStamp: number;\r\n value: T;\r\n cookieName: string;\r\n OnUnMountCookie?: Boolean;\r\n};\r\nexport type CogsCookiesType<T extends string[] = string[]> = CookieType<\r\n ArrayToObject<T>\r\n>;\r\nexport type ReactivityType = \"none\" | \"component\" | \"deps\" | \"all\";\r\n\r\ntype ValidationOptionsType = {\r\n key?: string;\r\n zodSchema?: z.ZodTypeAny;\r\n onBlur?: boolean;\r\n};\r\n\r\nexport type OptionsType<T extends unknown = unknown> = {\r\n log?: boolean;\r\n componentId?: string;\r\n serverSync?: ServerSyncType<T>;\r\n validation?: ValidationOptionsType;\r\n enableServerState?: boolean;\r\n serverState?: {\r\n id?: string | number;\r\n data?: T;\r\n status?: \"pending\" | \"error\" | \"success\";\r\n };\r\n sync?: {\r\n action: (state: T) => Promise<{\r\n success: boolean;\r\n data?: any;\r\n error?: any;\r\n errors?: Array<{\r\n path: (string | number)[];\r\n message: string;\r\n }>;\r\n }>;\r\n onSuccess?: (data: any) => void;\r\n onError?: (error: any) => void;\r\n };\r\n middleware?: ({\r\n updateLog,\r\n update,\r\n }: {\r\n updateLog: UpdateTypeDetail[] | undefined;\r\n update: UpdateTypeDetail;\r\n }) => void;\r\n\r\n modifyState?: (state: T) => T;\r\n localStorage?: {\r\n key: string | ((state: T) => string);\r\n onChange?: (state: T) => void;\r\n };\r\n formElements?: FormsElementsType;\r\n enabledSync?: (state: T) => boolean;\r\n reactiveDeps?: (state: T) => any[] | true;\r\n reactiveType?: ReactivityType[] | ReactivityType;\r\n syncUpdate?: Partial<UpdateTypeDetail>;\r\n\r\n initialState?: T;\r\n dependencies?: any[];\r\n};\r\nexport type ServerSyncType<T> = {\r\n testKey?: string;\r\n syncKey: (({ state }: { state: T }) => string) | string;\r\n syncFunction: ({ state }: { state: T }) => void;\r\n debounce?: number;\r\n\r\n snapshot?: {\r\n name: (({ state }: { state: T }) => string) | string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\nexport type SyncActionsType<T> = {\r\n syncKey: string;\r\n\r\n rollBackState?: T;\r\n actionTimeStamp: number;\r\n retryCount?: number;\r\n status:\r\n | \"success\"\r\n | \"waiting\"\r\n | \"rolledBack\"\r\n | \"error\"\r\n | \"cancelled\"\r\n | \"failed\";\r\n snapshot?: {\r\n name: string;\r\n stateKeys: StateKeys[];\r\n currentUrl: string;\r\n currentParams?: URLSearchParams;\r\n };\r\n};\r\n\r\nexport type ValidationWrapperOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n active: boolean;\r\n stretch?: boolean;\r\n path: string[];\r\n message?: string;\r\n data?: T;\r\n key?: string;\r\n};\r\nexport type SyncRenderOptions<T extends unknown = unknown> = {\r\n children: React.ReactNode;\r\n time: number;\r\n data?: T;\r\n key?: string;\r\n};\r\n\r\ntype FormsElementsType<T extends unknown = unknown> = {\r\n validation?: (options: ValidationWrapperOptions<T>) => React.ReactNode;\r\n syncRender?: (options: SyncRenderOptions<T>) => React.ReactNode;\r\n};\r\n\r\nexport type InitialStateInnerType<T extends unknown = unknown> = {\r\n initialState: T;\r\n} & OptionsType<T>;\r\n\r\nexport type InitialStateType<T> = {\r\n [key: string]: InitialStateInnerType<T>;\r\n};\r\n\r\nexport type AllStateTypes<T extends unknown> = Record<string, T>;\r\n\r\nexport type CogsInitialState<T> = {\r\n initialState: T;\r\n formElements?: FormsElementsType<T>;\r\n};\r\n\r\nexport type TransformedStateType<T> = {\r\n [P in keyof T]: T[P] extends CogsInitialState<infer U> ? U : T[P];\r\n};\r\n\r\nfunction setAndMergeOptions(stateKey: string, newOptions: OptionsType<any>) {\r\n const getInitialOptions = getGlobalStore.getState().getInitialOptions;\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n\r\n setInitialStateOptions(stateKey as string, {\r\n ...initialOptions,\r\n ...newOptions,\r\n });\r\n}\r\n\r\n// Fix for the setOptions function\r\nfunction setOptions<StateKey, Opt>({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n}: {\r\n stateKey: StateKey;\r\n options?: OptionsType<any>;\r\n initialOptionsPart: Record<string, any>;\r\n}) {\r\n const initialOptions = getInitialOptions(stateKey as string) || {};\r\n const initialOptionsPartState = initialOptionsPart[stateKey as string] || {};\r\n const setInitialStateOptions =\r\n getGlobalStore.getState().setInitialStateOptions;\r\n const mergedOptions = { ...initialOptionsPartState, ...initialOptions };\r\n\r\n let needToAdd = false;\r\n if (options) {\r\n for (const key in options) {\r\n if (!mergedOptions.hasOwnProperty(key)) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key as keyof typeof options];\r\n } else {\r\n if (\r\n key == \"localStorage\" &&\r\n options[key] &&\r\n mergedOptions[key].key !== options[key]?.key\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n if (\r\n key == \"initialState\" &&\r\n options[key] &&\r\n mergedOptions[key] !== options[key] && // Different references\r\n !isDeepEqual(mergedOptions[key], options[key]) // And different values\r\n ) {\r\n needToAdd = true;\r\n mergedOptions[key] = options[key];\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (needToAdd) {\r\n setInitialStateOptions(stateKey as string, mergedOptions);\r\n }\r\n}\r\nexport function addStateOptions<T extends unknown>(\r\n initialState: T,\r\n { formElements, validation }: OptionsType<T>\r\n) {\r\n return { initialState: initialState, formElements, validation } as T;\r\n}\r\n\r\nexport const createCogsState = <State extends Record<string, unknown>>(\r\n initialState: State,\r\n opt?: { formElements?: FormsElementsType; validation?: ValidationOptionsType }\r\n) => {\r\n let newInitialState = initialState;\r\n\r\n // Extract state parts and options using transformStateFunc\r\n const [statePart, initialOptionsPart] =\r\n transformStateFunc<State>(newInitialState);\r\n\r\n // Apply global formElements as defaults to each state key's options\r\n if (\r\n Object.keys(initialOptionsPart).length > 0 ||\r\n (opt && Object.keys(opt).length > 0)\r\n ) {\r\n Object.keys(initialOptionsPart).forEach((key) => {\r\n // Get the existing options for this state key\r\n initialOptionsPart[key] = initialOptionsPart[key] || {};\r\n\r\n initialOptionsPart[key].formElements = {\r\n ...opt?.formElements, // Global defaults first\r\n ...opt?.validation,\r\n ...(initialOptionsPart[key].formElements || {}), // State-specific overrides\r\n };\r\n const existingOptions = getInitialOptions(key);\r\n\r\n if (!existingOptions) {\r\n getGlobalStore\r\n .getState()\r\n .setInitialStateOptions(key, initialOptionsPart[key]);\r\n }\r\n });\r\n }\r\n\r\n getGlobalStore.getState().setInitialStates(statePart);\r\n getGlobalStore.getState().setCreatedState(statePart);\r\n type StateKeys = keyof typeof statePart;\r\n\r\n const useCogsState = <StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options?: OptionsType<(typeof statePart)[StateKey]>\r\n ) => {\r\n const [componentId] = useState(options?.componentId ?? uuidv4());\r\n\r\n setOptions({\r\n stateKey,\r\n options,\r\n initialOptionsPart,\r\n });\r\n\r\n const thiState =\r\n getGlobalStore.getState().cogsStateStore[stateKey as string] ||\r\n statePart[stateKey as string];\r\n const partialState = options?.modifyState\r\n ? options.modifyState(thiState)\r\n : thiState;\r\n\r\n const [state, updater] = useCogsStateFn<(typeof statePart)[StateKey]>(\r\n partialState,\r\n {\r\n stateKey: stateKey as string,\r\n syncUpdate: options?.syncUpdate,\r\n componentId,\r\n localStorage: options?.localStorage,\r\n middleware: options?.middleware,\r\n enabledSync: options?.enabledSync,\r\n reactiveType: options?.reactiveType,\r\n reactiveDeps: options?.reactiveDeps,\r\n initialState: options?.initialState as any,\r\n dependencies: options?.dependencies,\r\n serverState: options?.serverState,\r\n }\r\n );\r\n\r\n return updater;\r\n };\r\n\r\n function setCogsOptions<StateKey extends StateKeys>(\r\n stateKey: StateKey,\r\n options: OptionsType<(typeof statePart)[StateKey]>\r\n ) {\r\n setOptions({ stateKey, options, initialOptionsPart });\r\n\r\n if (options.localStorage) {\r\n loadAndApplyLocalStorage(stateKey as string, options);\r\n }\r\n\r\n notifyComponents(stateKey as string);\r\n }\r\n\r\n return { useCogsState, setCogsOptions };\r\n};\r\n\r\nconst {\r\n setUpdaterState,\r\n setState,\r\n getInitialOptions,\r\n getKeyState,\r\n getValidationErrors,\r\n setStateLog,\r\n updateInitialStateGlobal,\r\n addValidationError,\r\n removeValidationError,\r\n setServerSyncActions,\r\n} = getGlobalStore.getState();\r\nconst saveToLocalStorage = <T,>(\r\n state: T,\r\n thisKey: string,\r\n currentInitialOptions: any,\r\n sessionId?: string,\r\n lastSyncedWithServer?: number\r\n) => {\r\n if (currentInitialOptions?.log) {\r\n console.log(\r\n \"saving to localstorage\",\r\n thisKey,\r\n currentInitialOptions.localStorage?.key,\r\n sessionId\r\n );\r\n }\r\n\r\n const key = isFunction(currentInitialOptions?.localStorage?.key)\r\n ? currentInitialOptions.localStorage?.key(state)\r\n : currentInitialOptions?.localStorage?.key;\r\n\r\n if (key && sessionId) {\r\n const storageKey = `${sessionId}-${thisKey}-${key}`;\r\n\r\n // Get existing data to preserve lastSyncedWithServer if not explicitly updating it\r\n let existingLastSynced: number | undefined;\r\n try {\r\n const existing = loadFromLocalStorage(storageKey);\r\n existingLastSynced = existing?.lastSyncedWithServer;\r\n } catch {\r\n // Ignore errors, will use undefined\r\n }\r\n\r\n const data: LocalStorageData<T> = {\r\n state,\r\n lastUpdated: Date.now(),\r\n lastSyncedWithServer: lastSyncedWithServer ?? existingLastSynced,\r\n };\r\n\r\n // Use SuperJSON serialize to get the json part only\r\n const superJsonResult = superjson.serialize(data);\r\n window.localStorage.setItem(\r\n storageKey,\r\n JSON.stringify(superJsonResult.json)\r\n );\r\n }\r\n};\r\n\r\nconst loadFromLocalStorage = (localStorageKey: string) => {\r\n if (!localStorageKey) return null;\r\n\r\n try {\r\n const storedData = window.localStorage.getItem(localStorageKey);\r\n if (!storedData) return null;\r\n\r\n // Parse the json part back normally\r\n const parsedData = JSON.parse(storedData);\r\n\r\n return parsedData;\r\n } catch (error) {\r\n console.error(\"Error loading from localStorage:\", error);\r\n return null;\r\n }\r\n};\r\nconst loadAndApplyLocalStorage = (stateKey: string, options: any) => {\r\n const currentState = getGlobalStore.getState().cogsStateStore[stateKey];\r\n const { sessionId } = useCogsConfig();\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options.localStorage.key(currentState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n const localData = loadFromLocalStorage(\r\n `${sessionId}-${stateKey}-${localkey}`\r\n );\r\n\r\n if (\r\n localData &&\r\n localData.lastUpdated > (localData.lastSyncedWithServer || 0)\r\n ) {\r\n setState(stateKey, localData.state);\r\n\r\n notifyComponents(stateKey);\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\ntype LocalStorageData<T> = {\r\n state: T;\r\n lastUpdated: number;\r\n lastSyncedWithServer?: number;\r\n baseServerState?: T; // Add this to track what server state our changes are based on\r\n};\r\n\r\nconst updateGlobalState = (\r\n thisKey: string,\r\n initialState: any,\r\n newState: any,\r\n effectiveSetState: EffectiveSetState<any>,\r\n componentId: string,\r\n sessionId?: string\r\n) => {\r\n // Update all global state at once\r\n const updates = {\r\n initialState: initialState,\r\n updaterState: createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n ),\r\n state: newState,\r\n };\r\n\r\n updateInitialStateGlobal(thisKey, updates.initialState);\r\n setUpdaterState(thisKey, updates.updaterState);\r\n setState(thisKey, updates.state);\r\n};\r\n\r\nconst notifyComponents = (thisKey: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(thisKey);\r\n if (!stateEntry) return;\r\n\r\n // Batch component updates\r\n const updates = new Set<() => void>();\r\n stateEntry.components.forEach((component) => {\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n if (!reactiveTypes?.includes(\"none\")) {\r\n updates.add(() => component.forceUpdate());\r\n }\r\n });\r\n\r\n // Schedule updates in the next tick to allow batching\r\n queueMicrotask(() => {\r\n updates.forEach((update) => update());\r\n });\r\n};\r\n\r\nexport const notifyComponent = (stateKey: string, componentId: string) => {\r\n const stateEntry = getGlobalStore.getState().stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n const component = stateEntry.components.get(fullComponentId);\r\n const reactiveTypes = component\r\n ? Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"]\r\n : null;\r\n\r\n // Skip if reactivity is disabled\r\n if (reactiveTypes?.includes(\"none\")) {\r\n return;\r\n }\r\n\r\n if (component) {\r\n // Force an update to ensure the current value is saved\r\n\r\n component.forceUpdate();\r\n }\r\n }\r\n};\r\nconst getUpdateValues = (\r\n updateType: string,\r\n prevValue: any,\r\n payload: any,\r\n path: string[]\r\n) => {\r\n switch (updateType) {\r\n case \"update\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"insert\":\r\n return {\r\n oldValue: null, // or undefined\r\n newValue: getNestedValue(payload, path),\r\n };\r\n case \"cut\":\r\n return {\r\n oldValue: getNestedValue(prevValue, path),\r\n newValue: null, // or undefined\r\n };\r\n default:\r\n return { oldValue: null, newValue: null };\r\n }\r\n};\r\nexport function useCogsStateFn<TStateObject extends unknown>(\r\n stateObject: TStateObject,\r\n {\r\n stateKey,\r\n serverSync,\r\n localStorage,\r\n formElements,\r\n reactiveDeps,\r\n reactiveType,\r\n componentId,\r\n initialState,\r\n syncUpdate,\r\n dependencies,\r\n serverState,\r\n }: {\r\n stateKey?: string;\r\n componentId?: string;\r\n initialState?: TStateObject;\r\n } & OptionsType<TStateObject> = {}\r\n) {\r\n const [reactiveForce, forceUpdate] = useState({}); //this is the key to reactivity\r\n const { sessionId } = useCogsConfig();\r\n\r\n let noStateKey = stateKey ? false : true;\r\n const [thisKey] = useState(stateKey ?? uuidv4());\r\n const stateLog = getGlobalStore.getState().stateLog[thisKey];\r\n const componentUpdatesRef = useRef(new Set<string>());\r\n const componentIdRef = useRef(componentId ?? uuidv4());\r\n const latestInitialOptionsRef = useRef<OptionsType<TStateObject> | null>(\r\n null\r\n );\r\n latestInitialOptionsRef.current = (getInitialOptions(thisKey as string) ??\r\n null) as OptionsType<TStateObject> | null;\r\n\r\n useEffect(() => {\r\n if (syncUpdate && syncUpdate.stateKey === thisKey && syncUpdate.path?.[0]) {\r\n // Update the actual state value\r\n setState(thisKey, (prevState: any) => ({\r\n ...prevState,\r\n [syncUpdate.path![0]!]: syncUpdate.newValue,\r\n }));\r\n\r\n // Create combined key and update sync info\r\n const syncKey = `${syncUpdate.stateKey}:${syncUpdate.path.join(\".\")}`;\r\n getGlobalStore.getState().setSyncInfo(syncKey, {\r\n timeStamp: syncUpdate.timeStamp!,\r\n userId: syncUpdate.userId!,\r\n });\r\n }\r\n }, [syncUpdate]);\r\n useEffect(() => {\r\n // Only proceed if initialState is provided\r\n if (initialState) {\r\n setAndMergeOptions(thisKey as string, {\r\n initialState,\r\n });\r\n\r\n const options = latestInitialOptionsRef.current;\r\n const hasServerId = options?.serverState?.id !== undefined;\r\n const hasServerData =\r\n hasServerId &&\r\n options?.serverState?.status === \"success\" &&\r\n options?.serverState?.data;\r\n\r\n const currentGloballyStoredInitialState =\r\n getGlobalStore.getState().initialStateGlobal[thisKey];\r\n\r\n const initialStateChanged =\r\n (currentGloballyStoredInitialState &&\r\n !isDeepEqual(currentGloballyStoredInitialState, initialState)) ||\r\n !currentGloballyStoredInitialState;\r\n\r\n if (!initialStateChanged && !hasServerData) {\r\n return;\r\n }\r\n\r\n let localData = null;\r\n const localkey = isFunction(options?.localStorage?.key)\r\n ? options?.localStorage?.key(initialState)\r\n : options?.localStorage?.key;\r\n\r\n if (localkey && sessionId) {\r\n localData = loadFromLocalStorage(`${sessionId}-${thisKey}-${localkey}`);\r\n }\r\n\r\n let newState = initialState;\r\n let isFromServer = false;\r\n\r\n const serverTimestamp = hasServerData ? Date.now() : 0;\r\n const localTimestamp = localData?.lastUpdated || 0;\r\n const lastSyncTimestamp = localData?.lastSyncedWithServer || 0;\r\n\r\n if (hasServerData && serverTimestamp > localTimestamp) {\r\n newState = options.serverState!.data!;\r\n isFromServer = true;\r\n } else if (localData && localTimestamp > lastSyncTimestamp) {\r\n newState = localData.state;\r\n if (options?.localStorage?.onChange) {\r\n options?.localStorage?.onChange(newState);\r\n }\r\n }\r\n getGlobalStore.getState().initializeShadowState(thisKey, initialState);\r\n // Update the global state\r\n updateGlobalState(\r\n thisKey,\r\n initialState,\r\n newState,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n\r\n // Save to localStorage if we used server data\r\n if (isFromServer && localkey && sessionId) {\r\n saveToLocalStorage(newState, thisKey, options, sessionId, Date.now());\r\n }\r\n\r\n // Notify components of the change\r\n notifyComponents(thisKey);\r\n\r\n const reactiveTypes = Array.isArray(reactiveType)\r\n ? reactiveType\r\n : [reactiveType || \"component\"];\r\n\r\n if (!reactiveTypes.includes(\"none\")) {\r\n forceUpdate({});\r\n }\r\n }\r\n }, [\r\n initialState,\r\n serverState?.status,\r\n serverState?.data,\r\n ...(dependencies || []),\r\n ]);\r\n useLayoutEffect(() => {\r\n if (noStateKey) {\r\n setAndMergeOptions(thisKey as string, {\r\n serverSync,\r\n formElements,\r\n initialState,\r\n localStorage,\r\n middleware: latestInitialOptionsRef.current?.middleware,\r\n });\r\n }\r\n\r\n const componentKey = `${thisKey}////${componentIdRef.current}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(thisKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(componentKey, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set(),\r\n deps: [],\r\n depsFunction: reactiveDeps || undefined,\r\n reactiveType: reactiveType ?? [\"component\", \"deps\"],\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(thisKey, stateEntry);\r\n //need to force update to create the stateUpdates references\r\n forceUpdate({});\r\n return () => {\r\n if (stateEntry) {\r\n stateEntry.components.delete(componentKey);\r\n if (stateEntry.components.size === 0) {\r\n getGlobalStore.getState().stateComponents.delete(thisKey);\r\n }\r\n }\r\n };\r\n }, []);\r\n\r\n const effectiveSetState = (\r\n newStateOrFunction: UpdateArg<TStateObject>,\r\n path: string[],\r\n updateObj: { updateType: \"insert\" | \"cut\" | \"update\" },\r\n validationKey?: string\r\n ) => {\r\n if (Array.isArray(path)) {\r\n const pathKey = `${thisKey}-${path.join(\".\")}`;\r\n componentUpdatesRef.current.add(pathKey);\r\n }\r\n const store = getGlobalStore.getState();\r\n\r\n setState(thisKey, (prevValue: TStateObject) => {\r\n const payload = isFunction<TStateObject>(newStateOrFunction)\r\n ? newStateOrFunction(prevValue as TStateObject)\r\n : newStateOrFunction;\r\n\r\n const signalId = `${thisKey}-${path.join(\".\")}`;\r\n if (signalId) {\r\n let isArrayOperation = false;\r\n let elements = store.signalDomElements.get(signalId);\r\n\r\n if (\r\n (!elements || elements.size === 0) &&\r\n (updateObj.updateType === \"insert\" || updateObj.updateType === \"cut\")\r\n ) {\r\n // Remove last segment (index) from path\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n // If it's an array, use that path for signal\r\n if (Array.isArray(arrayValue)) {\r\n isArrayOperation = true;\r\n const arraySignalId = `${thisKey}-${arrayPath.join(\".\")}`;\r\n elements = store.signalDomElements.get(arraySignalId);\r\n }\r\n }\r\n\r\n if (elements) {\r\n const newValue = isArrayOperation\r\n ? getNestedValue(payload, path.slice(0, -1))\r\n : getNestedValue(payload, path);\r\n elements.forEach(({ parentId, position, effect }) => {\r\n const parent = document.querySelector(\r\n `[data-parent-id=\"${parentId}\"]`\r\n );\r\n if (parent) {\r\n const childNodes = Array.from(parent.childNodes);\r\n if (childNodes[position]) {\r\n const displayValue = effect\r\n ? new Function(\"state\", `return (${effect})(state)`)(newValue)\r\n : newValue;\r\n childNodes[position].textContent = String(displayValue);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n\r\n console.log(\"shadowState\", store.shadowStateStore);\r\n if (\r\n updateObj.updateType === \"update\" &&\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) &&\r\n path\r\n ) {\r\n removeValidationError(\r\n (validationKey || latestInitialOptionsRef.current?.validation?.key) +\r\n \".\" +\r\n path.join(\".\")\r\n );\r\n }\r\n const arrayWithoutIndex = path.slice(0, path.length - 1);\r\n if (\r\n updateObj.updateType === \"cut\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n removeValidationError(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n }\r\n if (\r\n updateObj.updateType === \"insert\" &&\r\n latestInitialOptionsRef.current?.validation?.key\r\n ) {\r\n let getValidation = getValidationErrors(\r\n latestInitialOptionsRef.current?.validation?.key +\r\n \".\" +\r\n arrayWithoutIndex.join(\".\")\r\n );\r\n\r\n //TODO this is untested its supposed to cahnge teh validation errors alreaady stored when a new entry is push\r\n\r\n getValidation.filter(([k, v]) => {\r\n let length = k?.split(\".\").length;\r\n\r\n if (\r\n k == arrayWithoutIndex.join(\".\") &&\r\n length == arrayWithoutIndex.length - 1\r\n ) {\r\n // console.log(length, pathWithoutIndex.length);\r\n let newKey = k + \".\" + arrayWithoutIndex;\r\n removeValidationError(k!);\r\n addValidationError(newKey, v!);\r\n }\r\n });\r\n }\r\n\r\n const stateEntry = store.stateComponents.get(thisKey);\r\n console.log(\"stateEntry >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\", stateEntry);\r\n if (stateEntry) {\r\n const changedPaths = getDifferences(prevValue, payload);\r\n const changedPathsSet = new Set(changedPaths);\r\n const primaryPathToCheck =\r\n updateObj.updateType === \"update\"\r\n ? path.join(\".\")\r\n : path.slice(0, -1).join(\".\") || \"\";\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n console.log(\"component\", component);\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n if (\r\n component.paths.has(primaryPathToCheck) ||\r\n component.paths.has(\"\")\r\n ) {\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n let currentPathToCheck = changedPath;\r\n while (true) {\r\n if (component.paths.has(currentPathToCheck)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n const lastDotIndex = currentPathToCheck.lastIndexOf(\".\");\r\n if (lastDotIndex !== -1) {\r\n const parentPath = currentPathToCheck.substring(\r\n 0,\r\n lastDotIndex\r\n );\r\n if (\r\n !isNaN(\r\n Number(currentPathToCheck.substring(lastDotIndex + 1))\r\n )\r\n ) {\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n currentPathToCheck = parentPath;\r\n } else {\r\n currentPathToCheck = \"\";\r\n }\r\n if (currentPathToCheck === \"\") {\r\n break;\r\n }\r\n }\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(payload);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n const timeStamp = Date.now();\r\n\r\n path = path.map((p, i) => {\r\n const arrayPath = path.slice(0, -1);\r\n const arrayValue = getNestedValue(payload, arrayPath);\r\n\r\n return i === path.length - 1 &&\r\n [\"insert\", \"cut\"].includes(updateObj.updateType)\r\n ? (arrayValue.length - 1).toString()\r\n : p;\r\n });\r\n\r\n const { oldValue, newValue } = getUpdateValues(\r\n updateObj.updateType,\r\n prevValue,\r\n payload,\r\n path\r\n );\r\n const newUpdate = {\r\n timeStamp,\r\n stateKey: thisKey,\r\n path,\r\n updateType: updateObj.updateType,\r\n status: \"new\" as const,\r\n oldValue,\r\n newValue,\r\n } satisfies UpdateTypeDetail;\r\n\r\n switch (updateObj.updateType) {\r\n case \"update\":\r\n // For updates, just mirror the structure at the path\r\n store.updateShadowAtPath(thisKey, path, payload);\r\n break;\r\n\r\n case \"insert\":\r\n // For array insert, add empty element to shadow array\r\n\r\n const parentPath = path.slice(0, -1);\r\n store.insertShadowArrayElement(thisKey, parentPath, newValue);\r\n break;\r\n\r\n case \"cut\":\r\n // For array cut, remove element from shadow array\r\n const arrayPath = path.slice(0, -1);\r\n const index = parseInt(path[path.length - 1]!);\r\n store.removeShadowArrayElement(thisKey, arrayPath, index);\r\n break;\r\n }\r\n\r\n setStateLog(thisKey, (prevLogs) => {\r\n const logs = [...(prevLogs ?? []), newUpdate];\r\n\r\n // Aggregate the updates by stateKey and path\r\n const aggregatedLogs = logs.reduce((acc, log) => {\r\n const uniqueKey = `${log.stateKey}:${JSON.stringify(log.path)}`;\r\n const existing = acc.get(uniqueKey);\r\n\r\n if (existing) {\r\n // Update the existing entry with the most recent details\r\n existing.timeStamp = Math.max(existing.timeStamp, log.timeStamp);\r\n existing.newValue = log.newValue; // Overwrite with the latest value\r\n existing.oldValue = existing.oldValue ?? log.oldValue; // Retain the initial oldValue\r\n existing.updateType = log.updateType; // Update to the most recent type\r\n } else {\r\n // Add the log if no existing match is found\r\n acc.set(uniqueKey, { ...(log as any) });\r\n }\r\n\r\n return acc;\r\n }, new Map<string, typeof newUpdate>());\r\n\r\n // Convert the aggregated map back to an array\r\n return Array.from(aggregatedLogs.values());\r\n });\r\n\r\n saveToLocalStorage(\r\n payload,\r\n thisKey,\r\n latestInitialOptionsRef.current,\r\n sessionId\r\n );\r\n\r\n if (latestInitialOptionsRef.current?.middleware) {\r\n latestInitialOptionsRef.current!.middleware({\r\n updateLog: stateLog,\r\n update: newUpdate,\r\n });\r\n }\r\n if (latestInitialOptionsRef.current?.serverSync) {\r\n const serverStateStore = store.serverState[thisKey];\r\n const serverSync = latestInitialOptionsRef.current?.serverSync;\r\n setServerSyncActions(thisKey, {\r\n syncKey:\r\n typeof serverSync.syncKey == \"string\"\r\n ? serverSync.syncKey\r\n : serverSync.syncKey({ state: payload }),\r\n rollBackState: serverStateStore,\r\n actionTimeStamp: Date.now() + (serverSync.debounce ?? 3000),\r\n status: \"waiting\",\r\n });\r\n }\r\n\r\n return payload;\r\n });\r\n };\r\n if (!getGlobalStore.getState().updaterState[thisKey]) {\r\n setUpdaterState(\r\n thisKey,\r\n createProxyHandler(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n )\r\n );\r\n if (!getGlobalStore.getState().cogsStateStore[thisKey]) {\r\n setState(thisKey, stateObject);\r\n }\r\n if (!getGlobalStore.getState().initialStateGlobal[thisKey]) {\r\n updateInitialStateGlobal(thisKey, stateObject);\r\n }\r\n }\r\n\r\n const updaterFinal = useMemo(() => {\r\n // Create proxy with baseObject as target\r\n return createProxyHandler<TStateObject>(\r\n thisKey,\r\n effectiveSetState,\r\n componentIdRef.current,\r\n sessionId\r\n );\r\n }, [thisKey, sessionId]);\r\n\r\n return [getKeyState(thisKey), updaterFinal] as [\r\n TStateObject,\r\n StateObject<TStateObject>,\r\n ];\r\n}\r\n\r\nfunction createProxyHandler<T>(\r\n stateKey: string,\r\n effectiveSetState: EffectiveSetState<T>,\r\n componentId: string,\r\n sessionId?: string\r\n): StateObject<T> {\r\n // ADDED: Enhanced cache with versioning\r\n type CacheEntry = {\r\n proxy: any;\r\n stateVersion: number;\r\n };\r\n const shapeCache = new Map<string, CacheEntry>();\r\n let stateVersion = 0;\r\n\r\n // ADDED: Cache invalidation helper\r\n const invalidateCachePath = (path: string[]) => {\r\n const pathKey = path.join(\".\");\r\n for (const [key] of shapeCache) {\r\n if (key === pathKey || key.startsWith(pathKey + \".\")) {\r\n shapeCache.delete(key);\r\n }\r\n }\r\n stateVersion++;\r\n };\r\n\r\n const baseObj = {\r\n removeValidation: (obj?: { validationKey?: string }) => {\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n },\r\n\r\n revertToInitialState: (obj?: { validationKey?: string }) => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n if (init?.key) {\r\n removeValidationError(init?.key);\r\n }\r\n\r\n if (obj?.validationKey) {\r\n removeValidationError(obj.validationKey);\r\n }\r\n\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n\r\n getGlobalStore.getState().clearSelectedIndexesForState(stateKey);\r\n // ADDED: Clear cache on revert\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newProxy = rebuildStateShape(initialState, []);\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n\r\n setUpdaterState(stateKey, newProxy);\r\n setState(stateKey, initialState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n\r\n return initialState;\r\n },\r\n updateInitialState: (newState: T) => {\r\n // ADDED: Clear cache on initial state update\r\n shapeCache.clear();\r\n stateVersion++;\r\n\r\n const newUpdaterState = createProxyHandler(\r\n stateKey,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (localStorage.getItem(storageKey)) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n startTransition(() => {\r\n updateInitialStateGlobal(stateKey, newState);\r\n getGlobalStore.getState().initializeShadowState(stateKey, newState);\r\n setUpdaterState(stateKey, newUpdaterState);\r\n setState(stateKey, newState);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n });\r\n\r\n return {\r\n fetchId: (field: keyof T) => newUpdaterState.get()[field],\r\n };\r\n },\r\n _initialState: getGlobalStore.getState().initialStateGlobal[stateKey],\r\n _serverState: getGlobalStore.getState().serverState[stateKey],\r\n _isLoading: getGlobalStore.getState().isLoadingGlobal[stateKey],\r\n _isServerSynced: () => {\r\n const serverState = getGlobalStore.getState().serverState[stateKey];\r\n return Boolean(\r\n serverState && isDeepEqual(serverState, getKeyState(stateKey))\r\n );\r\n },\r\n };\r\n\r\n function rebuildStateShape(\r\n currentState: T,\r\n path: string[] = [],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ): any {\r\n const cacheKey = path.map(String).join(\".\");\r\n\r\n // MODIFIED: Cache check with version\r\n const cachedEntry = shapeCache.get(cacheKey);\r\n\r\n type CallableStateObject<T> = {\r\n (): T;\r\n } & {\r\n [key: string]: any;\r\n };\r\n\r\n const baseFunction = function () {\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n } as unknown as CallableStateObject<T>;\r\n\r\n // Copy properties from baseObj to the function with type assertion\r\n Object.keys(baseObj).forEach((key) => {\r\n (baseFunction as any)[key] = (baseObj as any)[key];\r\n });\r\n\r\n const handler = {\r\n apply(target: any, thisArg: any, args: any[]) {\r\n console.log(\r\n `PROXY APPLY TRAP HIT: stateKey=${stateKey}, path=${path.join(\".\")}`\r\n ); // <--- ADD LOGGING\r\n console.trace(\"Apply trap stack trace\");\r\n return getGlobalStore().getNestedState(stateKey, path);\r\n },\r\n\r\n get(target: any, prop: string) {\r\n if (meta?.validIndices && !Array.isArray(currentState)) {\r\n meta = { ...meta, validIndices: undefined };\r\n }\r\n const mutationMethods = new Set([\r\n \"insert\",\r\n \"cut\",\r\n \"cutByValue\",\r\n \"toggleByValue\",\r\n \"uniqueInsert\",\r\n \"update\",\r\n \"applyJsonPatch\",\r\n \"setSelected\",\r\n \"toggleSelected\",\r\n \"clearSelected\",\r\n \"sync\",\r\n \"validateZodSchema\",\r\n \"revertToInitialState\",\r\n \"updateInitialState\",\r\n \"removeValidation\",\r\n \"setValidation\",\r\n \"removeStorage\",\r\n \"middleware\",\r\n \"_componentId\",\r\n \"_stateKey\",\r\n \"getComponents\",\r\n ]);\r\n\r\n if (\r\n prop !== \"then\" &&\r\n !prop.startsWith(\"$\") &&\r\n prop !== \"stateMapNoRender\" &&\r\n !mutationMethods.has(prop)\r\n ) {\r\n const fullComponentId = `${stateKey}////${componentId}`;\r\n // console.log(\"adding path\", fullComponentId, path, prop);\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n\r\n if (stateEntry) {\r\n const component = stateEntry.components.get(fullComponentId);\r\n\r\n if (component) {\r\n // Mark as initialized immediately to prevent re-processing\r\n\r\n // Now do the path tracking logic ONCE\r\n if (!component.paths.has(\"\")) {\r\n const currentPath = path.join(\".\");\r\n let needsAdd = true;\r\n for (const existingPath of component.paths) {\r\n if (\r\n currentPath.startsWith(existingPath) &&\r\n (currentPath === existingPath ||\r\n currentPath[existingPath.length] === \".\")\r\n ) {\r\n needsAdd = false;\r\n break;\r\n }\r\n }\r\n\r\n if (needsAdd) {\r\n component.paths.add(currentPath);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (prop === \"getDifferences\") {\r\n return () => {\r\n const differences = getDifferences(\r\n getGlobalStore.getState().cogsStateStore[stateKey],\r\n getGlobalStore.getState().initialStateGlobal[stateKey]\r\n );\r\n return differences;\r\n };\r\n }\r\n if (prop === \"sync\" && path.length === 0) {\r\n return async function () {\r\n // Get the options for this state key\r\n const options = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey);\r\n const sync = options?.sync;\r\n\r\n if (!sync) {\r\n console.error(`No mutation defined for state key \"${stateKey}\"`);\r\n return { success: false, error: `No mutation defined` };\r\n }\r\n\r\n // Get the root state\r\n const state = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, []);\r\n\r\n // Get validation key\r\n const validationKey = options?.validation?.key;\r\n\r\n try {\r\n // Execute the mutation action\r\n const response = await sync.action(state);\r\n\r\n // Handle validation errors\r\n if (\r\n response &&\r\n !response.success &&\r\n response.errors &&\r\n validationKey\r\n ) {\r\n // Clear existing errors\r\n getGlobalStore.getState().removeValidationError(validationKey);\r\n\r\n // Add new validation errors\r\n response.errors.forEach((error) => {\r\n const errorPath = [validationKey, ...error.path].join(\".\");\r\n\r\n getGlobalStore\r\n .getState()\r\n .addValidationError(errorPath, error.message);\r\n });\r\n\r\n // Notify components to update\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (stateEntry) {\r\n stateEntry.components.forEach((component) => {\r\n component.forceUpdate();\r\n });\r\n }\r\n }\r\n\r\n // Call success/error callbacks\r\n if (response?.success && sync.onSuccess) {\r\n sync.onSuccess(response.data);\r\n } else if (!response?.success && sync.onError) {\r\n sync.onError(response.error);\r\n }\r\n\r\n return response;\r\n } catch (error) {\r\n if (sync.onError) {\r\n sync.onError(error);\r\n }\r\n return { success: false, error };\r\n }\r\n };\r\n }\r\n if (prop === \"_status\") {\r\n // Get current state at this path (non-reactive version)\r\n const thisReactiveState = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n }\r\n if (prop === \"getStatus\") {\r\n return function () {\r\n // Get current state at this path (reactive version)\r\n const thisReactiveState = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n );\r\n\r\n // Get initial state at this path\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initialStateAtPath = getNestedValue(initialState, path);\r\n // Simply compare current state with initial state\r\n if (isDeepEqual(thisReactiveState, initialStateAtPath)) {\r\n return \"fresh\"; // Matches initial state\r\n } else {\r\n return \"stale\"; // Different from initial state\r\n }\r\n };\r\n }\r\n if (prop === \"removeStorage\") {\r\n return () => {\r\n const initialState =\r\n getGlobalStore.getState().initialStateGlobal[stateKey];\r\n const initalOptionsGet = getInitialOptions(stateKey as string);\r\n const localKey = isFunction(initalOptionsGet?.localStorage?.key)\r\n ? initalOptionsGet?.localStorage?.key(initialState)\r\n : initalOptionsGet?.localStorage?.key;\r\n\r\n const storageKey = `${sessionId}-${stateKey}-${localKey}`;\r\n\r\n if (storageKey) {\r\n localStorage.removeItem(storageKey);\r\n }\r\n };\r\n }\r\n if (prop === \"showValidationErrors\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n const errors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key + \".\" + path.join(\".\"));\r\n\r\n return errors;\r\n };\r\n }\r\n if (Array.isArray(currentState)) {\r\n const getSourceArrayAndIndices = (): {\r\n item: any;\r\n originalIndex: number;\r\n }[] => {\r\n // If meta exists, we're in a chain. Use the currentState and map it to its original index.\r\n if (meta?.validIndices) {\r\n return (currentState as any[]).map((item, index) => ({\r\n item,\r\n originalIndex: meta!.validIndices![index]!,\r\n }));\r\n }\r\n // Otherwise, this is the first operation. Use the full array from the global store.\r\n const sourceArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return sourceArray.map((item, index) => ({\r\n item,\r\n originalIndex: index,\r\n }));\r\n };\r\n if (prop === \"getSelected\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n if (selectedIndex === undefined) return undefined;\r\n return rebuildStateShape(\r\n currentState[selectedIndex],\r\n [...path, selectedIndex.toString()],\r\n meta\r\n );\r\n };\r\n }\r\n if (prop === \"clearSelected\") {\r\n return () => {\r\n getGlobalStore.getState().clearSelectedIndex({ stateKey, path });\r\n };\r\n }\r\n if (prop === \"getSelectedIndex\") {\r\n return () => {\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, path.join(\".\"));\r\n\r\n return selectedIndex ?? -1;\r\n };\r\n }\r\n\r\n if (prop === \"useVirtualView\") {\r\n return (\r\n options: VirtualViewOptions\r\n ): VirtualStateObjectResult<any[]> => {\r\n // --- CHANGE 1: itemHeight is now optional, with a default fallback.\r\n const {\r\n itemHeight = 50, // Default/estimated height\r\n overscan = 5,\r\n stickToBottom = false,\r\n } = options;\r\n\r\n const containerRef = useRef<HTMLDivElement | null>(null);\r\n const [range, setRange] = useState({\r\n startIndex: 0,\r\n endIndex: 10,\r\n });\r\n\r\n // --- CHANGE 2: Add a helper to get the real height of each item. ---\r\n const getItemHeight = useCallback(\r\n (index: number): number => {\r\n const metadata = getGlobalStore\r\n .getState()\r\n .getShadowMetadata(stateKey, [...path, index.toString()]);\r\n return metadata?.virtualizer?.itemHeight || itemHeight;\r\n },\r\n [itemHeight, stateKey, path]\r\n );\r\n\r\n // --- These refs are from your original code. NO CHANGE. ---\r\n const isAtBottomRef = useRef(stickToBottom);\r\n const previousTotalCountRef = useRef(0);\r\n const isInitialMountRef = useRef(true);\r\n\r\n const sourceArray = getGlobalStore().getNestedState(\r\n stateKey,\r\n path\r\n ) as any[];\r\n const totalCount = sourceArray.length;\r\n\r\n // --- CHANGE 3: Calculate the total height and position of each item. ---\r\n // This is the only new block of logic required.\r\n const { totalHeight, positions } = useMemo(() => {\r\n let height = 0;\r\n const pos: number[] = [];\r\n for (let i = 0; i < totalCount; i++) {\r\n pos[i] = height;\r\n height += getItemHeight(i);\r\n }\r\n return { totalHeight: height, positions: pos };\r\n }, [totalCount, getItemHeight]);\r\n\r\n // --- The virtualState logic is IDENTICAL to your original. NO CHANGE. ---\r\n const virtualState = useMemo(() => {\r\n const start = Math.max(0, range.startIndex);\r\n const end = Math.min(totalCount, range.endIndex);\r\n const validIndices = Array.from(\r\n { length: end - start },\r\n (_, i) => start + i\r\n );\r\n const slicedArray = validIndices.map((idx) => sourceArray[idx]);\r\n return rebuildStateShape(slicedArray as any, path, {\r\n ...meta,\r\n validIndices,\r\n });\r\n }, [range.startIndex, range.endIndex, sourceArray, totalCount]);\r\n\r\n // --- This useLayoutEffect is from your original code. ---\r\n // --- We only change the math inside handleScroll. ---\r\n useLayoutEffect(() => {\r\n const container = containerRef.current;\r\n if (!container) return;\r\n\r\n const wasAtBottom = isAtBottomRef.current;\r\n const listGrew = totalCount > previousTotalCountRef.current;\r\n previousTotalCountRef.current = totalCount;\r\n\r\n const handleScroll = () => {\r\n const { scrollTop, clientHeight, scrollHeight } = container;\r\n isAtBottomRef.current =\r\n scrollHeight - scrollTop - clientHeight < 10;\r\n\r\n // --- CHANGE 4: The math to find the start and end index. ---\r\n // This replaces `scrollTop / itemHeight` with a more accurate search.\r\n let startIndex = 0;\r\n // Find the first item whose top position is past the scroll top.\r\n for (let i = 0; i < positions.length; i++) {\r\n if (positions[i]! >= scrollTop) {\r\n startIndex = i;\r\n break;\r\n }\r\n }\r\n\r\n let endIndex = startIndex;\r\n // Find the first item whose top position is past the bottom of the viewport.\r\n while (\r\n endIndex < totalCount &&\r\n positions[endIndex]! < scrollTop + clientHeight\r\n ) {\r\n endIndex++;\r\n }\r\n\r\n // Apply overscan, identical to your original code.\r\n startIndex = Math.max(0, startIndex - overscan);\r\n endIndex = Math.min(totalCount, endIndex + overscan);\r\n console.log(\r\n \"startIndex\",\r\n startIndex,\r\n \"endIndex\",\r\n endIndex,\r\n \"totalHeight\",\r\n totalHeight\r\n );\r\n setRange((prevRange) => {\r\n if (\r\n prevRange.startIndex !== startIndex ||\r\n prevRange.endIndex !== endIndex\r\n ) {\r\n return { startIndex: startIndex, endIndex: endIndex };\r\n }\r\n return prevRange;\r\n });\r\n };\r\n\r\n container.addEventListener(\"scroll\", handleScroll, {\r\n passive: true,\r\n });\r\n\r\n // --- This stickToBottom logic is IDENTICAL to your original. NO CHANGE. ---\r\n if (stickToBottom) {\r\n if (isInitialMountRef.current) {\r\n container.scrollTo({\r\n top: container.scrollHeight,\r\n behavior: \"auto\",\r\n });\r\n } else if (wasAtBottom && listGrew) {\r\n requestAnimationFrame(() => {\r\n container.scrollTo({\r\n top: container.scrollHeight,\r\n behavior: \"smooth\",\r\n });\r\n });\r\n }\r\n }\r\n\r\n isInitialMountRef.current = false;\r\n handleScroll();\r\n\r\n return () =>\r\n container.removeEventListener(\"scroll\", handleScroll);\r\n // --- We swap `itemHeight` for `positions` in the dependency array. ---\r\n }, [totalCount, overscan, stickToBottom, positions]);\r\n\r\n const scrollToBottom = useCallback(\r\n (behavior: ScrollBehavior = \"smooth\") => {\r\n if (containerRef.current) {\r\n containerRef.current.scrollTo({\r\n top: containerRef.current.scrollHeight,\r\n behavior,\r\n });\r\n }\r\n },\r\n []\r\n );\r\n\r\n // --- CHANGE 5: Update scrollToIndex to use the positions array. ---\r\n const scrollToIndex = useCallback(\r\n (index: number, behavior: ScrollBehavior = \"smooth\") => {\r\n if (containerRef.current) {\r\n containerRef.current.scrollTo({\r\n top: positions[index] || 0, // Use the calculated position\r\n behavior,\r\n });\r\n }\r\n },\r\n [positions] // Dependency is now `positions`\r\n );\r\n\r\n // --- CHANGE 6: Update virtualizer props to use dynamic values. ---\r\n const virtualizerProps = {\r\n outer: {\r\n ref: containerRef,\r\n style: { overflowY: \"auto\", height: \"100%\" },\r\n },\r\n inner: {\r\n style: {\r\n height: `${totalHeight}px`, // Use calculated dynamic height\r\n position: \"relative\",\r\n },\r\n },\r\n list: {\r\n style: {\r\n transform: `translateY(${positions[range.startIndex] || 0}px)`, // Use calculated position\r\n },\r\n },\r\n };\r\n\r\n return {\r\n virtualState,\r\n virtualizerProps: virtualizerProps as any,\r\n scrollToBottom,\r\n scrollToIndex,\r\n };\r\n };\r\n }\r\n if (prop === \"stateSort\") {\r\n return (\r\n compareFn: (\r\n a: InferArrayElement<T>,\r\n b: InferArrayElement<T>\r\n ) => number\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const sortedResult = [...sourceWithIndices].sort((a, b) =>\r\n compareFn(a.item, b.item)\r\n );\r\n const newCurrentState = sortedResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: sortedResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateFilter\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const filteredResult = sourceWithIndices.filter(\r\n ({ item }, index) => callbackfn(item, index)\r\n );\r\n const newCurrentState = filteredResult.map(({ item }) => item);\r\n // We construct the meta object with the CORRECT property name: `validIndices`.\r\n const newMeta = {\r\n ...meta,\r\n validIndices: filteredResult.map(\r\n ({ originalIndex }) => originalIndex\r\n ),\r\n };\r\n return rebuildStateShape(newCurrentState as any, path, newMeta);\r\n };\r\n }\r\n\r\n if (prop === \"stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n info: {\r\n register: () => void;\r\n index: number;\r\n originalIndex: number;\r\n }\r\n ) => any\r\n ) => {\r\n const arrayToMap = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n // Defensive check to make sure we are mapping over an array\r\n if (!Array.isArray(arrayToMap)) {\r\n console.warn(\r\n `stateMap called on a non-array value at path: ${path.join(\".\")}. The current value is:`,\r\n arrayToMap\r\n );\r\n return null;\r\n }\r\n\r\n // If we have validIndices, only map those items\r\n const indicesToMap =\r\n meta?.validIndices ||\r\n Array.from({ length: arrayToMap.length }, (_, i) => i);\r\n\r\n return indicesToMap.map((originalIndex, localIndex) => {\r\n const item = arrayToMap[originalIndex];\r\n const finalPath = [...path, originalIndex.toString()];\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n\r\n // Create the register function right here. It closes over the necessary variables.\r\n const register = () => {\r\n const [, forceUpdate] = useState({});\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([finalPath.join(\".\")]),\r\n });\r\n\r\n getGlobalStore\r\n .getState()\r\n .stateComponents.set(stateKey, stateEntry);\r\n\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId]);\r\n };\r\n\r\n return callbackfn(item, setter, {\r\n register,\r\n index: localIndex,\r\n originalIndex,\r\n });\r\n });\r\n };\r\n }\r\n if (prop === \"stateMapNoRender\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = currentState as any[];\r\n return arrayToMap.map((item, index) => {\r\n let originalIndex: number;\r\n // We READ from the meta object using the CORRECT property name: `validIndices`.\r\n if (\r\n meta?.validIndices &&\r\n meta.validIndices[index] !== undefined\r\n ) {\r\n originalIndex = meta.validIndices[index]!;\r\n } else {\r\n originalIndex = index;\r\n }\r\n const finalPath = [...path, originalIndex.toString()];\r\n\r\n const setter = rebuildStateShape(item, finalPath, meta); // Pass meta through\r\n return callbackfn(\r\n item,\r\n setter,\r\n index,\r\n currentState as any,\r\n rebuildStateShape(currentState as any, path, meta)\r\n );\r\n });\r\n };\r\n }\r\n if (prop === \"$stateMap\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => void\r\n ) => {\r\n return createElement(SignalMapRenderer, {\r\n proxy: {\r\n _stateKey: stateKey,\r\n _path: path,\r\n _mapFn: callbackfn as any, // Pass the actual function, not string\r\n },\r\n\r\n rebuildStateShape,\r\n });\r\n };\r\n }\r\n if (prop === \"stateList\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n setter: StateObject<InferArrayElement<T>>,\r\n index: number,\r\n array: T,\r\n arraySetter: StateObject<T>\r\n ) => any\r\n ) => {\r\n const arrayToMap = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n\r\n if (!Array.isArray(arrayToMap)) {\r\n console.warn(\r\n `stateList called on a non-array value at path: ${path.join(\".\")}.`\r\n );\r\n return null;\r\n }\r\n\r\n const indicesToMap =\r\n meta?.validIndices ||\r\n Array.from({ length: arrayToMap.length }, (_, i) => i);\r\n\r\n return indicesToMap.map((originalIndex, localIndex) => {\r\n const item = arrayToMap[originalIndex];\r\n const finalPath = [...path, originalIndex.toString()];\r\n const setter = rebuildStateShape(item, finalPath, meta);\r\n const itemComponentId = `${componentId}-${path.join(\".\")}-${originalIndex}`;\r\n\r\n return createElement(CogsItemWrapper, {\r\n key: originalIndex,\r\n stateKey,\r\n itemComponentId,\r\n itemPath: finalPath,\r\n children: callbackfn(\r\n item,\r\n setter,\r\n localIndex,\r\n arrayToMap as any,\r\n rebuildStateShape(arrayToMap as any, path, meta)\r\n ),\r\n });\r\n });\r\n };\r\n }\r\n if (prop === \"stateFlattenOn\") {\r\n return (fieldName: string) => {\r\n const arrayToMap = currentState as any[];\r\n shapeCache.clear();\r\n stateVersion++;\r\n const flattenedResults = arrayToMap.flatMap(\r\n (val: any) => val[fieldName] ?? []\r\n );\r\n return rebuildStateShape(\r\n flattenedResults as any,\r\n [...path, \"[*]\", fieldName],\r\n meta\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"index\") {\r\n return (index: number) => {\r\n const indexValue = currentState[index];\r\n return rebuildStateShape(indexValue, [...path, index.toString()]);\r\n };\r\n }\r\n if (prop === \"last\") {\r\n // Added handler for 'last'\r\n return () => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n if (currentArray.length === 0) return undefined;\r\n const lastIndex = currentArray.length - 1;\r\n const lastValue = currentArray[lastIndex];\r\n const newPath = [...path, lastIndex.toString()];\r\n // shapeCache.clear(); // Decide if you need cache invalidation for 'last' access\r\n // stateVersion++;\r\n return rebuildStateShape(lastValue, newPath);\r\n };\r\n }\r\n if (prop === \"insert\") {\r\n return (payload: UpdateArg<T>) => {\r\n // ADDED: Invalidate cache on insert\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, payload, path, stateKey);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n\r\n if (prop === \"uniqueInsert\") {\r\n return (\r\n payload: UpdateArg<T>,\r\n fields?: (keyof InferArrayElement<T>)[],\r\n onMatch?: (existingItem: any) => any\r\n ) => {\r\n const currentArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n const newValue = isFunction<T>(payload)\r\n ? payload(currentArray as any)\r\n : (payload as any);\r\n\r\n let matchedItem: any = null;\r\n const isUnique = !currentArray.some((item) => {\r\n if (fields) {\r\n const isMatch = fields.every((field) =>\r\n isDeepEqual(item[field], newValue[field])\r\n );\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n }\r\n const isMatch = isDeepEqual(item, newValue);\r\n if (isMatch) {\r\n matchedItem = item;\r\n }\r\n return isMatch;\r\n });\r\n\r\n if (isUnique) {\r\n invalidateCachePath(path);\r\n pushFunc(effectiveSetState, newValue, path, stateKey);\r\n } else if (onMatch && matchedItem) {\r\n const updatedItem = onMatch(matchedItem);\r\n const updatedArray = currentArray.map((item) =>\r\n isDeepEqual(item, matchedItem) ? updatedItem : item\r\n );\r\n invalidateCachePath(path);\r\n updateFn(effectiveSetState, updatedArray as any, path);\r\n }\r\n };\r\n }\r\n\r\n if (prop === \"cut\") {\r\n return (index: number, options?: { waitForSync?: boolean }) => {\r\n if (options?.waitForSync) return;\r\n // ADDED: Invalidate cache on cut\r\n invalidateCachePath(path);\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, path),\r\n path\r\n );\r\n };\r\n }\r\n if (prop === \"cutByValue\") {\r\n return (value: string | number | boolean) => {\r\n for (let index = 0; index < currentState.length; index++) {\r\n if (currentState[index] === value) {\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"toggleByValue\") {\r\n return (value: string | number | boolean) => {\r\n const index = currentState.findIndex((item) => item === value);\r\n if (index > -1) {\r\n // Value exists, so cut it\r\n cutFunc(effectiveSetState, path, stateKey, index);\r\n } else {\r\n // Value doesn't exist, so insert it\r\n pushFunc(effectiveSetState, value as any, path, stateKey);\r\n }\r\n };\r\n }\r\n if (prop === \"stateFind\") {\r\n return (\r\n callbackfn: (\r\n value: InferArrayElement<T>,\r\n index: number\r\n ) => boolean\r\n ) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(({ item }, index) =>\r\n callbackfn(item, index)\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n\r\n if (prop === \"findWith\") {\r\n return (thisKey: keyof InferArrayElement<T>, thisValue: any) => {\r\n const sourceWithIndices = getSourceArrayAndIndices();\r\n const found = sourceWithIndices.find(\r\n ({ item }) => item[thisKey] === thisValue\r\n );\r\n if (!found) return undefined;\r\n const finalPath = [...path, found.originalIndex.toString()];\r\n return rebuildStateShape(found.item, finalPath, meta);\r\n };\r\n }\r\n }\r\n const lastPathElement = path[path.length - 1];\r\n if (!isNaN(Number(lastPathElement))) {\r\n const parentPath = path.slice(0, -1);\r\n const parentValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n\r\n if (Array.isArray(parentValue) && prop === \"cut\") {\r\n return () =>\r\n cutFunc(\r\n effectiveSetState,\r\n parentPath,\r\n stateKey,\r\n Number(lastPathElement)\r\n );\r\n }\r\n }\r\n\r\n if (prop === \"get\") {\r\n return () => {\r\n if (meta?.validIndices && Array.isArray(currentState)) {\r\n // For filtered arrays, return only the items at validIndices\r\n const fullArray = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path) as any[];\r\n return meta.validIndices.map((index) => fullArray[index]);\r\n }\r\n return getGlobalStore.getState().getNestedState(stateKey, path);\r\n };\r\n }\r\n if (prop === \"$derive\") {\r\n return (fn: any) =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n _effect: fn.toString(),\r\n });\r\n }\r\n\r\n if (prop === \"$get\") {\r\n return () =>\r\n $cogsSignal({\r\n _stateKey: stateKey,\r\n _path: path,\r\n });\r\n }\r\n if (prop === \"lastSynced\") {\r\n const syncKey = `${stateKey}:${path.join(\".\")}`;\r\n return getGlobalStore.getState().getSyncInfo(syncKey);\r\n }\r\n\r\n if (prop == \"getLocalStorage\") {\r\n return (key: string) =>\r\n loadFromLocalStorage(sessionId + \"-\" + stateKey + \"-\" + key);\r\n }\r\n if (prop === \"_selected\") {\r\n const parentPath = path.slice(0, -1);\r\n const parentKey = parentPath.join(\".\");\r\n const parent = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, parentPath);\r\n if (Array.isArray(parent)) {\r\n const currentIndex = Number(path[path.length - 1]);\r\n return (\r\n currentIndex ===\r\n getGlobalStore.getState().getSelectedIndex(stateKey, parentKey)\r\n );\r\n }\r\n return undefined;\r\n }\r\n if (prop === \"setSelected\") {\r\n return (value: boolean) => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n\r\n if (value) {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, thisIndex);\r\n } else {\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(stateKey, parentKey, undefined);\r\n }\r\n\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n // Invalidate cache for this path\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (prop === \"toggleSelected\") {\r\n return () => {\r\n const parentPath = path.slice(0, -1);\r\n const thisIndex = Number(path[path.length - 1]);\r\n const parentKey = parentPath.join(\".\");\r\n const selectedIndex = getGlobalStore\r\n .getState()\r\n .getSelectedIndex(stateKey, parentKey);\r\n\r\n getGlobalStore\r\n .getState()\r\n .setSelectedIndex(\r\n stateKey,\r\n parentKey,\r\n selectedIndex === thisIndex ? undefined : thisIndex\r\n );\r\n const nested = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, [...parentPath]);\r\n updateFn(effectiveSetState, nested, parentPath);\r\n\r\n invalidateCachePath(parentPath);\r\n };\r\n }\r\n if (path.length == 0) {\r\n if (prop === \"applyJsonPatch\") {\r\n return (patches: any[]) => {\r\n // This part is correct.\r\n const currentState =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n const patchResult = applyPatch(currentState, patches);\r\n const newState = patchResult.newDocument;\r\n\r\n // This is also correct.\r\n updateGlobalState(\r\n stateKey,\r\n getGlobalStore.getState().initialStateGlobal[stateKey],\r\n newState,\r\n effectiveSetState,\r\n componentId,\r\n sessionId\r\n );\r\n\r\n // ===================================================================\r\n // REPLACE THE OLD LOGIC WITH THIS DIRECT COPY\r\n // ===================================================================\r\n\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey); // Use stateKey here\r\n\r\n if (stateEntry) {\r\n // Use `getDifferences` between the state before and after the patch.\r\n const changedPaths = getDifferences(currentState, newState);\r\n const changedPathsSet = new Set(changedPaths);\r\n\r\n // There is no single `primaryPathToCheck` for a patch, so we just check against the full set.\r\n\r\n for (const [\r\n componentKey,\r\n component,\r\n ] of stateEntry.components.entries()) {\r\n let shouldUpdate = false;\r\n const reactiveTypes = Array.isArray(component.reactiveType)\r\n ? component.reactiveType\r\n : [component.reactiveType || \"component\"];\r\n\r\n if (reactiveTypes.includes(\"none\")) continue;\r\n if (reactiveTypes.includes(\"all\")) {\r\n component.forceUpdate();\r\n continue;\r\n }\r\n\r\n if (reactiveTypes.includes(\"component\")) {\r\n // This is the core logic that needs to be copied.\r\n // Check if any of the component's watched paths are in the set of changed paths.\r\n if (component.paths.has(\"\")) {\r\n // Always update for root listeners\r\n shouldUpdate = true;\r\n }\r\n\r\n if (!shouldUpdate) {\r\n for (const changedPath of changedPathsSet) {\r\n // Direct match first (fastest)\r\n if (component.paths.has(changedPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n\r\n // Check parent paths more efficiently\r\n let dotIndex = changedPath.lastIndexOf(\".\");\r\n while (dotIndex !== -1) {\r\n const parentPath = changedPath.substring(0, dotIndex);\r\n if (component.paths.has(parentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n // Skip numeric segments more efficiently\r\n const lastSegment = changedPath.substring(\r\n dotIndex + 1\r\n );\r\n if (!isNaN(Number(lastSegment))) {\r\n // For array indices, check the parent collection path\r\n const parentDotIndex = parentPath.lastIndexOf(\".\");\r\n if (parentDotIndex !== -1) {\r\n const grandParentPath = parentPath.substring(\r\n 0,\r\n parentDotIndex\r\n );\r\n if (component.paths.has(grandParentPath)) {\r\n shouldUpdate = true;\r\n break;\r\n }\r\n }\r\n }\r\n dotIndex = parentPath.lastIndexOf(\".\");\r\n }\r\n\r\n if (shouldUpdate) break;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldUpdate && reactiveTypes.includes(\"deps\")) {\r\n // Use `newState` (the result of the patch) for dependency checks.\r\n if (component.depsFunction) {\r\n const depsResult = component.depsFunction(newState);\r\n let depsChanged = false;\r\n if (typeof depsResult === \"boolean\") {\r\n if (depsResult) depsChanged = true;\r\n } else if (!isDeepEqual(component.deps, depsResult)) {\r\n component.deps = depsResult;\r\n depsChanged = true;\r\n }\r\n if (depsChanged) {\r\n shouldUpdate = true;\r\n }\r\n }\r\n }\r\n\r\n if (shouldUpdate) {\r\n component.forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n }\r\n if (prop === \"validateZodSchema\") {\r\n return () => {\r\n const init = getGlobalStore\r\n .getState()\r\n .getInitialOptions(stateKey)?.validation;\r\n const addValidationError =\r\n getGlobalStore.getState().addValidationError;\r\n\r\n if (!init?.zodSchema) {\r\n throw new Error(\"Zod schema not found\");\r\n }\r\n\r\n if (!init?.key) {\r\n throw new Error(\"Validation key not found\");\r\n }\r\n removeValidationError(init.key);\r\n const thisObject =\r\n getGlobalStore.getState().cogsStateStore[stateKey];\r\n\r\n try {\r\n // First clear any existing validation errors for this schema\r\n // This ensures we don't have stale errors\r\n const existingErrors = getGlobalStore\r\n .getState()\r\n .getValidationErrors(init.key);\r\n if (existingErrors && existingErrors.length > 0) {\r\n existingErrors.forEach(([errorPath]) => {\r\n if (errorPath && errorPath.startsWith(init.key!)) {\r\n removeValidationError(errorPath);\r\n }\r\n });\r\n }\r\n\r\n // Attempt to validate with Zod\r\n const result = init.zodSchema.safeParse(thisObject);\r\n\r\n if (!result.success) {\r\n // Process Zod errors and add them to the validation store\r\n const zodErrors = result.error.errors;\r\n\r\n zodErrors.forEach((error) => {\r\n const errorPath = error.path;\r\n const errorMessage = error.message;\r\n\r\n // Build the full path for the validation error\r\n // Format: validationKey.path.to.field\r\n const fullErrorPath = [init.key, ...errorPath].join(\".\");\r\n\r\n // Add the error to the store\r\n addValidationError(fullErrorPath, errorMessage);\r\n });\r\n\r\n notifyComponents(stateKey);\r\n\r\n return false;\r\n }\r\n\r\n return true;\r\n } catch (error) {\r\n console.error(\"Zod schema validation failed\", error);\r\n return false;\r\n }\r\n };\r\n }\r\n if (prop === \"_componentId\") return componentId;\r\n if (prop === \"getComponents\") {\r\n return () => getGlobalStore().stateComponents.get(stateKey);\r\n }\r\n if (prop === \"getAllFormRefs\") {\r\n return () => {\r\n return formRefStore.getState().getFormRefsByStateKey(stateKey);\r\n };\r\n }\r\n\r\n if (prop === \"_initialState\")\r\n return getGlobalStore.getState().initialStateGlobal[stateKey];\r\n if (prop === \"_serverState\")\r\n return getGlobalStore.getState().serverState[stateKey];\r\n if (prop === \"_isLoading\")\r\n return getGlobalStore.getState().isLoadingGlobal[stateKey];\r\n if (prop === \"revertToInitialState\")\r\n return baseObj.revertToInitialState;\r\n if (prop === \"updateInitialState\") return baseObj.updateInitialState;\r\n if (prop === \"removeValidation\") return baseObj.removeValidation;\r\n }\r\n if (prop === \"getFormRef\") {\r\n return () => {\r\n return formRefStore\r\n .getState()\r\n .getFormRef(stateKey + \".\" + path.join(\".\"));\r\n };\r\n }\r\n\r\n if (prop === \"validationWrapper\") {\r\n return ({\r\n children,\r\n hideMessage,\r\n }: {\r\n children: React.ReactNode;\r\n hideMessage?: boolean;\r\n }) => (\r\n <ValidationWrapper\r\n formOpts={\r\n hideMessage ? { validation: { message: \"\" } } : undefined\r\n }\r\n path={path}\r\n validationKey={\r\n getGlobalStore.getState().getInitialOptions(stateKey)\r\n ?.validation?.key || \"\"\r\n }\r\n stateKey={stateKey}\r\n validIndices={meta?.validIndices}\r\n >\r\n {children}\r\n </ValidationWrapper>\r\n );\r\n }\r\n\r\n if (prop === \"_stateKey\") return stateKey;\r\n if (prop === \"_path\") return path;\r\n if (prop === \"_isServerSynced\") return baseObj._isServerSynced;\r\n\r\n if (prop === \"update\") {\r\n return (payload: UpdateArg<T>, opts?: UpdateOpts<T>) => {\r\n // ADDED: Invalidate cache on update\r\n if (opts?.debounce) {\r\n debounce(() => {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }, opts.debounce);\r\n } else {\r\n updateFn(effectiveSetState, payload, path, \"\");\r\n const newValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, path);\r\n if (opts?.afterUpdate) opts.afterUpdate(newValue);\r\n }\r\n invalidateCachePath(path);\r\n };\r\n }\r\n\r\n if (prop === \"formElement\") {\r\n return (child: FormControl<T>, formOpts?: FormOptsType) => {\r\n return (\r\n <FormControlComponent<T>\r\n setState={effectiveSetState}\r\n stateKey={stateKey}\r\n path={path}\r\n child={child}\r\n formOpts={formOpts}\r\n />\r\n );\r\n };\r\n }\r\n\r\n const nextPath = [...path, prop];\r\n const nextValue = getGlobalStore\r\n .getState()\r\n .getNestedState(stateKey, nextPath);\r\n return rebuildStateShape(nextValue, nextPath, meta);\r\n },\r\n };\r\n\r\n const proxyInstance = new Proxy(baseFunction, handler);\r\n\r\n shapeCache.set(cacheKey, {\r\n proxy: proxyInstance,\r\n stateVersion: stateVersion,\r\n });\r\n\r\n return proxyInstance;\r\n }\r\n\r\n return rebuildStateShape(\r\n getGlobalStore.getState().getNestedState(stateKey, [])\r\n );\r\n}\r\n\r\nexport function $cogsSignal(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n}) {\r\n return createElement(SignalRenderer, { proxy });\r\n}\r\n\r\nfunction SignalMapRenderer({\r\n proxy,\r\n\r\n rebuildStateShape,\r\n}: {\r\n proxy: {\r\n _stateKey: string;\r\n _path: string[];\r\n _mapFn: (\r\n value: any,\r\n setter: any,\r\n index: number,\r\n array: any[],\r\n arraySetter: any\r\n ) => ReactNode;\r\n };\r\n\r\n rebuildStateShape: (\r\n currentState: any,\r\n path: string[],\r\n meta?: { filtered?: string[][]; validIndices?: number[] }\r\n ) => any;\r\n}) {\r\n const value = getGlobalStore().getNestedState(proxy._stateKey, proxy._path);\r\n\r\n if (!Array.isArray(value)) {\r\n return null;\r\n }\r\n const arraySetter = rebuildStateShape(\r\n value,\r\n proxy._path\r\n ) as ArrayEndType<any>;\r\n // Use existing global state management\r\n return arraySetter.stateMapNoRender(\r\n (item, setter, index, value, arraysetter) => {\r\n // Execute map function in React context with existing state/proxies\r\n return proxy._mapFn(item, setter, index, value, arraysetter);\r\n }\r\n );\r\n}\r\nfunction SignalRenderer({\r\n proxy,\r\n}: {\r\n proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n _effect?: string;\r\n };\r\n}) {\r\n const elementRef = useRef<HTMLSpanElement>(null);\r\n const signalId = `${proxy._stateKey}-${proxy._path.join(\".\")}`;\r\n\r\n useEffect(() => {\r\n const element = elementRef.current;\r\n if (!element || !element.parentElement) return;\r\n\r\n const parentElement = element.parentElement;\r\n const childNodes = Array.from(parentElement.childNodes);\r\n const position = childNodes.indexOf(element);\r\n\r\n let parentId = parentElement.getAttribute(\"data-parent-id\");\r\n if (!parentId) {\r\n parentId = `parent-${crypto.randomUUID()}`;\r\n parentElement.setAttribute(\"data-parent-id\", parentId);\r\n }\r\n\r\n const instanceId = `instance-${crypto.randomUUID()}`;\r\n const elementInfo = {\r\n instanceId,\r\n parentId,\r\n position,\r\n effect: proxy._effect,\r\n };\r\n\r\n getGlobalStore.getState().addSignalElement(signalId, elementInfo);\r\n\r\n // Get the raw value from the store\r\n const value = getGlobalStore\r\n .getState()\r\n .getNestedState(proxy._stateKey, proxy._path);\r\n\r\n let displayValue;\r\n if (proxy._effect) {\r\n try {\r\n displayValue = new Function(\r\n \"state\",\r\n `return (${proxy._effect})(state)`\r\n )(value);\r\n } catch (err) {\r\n console.error(\"Error evaluating effect function during mount:\", err);\r\n displayValue = value; // Fallback to raw value\r\n }\r\n } else {\r\n displayValue = value;\r\n }\r\n\r\n if (displayValue !== null && typeof displayValue === \"object\") {\r\n displayValue = JSON.stringify(displayValue);\r\n }\r\n\r\n const textNode = document.createTextNode(String(displayValue));\r\n element.replaceWith(textNode);\r\n }, [proxy._stateKey, proxy._path.join(\".\"), proxy._effect]);\r\n\r\n return createElement(\"span\", {\r\n ref: elementRef,\r\n style: { display: \"none\" },\r\n \"data-signal-id\": signalId,\r\n });\r\n}\r\nexport function $cogsSignalStore(proxy: {\r\n _path: string[];\r\n _stateKey: string;\r\n}) {\r\n const value = useSyncExternalStore(\r\n (notify) => {\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(proxy._stateKey) || {\r\n components: new Map(),\r\n };\r\n stateEntry.components.set(proxy._stateKey, {\r\n forceUpdate: notify,\r\n paths: new Set([proxy._path.join(\".\")]),\r\n });\r\n return () => stateEntry.components.delete(proxy._stateKey);\r\n },\r\n () => getGlobalStore.getState().getNestedState(proxy._stateKey, proxy._path)\r\n );\r\n return createElement(\"text\", {}, String(value));\r\n}\r\n\r\nfunction CogsItemWrapper({\r\n stateKey,\r\n itemComponentId,\r\n itemPath,\r\n children,\r\n}: {\r\n stateKey: string;\r\n itemComponentId: string;\r\n itemPath: string[];\r\n children: React.ReactNode;\r\n}) {\r\n const [, forceUpdate] = useState({});\r\n const [ref, bounds] = useMeasure();\r\n\r\n useEffect(() => {\r\n if (bounds.height > 0) {\r\n getGlobalStore.getState().setShadowMetadata(stateKey, itemPath, {\r\n virtualizer: {\r\n itemHeight: bounds.height,\r\n },\r\n });\r\n }\r\n }, [bounds.height]);\r\n\r\n useLayoutEffect(() => {\r\n const fullComponentId = `${stateKey}////${itemComponentId}`;\r\n const stateEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey) || {\r\n components: new Map(),\r\n };\r\n\r\n stateEntry.components.set(fullComponentId, {\r\n forceUpdate: () => forceUpdate({}),\r\n paths: new Set([itemPath.join(\".\")]),\r\n });\r\n\r\n getGlobalStore.getState().stateComponents.set(stateKey, stateEntry);\r\n\r\n return () => {\r\n const currentEntry = getGlobalStore\r\n .getState()\r\n .stateComponents.get(stateKey);\r\n if (currentEntry) {\r\n currentEntry.components.delete(fullComponentId);\r\n }\r\n };\r\n }, [stateKey, itemComponentId, itemPath.join(\".\")]);\r\n\r\n return <div ref={ref}>{children}</div>;\r\n}\r\n"],"names":["setAndMergeOptions","stateKey","newOptions","getInitialOptions","getGlobalStore","setInitialStateOptions","initialOptions","setOptions","options","initialOptionsPart","initialOptionsPartState","mergedOptions","needToAdd","key","isDeepEqual","addStateOptions","initialState","formElements","validation","createCogsState","opt","newInitialState","statePart","transformStateFunc","useCogsState","componentId","useState","uuidv4","thiState","partialState","state","updater","useCogsStateFn","setCogsOptions","loadAndApplyLocalStorage","notifyComponents","setUpdaterState","setState","getKeyState","getValidationErrors","setStateLog","updateInitialStateGlobal","addValidationError","removeValidationError","setServerSyncActions","saveToLocalStorage","thisKey","currentInitialOptions","sessionId","lastSyncedWithServer","isFunction","storageKey","existingLastSynced","loadFromLocalStorage","data","superJsonResult","superjson","localStorageKey","storedData","error","currentState","useCogsConfig","localkey","localData","updateGlobalState","newState","effectiveSetState","updates","createProxyHandler","stateEntry","component","update","notifyComponent","fullComponentId","getUpdateValues","updateType","prevValue","payload","path","getNestedValue","stateObject","serverSync","localStorage","reactiveDeps","reactiveType","syncUpdate","dependencies","serverState","reactiveForce","forceUpdate","noStateKey","stateLog","componentUpdatesRef","useRef","componentIdRef","latestInitialOptionsRef","useEffect","prevState","syncKey","hasServerData","currentGloballyStoredInitialState","isFromServer","serverTimestamp","localTimestamp","lastSyncTimestamp","useLayoutEffect","componentKey","newStateOrFunction","updateObj","validationKey","pathKey","store","signalId","isArrayOperation","elements","arrayPath","arrayValue","arraySignalId","newValue","parentId","position","effect","parent","childNodes","displayValue","arrayWithoutIndex","k","v","length","newKey","changedPaths","getDifferences","changedPathsSet","primaryPathToCheck","shouldUpdate","reactiveTypes","changedPath","currentPathToCheck","lastDotIndex","parentPath","depsResult","depsChanged","timeStamp","p","i","oldValue","newUpdate","index","prevLogs","aggregatedLogs","acc","log","uniqueKey","existing","serverStateStore","updaterFinal","useMemo","shapeCache","stateVersion","invalidateCachePath","baseObj","obj","init","newProxy","rebuildStateShape","initalOptionsGet","localKey","newUpdaterState","startTransition","field","meta","cacheKey","baseFunction","handler","target","thisArg","args","prop","mutationMethods","currentPath","needsAdd","existingPath","sync","response","errorPath","thisReactiveState","initialStateAtPath","getSourceArrayAndIndices","item","selectedIndex","itemHeight","overscan","stickToBottom","containerRef","range","setRange","getItemHeight","useCallback","isAtBottomRef","previousTotalCountRef","isInitialMountRef","sourceArray","totalCount","totalHeight","positions","height","pos","virtualState","start","end","validIndices","_","slicedArray","idx","container","wasAtBottom","listGrew","handleScroll","scrollTop","clientHeight","scrollHeight","startIndex","endIndex","prevRange","scrollToBottom","behavior","scrollToIndex","virtualizerProps","compareFn","sortedResult","a","b","newCurrentState","newMeta","originalIndex","callbackfn","filteredResult","arrayToMap","localIndex","finalPath","setter","itemComponentId","currentEntry","createElement","SignalMapRenderer","CogsItemWrapper","fieldName","flattenedResults","val","indexValue","currentArray","lastIndex","lastValue","newPath","pushFunc","fields","onMatch","matchedItem","isMatch","updatedItem","updatedArray","updateFn","cutFunc","value","found","thisValue","lastPathElement","parentValue","fullArray","fn","$cogsSignal","parentKey","thisIndex","nested","patches","applyPatch","dotIndex","lastSegment","parentDotIndex","grandParentPath","thisObject","existingErrors","result","errorMessage","fullErrorPath","formRefStore","children","hideMessage","jsx","ValidationWrapper","opts","debounce","child","formOpts","FormControlComponent","nextPath","nextValue","proxyInstance","proxy","SignalRenderer","arraysetter","elementRef","element","parentElement","elementInfo","err","textNode","$cogsSignalStore","useSyncExternalStore","notify","itemPath","ref","bounds","useMeasure"],"mappings":";;;;;;;;;;;;AA6eA,SAASA,GAAmBC,GAAkBC,GAA8B;AACpEC,QAAAA,IAAoBC,EAAe,SAAA,EAAW,mBAC9CC,IACJD,EAAe,SAAA,EAAW,wBAEtBE,IAAiBH,EAAkBF,CAAkB,KAAK,CAAC;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