Communitygithub.com

lobehub/store-data-structures

Padrões de estrutura de dados para stores Zustand do LobeHub. Use ao projetar estado de store, divisões lista/detalhe, mapas normalizados, reducers, messagesMap, topicsMap, ou ao escolher fontes de tipos compartilhadas.

O que é store-data-structures?

Este skill fornece padrões reutilizáveis de estrutura de dados para stores Zustand utilizadas no ecossistema LobeHub. Ele define convenções para modelar estados de store, incluindo divisões entre views de lista e detalhe, mapas normalizados para entidades, reducers para atualizações imutáveis, bem como estruturas especializadas como `messagesMap` e `topicsMap` para gerenciar mensagens e tópicos. O principal objetivo é ajudar desenvolvedores a manter consistência e previsibilidade no design de estado, evitando duplicação e facilitando a manutenção. Ele funciona orientando a escolha entre fontes de tipos compartilhadas e promovendo patterns como normalização de dados e reducers, suportando plataformas baseadas em React e Zustand, como aplicações LobeHub.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lobehub/lobehub/tree/main/skills/store-data-structures

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

O que store-data-structures faz?

Padrões de estrutura de dados para stores Zustand do LobeHub. Use ao projetar estado de store, divisões lista/detalhe, mapas normalizados, reducers, messagesMap, topicsMap, ou ao escolher fontes de tipos compartilhadas.

Visão Geral

Este repositório contém padrões e convenções para modelar dados em stores Zustand dentro do ecossistema LobeHub. Ele fornece uma abordagem consistente para gerenciar estado, garantindo que as estruturas de dados sejam previsíveis, fáceis de manter e escaláveis.

Padrões Principais

Divisões Lista/Detalhe

Para gerenciar views de lista e detalhe, use um mapa normalizado para entidades e um array de IDs para a ordem da lista. Isso permite acesso rápido a entidades individuais e iteração eficiente sobre a lista.

interface StoreState {
  entities: Record<string, Entity>;
  listIds: string[];
  selectedId: string | null;
}

Mapas Normalizados

Use mapas normalizados (Record<string, Entity>) para armazenar entidades. Isso evita duplicação e facilita atualizações.

interface NormalizedStore<T> {
  byId: Record<string, T>;
  allIds: string[];
}

Reducers

Implemente reducers como funções puras para atualizar o estado de forma imutável. Use um padrão de ação para acionar mudanças.

type Action =
  | { type: 'ADD_ENTITY'; payload: Entity }
  | { type: 'REMOVE_ENTITY'; payload: string };

function reducer(state: StoreState, action: Action): StoreState {
  switch (action.type) {
    case 'ADD_ENTITY':
      return {
        ...state,
        entities: { ...state.entities, [action.payload.id]: action.payload },
        listIds: [...state.listIds, action.payload.id],
      };
    case 'REMOVE_ENTITY':
      const { [action.payload]: _, ...rest } = state.entities;
      return {
        ...state,
        entities: rest,
        listIds: state.listIds.filter(id => id !== action.payload),
      };
    default:
      return state;
  }
}

MessagesMap e TopicsMap

Para gerenciar mensagens e tópicos, use estruturas dedicadas:

interface MessagesMap {
  byId: Record<string, Message>;
  byTopic: Record<string, string[]>; // topicId -> messageIds
}

interface TopicsMap {
  byId: Record<string, Topic>;
  byParent: Record<string, string[]>; // parentTopicId -> topicIds
}

Fontes de Tipos Compartilhadas

Defina tipos compartilhados em um arquivo central, como types.ts, e importe-os conforme necessário. Isso garante consistência e facilita refatorações.

Plataformas Suportadas

  • Aplicações baseadas em React
  • Zustand (gerenciamento de estado)
  • Ecossistema LobeHub

