@voidhash/mimic-react 0.0.1-alpha.10

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.
Files changed (37) hide show
  1. package/.turbo/turbo-build.log +35 -0
  2. package/LICENSE.md +663 -0
  3. package/dist/index.cjs +0 -0
  4. package/dist/index.d.cts +1 -0
  5. package/dist/index.d.mts +1 -0
  6. package/dist/index.mjs +1 -0
  7. package/dist/objectSpread2-CIP_6jda.cjs +73 -0
  8. package/dist/objectSpread2-CxTyNSYl.mjs +67 -0
  9. package/dist/zustand/index.cjs +95 -0
  10. package/dist/zustand/index.d.cts +115 -0
  11. package/dist/zustand/index.d.cts.map +1 -0
  12. package/dist/zustand/index.d.mts +115 -0
  13. package/dist/zustand/index.d.mts.map +1 -0
  14. package/dist/zustand/index.mjs +96 -0
  15. package/dist/zustand/index.mjs.map +1 -0
  16. package/dist/zustand-commander/index.cjs +364 -0
  17. package/dist/zustand-commander/index.d.cts +325 -0
  18. package/dist/zustand-commander/index.d.cts.map +1 -0
  19. package/dist/zustand-commander/index.d.mts +325 -0
  20. package/dist/zustand-commander/index.d.mts.map +1 -0
  21. package/dist/zustand-commander/index.mjs +355 -0
  22. package/dist/zustand-commander/index.mjs.map +1 -0
  23. package/package.json +53 -0
  24. package/src/index.ts +0 -0
  25. package/src/zustand/index.ts +24 -0
  26. package/src/zustand/middleware.ts +171 -0
  27. package/src/zustand/types.ts +117 -0
  28. package/src/zustand-commander/commander.ts +395 -0
  29. package/src/zustand-commander/hooks.ts +259 -0
  30. package/src/zustand-commander/index.ts +139 -0
  31. package/src/zustand-commander/types.ts +347 -0
  32. package/tests/zustand/middleware.test.ts +584 -0
  33. package/tests/zustand-commander/commander.test.ts +774 -0
  34. package/tsconfig.build.json +24 -0
  35. package/tsconfig.json +8 -0
  36. package/tsdown.config.ts +18 -0
  37. package/vitest.mts +11 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["DEFAULT_OPTIONS: Required<CommanderOptions>","_storeApi: StoreApi<TStore & CommanderSlice> | null","ctx: CommandContext<TStore & CommanderSlice>","entry: UndoEntry<TParams, TReturn>","ctx: CommandContext<TStore>","newEntry: UndoEntry","dispatch: CommandDispatch<TStore>","ctx: CommandContext<TStore>"],"sources":["../../src/zustand-commander/types.ts","../../src/zustand-commander/commander.ts","../../src/zustand-commander/hooks.ts"],"sourcesContent":["/**\n * @voidhash/mimic-react/zustand-commander\n *\n * Type definitions for the zustand-commander package.\n *\n * @since 0.0.1\n */\n\nimport type { Schema } from \"effect\";\nimport type { StoreApi, UseBoundStore } from \"zustand\";\n\n// =============================================================================\n// Schema Types\n// =============================================================================\n\n/**\n * Any Effect Schema type (used for type constraints).\n */\nexport type AnyEffectSchema = Schema.Schema<any, any, any>;\n\n/**\n * Infer the Type from an Effect Schema.\n */\nexport type InferSchemaType<T> = T extends Schema.Schema<infer A, any, any>\n ? A\n : never;\n\n// =============================================================================\n// Command Symbol & Type Guard\n// =============================================================================\n\n/**\n * Symbol used to identify Command objects at runtime.\n */\nexport const COMMAND_SYMBOL = Symbol.for(\"zustand-commander/command\");\n\n/**\n * Symbol used to identify UndoableCommand objects at runtime.\n */\nexport const UNDOABLE_COMMAND_SYMBOL = Symbol.for(\n \"zustand-commander/undoable-command\"\n);\n\n// =============================================================================\n// Command Context\n// =============================================================================\n\n/**\n * Context provided to command functions.\n * Gives access to store state and dispatch capabilities.\n */\nexport interface CommandContext<TStore> {\n /**\n * Get the current store state.\n */\n readonly getState: () => TStore;\n\n /**\n * Set partial store state (for local/browser state updates).\n */\n readonly setState: (partial: Partial<TStore>) => void;\n\n /**\n * Dispatch another command.\n * Returns the result of the dispatched command.\n *\n * @example\n * dispatch(otherCommand)({ param: \"value\" });\n */\n readonly dispatch: CommandDispatch<TStore>;\n}\n\n// =============================================================================\n// Command Function Types\n// =============================================================================\n\n/**\n * The function signature for a command handler.\n */\nexport type CommandFn<TStore, TParams, TReturn> = (\n ctx: CommandContext<TStore>,\n params: TParams\n) => TReturn;\n\n/**\n * The function signature for an undoable command's revert handler.\n * Receives the original params and the result from the forward execution.\n */\nexport type RevertFn<TStore, TParams, TReturn> = (\n ctx: CommandContext<TStore>,\n params: TParams,\n result: TReturn\n) => void;\n\n// =============================================================================\n// Command Types\n// =============================================================================\n\n/**\n * A command that can be dispatched to modify store state.\n * Regular commands do not support undo/redo.\n */\nexport interface Command<TStore, TParams, TReturn> {\n readonly [COMMAND_SYMBOL]: true;\n readonly fn: CommandFn<TStore, TParams, TReturn>;\n readonly paramsSchema: AnyEffectSchema | null;\n}\n\n/**\n * An undoable command that supports undo/redo.\n * Must provide a revert function that knows how to undo the change.\n */\nexport interface UndoableCommand<TStore, TParams, TReturn>\n extends Command<TStore, TParams, TReturn> {\n readonly [UNDOABLE_COMMAND_SYMBOL]: true;\n readonly revert: RevertFn<TStore, TParams, TReturn>;\n}\n\n/**\n * Any command type (regular or undoable).\n */\nexport type AnyCommand = Command<any, any, any>;\n\n/**\n * Any undoable command type.\n */\nexport type AnyUndoableCommand = UndoableCommand<any, any, any>;\n\n// =============================================================================\n// Command Dispatch\n// =============================================================================\n\n/**\n * Dispatch function that accepts commands and returns a function to call with params.\n * Returns the result of the command execution.\n *\n * @example\n * const result = dispatch(myCommand)({ param: \"value\" });\n */\nexport type CommandDispatch<TStore> = <TParams, TReturn>(\n command: Command<TStore, TParams, TReturn>\n) => (params: TParams) => TReturn;\n\n// =============================================================================\n// Undo/Redo Stack Types\n// =============================================================================\n\n/**\n * An entry in the undo/redo stack.\n * Contains all information needed to revert or redo a command.\n */\nexport interface UndoEntry<TParams = unknown, TReturn = unknown> {\n /** The undoable command that was executed */\n readonly command: AnyUndoableCommand;\n /** The parameters that were passed to the command */\n readonly params: TParams;\n /** The result returned by the command (passed to revert) */\n readonly result: TReturn;\n /** Timestamp when the command was executed */\n readonly timestamp: number;\n}\n\n/**\n * State slice for undo/redo functionality.\n */\nexport interface CommanderSlice {\n readonly _commander: {\n /** Stack of commands that can be undone */\n readonly undoStack: ReadonlyArray<UndoEntry>;\n /** Stack of commands that can be redone */\n readonly redoStack: ReadonlyArray<UndoEntry>;\n };\n}\n\n// =============================================================================\n// Commander Types\n// =============================================================================\n\n/**\n * Options for creating a commander.\n */\nexport interface CommanderOptions {\n /**\n * Maximum number of undo entries to keep.\n * @default 100\n */\n readonly maxUndoStackSize?: number;\n}\n\n/**\n * A commander instance bound to a specific store type.\n * Used to create commands and the middleware.\n */\nexport interface Commander<TStore> {\n /**\n * Create a regular command (no undo support).\n *\n * @example\n * // With params schema\n * const addItem = commander.action(\n * Schema.Struct({ name: Schema.String }),\n * (ctx, params) => {\n * // modify state\n * }\n * );\n *\n * // Without params\n * const clearAll = commander.action((ctx) => {\n * // modify state\n * });\n */\n readonly action: {\n // With params schema\n <TParamsSchema extends AnyEffectSchema, TReturn = void>(\n paramsSchema: TParamsSchema,\n fn: CommandFn<TStore, InferSchemaType<TParamsSchema>, TReturn>\n ): Command<TStore, InferSchemaType<TParamsSchema>, TReturn>;\n\n // Without params (void)\n <TReturn = void>(\n fn: CommandFn<TStore, void, TReturn>\n ): Command<TStore, void, TReturn>;\n };\n\n /**\n * Create an undoable command with undo/redo support.\n * The revert function is called when undoing the command.\n *\n * @example\n * const moveItem = commander.undoableAction(\n * Schema.Struct({ id: Schema.String, toIndex: Schema.Number }),\n * (ctx, params) => {\n * const fromIndex = // get current index\n * // perform move\n * return { fromIndex }; // return data needed for revert\n * },\n * (ctx, params, result) => {\n * // revert: move back to original position\n * ctx.dispatch(moveItem)({ id: params.id, toIndex: result.fromIndex });\n * }\n * );\n */\n readonly undoableAction: {\n // With params schema\n <TParamsSchema extends AnyEffectSchema, TReturn>(\n paramsSchema: TParamsSchema,\n fn: CommandFn<TStore, InferSchemaType<TParamsSchema>, TReturn>,\n revert: RevertFn<TStore, InferSchemaType<TParamsSchema>, TReturn>\n ): UndoableCommand<TStore, InferSchemaType<TParamsSchema>, TReturn>;\n\n // Without params (void)\n <TReturn>(\n fn: CommandFn<TStore, void, TReturn>,\n revert: RevertFn<TStore, void, TReturn>\n ): UndoableCommand<TStore, void, TReturn>;\n };\n\n /**\n * Zustand middleware that adds commander functionality.\n * Adds undo/redo stacks to the store state.\n */\n readonly middleware: CommanderMiddleware<TStore>;\n}\n\n/**\n * Type for the commander middleware.\n * Note: TStore is intentionally unused here to match the Commander interface signature.\n * The middleware is generic over T (the inner store type) and adds CommanderSlice.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type CommanderMiddleware<_TStore> = <T extends object>(\n config: (\n set: StoreApi<T & CommanderSlice>[\"setState\"],\n get: StoreApi<T & CommanderSlice>[\"getState\"],\n api: StoreApi<T & CommanderSlice>\n ) => T\n) => (\n set: StoreApi<T & CommanderSlice>[\"setState\"],\n get: StoreApi<T & CommanderSlice>[\"getState\"],\n api: StoreApi<T & CommanderSlice>\n) => T & CommanderSlice;\n\n// =============================================================================\n// Type Helpers\n// =============================================================================\n\n/**\n * Extract the params type from a command.\n */\nexport type CommandParams<T> = T extends Command<any, infer P, any> ? P : never;\n\n/**\n * Extract the return type from a command.\n */\nexport type CommandReturn<T> = T extends Command<any, any, infer R>\n ? R\n : undefined;\n\n/**\n * Extract the store type from a command.\n */\nexport type CommandStore<T> = T extends Command<infer S, any, any> ? S : never;\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Type guard to check if a value is a Command.\n */\nexport function isCommand(value: unknown): value is AnyCommand {\n return (\n typeof value === \"object\" &&\n value !== null &&\n COMMAND_SYMBOL in value &&\n value[COMMAND_SYMBOL] === true\n );\n}\n\n/**\n * Type guard to check if a command is undoable.\n */\nexport function isUndoableCommand(\n value: unknown\n): value is AnyUndoableCommand {\n return (\n isCommand(value) &&\n UNDOABLE_COMMAND_SYMBOL in value &&\n value[UNDOABLE_COMMAND_SYMBOL] === true\n );\n}\n\n// =============================================================================\n// Store Type Helper\n// =============================================================================\n\n/**\n * Helper type to extract the state type from a zustand store.\n */\nexport type ExtractState<TStore> = TStore extends UseBoundStore<\n StoreApi<infer S>\n>\n ? S\n : TStore extends StoreApi<infer S>\n ? S\n : never;\n\n","/**\n * @voidhash/mimic-react/zustand-commander\n *\n * Commander creation and command definition.\n *\n * @since 0.0.1\n */\n\nimport type { StoreApi } from \"zustand\";\nimport {\n COMMAND_SYMBOL,\n UNDOABLE_COMMAND_SYMBOL,\n isUndoableCommand,\n type AnyEffectSchema,\n type Command,\n type Commander,\n type CommanderOptions,\n type CommanderSlice,\n type CommandContext,\n type CommandDispatch,\n type CommandFn,\n type InferSchemaType,\n type RevertFn,\n type UndoableCommand,\n type UndoEntry,\n} from \"./types.js\";\n\n// =============================================================================\n// Default Options\n// =============================================================================\n\nconst DEFAULT_OPTIONS: Required<CommanderOptions> = {\n maxUndoStackSize: 100,\n};\n\n// =============================================================================\n// Commander Implementation\n// =============================================================================\n\n/**\n * Creates a commander instance bound to a specific store type.\n *\n * @example\n * ```ts\n * // Create commander for your store type\n * const commander = createCommander<StoreState>();\n *\n * // Define commands\n * const addItem = commander.action(\n * Schema.Struct({ name: Schema.String }),\n * (ctx, params) => {\n * const { mimic } = ctx.getState();\n * mimic.document.transaction(root => {\n * // add item\n * });\n * }\n * );\n *\n * // Create store with middleware\n * const useStore = create(\n * commander.middleware(\n * mimic(document, (set, get) => ({\n * // your state\n * }))\n * )\n * );\n * ```\n */\nexport function createCommander<TStore extends object>(\n options: CommanderOptions = {}\n): Commander<TStore & CommanderSlice> {\n const { maxUndoStackSize } = { ...DEFAULT_OPTIONS, ...options };\n\n // Track the store API once middleware is applied\n let _storeApi: StoreApi<TStore & CommanderSlice> | null = null;\n\n /**\n * Creates the dispatch function for use within command handlers.\n */\n const createDispatch = (): CommandDispatch<TStore & CommanderSlice> => {\n return <TParams, TReturn>(\n command: Command<TStore & CommanderSlice, TParams, TReturn>\n ) => {\n return (params: TParams): TReturn => {\n if (!_storeApi) {\n throw new Error(\n \"Commander: Store not initialized. Make sure to use the commander middleware.\"\n );\n }\n\n // Create context for the command\n const ctx: CommandContext<TStore & CommanderSlice> = {\n getState: () => _storeApi!.getState(),\n setState: (partial) => _storeApi!.setState(partial as any),\n dispatch: createDispatch(),\n };\n\n // Execute the command\n const result = command.fn(ctx, params);\n\n // If it's an undoable command, add to undo stack\n if (isUndoableCommand(command)) {\n const entry: UndoEntry<TParams, TReturn> = {\n command,\n params,\n result,\n timestamp: Date.now(),\n };\n\n _storeApi.setState((state: TStore & CommanderSlice) => {\n const { undoStack, redoStack } = state._commander;\n\n // Add to undo stack, respecting max size\n const newUndoStack = [...undoStack, entry].slice(-maxUndoStackSize);\n\n // Clear redo stack when a new command is executed\n return {\n ...state,\n _commander: {\n undoStack: newUndoStack,\n redoStack: [],\n },\n };\n });\n }\n\n return result;\n };\n };\n };\n\n /**\n * Create a regular command (no undo support).\n */\n function action<TParamsSchema extends AnyEffectSchema, TReturn = void>(\n paramsSchema: TParamsSchema,\n fn: CommandFn<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>\n ): Command<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>;\n function action<TReturn = void>(\n fn: CommandFn<TStore & CommanderSlice, void, TReturn>\n ): Command<TStore & CommanderSlice, void, TReturn>;\n function action<TParamsSchema extends AnyEffectSchema, TReturn = void>(\n paramsSchemaOrFn:\n | TParamsSchema\n | CommandFn<TStore & CommanderSlice, void, TReturn>,\n maybeFn?: CommandFn<\n TStore & CommanderSlice,\n InferSchemaType<TParamsSchema>,\n TReturn\n >\n ): Command<TStore & CommanderSlice, any, TReturn> {\n // Check if we have two arguments (schema + fn) or just one (fn only)\n if (maybeFn !== undefined) {\n // First arg is schema, second is fn\n return {\n [COMMAND_SYMBOL]: true,\n fn: maybeFn,\n paramsSchema: paramsSchemaOrFn as TParamsSchema,\n };\n }\n\n // Single argument - must be the action function (no params schema)\n if (typeof paramsSchemaOrFn !== \"function\") {\n throw new Error(\"Commander: action requires a function\");\n }\n\n return {\n [COMMAND_SYMBOL]: true,\n fn: paramsSchemaOrFn as CommandFn<TStore & CommanderSlice, void, TReturn>,\n paramsSchema: null,\n };\n }\n\n /**\n * Create an undoable command with undo/redo support.\n */\n function undoableAction<TParamsSchema extends AnyEffectSchema, TReturn>(\n paramsSchema: TParamsSchema,\n fn: CommandFn<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>,\n revert: RevertFn<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>\n ): UndoableCommand<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>;\n function undoableAction<TReturn>(\n fn: CommandFn<TStore & CommanderSlice, void, TReturn>,\n revert: RevertFn<TStore & CommanderSlice, void, TReturn>\n ): UndoableCommand<TStore & CommanderSlice, void, TReturn>;\n function undoableAction<TParamsSchema extends AnyEffectSchema, TReturn>(\n paramsSchemaOrFn:\n | TParamsSchema\n | CommandFn<TStore & CommanderSlice, void, TReturn>,\n fnOrRevert:\n | CommandFn<TStore & CommanderSlice, InferSchemaType<TParamsSchema>, TReturn>\n | RevertFn<TStore & CommanderSlice, void, TReturn>,\n maybeRevert?: RevertFn<\n TStore & CommanderSlice,\n InferSchemaType<TParamsSchema>,\n TReturn\n >\n ): UndoableCommand<TStore & CommanderSlice, any, TReturn> {\n // Check if we have three arguments (schema + fn + revert) or two (fn + revert)\n if (maybeRevert !== undefined) {\n // First arg is schema, second is fn, third is revert\n return {\n [COMMAND_SYMBOL]: true,\n [UNDOABLE_COMMAND_SYMBOL]: true,\n fn: fnOrRevert as CommandFn<\n TStore & CommanderSlice,\n InferSchemaType<TParamsSchema>,\n TReturn\n >,\n paramsSchema: paramsSchemaOrFn as TParamsSchema,\n revert: maybeRevert,\n };\n }\n\n // Two arguments - fn + revert (no params schema)\n if (typeof paramsSchemaOrFn !== \"function\") {\n throw new Error(\"Commander: undoableAction requires a function\");\n }\n\n return {\n [COMMAND_SYMBOL]: true,\n [UNDOABLE_COMMAND_SYMBOL]: true,\n fn: paramsSchemaOrFn as CommandFn<TStore & CommanderSlice, void, TReturn>,\n paramsSchema: null,\n revert: fnOrRevert as RevertFn<TStore & CommanderSlice, void, TReturn>,\n };\n }\n\n /**\n * Zustand middleware that adds commander functionality.\n */\n const middleware = <T extends object>(\n config: (\n set: StoreApi<T & CommanderSlice>[\"setState\"],\n get: StoreApi<T & CommanderSlice>[\"getState\"],\n api: StoreApi<T & CommanderSlice>\n ) => T\n ) => {\n return (\n set: StoreApi<T & CommanderSlice>[\"setState\"],\n get: StoreApi<T & CommanderSlice>[\"getState\"],\n api: StoreApi<T & CommanderSlice>\n ): T & CommanderSlice => {\n // Store the API reference for dispatch\n _storeApi = api as unknown as StoreApi<TStore & CommanderSlice>;\n\n // Get user's state\n const userState = config(set, get, api);\n\n // Add commander slice\n return {\n ...userState,\n _commander: {\n undoStack: [],\n redoStack: [],\n },\n };\n };\n };\n\n return {\n action,\n undoableAction,\n middleware: middleware as Commander<TStore & CommanderSlice>[\"middleware\"],\n };\n}\n\n// =============================================================================\n// Undo/Redo Functions\n// =============================================================================\n\n/**\n * Perform an undo operation on the store.\n * Returns true if an undo was performed, false if undo stack was empty.\n */\nexport function performUndo<TStore extends CommanderSlice>(\n storeApi: StoreApi<TStore>\n): boolean {\n const state = storeApi.getState();\n const { undoStack, redoStack } = state._commander;\n\n // Pop the last entry from undo stack\n const entry = undoStack[undoStack.length - 1];\n if (!entry) {\n return false;\n }\n\n const newUndoStack = undoStack.slice(0, -1);\n\n // Create context for the revert function\n const ctx: CommandContext<TStore> = {\n getState: () => storeApi.getState(),\n setState: (partial) => storeApi.setState(partial as any),\n dispatch: createDispatchForUndo(storeApi),\n };\n\n // Execute the revert function\n entry.command.revert(ctx, entry.params, entry.result);\n\n // Move entry to redo stack\n storeApi.setState((state: TStore) => ({\n ...state,\n _commander: {\n undoStack: newUndoStack,\n redoStack: [...redoStack, entry],\n },\n }));\n\n return true;\n}\n\n/**\n * Perform a redo operation on the store.\n * Returns true if a redo was performed, false if redo stack was empty.\n */\nexport function performRedo<TStore extends CommanderSlice>(\n storeApi: StoreApi<TStore>\n): boolean {\n const state = storeApi.getState();\n const { undoStack, redoStack } = state._commander;\n\n // Pop the last entry from redo stack\n const entry = redoStack[redoStack.length - 1];\n if (!entry) {\n return false;\n }\n\n const newRedoStack = redoStack.slice(0, -1);\n\n // Create context for re-executing the command\n const ctx: CommandContext<TStore> = {\n getState: () => storeApi.getState(),\n setState: (partial) => storeApi.setState(partial as any),\n dispatch: createDispatchForUndo(storeApi),\n };\n\n // Re-execute the command\n const result = entry.command.fn(ctx, entry.params);\n\n // Create new entry with potentially new result\n const newEntry: UndoEntry = {\n command: entry.command,\n params: entry.params,\n result,\n timestamp: Date.now(),\n };\n\n // Move entry back to undo stack\n storeApi.setState((state: TStore) => ({\n ...state,\n _commander: {\n undoStack: [...undoStack, newEntry],\n redoStack: newRedoStack,\n },\n }));\n\n return true;\n}\n\n/**\n * Creates a dispatch function for use during undo/redo operations.\n * This dispatch does NOT add to undo stack (to avoid infinite loops).\n */\nfunction createDispatchForUndo<TStore>(\n storeApi: StoreApi<TStore>\n): CommandDispatch<TStore> {\n return <TParams, TReturn>(command: Command<TStore, TParams, TReturn>) => {\n return (params: TParams): TReturn => {\n const ctx: CommandContext<TStore> = {\n getState: () => storeApi.getState(),\n setState: (partial) => storeApi.setState(partial as any),\n dispatch: createDispatchForUndo(storeApi),\n };\n\n // Execute without adding to undo stack\n return command.fn(ctx, params);\n };\n };\n}\n\n/**\n * Clear the undo and redo stacks.\n */\nexport function clearUndoHistory<TStore extends CommanderSlice>(\n storeApi: StoreApi<TStore>\n): void {\n storeApi.setState((state: TStore) => ({\n ...state,\n _commander: {\n undoStack: [],\n redoStack: [],\n },\n }));\n}\n\n","/**\n * @voidhash/mimic-react/zustand-commander\n *\n * React hooks for zustand-commander.\n *\n * @since 0.0.1\n */\n\nimport { useCallback, useEffect, useMemo } from \"react\";\nimport { useStore, type StoreApi, type UseBoundStore } from \"zustand\";\nimport { performRedo, performUndo, clearUndoHistory } from \"./commander\";\nimport {\n isUndoableCommand,\n type Command,\n type CommandContext,\n type CommandDispatch,\n type CommanderSlice,\n type ExtractState,\n} from \"./types.js\";\n\n// =============================================================================\n// useCommander Hook\n// =============================================================================\n\n/**\n * Creates a dispatch function for commands.\n * This is for use outside of React components (e.g., in command handlers).\n */\nfunction createDispatchFromApi<TStore extends CommanderSlice>(\n storeApi: StoreApi<TStore>,\n maxUndoStackSize = 100\n): CommandDispatch<TStore> {\n const dispatch: CommandDispatch<TStore> = <TParams, TReturn>(\n command: Command<TStore, TParams, TReturn>\n ) => {\n return (params: TParams): TReturn => {\n // Create context for the command\n const ctx: CommandContext<TStore> = {\n getState: () => storeApi.getState(),\n setState: (partial) => storeApi.setState(partial as Partial<TStore>),\n dispatch,\n };\n\n // Execute the command\n const result = command.fn(ctx, params);\n\n // If it's an undoable command, add to undo stack\n if (isUndoableCommand(command)) {\n storeApi.setState((state: TStore) => {\n const { undoStack } = state._commander;\n\n // Add to undo stack, respecting max size\n const newUndoStack = [\n ...undoStack,\n {\n command,\n params,\n result,\n timestamp: Date.now(),\n },\n ].slice(-maxUndoStackSize);\n\n // Clear redo stack when a new command is executed\n return {\n ...state,\n _commander: {\n undoStack: newUndoStack,\n redoStack: [],\n },\n } as TStore;\n });\n }\n\n return result;\n };\n };\n\n return dispatch;\n}\n\n/**\n * React hook to get a dispatch function for commands.\n * The dispatch function executes commands and manages undo/redo state.\n *\n * @example\n * ```tsx\n * const dispatch = useCommander(useStore);\n *\n * const handleClick = () => {\n * dispatch(addCard)({ columnId: \"col-1\", title: \"New Card\" });\n * };\n * ```\n */\nexport function useCommander<TStore extends CommanderSlice>(\n store: UseBoundStore<StoreApi<TStore>>\n): CommandDispatch<TStore> {\n // Get the store API\n const storeApi = useMemo(() => {\n // UseBoundStore has the StoreApi attached\n return store as unknown as StoreApi<TStore>;\n }, [store]);\n\n // Create a stable dispatch function\n const dispatch = useMemo(\n () => createDispatchFromApi<TStore>(storeApi),\n [storeApi]\n );\n\n return dispatch as CommandDispatch<TStore>;\n}\n\n// =============================================================================\n// useUndoRedo Hook\n// =============================================================================\n\n/**\n * State and actions for undo/redo functionality.\n */\nexport interface UndoRedoState {\n /** Whether there are actions that can be undone */\n readonly canUndo: boolean;\n /** Whether there are actions that can be redone */\n readonly canRedo: boolean;\n /** Number of items in the undo stack */\n readonly undoCount: number;\n /** Number of items in the redo stack */\n readonly redoCount: number;\n /** Undo the last action */\n readonly undo: () => boolean;\n /** Redo the last undone action */\n readonly redo: () => boolean;\n /** Clear the undo/redo history */\n readonly clear: () => void;\n}\n\n/**\n * React hook for undo/redo functionality.\n * Provides state (canUndo, canRedo) and actions (undo, redo, clear).\n *\n * @example\n * ```tsx\n * const { canUndo, canRedo, undo, redo } = useUndoRedo(useStore);\n *\n * return (\n * <>\n * <button onClick={undo} disabled={!canUndo}>Undo</button>\n * <button onClick={redo} disabled={!canRedo}>Redo</button>\n * </>\n * );\n * ```\n */\nexport function useUndoRedo<TStore extends CommanderSlice>(\n store: UseBoundStore<StoreApi<TStore>>\n): UndoRedoState {\n // Get the store API\n const storeApi = useMemo(() => {\n return store as unknown as StoreApi<TStore>;\n }, [store]);\n\n // Subscribe to commander state\n const commanderState = useStore(\n store,\n (state: TStore) => state._commander\n );\n\n const canUndo = commanderState.undoStack.length > 0;\n const canRedo = commanderState.redoStack.length > 0;\n const undoCount = commanderState.undoStack.length;\n const redoCount = commanderState.redoStack.length;\n\n const undo = useCallback(() => {\n return performUndo(storeApi);\n }, [storeApi]);\n\n const redo = useCallback(() => {\n return performRedo(storeApi);\n }, [storeApi]);\n\n const clear = useCallback(() => {\n clearUndoHistory(storeApi);\n }, [storeApi]);\n\n return {\n canUndo,\n canRedo,\n undoCount,\n redoCount,\n undo,\n redo,\n clear,\n };\n}\n\n// =============================================================================\n// Keyboard Shortcut Hook\n// =============================================================================\n\n/**\n * Options for the keyboard shortcut hook.\n */\nexport interface UseUndoRedoKeyboardOptions {\n /** Enable Ctrl/Cmd+Z for undo (default: true) */\n readonly enableUndo?: boolean;\n /** Enable Ctrl/Cmd+Shift+Z or Ctrl+Y for redo (default: true) */\n readonly enableRedo?: boolean;\n}\n\n/**\n * React hook that adds keyboard shortcuts for undo/redo.\n * Listens for Ctrl/Cmd+Z (undo) and Ctrl/Cmd+Shift+Z or Ctrl+Y (redo).\n *\n * @example\n * ```tsx\n * // In your app component\n * useUndoRedoKeyboard(useStore);\n * ```\n */\nexport function useUndoRedoKeyboard<TStore extends CommanderSlice>(\n store: UseBoundStore<StoreApi<TStore>>,\n options: UseUndoRedoKeyboardOptions = {}\n): void {\n const { enableUndo = true, enableRedo = true } = options;\n\n const storeApi = useMemo(() => {\n return store as unknown as StoreApi<TStore>;\n }, [store]);\n\n // Set up keyboard listener\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n const handleKeyDown = (event: KeyboardEvent) => {\n const isMac = navigator.platform.toUpperCase().indexOf(\"MAC\") >= 0;\n const modKey = isMac ? event.metaKey : event.ctrlKey;\n\n if (!modKey) return;\n\n // Undo: Ctrl/Cmd + Z (without Shift)\n if (enableUndo && event.key === \"z\" && !event.shiftKey) {\n event.preventDefault();\n performUndo(storeApi);\n return;\n }\n\n // Redo: Ctrl/Cmd + Shift + Z or Ctrl + Y\n if (enableRedo) {\n if ((event.key === \"z\" && event.shiftKey) || event.key === \"y\") {\n event.preventDefault();\n performRedo(storeApi);\n }\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => window.removeEventListener(\"keydown\", handleKeyDown);\n }, [storeApi, enableUndo, enableRedo]);\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,iBAAiB,OAAO,IAAI,4BAA4B;;;;AAKrE,MAAa,0BAA0B,OAAO,IAC5C,qCACD;;;;AA6QD,SAAgB,UAAU,OAAqC;AAC7D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,kBAAkB,SAClB,MAAM,oBAAoB;;;;;AAO9B,SAAgB,kBACd,OAC6B;AAC7B,QACE,UAAU,MAAM,IAChB,2BAA2B,SAC3B,MAAM,6BAA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BhD,SAlBc,eAAe,UAAU,SAAS;EAmBhD,WAlBgB,eAAe,UAAU;EAmBzC,WAlBgB,eAAe,UAAU;EAmBzC,MAjBW,kBAAkB;AAC7B,UAAO,YAAY,SAAS;KAC3B,CAAC,SAAS,CAAC;EAgBZ,MAdW,kBAAkB;AAC7B,UAAO,YAAY,SAAS;KAC3B,CAAC,SAAS,CAAC;EAaZ,OAXY,kBAAkB;AAC9B,oBAAiB,SAAS;KACzB,CAAC,SAAS,CAAC;EAUb;;;;;;;;;;;;AA2BH,SAAgB,oBACd,OACA,UAAsC,EAAE,EAClC;CACN,MAAM,EAAE,aAAa,MAAM,aAAa,SAAS;CAEjD,MAAM,WAAW,cAAc;AAC7B,SAAO;IACN,CAAC,MAAM,CAAC;AAGX,iBAAgB;AACd,MAAI,OAAO,WAAW,YACpB;EAGF,MAAM,iBAAiB,UAAyB;AAI9C,OAAI,EAHU,UAAU,SAAS,aAAa,CAAC,QAAQ,MAAM,IAAI,IAC1C,MAAM,UAAU,MAAM,SAEhC;AAGb,OAAI,cAAc,MAAM,QAAQ,OAAO,CAAC,MAAM,UAAU;AACtD,UAAM,gBAAgB;AACtB,gBAAY,SAAS;AACrB;;AAIF,OAAI,YACF;QAAK,MAAM,QAAQ,OAAO,MAAM,YAAa,MAAM,QAAQ,KAAK;AAC9D,WAAM,gBAAgB;AACtB,iBAAY,SAAS;;;;AAK3B,SAAO,iBAAiB,WAAW,cAAc;AACjD,eAAa,OAAO,oBAAoB,WAAW,cAAc;IAChE;EAAC;EAAU;EAAY;EAAW,CAAC"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@voidhash/mimic-react",
3
+ "version": "0.0.1-alpha.10",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/voidhashcom/mimic",
8
+ "directory": "packages/mimic-react"
9
+ },
10
+ "main": "./src/index.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.mjs",
14
+ "types": "./dist/index.d.mts",
15
+ "require": "./dist/index.cjs"
16
+ },
17
+ "./zustand": {
18
+ "import": "./dist/zustand/index.mjs",
19
+ "types": "./dist/zustand/index.d.mts",
20
+ "require": "./dist/zustand/index.cjs"
21
+ },
22
+ "./zustand-commander": {
23
+ "import": "./dist/zustand-commander/index.mjs",
24
+ "types": "./dist/zustand-commander/index.d.mts",
25
+ "require": "./dist/zustand-commander/index.cjs"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "zustand": "^5.0.9"
30
+ },
31
+ "devDependencies": {
32
+ "@effect/vitest": "^0.26.0",
33
+ "@types/react": "^19.0.0",
34
+ "effect": "^3.16.0",
35
+ "react": "^19.0.0",
36
+ "tsdown": "^0.18.2",
37
+ "typescript": "5.8.3",
38
+ "vite-tsconfig-paths": "^5.1.4",
39
+ "vitest": "^3.2.4",
40
+ "@voidhash/tsconfig": "0.0.1-alpha.10"
41
+ },
42
+ "peerDependencies": {
43
+ "effect": "^3.16.0",
44
+ "react": "^18.0.0 || ^19.0.0",
45
+ "@voidhash/mimic": "0.0.1-alpha.10"
46
+ },
47
+ "scripts": {
48
+ "build": "tsdown",
49
+ "lint": "biome check .",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "vitest run -c vitest.mts"
52
+ }
53
+ }
package/src/index.ts ADDED
File without changes
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @voidhash/mimic-react/zustand
3
+ *
4
+ * Zustand middleware for integrating mimic ClientDocument with reactive state.
5
+ *
6
+ * @since 0.0.1
7
+ */
8
+
9
+ // =============================================================================
10
+ // Middleware
11
+ // =============================================================================
12
+
13
+ export { mimic } from "./middleware.js";
14
+
15
+ // =============================================================================
16
+ // Types
17
+ // =============================================================================
18
+
19
+ export type {
20
+ MimicObject,
21
+ MimicSlice,
22
+ MimicMiddlewareOptions,
23
+ MimicStateCreator,
24
+ } from "./types.js";
@@ -0,0 +1,171 @@
1
+ import type { StateCreator, StoreMutatorIdentifier } from "zustand";
2
+ import type { ClientDocument } from "@voidhash/mimic/client";
3
+ import type { Primitive, Presence } from "@voidhash/mimic";
4
+ import type {
5
+ MimicSlice,
6
+ MimicObject,
7
+ MimicMiddlewareOptions,
8
+ } from "./types.js";
9
+
10
+ // =============================================================================
11
+ // Middleware Implementation
12
+ // =============================================================================
13
+
14
+ type MimicMiddleware = <
15
+ TSchema extends Primitive.AnyPrimitive,
16
+ TPresence extends Presence.AnyPresence | undefined = undefined,
17
+ T extends object = object,
18
+ Mps extends [StoreMutatorIdentifier, unknown][] = [],
19
+ Mcs extends [StoreMutatorIdentifier, unknown][] = [],
20
+ >(
21
+ document: ClientDocument.ClientDocument<TSchema, TPresence>,
22
+ config: StateCreator<T & MimicSlice<TSchema, TPresence>, Mps, Mcs, T>,
23
+ options?: MimicMiddlewareOptions
24
+ ) => StateCreator<T & MimicSlice<TSchema, TPresence>, Mps, Mcs, T & MimicSlice<TSchema, TPresence>>;
25
+
26
+ type MimicMiddlewareImpl = <
27
+ TSchema extends Primitive.AnyPrimitive,
28
+ TPresence extends Presence.AnyPresence | undefined = undefined,
29
+ T extends object = object,
30
+ >(
31
+ document: ClientDocument.ClientDocument<TSchema, TPresence>,
32
+ config: StateCreator<T & MimicSlice<TSchema, TPresence>, [], [], T>,
33
+ options?: MimicMiddlewareOptions
34
+ ) => StateCreator<T & MimicSlice<TSchema, TPresence>, [], [], T & MimicSlice<TSchema, TPresence>>;
35
+
36
+ /**
37
+ * Creates a MimicObject from the current document state.
38
+ */
39
+ const createMimicObject = <
40
+ TSchema extends Primitive.AnyPrimitive,
41
+ TPresence extends Presence.AnyPresence | undefined = undefined
42
+ >(
43
+ document: ClientDocument.ClientDocument<TSchema, TPresence>
44
+ ): MimicObject<TSchema, TPresence> => {
45
+ const presence = document.presence
46
+ ? {
47
+ selfId: document.presence.selfId(),
48
+ self: document.presence.self(),
49
+ // Important: clone Maps to ensure zustand selectors re-render
50
+ // when presence changes (the underlying ClientDocument mutates Maps in-place).
51
+ others: new Map(document.presence.others()),
52
+ all: new Map(document.presence.all()),
53
+ }
54
+ : undefined;
55
+
56
+ return {
57
+ document,
58
+ snapshot: document.root.toSnapshot() as Primitive.InferSnapshot<TSchema>,
59
+ presence: presence as MimicObject<TSchema, TPresence>["presence"],
60
+ isConnected: document.isConnected(),
61
+ isReady: document.isReady(),
62
+ pendingCount: document.getPendingCount(),
63
+ hasPendingChanges: document.hasPendingChanges(),
64
+ };
65
+ };
66
+
67
+ /**
68
+ * Implementation of the mimic middleware.
69
+ */
70
+ const mimicImpl: MimicMiddlewareImpl = <
71
+ TSchema extends Primitive.AnyPrimitive,
72
+ TPresence extends Presence.AnyPresence | undefined = undefined,
73
+ _T extends object = object
74
+ >(
75
+ document: ClientDocument.ClientDocument<TSchema, TPresence>,
76
+ config: any,
77
+ options: MimicMiddlewareOptions = {}
78
+ ) => {
79
+ const { autoSubscribe = true, autoConnect = true } = options;
80
+
81
+ return (set: any, get: any, api: any) => {
82
+ // Create initial mimic slice
83
+ const initialMimic = createMimicObject(document);
84
+
85
+ // Helper to update mimic state
86
+ const updateMimicState = () => {
87
+ const newMimic = createMimicObject(document);
88
+ set(
89
+ (state: any) => ({
90
+ ...state,
91
+ mimic: newMimic,
92
+ }),
93
+ false
94
+ );
95
+ };
96
+
97
+ // Subscribe to document changes
98
+ if (autoSubscribe) {
99
+ document.subscribe({
100
+ onStateChange: () => {
101
+ updateMimicState();
102
+ },
103
+ onConnectionChange: () => {
104
+ updateMimicState();
105
+ },
106
+ onReady: () => {
107
+ updateMimicState();
108
+ },
109
+ });
110
+
111
+ // Subscribe to presence changes (if presence schema is enabled)
112
+ document.presence?.subscribe({
113
+ onPresenceChange: () => {
114
+ updateMimicState();
115
+ },
116
+ });
117
+ }
118
+
119
+ if (autoConnect) {
120
+ document.connect();
121
+ }
122
+
123
+ // Get user's state - pass through set/get/api directly
124
+ // The user's set calls won't affect mimic state since we update it separately
125
+ const userState = config(set, get, api);
126
+
127
+ // Combine user state with mimic slice
128
+ return {
129
+ ...userState,
130
+ mimic: initialMimic,
131
+ };
132
+ };
133
+ };
134
+
135
+ /**
136
+ * Zustand middleware that integrates a ClientDocument.
137
+ *
138
+ * Adds a `mimic` object to the store containing:
139
+ * - `document`: The ClientDocument instance for performing transactions
140
+ * - `snapshot`: Read-only snapshot of the document state (reactive)
141
+ * - `presence`: Reactive presence snapshot (self + others). Undefined if presence is not enabled on the ClientDocument.
142
+ * - `isConnected`: Connection status
143
+ * - `isReady`: Ready status
144
+ * - `pendingCount`: Number of pending transactions
145
+ * - `hasPendingChanges`: Whether there are pending changes
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * import { create } from 'zustand'
150
+ * import { mimic } from '@voidhash/mimic-react/zustand'
151
+ *
152
+ * const useStore = create(
153
+ * mimic(clientDocument, (set, get) => ({
154
+ * // Your additional store state
155
+ * }))
156
+ * )
157
+ *
158
+ * // Read snapshot (reactive)
159
+ * const snapshot = useStore(state => state.mimic.snapshot)
160
+ *
161
+ * // Read presence (reactive, if enabled)
162
+ * const myPresence = useStore(state => state.mimic.presence?.self)
163
+ * const othersPresence = useStore(state => state.mimic.presence?.others)
164
+ *
165
+ * // Write via document
166
+ * store.getState().mimic.document.transaction(root => {
167
+ * root.name.set("New Name")
168
+ * })
169
+ * ```
170
+ */
171
+ export const mimic = mimicImpl as unknown as MimicMiddleware;
@@ -0,0 +1,117 @@
1
+ import type { StateCreator, StoreMutatorIdentifier } from "zustand";
2
+ import type { ClientDocument } from "@voidhash/mimic/client";
3
+ import type { Primitive, Presence } from "@voidhash/mimic";
4
+
5
+ // =============================================================================
6
+ // Mimic State Types
7
+ // =============================================================================
8
+
9
+ /**
10
+ * Presence data exposed on the zustand store (reactive snapshot).
11
+ */
12
+ export interface MimicPresence<TPresence extends Presence.AnyPresence> {
13
+ /**
14
+ * This client's connection ID (set after receiving presence snapshot).
15
+ * Undefined before the snapshot is received.
16
+ */
17
+ readonly selfId: string | undefined;
18
+
19
+ /**
20
+ * This client's current presence data.
21
+ * Undefined if not set.
22
+ */
23
+ readonly self: Presence.Infer<TPresence> | undefined;
24
+
25
+ /**
26
+ * Other clients' presence entries (connectionId -> entry).
27
+ */
28
+ readonly others: ReadonlyMap<
29
+ string,
30
+ Presence.PresenceEntry<Presence.Infer<TPresence>>
31
+ >;
32
+
33
+ /**
34
+ * All presence entries including self (connectionId -> entry).
35
+ */
36
+ readonly all: ReadonlyMap<
37
+ string,
38
+ Presence.PresenceEntry<Presence.Infer<TPresence>>
39
+ >;
40
+ }
41
+
42
+ /**
43
+ * The mimic object containing the document and client state.
44
+ * This is added to the zustand store by the middleware.
45
+ */
46
+ export interface MimicObject<
47
+ TSchema extends Primitive.AnyPrimitive,
48
+ TPresence extends Presence.AnyPresence | undefined = undefined
49
+ > {
50
+ /** The ClientDocument instance for performing transactions */
51
+ readonly document: ClientDocument.ClientDocument<TSchema, TPresence>;
52
+ /** Read-only snapshot of the document state */
53
+ readonly snapshot: Primitive.InferSnapshot<TSchema>;
54
+ /**
55
+ * Reactive presence snapshot (self + others).
56
+ * Undefined when the ClientDocument was created without a presence schema.
57
+ */
58
+ readonly presence: TPresence extends Presence.AnyPresence
59
+ ? MimicPresence<TPresence>
60
+ : undefined;
61
+ /** Whether the client is connected to the server */
62
+ readonly isConnected: boolean;
63
+ /** Whether the client is fully initialized and ready */
64
+ readonly isReady: boolean;
65
+ /** Number of pending transactions */
66
+ readonly pendingCount: number;
67
+ /** Whether there are pending changes */
68
+ readonly hasPendingChanges: boolean;
69
+ }
70
+
71
+ /**
72
+ * The state slice added by the mimic middleware.
73
+ */
74
+ export interface MimicSlice<
75
+ TSchema extends Primitive.AnyPrimitive,
76
+ TPresence extends Presence.AnyPresence | undefined = undefined
77
+ > {
78
+ /** The mimic object containing document and state */
79
+ readonly mimic: MimicObject<TSchema, TPresence>;
80
+ }
81
+
82
+ // =============================================================================
83
+ // Middleware Types
84
+ // =============================================================================
85
+
86
+ /**
87
+ * Type for the mimic middleware mutator.
88
+ */
89
+ export type MimicMutator<
90
+ TSchema extends Primitive.AnyPrimitive,
91
+ TPresence extends Presence.AnyPresence | undefined = undefined
92
+ > = [
93
+ "mimic",
94
+ TSchema,
95
+ TPresence
96
+ ];
97
+
98
+ /**
99
+ * Type for state creator with mimic slice merged.
100
+ */
101
+ export type MimicStateCreator<
102
+ TSchema extends Primitive.AnyPrimitive,
103
+ TPresence extends Presence.AnyPresence | undefined,
104
+ T,
105
+ Mps extends [StoreMutatorIdentifier, unknown][] = [],
106
+ Mcs extends [StoreMutatorIdentifier, unknown][] = [],
107
+ > = StateCreator<T & MimicSlice<TSchema, TPresence>, Mps, Mcs, T>;
108
+
109
+ /**
110
+ * Options for the mimic middleware.
111
+ */
112
+ export interface MimicMiddlewareOptions {
113
+ /** If true, automatically subscribe when store is created (default: true) */
114
+ readonly autoSubscribe?: boolean;
115
+ /** If true, automatically attempt to connect the document to the remote server */
116
+ readonly autoConnect?: boolean;
117
+ }