zustand-store-scaffold

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zustand Store Scaffold

Zustand Store 脚手架

Generate type-safe class-based Zustand stores with
flattenActions
for prototype-safe slice composition.
使用
flattenActions
生成类型安全的基于类的Zustand store,实现原型安全的切片组合。

Quick Start

快速开始

Web Pattern (Component-level Store)

Web模式(组件级Store)

bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern web \
  --name ToolList \
  --path web/src/pages/_components/ToolList/store
Generates:
  • types.ts
    StoreSetter<T>
    type definition
  • utils/flattenActions.ts
    — Prototype-safe action flattener
  • index.ts
    — Class-based store with
    ActionImpl
    +
    flattenActions
  • context.ts
    — React Context and typed
    useContext
    hook
  • provider.tsx
    — Memo-wrapped Provider component
bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern web \
  --name ToolList \
  --path web/src/pages/_components/ToolList/store
生成文件:
  • types.ts
    StoreSetter<T>
    类型定义
  • utils/flattenActions.ts
    — 原型安全的操作扁平化工具
  • index.ts
    — 结合
    ActionImpl
    flattenActions
    的基于类的store
  • context.ts
    — React Context及类型化
    useContext
    钩子
  • provider.tsx
    — 经过Memo包装的Provider组件

Core Pattern (Slice-based Store)

Core模式(切片式Store)

Single Slice:
bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name CoreAgent \
  --path packages/ag-ui-view/src/core/helpers/isomorphic/store
Multiple Slices (Interactive):
bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name AppStore \
  --path src/store
单切片:
bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name CoreAgent \
  --path packages/ag-ui-view/src/core/helpers/isomorphic/store
多切片(交互式):
bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name AppStore \
  --path src/store

Will prompt: Enter slice names (comma-separated, or press Enter for 'core'):

会提示:输入切片名称(逗号分隔,或按Enter使用默认值'core'):

Example input: auth,user,ui

示例输入: auth,user,ui


**Multiple Slices (Direct):**

```bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name AppStore \
  --path src/store \
  --slices auth,user,ui
Generates:
  • types.ts
    StoreSetter<T>
    type definition
  • utils/flattenActions.ts
    — Prototype-safe action flattener
  • index.ts
    — Store factory with
    flattenActions
    slice composition
  • slices/[name].ts
    — Class-based slice with
    ActionImpl
    +
    #private
    fields

**多切片(直接指定):**

```bash
python3 ~/.claude/skills/zustand-store-scaffold/scripts/scaffold_zustand_store.py \
  --pattern core \
  --name AppStore \
  --path src/store \
  --slices auth,user,ui
生成文件:
  • types.ts
    StoreSetter<T>
    类型定义
  • utils/flattenActions.ts
    — 原型安全的操作扁平化工具
  • index.ts
    — 结合
    flattenActions
    切片组合的Store工厂
  • slices/[name].ts
    — 包含
    ActionImpl
    #private
    字段的基于类的切片

Options

选项说明