Como Usar

  1. Escolha um pattern com base na complexidade dos dados.
  2. Defina os tipos no arquivo de tipos compartilhados.
  3. Implemente a store usando Zustand, seguindo os patterns acima.
  4. Use os reducers para gerenciar mutações de estado.

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

lobehub/add-provider-doc

Add documentation for a new AI provider — usage docs, env vars, Docker config, image resources.

lobehub/add-setting-env

Add server-side environment variables that control default values for user settings.

lobehub/debug

Debug package usage guide. Use when adding debug logging, understanding log namespaces, or implementing debugging features. Triggers on debug logging requests or logging implementation.

lobehub/desktop

Electron desktop development guide — IPC handlers, controllers, preload scripts, window/menu management.

lobehub/drizzle

LobeHub Drizzle ORM schema and query style. Use for pgTable schemas, indexes, joins, inferred types, db.select/db.query, schema fields, foreign keys, junction tables, or postgres query patterns.

lobehub/hotkey

Add or edit LobeHub keyboard shortcuts. Use for HotkeyEnum, HOTKEYS_REGISTRATION, combineKeys, useHotkeyById, tooltip hotkeys, shortcut scope, conflicts, or Cmd/Ctrl key combos.

lobehub/i18n

LobeHub i18n with react-i18next. Use for user-facing strings, locale keys, namespaces, useTranslation, t(), interpolation, zh-CN/en-US previews, hardcoded UI copy, or pnpm i18n.

lobehub/linear

Linear issue management. Use for LOBE-xxx issues, Linear links, PRs referencing Linear, retrieving issues, updating status, completion comments, or sub-issue trees.

lobehub/lobehub

Use for public LobeHub website documentation under docs/**, including self-hosting, deployment, migration, and configuration guides. Excludes product changelogs and source-code API docs.

lobehub/microcopy

UI copy and microcopy guidelines. Use for user-facing copy, buttons, errors, empty states, onboarding, i18n wording, translation, or copy improvements in Chinese or English.

lobehub/modal

LobeHub imperative modal conventions. Use when creating or migrating modals, dialogs, popups, confirm flows, ModalHost wiring, createModal, confirmModal, useModalContext, or base-ui modal APIs.

lobehub/pr

Create a PR for the current branch (targets `canary` by default), including splitting one cross-layer branch into ordered stacked PRs so a lower layer (db / shared package / server TRPC) merges before its callers (desktop / CLI / UI). Use when the user asks to create / submit a PR, or to split a branch because clients call a server contract that isn't on the trunk yet. Triggers on 'pr', 'create pr', 'submit pr', 'open a PR', 'pull request', 'split this PR', 'stacked PR', 'backend should merge first', '提 PR', '提个 PR', '新建 PR', '拆 PR', '后端先合', '分层合并'.

lobehub/project-overview

LobeHub open-source monorepo architecture map. Use when locating code layers, understanding apps/packages/src layout, business stubs, project structure, or onboarding to the repository.

lobehub/react

LobeHub React component conventions. Use when editing TSX UI, choosing base-ui vs @lobehub/ui vs antd, styling with antd-style, routing, desktop variants, layouts, or component state.

lobehub/testing

Vitest testing guide. Use when writing or updating tests, fixing failing tests, improving coverage, debugging test issues, or setting up mocks.

lobehub/typescript

LobeHub TypeScript style and type-safety guide. Use when editing TS/TSX/MTS, fixing types, choosing interface vs type, avoiding any/object, import type, async flow, or ts-expect-error.

lobehub/upstash-workflow

LobeHub Upstash Workflow and QStash guide. Use for async workflows, process/paginate/execute fan-out, serve handlers, context.run/call/sleep, or workflow triggers.

lobehub/version-release

Version release workflow — release process and GitHub Release notes (not docs/changelog pages).

lobehub/zustand

LobeHub Zustand store conventions. Use when editing src/store, store slices, public/internal actions, dispatch actions, flattenActions, optimistic updates, selectors, maps, or class action migration.

Habilidades Relacionadas