### Run Development Server with Bun
Source: https://github.com/codebelt/classy-store/blob/main/examples/nextjs/README.md
This command initiates the Next.js development server using the Bun runtime. It's the primary way to start the application and view the example in a browser.
```bash
bun dev
```
--------------------------------
### Combining withHistory with persist Utility
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Demonstrates how to use `withHistory` alongside the `persist` utility. This setup allows for in-memory undo/redo functionality while persisting the latest state of the store, for example, to localStorage, surviving page reloads.
```typescript
import {persist, withHistory} from '@codebelt/classy-store/utils';
const todoStore = createClassyStore(new TodoStore());
// Persist to localStorage (survives page reload)
persist(todoStore, { name: 'todos' });
// Undo/redo in memory (resets on page reload)
const history = withHistory(todoStore);
```
--------------------------------
### Install @codebelt/classy-store
Source: https://github.com/codebelt/classy-store/blob/main/README.md
Instructions for installing the @codebelt/classy-store package using npm or bun.
```bash
npm install @codebelt/classy-store
# or
bun add @codebelt/classy-store
```
--------------------------------
### Complete Classy Store Example with Persistence and Migration (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/PERSIST_TUTORIAL.md
This example demonstrates creating a Classy Store, persisting its state using custom serialization for dates, and implementing schema migration for versioning. It shows how to initialize the store, set up persistence options, and wait for hydration before interacting with the store.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
import {persist} from '@codebelt/classy-store/utils';
class AppStore {
theme: 'light' | 'dark' = 'light';
language = 'en';
lastLogin = new Date(0);
setTheme(theme: 'light' | 'dark') {
this.theme = theme;
}
}
const appStore = createClassyStore(new AppStore());
const handle = persist(appStore, {
name: 'app-store',
version: 1,
debounce: 300,
properties: [
'theme',
'language',
{
key: 'lastLogin',
serialize: (date) => date.toISOString(),
deserialize: (stored) => new Date(stored as string),
},
],
migrate: (state, oldVersion) => {
if (oldVersion === 0) {
// v0 didn't have language
return {...state, language: 'en'};
}
return state;
},
});
// Wait for hydration, then start the app
await handle.hydrated;
console.log(`Welcome back! Theme: ${appStore.theme}`);
```
--------------------------------
### Install Classy Store
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/index.md
Installs the Classy Store package using Bun. This command adds the necessary library to your project's dependencies.
```bash
bun add @codebelt/classy-store
```
--------------------------------
### Install Classy Store for Solid
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Installs the @codebelt/classy-store package and SolidJS as peer dependencies for Solid integration.
```bash
npm install @codebelt/classy-store solid-js
```
--------------------------------
### Creating a Classy Store Instance
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Demonstrates the initial setup for Classy Store. It shows how to define a state class (`Counter`) and then create a store instance using `createClassyStore` from the `@codebelt/classy-store` library.
```typescript
// stores.ts
import {createClassyStore} from '@codebelt/classy-store';
class Counter {
count = 0;
increment() {
this.count++;
}
}
export const counterStore = createClassyStore(new Counter());
```
--------------------------------
### Structural Sharing Example
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/ARCHITECTURE.md
Demonstrates how Classy-Store maintains structural sharing between snapshots. When a sub-tree remains unchanged, its reference is preserved across snapshots, leading to cache hits.
```text
Snapshot v1: Snapshot v2 (after user.name = 'Bob'):
┌──────────┐ ┌──────────┐
│ root │ │ root │ (new object)
│ user ────┼──→ {name:'Alice'} │ user ────┼──→ {name:'Bob'} (new)
│ settings─┼──→ {theme:'dark'} │ settings─┼──→ {theme:'dark'} (SAME ref ===)
└──────────┘ └──────────┘
`snap2.settings === snap1.settings` because the `settings` sub-tree's version didn't change → cache hit → same reference.
```
--------------------------------
### Text Editor with Undo/Redo Example (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
A practical use case demonstrating how to integrate `withHistory` into a text editor store. It includes handling keyboard events for undo (Ctrl+Z) and redo (Ctrl+Shift+Z) actions.
```typescript
class EditorStore {
content = '';
cursorPosition = 0;
type(text: string) {
this.content =
this.content.slice(0, this.cursorPosition) +
text +
this.content.slice(this.cursorPosition);
this.cursorPosition += text.length;
}
backspace() {
if (this.cursorPosition === 0) return;
this.content =
this.content.slice(0, this.cursorPosition - 1) +
this.content.slice(this.cursorPosition);
this.cursorPosition--;
}
}
const editorStore = createClassyStore(new EditorStore());
const history = withHistory(editorStore, { limit: 200 });
// Cmd+Z / Ctrl+Z
document.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'z') {
e.preventDefault();
if (e.shiftKey) {
history.redo();
} else {
history.undo();
}
}
});
```
--------------------------------
### Version Propagation Example (Mermaid)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/ARCHITECTURE.md
Visualizes how version numbers are propagated upwards from a mutated nested property to the root of the store. This mechanism is crucial for enabling structural sharing in immutable snapshots.
```mermaid
graph TD
Root["Root (v=10 → v=13)"] --> User["user (v=11 → v=12)"]
Root --> Settings["settings (v=5, unchanged)"]
User --> Name["name = 'Bob' (mutation here, v=12)"]
User --> Age["age = 30 (unchanged)"]
```
--------------------------------
### Build and Test Commands
Source: https://github.com/codebelt/classy-store/blob/main/CLAUDE.md
Provides a comprehensive list of commands for managing the monorepo, including dependency installation, building packages, running tests, linting, type checking, and serving documentation.
```bash
# Install all workspace dependencies
bun install
# Build all packages
bun run build
# Run all tests
bun run test
# Start Docusaurus dev server
bun run docs:dev
```
--------------------------------
### Vue 3 Store Class Example
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Demonstrates defining a store using a class and integrating it with the `useStore` hook in Vue 3. It shows how to access reactive state and call actions.
```typescript
// stores.ts
import { createClassyStore } from '@codebelt/classy-store';
class CounterStore {
count = 0;
get doubled() { return this.count * 2; }
increment() { this.count++; }
}
export const counterStore = createClassyStore(new CounterStore());
```
```vue
```
--------------------------------
### Install Classy Store for Vue
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Installs the @codebelt/classy-store package and Vue as peer dependencies for Vue 3 integration.
```bash
npm install @codebelt/classy-store vue
```
--------------------------------
### Perform Undo and Redo Operations (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Illustrates how to use the `undo()` and `redo()` methods provided by the `history` handle returned by `withHistory`. This example shows changing store state and then reverting or reapplying those changes.
```typescript
drawingStore.setColor('#ff0000');
drawingStore.setStrokeWidth(5);
// history: [initial, {color: '#ff0000'}, {strokeWidth: 5}]
history.undo();
// strokeWidth is back to 2
history.undo();
// color is back to '#000000'
history.redo();
// color is '#ff0000' again
```
--------------------------------
### Install Classy Store for Svelte
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Installs the @codebelt/classy-store package and Svelte as peer dependencies for Svelte integration.
```bash
npm install @codebelt/classy-store svelte
```
--------------------------------
### Reacting to Auth State Changes with subscribeKey
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/SUBSCRIBE_KEY_TUTORIAL.md
Illustrates using subscribeKey to react to changes in authentication token. This example redirects the user to the dashboard upon login and to the login page upon logout.
```typescript
class AuthStore {
token: string | null = null;
user: { name: string; role: string } | null = null;
login(token: string, user: { name: string; role: string }) {
this.token = token;
this.user = user;
}
logout() {
this.token = null;
this.user = null;
}
}
const authStore = createClassyStore(new AuthStore());
// Redirect on login/logout
subscribeKey(authStore, 'token', (token, previousToken) => {
if (token && !previousToken) {
router.push('/dashboard');
} else if (!token && previousToken) {
router.push('/login');
}
});
```
--------------------------------
### Define and Use a Classy Store
Source: https://github.com/codebelt/classy-store/blob/main/README.md
This example demonstrates how to define a state management class with computed properties and methods, then create a store instance and use it within a React component. It highlights the automatic memoization of getters and the simplified hook-based integration.
```typescript
class CartStore {
items: { name: string; price: number; qty: number }[] = [];
get total() {
return this.items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
add(name: string, price: number) {
this.items.push({ name, price, qty: 1 });
}
}
const cartStore = createClassyStore(new CartStore());
function CartTotal() {
const total = useStore(cartStore, (store) => store.total);
return ${total.toFixed(2)};
}
function AddButton() {
return ;
}
```
--------------------------------
### Implement Undo/Redo Buttons with React Hooks (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Provides a React component example using the `useStore` hook to access the store's state and the `history` handle to trigger undo/redo actions. Buttons are disabled based on `history.canUndo` and `history.canRedo`.
```typescript
import { useStore } from '@codebelt/classy-store';
function UndoRedoButtons() {
const snap = useStore(drawingStore);
return (
);
}
```
--------------------------------
### Create a Classy Store Instance (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/PERSIST_TUTORIAL.md
This snippet demonstrates how to define a store class and create an instance of it using `createClassyStore` from the `@codebelt/classy-store` library. It includes example properties and methods for a typical store.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
class TodoStore {
filter: 'all' | 'active' | 'done' = 'all';
todos: {text: string; done: boolean}[] = [];
get remaining() {
return this.todos.filter((todo) => !todo.done).length;
}
addTodo(text: string) {
this.todos.push({text, done: false});
}
toggle(index: number) {
this.todos[index].done = !this.todos[index]!.done;
}
}
export const todoStore = createClassyStore(new TodoStore());
```
--------------------------------
### Define and Persist a Classy Store
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Shows the basic setup for creating a Classy Store with a `TodoStore` class and then persisting its state using the `persist` utility. The `persist` function automatically saves and loads the `todos` and `filter` properties to `localStorage`.
```ts
import {createClassyStore} from '@codebelt/classy-store';
class TodoStore {
todos: { text: string; done: boolean }[] = [];
filter: 'all' | 'active' | 'done' = 'all';
get remaining() {
return this.todos.filter((todo) => !todo.done).length;
}
addTodo(text: string) {
this.todos.push({text, done: false});
}
toggle(index: number) {
this.todos[index]!.done = !this.todos[index]!.done;
}
}
export const todoStore = createClassyStore(new TodoStore());
import {persist} from '@codebelt/classy-store/utils';
const handle = persist(todoStore, {
name: 'todo-store',
});
```
--------------------------------
### Create a Classy Store Instance
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/SUBSCRIBE_KEY_TUTORIAL.md
Demonstrates how to create a reactive store using createClassyStore from @codebelt/classy-store. This involves defining a class with properties and methods, then instantiating the store.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
class SettingsStore {
theme: 'light' | 'dark' = 'light';
fontSize = 14;
language = 'en';
setTheme(theme: 'light' | 'dark') {
this.theme = theme;
}
setFontSize(size: number) {
this.fontSize = size;
}
}
export const settingsStore = createClassyStore(new SettingsStore());
```
--------------------------------
### Acceptable Barrel File Usage for NPM Libraries (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Details the exception to the 'no barrel files' rule: NPM libraries. Barrel files are acceptable as the single entry point for published packages, simplifying the user's import path. This example shows a typical structure for a library's main export file.
```typescript
// packages/my-library/index.ts (package.json "main" field)
export {Button} from './components/Button';
export {useTheme} from './hooks/useTheme';
```
--------------------------------
### Creating a Classy Store Instance
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Demonstrates how to create a new store instance using `createClassyStore` with defined properties and methods for state management.
```typescript
import { createClassyStore } from '@codebelt/classy-store';
class CounterStore {
count = 0;
step = 1;
get doubled() {
return this.count * 2;
}
increment() {
this.count += this.step;
}
decrement() {
this.count -= this.step;
}
setStep(step: number) {
this.step = step;
}
}
export const counterStore = createClassyStore(new CounterStore());
```
--------------------------------
### Syncing Player Volume with subscribeKey
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/SUBSCRIBE_KEY_TUTORIAL.md
Demonstrates syncing a store's 'volume' property with the Web Audio API's gain node. This ensures the audio volume reflects the value stored in the playerStore.
```typescript
class PlayerStore {
volume = 0.8;
track: string | null = null;
playing = false;
setVolume(v: number) {
this.volume = v;
}
play(track: string) {
this.track = track;
this.playing = true;
}
}
const playerStore = createClassyStore(new PlayerStore());
// Sync volume slider with the Web Audio API
subscribeKey(playerStore, 'volume', (volume) => {
audioContext.gainNode.gain.value = volume;
});
```
--------------------------------
### Install Classy Store for Angular
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Installs the @codebelt/classy-store package and Angular core as peer dependencies for Angular integration.
```bash
npm install @codebelt/classy-store @angular/core
```
--------------------------------
### Create a Classy Store Instance (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Demonstrates how to create a basic store class and instantiate it using `createClassyStore` from the `@codebelt/classy-store` library. This sets up the initial store that will later have history functionality added.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
class DrawingStore {
color = '#000000';
strokeWidth = 2;
points: { x: number; y: number }[] = [];
addPoint(x: number, y: number) {
this.points = [...this.points, { x, y }];
}
setColor(color: string) {
this.color = color;
}
setStrokeWidth(width: number) {
this.strokeWidth = width;
}
clear() {
this.points = [];
}
}
export const drawingStore = createClassyStore(new DrawingStore());
```
--------------------------------
### Proxy GET Trap Logic (Conceptual)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/ARCHITECTURE.md
Details the priority order for handling GET trap requests. It prioritizes memoized getters, method binding, lazy creation of child proxies for nested objects/arrays, and finally returning primitive values.
```plaintext
GET trap (priority order):
1. **Memoized getter detection** — walk prototype chain with `Object.getOwnPropertyDescriptor`. If a getter is found, call `evaluateComputed()` which checks dependency validity and returns the cached result or re-evaluates with dependency tracking.
2. **Method binding** — if value is a function, bind to proxy so `this.count++` in methods goes through the SET trap. Bound methods are cached.
3. **Nested objects/arrays** — if value passes `canProxy()` (plain object or array), lazily wrap in a child proxy. Child proxies are cached in `childProxies` Map. Also records a dependency if a getter is currently being tracked.
4. **Primitives** — return as-is. Also records a dependency if a getter is currently being tracked.
```
--------------------------------
### Batch Operations with Pause/Resume in Classy Store
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Illustrates how to group multiple mutations into a single undoable step using `history.pause()` and `history.resume()`. This is useful for operations like pasting a block of data where all changes should be treated as one atomic action.
```typescript
class SpreadsheetStore {
cells: Record = {};
setCell(id: string, value: string) {
this.cells = { ...this.cells, [id]: value };
}
}
const spreadsheetStore = createClassyStore(new SpreadsheetStore());
const history = withHistory(spreadsheetStore);
// Paste a block of cells — should be a single undo step
function pasteBlock(data: Record) {
history.pause();
for (const [id, value] of Object.entries(data)) {
spreadsheetStore.setCell(id, value);
}
history.resume();
// Manually trigger a snapshot capture by making a final
// mutation after resume, or just let the next user action
// create the history entry.
}
```
--------------------------------
### Service Constants File (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Declares constants used within a service, such as query keys. This centralizes configuration and improves maintainability.
```typescript
// services/hyperion/users/users.constants.ts
export const getUsersKey = 'getUsers';
```
--------------------------------
### Component Supporting Constants (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Declares constants used by a component. This file centralizes static values, making them easy to manage and reference.
```typescript
// UserCard.constants.ts
export const maxNameLength = 30;
```
--------------------------------
### Attach History to a Store Proxy (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Shows how to use the `withHistory` utility from `@codebelt/classy-store/utils` to wrap an existing store proxy. This enables undo/redo functionality for all mutations made to the store.
```typescript
import {withHistory} from '@codebelt/classy-store/utils';
const history = withHistory(drawingStore);
```
--------------------------------
### Package-Specific Build and Test Commands
Source: https://github.com/codebelt/classy-store/blob/main/CLAUDE.md
Lists commands that can be run specifically within the `packages/classy-store/` directory for development, testing, and type checking, including options for watching builds and filtering tests.
```bash
# Build in watch mode
bun run dev
# Run tests for this package only
bun test
# Run a single test file
bun test src/core/core.test.ts
# Filter tests by name pattern
bun test --testNamePattern="batching" core.test.ts
```
--------------------------------
### useLocalStore Hook
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/index.md
Creates a component-scoped reactive store. Each component instance gets its own isolated store that is garbage collected upon unmount. The factory function runs only once per mount.
```APIDOC
## `useLocalStore(factory)`
### Description
Creates a component-scoped reactive store. Each component instance gets its own isolated store, which is garbage collected when the component unmounts. The provided factory function is executed only once per component mount.
### Method
`useLocalStore`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```tsx
import { useLocalStore, useStore } from '@codebelt/classy-store/react';
class CounterStore {
count = 0;
increment() { this.count++; }
}
function Counter() {
const store = useLocalStore(() => new CounterStore());
const count = useStore(store, (s) => s.count);
return ;
}
```
### Response
Returns an instance of the store created by the factory function.
#### Success Response (200)
- **storeInstance** (object) - The created store instance.
#### Response Example
```json
// The returned value is an instance of the class provided to the factory
// e.g., an instance of CounterStore in the example above
{
"count": 0,
"increment": "function"
}
```
```
--------------------------------
### Component Supporting Utilities (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Contains helper functions for a component. This file promotes code reusability and keeps the main component file clean.
```typescript
// UserCard.utils.ts
import {maxNameLength} from './UserCard.constants';
export function formatUserName(name: string): string {
return name.length > maxNameLength ? `${name.slice(0, maxNameLength)}...` : name;
}
```
--------------------------------
### Using useStore without shallowEqual (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/TUTORIAL.md
Demonstrates how `useStore` works with default `Object.is` comparison for stable references, avoiding the need for `shallowEqual` when selecting existing properties or primitives.
```typescript
import {useStore} from '@codebelt/classy-store/react';
// ✅ No shallowEqual needed — structural sharing keeps the reference stable
const count = useStore(todoStore, (store) => store.items.length);
const todos = useStore(todoStore, (store) => store.items);
```
--------------------------------
### Logging Coupon Changes with subscribeKey
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/SUBSCRIBE_KEY_TUTORIAL.md
An example of using subscribeKey to log only when the 'coupon' property in the CartStore changes. This avoids unnecessary analytics calls when other properties like 'items' are modified.
```typescript
class CartStore {
items: { id: string; qty: number }[] = [];
coupon: string | null = null;
get total() {
return this.items.reduce((sum, item) => sum + item.qty, 0);
}
addItem(id: string) {
this.items.push({ id, qty: 1 });
}
applyCoupon(code: string) {
this.coupon = code;
}
}
const cartStore = createClassyStore(new CartStore());
// Only log when coupon changes — not on every item add
subscribeKey(cartStore, 'coupon', (coupon, prev) => {
analytics.track('coupon_changed', { from: prev, to: coupon });
});
```
--------------------------------
### Service Schema File (TypeScript/Zod)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Defines data validation schemas using Zod for service responses. This ensures data integrity and provides type safety.
```typescript
// services/hyperion/users/users.schemas.ts
import {z} from 'zod';
export const GetUsersResponseSchema = z.object({
users: z.array(
z.object({
id: z.uuid(),
email: z.email(),
name: z.string(),
}),
),
});
export type GetUsersResponseSchema = z.infer;
```
--------------------------------
### Watch a Single Key with subscribeKey
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/SUBSCRIBE_KEY_TUTORIAL.md
Shows how to use the subscribeKey utility to listen for changes on a specific property ('theme' in this case) of a store. The callback receives the new and previous values and performs a DOM update.
```typescript
import {subscribeKey} from '@codebelt/classy-store/utils';
const unsub = subscribeKey(settingsStore, 'theme', (value, previousValue) => {
console.log(`Theme changed from "${previousValue}" to "${value}"`);
document.documentElement.setAttribute('data-theme', value);
});
```
--------------------------------
### Named Exports in TypeScript
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Demonstrates the standard practice of using named exports for functions and components within the project. This ensures clear and explicit module exports.
```typescript
export function Component() {}
```
--------------------------------
### Main Service File (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Implements the main logic for a service, including API calls and React Query hooks. It imports schemas and constants from their respective files.
```typescript
// services/hyperion/users/users.ts
import {useQuery} from '@tanstack/react-query';
import {http} from '@/utils/httpClient/httpClient';
import {api} from '@/utils/httpClient/httpClient.constants';
import {getUsersKey} from './users.constants';
import {GetUsersResponseSchema} from './users.schemas';
/* POST /api/v1/users */
export async function getUsers() {
return http.get(api.hyperion.users.v1.list, {
responseSchema: GetUsersResponseSchema,
});
}
export function useGetUsers() {
return useQuery({
queryKey: [getUsersKey],
queryFn: getUsers,
});
}
```
--------------------------------
### Component Supporting Types (TypeScript)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Defines the TypeScript types used within a component, such as the User type. This file separates type definitions from the main component logic.
```typescript
// UserCard.types.ts
export type User = {
id: string;
name: string;
status: 'active' | 'inactive';
};
```
--------------------------------
### Create a Reactive Store Instance
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/index.md
Creates a reactive store instance from a defined class using the `createClassyStore` function. This function wraps the class instance in a reactive proxy.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
const todoStore = createClassyStore(new TodoStore());
```
--------------------------------
### Component File Structure (TypeScript/JSX)
Source: https://github.com/codebelt/classy-store/blob/main/docs/code-style-guide.md
Illustrates the organization of a React component file, including its props type and JSX. It shows how to import types and utility functions from supporting files.
```typescript
// UserCard.tsx
import {formatUserName} from './UserCard.utils';
import type {User} from './UserCard.types';
type Props = {
user: User;
onSelect: (id: string) => void;
};
export function UserCard({user, onSelect}: Props) {
return
onSelect(user.id)}>{formatUserName(user.name)}
;
}
```
--------------------------------
### Combining withHistory with devtools Utility
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/HISTORY_TUTORIAL.md
Explains how to integrate `withHistory` with the `devtools` utility for a comprehensive debugging experience. This allows developers to inspect all mutations, including undo and redo actions, within the browser's Redux DevTools.
```typescript
import {devtools, withHistory} from '@codebelt/classy-store/utils';
const store = createClassyStore(new MyStore());
devtools(store, { name: 'MyStore' });
const history = withHistory(store);
// DevTools shows every mutation including undo/redo restores.
// Time-travel in DevTools is independent of withHistory's stack.
```
--------------------------------
### API: createClassyStore Function
Source: https://github.com/codebelt/classy-store/blob/main/website/static/llms-full.txt
Explains the 'createClassyStore' function, which takes a class instance and wraps it in a reactive Proxy. It highlights features like automatic method binding, memoized getters, and lazy deep-proxied nested objects.
```typescript
const myStore = createClassyStore(new MyClass());
// Methods are automatically bound so `this` mutations go through the proxy
// Getters are automatically memoized — they only recompute when a dependency changes (like MobX `@computed`)
// Nested objects/arrays are lazily deep-proxied on first access
```
--------------------------------
### Classy-Store Write Proxy Memoization
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/ARCHITECTURE.md
Explains the write proxy memoization mechanism in Classy-Store's core. It uses `evaluateComputed` to run getters with dependency tracking, caching results and dependencies.
```mermaid
flowchart TD
GetterAccess["store.filtered accessed"]
CheckDeps{"Dependencies\nchanged?"}
ReturnCached["Return cached value"]
Recompute["Re-run getter with\ndependency tracking"]
CacheResult["Cache result + deps"]
GetterAccess --> CheckDeps
CheckDeps -->|No| ReturnCached
CheckDeps -->|Yes| Recompute
Recompute --> CacheResult
CacheResult --> ReturnCached
```
--------------------------------
### Create a Classy Store
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/DEVTOOLS_TUTORIAL.md
Demonstrates how to create a new store using `createClassyStore` with a custom class definition. This sets up the initial state and methods for the store.
```typescript
import {createClassyStore} from '@codebelt/classy-store';
class CounterStore {
count = 0;
step = 1;
get doubled() {
return this.count * 2;
}
increment() {
this.count += this.step;
}
decrement() {
this.count -= this.step;
}
setStep(step: number) {
this.step = step;
}
}
export const counterStore = createClassyStore(new CounterStore());
```
--------------------------------
### Clearing Classy Store Persisted Data
Source: https://github.com/codebelt/classy-store/blob/main/website/docs/PERSIST_TUTORIAL.md
Removes the stored data associated with a store without altering its current in-memory state. Subsequent loads will start with the store's default values.
```typescript
// Remove the stored data without affecting in-memory state
await handle.clear();
// The store still has its current state in memory.
// Next page load starts with class defaults (nothing in storage).
```