OptionRequiredDescriptionExample
--pattern
YesStore pattern (
web
or
core
)
--pattern web
--name
YesStore name in PascalCase
--name ToolList
--path
YesTarget directory path
--path src/store
--slices
NoComma-separated slice names (core only)
--slices auth,user,ui
--force
NoOverwrite existing files
--force
Note: For
core
pattern without
--slices
, the script interactively asks for slice names. Shared files (
types.ts
,
utils/flattenActions.ts
) are skipped if they already exist (unless
--force
).
选项是否必填描述示例
--pattern
Store模式(
web
core
--pattern web
--name
采用大驼峰命名的Store名称
--name ToolList
--path
目标目录路径
--path src/store
--slices
逗号分隔的切片名称(仅core模式可用)
--slices auth,user,ui
--force
覆盖已存在的文件
--force
注意: 对于未指定
--slices
的core模式,脚本会交互式询问切片名称。共享文件(
types.ts
utils/flattenActions.ts
)若已存在则会跳过(除非使用
--force
)。

Choose the Right Pattern

选择合适的模式

PatternUse WhenLocation PatternSlices
webComponent-level state with Provider
web/src/pages/_components/**/store
N/A
coreIsomorphic/shared state with slices
packages/**/store
Single or multiple
模式使用场景路径模式切片支持
web需要Provider的组件级状态
web/src/pages/_components/**/store
不支持
core同构/共享状态,支持切片
packages/**/store
单切片或多切片

When to Use Multiple Slices (Core Pattern)

何时使用多切片(Core模式)

Use multiple slices to organize complex state by feature domains:
ScenarioRecommended Slices
Authentication app
auth, user, session
E-commerce store
cart, products, user, ui
Dashboard
data, filters, ui, settings
Chat application
messages, contacts, ui, notifications
使用多切片可按功能领域组织复杂状态:
场景推荐切片
认证应用
auth, user, session
电商商城
cart, products, user, ui
数据看板
data, filters, ui, settings
聊天应用
messages, contacts, ui, notifications

Generated Files

生成文件说明

FilePurpose
types.ts
StoreSetter<T>
— type-safe overloaded setter matching Zustand internals
utils/flattenActions.ts
flattenActions<T>
— walks prototype chain, binds methods, merges class instances
index.ts
Store factory combining initial state +
flattenActions
composition
slices/*.ts
(core)
*ActionImpl
class with
#set
/
#get
, exported via
create*Slice
context.ts
(web)
React Context + typed selector hook
provider.tsx
(web)
Memo-wrapped Provider with ref-stable store creation
文件用途
types.ts
StoreSetter<T>
— 与Zustand内部匹配的类型安全重载setter
utils/flattenActions.ts
flattenActions<T>
— 遍历原型链、绑定方法、合并类实例
index.ts
结合初始状态与
flattenActions
组合的Store工厂
slices/*.ts
(core模式)
*ActionImpl
类,包含
#set
/
#get
,通过
create*Slice
导出
context.ts
(web模式)
React Context + 类型化选择器钩子
provider.tsx
(web模式)
经过Memo包装的Provider,创建引用稳定的store

Post-Generation Steps

生成后步骤

  1. Define state in
    *SliceState
    interface (core) or
    *StoreState
    interface (web):
    ts
    export interface CoreSliceState {
      agents: Agent[]
      selectedId: string | null
    }
  2. Add action methods as arrow functions in
    *ActionImpl
    class:
    ts
    export class CoreActionImpl {
      readonly #set: StoreSetter<CoreSlice>
      readonly #get: () => CoreSlice
      // ...constructor
    
      selectAgent = (id: string): void => {
        this.#set({ selectedId: id })
      }
    
      getSelectedAgent = (): Agent | undefined => {
        const { agents, selectedId } = this.#get()
        return agents.find((a) => a.id === selectedId)
      }
    }
  3. Set initial state in the store factory or config:
    ts
    const store = createCoreAgentStore({
      initialState: { agents: [], selectedId: null }
    })
  1. 定义状态
    *SliceState
    接口(core模式)或
    *StoreState
    接口(web模式)中:
    ts
    export interface CoreSliceState {
      agents: Agent[]
      selectedId: string | null
    }
  2. 添加操作方法
    *ActionImpl
    类中添加箭头函数:
    ts
    export class CoreActionImpl {
      readonly #set: StoreSetter<CoreSlice>
      readonly #get: () => CoreSlice
      // ...构造函数
    
      selectAgent = (id: string): void => {
        this.#set({ selectedId: id })
      }
    
      getSelectedAgent = (): Agent | undefined => {
        const { agents, selectedId } = this.#get()
        return agents.find((a) => a.id === selectedId)
      }
    }
  3. 设置初始状态 在Store工厂或配置中:
    ts
    const store = createCoreAgentStore({
      initialState: { agents: [], selectedId: null }
    })

Usage Examples

使用示例

Web Store Usage

Web Store 使用方式

tsx
import Provider from './store/provider'
import { useToolListContext } from './store/context'

function ToolListPage() {
  return (
    <Provider>
      <ToolListContent />
    </Provider>
  )
}

function ToolListContent() {
  const toolList = useToolListContext((s) => s.toolList)
  const setToolList = useToolListContext((s) => s.setToolList)
  // Go to Definition on setToolList → lands directly on ActionImpl method
}
tsx
import Provider from './store/provider'
import { useToolListContext } from './store/context'

function ToolListPage() {
  return (
    <Provider>
      <ToolListContent />
    </Provider>
  )
}

function ToolListContent() {
  const toolList = useToolListContext((s) => s.toolList)
  const setToolList = useToolListContext((s) => s.setToolList)
  // 对setToolList执行跳转定义 → 直接定位到ActionImpl方法
}

Core Store Usage

Core Store 使用方式

ts
import { createCoreAgentStore } from './store'

const store = createCoreAgentStore({
  initialState: { agents: [], selectedId: null }
})

// Vanilla JS
const state = store.getState()
state.selectAgent('agent-1')

// React (with useStore)
import { useStore } from 'zustand'

function AgentList() {
  const agents = useStore(store, (s) => s.agents)
  const selectAgent = useStore(store, (s) => s.selectAgent)
}
ts
import { createCoreAgentStore } from './store'

const store = createCoreAgentStore({
  initialState: { agents: [], selectedId: null }
})

// 原生JS使用
const state = store.getState()
state.selectAgent('agent-1')

// React中使用(结合useStore)
import { useStore } from 'zustand'

function AgentList() {
  const agents = useStore(store, (s) => s.agents)
  const selectAgent = useStore(store, (s) => s.selectAgent)
}

References

参考资料

  • See
    references/class-based-pattern.md
    for detailed pattern documentation
  • See
    references/store-patterns.md
    for complete code examples
  • Reference PR: lobehub#12081
  • 查看
    references/class-based-pattern.md
    获取详细的模式文档
  • 查看
    references/store-patterns.md
    获取完整的代码示例
  • 参考PR: lobehub#12081