Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(loro): remove react package from loro-mirror (#3141)

teo751d75c41c5f
diff --git a/js/app/biome.jsonc b/js/app/biome.jsonc
index c57e982af9..55f0135e2b 100644
--- a/js/app/biome.jsonc
+++ b/js/app/biome.jsonc
@@ -73,12 +73,11 @@
"options": {
"paths": {
"@loro-mirror/core": "Use @loro-mirror/packages/core/src so app and loro-mirror share the app's loro-crdt instance.",
- "@loro-mirror/react": "Use @loro-mirror/packages/* source imports; do not consume loro-mirror as an installed package.",
"loro-mirror-monorepo": "Use @loro-mirror/packages/* source imports; do not consume loro-mirror as an installed package."
},
"patterns": [
{
- "group": ["@loro-mirror/core/*", "@loro-mirror/react/*"],
+ "group": ["@loro-mirror/core/*"],
"message": "Use @loro-mirror/packages/* source imports; do not consume loro-mirror as an installed package."
}
]
diff --git a/js/app/tsconfig.json b/js/app/tsconfig.json
index a9a7f26a4b..98f6d44eef 100644
--- a/js/app/tsconfig.json
+++ b/js/app/tsconfig.json
@@ -10,7 +10,6 @@
"./packages/core/**/*.spec.ts",
"./packages/block-code/scripts/**/*",
"./packages/service-clients/service-sync/scripts/**/*",
- "../loro-mirror/packages/react/**/*",
"../lexical-core/tests/**/*"
],
"compilerOptions": {
diff --git a/js/loro-mirror/README.md b/js/loro-mirror/README.md
index 890eb5b16c..21b055c8f1 100644
--- a/js/loro-mirror/README.md
+++ b/js/loro-mirror/README.md
@@ -6,15 +6,13 @@ A TypeScript state management library that syncs application state with [loro-cr
- 🔄 **Bidirectional Sync**: Seamlessly sync between application state and Loro CRDT
- 📊 **Schema Validation**: Type-safe schema system for validating state
-- 🧩 **Modular Design**: Core package for state management, React package for React integration
+- 🧩 **Composable Core**: Focused package for state management primitives
- 🔍 **Selective Updates**: Subscribe to specific parts of your state
- 🛠️ **Developer Friendly**: Familiar API inspired by popular state management libraries
-- 📱 **React Integration**: Hooks and context providers for React applications
## Packages
- [`@loro-mirror/core`](./packages/core): Core state management functionality
-- [`@loro-mirror/react`](./packages/react): React integration with hooks and context
## Installation
@@ -28,19 +26,9 @@ yarn add @loro-mirror/core loro-crdt
pnpm add @loro-mirror/core loro-crdt
```
-### React Package
-
-```bash
-npm install @loro-mirror/react @loro-mirror/core loro-crdt
-# or
-yarn add @loro-mirror/react @loro-mirror/core loro-crdt
-# or
-pnpm add @loro-mirror/react @loro-mirror/core loro-crdt
-```
-
## Quick Start
-### Core Usage
+### Usage
```typescript
import { LoroDoc } from 'loro-crdt';
@@ -83,104 +71,11 @@ store.subscribe((state) => {
});
```
-### React Usage
-
-```tsx
-import React, { useMemo } from 'react';
-import { LoroDoc } from 'loro-crdt';
-import { schema } from '@loro-mirror/core';
-import { createLoroContext } from '@loro-mirror/react';
-
-// Define your schema
-const todoSchema = schema({
- todos: schema.LoroList(
- schema.LoroMap({
- id: schema.String({ required: true }),
- text: schema.String({ required: true }),
- completed: schema.Boolean({ defaultValue: false }),
- })
- ),
-});
-
-// Create a context
-const {
- LoroProvider,
- useLoroState,
- useLoroSelector,
- useLoroAction,
-} = createLoroContext(todoSchema);
-
-// Root component
-function App() {
- const doc = useMemo(() => new LoroDoc(), []);
-
- return (
- <LoroProvider doc={doc} initialState={{ todos: [] }}>
- <TodoList />
- <AddTodoForm />
- </LoroProvider>
- );
-}
-
-// Todo list component
-function TodoList() {
- const todos = useLoroSelector(state => state.todos);
-
- return (
- <ul>
- {todos.map(todo => (
- <li key={todo.id}>
- <input
- type="checkbox"
- checked={todo.completed}
- onChange={() => toggleTodo(todo.id)}
- />
- <span>{todo.text}</span>
- </li>
- ))}
- </ul>
- );
-}
-
-// Add todo form component
-function AddTodoForm() {
- const [text, setText] = useState('');
-
- const addTodo = useLoroAction((state) => {
- state.todos.push({
- id: Date.now().toString(),
- text: text.trim(),
- completed: false,
- });
- }, [text]);
-
- const handleSubmit = (e) => {
- e.preventDefault();
- if (text.trim()) {
- addTodo();
- setText('');
- }
- };
-
- return (
- <form onSubmit={handleSubmit}>
- <input
- value={text}
- onChange={(e) => setText(e.target.value)}
- placeholder="What needs to be done?"
- />
- <button type="submit">Add Todo</button>
- </form>
- );
-}
-```
-
## Documentation
-For detailed documentation, see the README files in each package:
+For detailed documentation, see the core package README:
- [Core Documentation](./packages/core/README.md)
-- [React Documentation](./packages/react/README.md)
## License
diff --git a/js/loro-mirror/packages/core/README.md b/js/loro-mirror/packages/core/README.md
index fee253634f..c2cf0facf1 100644
--- a/js/loro-mirror/packages/core/README.md
+++ b/js/loro-mirror/packages/core/README.md
@@ -130,7 +130,6 @@ application:
import { Mirror } from "loro-mirror-core";
import { schema } from "loro-mirror-core/schema";
import { LoroDoc } from "loro-crdt";
-import { useEffect, useState } from "react";
// Define the schema
const todoAppSchema = schema({
@@ -149,143 +148,72 @@ const todoAppSchema = schema({
sorting: schema.String({ defaultValue: "createdAt" }),
});
-// Create a custom hook to use the Mirror
-function useTodoApp() {
- const [mirror] = useState(() => {
- const doc = new LoroDoc();
- return new Mirror({
- doc,
- schema: todoAppSchema,
- });
+const mirror = new Mirror({
+ doc: new LoroDoc(),
+ schema: todoAppSchema,
+});
+
+const addTodo = (text: string) => {
+ const state = mirror.getState();
+
+ mirror.setState({
+ ...state,
+ todos: [
+ ...state.todos,
+ {
+ id: Date.now().toString(),
+ text,
+ completed: false,
+ priority: 0,
+ createdAt: Date.now(),
+ },
+ ],
});
+};
- const [state, setState] = useState(mirror.getState());
+const toggleTodo = (id: string) => {
+ const state = mirror.getState();
- useEffect(() => {
- // Subscribe to state changes
- return mirror.subscribe((newState) => {
- setState(newState);
- });
- }, [mirror]);
-
- // Add a new todo
- const addTodo = (text) => {
- setState({
- ...state,
- todos: [
- ...state.todos,
- {
- id: Date.now().toString(),
- text,
- completed: false,
- priority: 0,
- createdAt: Date.now(),
- },
- ],
- });
- };
-
- // Toggle a todo's completed status
- const toggleTodo = (id) => {
- setState({
- ...state,
- todos: state.todos.map((todo) =>
- todo.id === id ? { ...todo, completed: !todo.completed } : todo
- ),
- });
- };
+ mirror.setState({
+ ...state,
+ todos: state.todos.map((todo) =>
+ todo.id === id ? { ...todo, completed: !todo.completed } : todo
+ ),
+ });
+};
- // Remove a todo
- const removeTodo = (id) => {
- setState({
- ...state,
- todos: state.todos.filter((todo) => todo.id !== id),
- });
- };
-
- // Change sort order - notice how this requires reordering
- // but with idSelector, Mirror will use efficient move operations
- const setSorting = (sortField) => {
- const sortedTodos = [...state.todos].sort((a, b) => {
- if (sortField === "priority") {
- return b.priority - a.priority;
- }
- return a.createdAt - b.createdAt;
- });
+const removeTodo = (id: string) => {
+ const state = mirror.getState();
- setState({
- ...state,
- sorting: sortField,
- todos: sortedTodos,
- });
- };
-
- return {
- state,
- addTodo,
- toggleTodo,
- removeTodo,
- setSorting,
- };
-}
-
-// Example React component
-function TodoApp() {
- const { state, addTodo, toggleTodo, removeTodo, setSorting } = useTodoApp();
- const [newTodo, setNewTodo] = useState("");
-
- const handleSubmit = (e) => {
- e.preventDefault();
- if (newTodo.trim()) {
- addTodo(newTodo);
- setNewTodo("");
+ mirror.setState({
+ ...state,
+ todos: state.todos.filter((todo) => todo.id !== id),
+ });
+};
+
+const setSorting = (sortField: "createdAt" | "priority") => {
+ const state = mirror.getState();
+ const sortedTodos = [...state.todos].sort((a, b) => {
+ if (sortField === "priority") {
+ return b.priority - a.priority;
}
- };
-
- return (
- <div>
- <h1>Todo List</h1>
-
- <form onSubmit={handleSubmit}>
- <input
- value={newTodo}
- onChange={(e) => setNewTodo(e.target.value)}
- placeholder="Add todo"
- />
- <button type="submit">Add</button>
- </form>
-
- <div>
- <button onClick={() => setSorting("createdAt")}>
- Sort by Date
- </button>
- <button onClick={() => setSorting("priority")}>
- Sort by Priority
- </button>
- </div>
-
- <ul>
- {state.todos.map((todo) => (
- <li key={todo.id}>
- <input
- type="checkbox"
- checked={todo.completed}
- onChange={() => toggleTodo(todo.id)}
- />
- <span
- style={{
- textDecoration: todo.completed ? "line-through" : "none",
- }}
- >
- {todo.text}
- </span>
- <button onClick={() => removeTodo(todo.id)}>Delete</button>
- </li>
- ))}
- </ul>
- </div>
- );
-}
+ return a.createdAt - b.createdAt;
+ });
+
+ mirror.setState({
+ ...state,
+ sorting: sortField,
+ todos: sortedTodos,
+ });
+};
+
+const unsubscribe = mirror.subscribe((state) => {
+ console.log("Todo state changed", state);
+});
+
+addTodo("Ship the core package");
+setSorting("priority");
+unsubscribe();
```
In this example:
@@ -304,8 +232,7 @@ For large lists, using an `idSelector` can significantly improve performance by:
- Reducing the number of operations sent to Loro
- Minimizing network traffic in collaborative scenarios
-- Preserving item identity which can help with animations and React rendering
- optimizations
+- Preserving item identity, which helps UI layers avoid unnecessary work
For more examples and detailed API documentation, see the
[API Reference](API.md).
diff --git a/js/loro-mirror/packages/core/package.json b/js/loro-mirror/packages/core/package.json
index 9640f5ad8c..f6a3b5cd15 100644
--- a/js/loro-mirror/packages/core/package.json
+++ b/js/loro-mirror/packages/core/package.json
@@ -12,7 +12,7 @@
"build": "rollup -c",
"test": "vitest run",
"test:watch": "vitest",
- "lint": "eslint src --ext .ts,.tsx",
+ "lint": "eslint src --ext .ts",
"typecheck": "tsc --noEmit"
},
"keywords": [
diff --git a/js/loro-mirror/packages/core/rollup.config.js b/js/loro-mirror/packages/core/rollup.config.js
index 85f38b0b07..4b58acb7fd 100644
--- a/js/loro-mirror/packages/core/rollup.config.js
+++ b/js/loro-mirror/packages/core/rollup.config.js
@@ -31,7 +31,7 @@ module.exports = {
declaration: true,
declarationDir: 'dist',
},
- exclude: ['**/*.test.ts', '**/*.test.tsx', 'tests'],
+ exclude: ['**/*.test.ts', 'tests'],
},
}),
],
diff --git a/js/loro-mirror/packages/react/README.md b/js/loro-mirror/packages/react/README.md
deleted file mode 100644
index 6dc8149939..0000000000
--- a/js/loro-mirror/packages/react/README.md
+++ /dev/null
@@ -1,265 +0,0 @@
-# Loro Mirror React
-
-React integration for Loro Mirror - a state management library with Loro CRDT synchronization.
-
-## Installation
-
-```bash
-npm install @loro-mirror/react @loro-mirror/core loro-crdt
-# or
-yarn add @loro-mirror/react @loro-mirror/core loro-crdt
-# or
-pnpm add @loro-mirror/react @loro-mirror/core loro-crdt
-```
-
-## Usage
-
-### Basic Usage with Hooks
-
-```tsx
-import React, { useMemo } from 'react';
-import { LoroDoc } from 'loro-crdt';
-import { schema } from '@loro-mirror/core';
-import { useLoroStore } from '@loro-mirror/react';
-
-// Define your schema
-const todoSchema = schema({
- todos: schema.LoroList(
- schema.LoroMap({
- id: schema.String({ required: true }),
- text: schema.String({ required: true }),
- completed: schema.Boolean({ defaultValue: false }),
- }),
- // ID selector for the list items
- (item) => item.id
- ),
- filter: schema.String({ defaultValue: 'all' }),
-});
-
-function TodoApp() {
- // Create a Loro document
- const doc = useMemo(() => new LoroDoc(), []);
-
- // Create a store
- const { state, setState } = useLoroStore({
- doc,
- schema: todoSchema,
- initialState: { todos: [], filter: 'all' },
- });
-
- // Add a new todo
- const addTodo = (text: string) => {
- setState((state) => {
- state.todos.push({
- id: Date.now().toString(),
- text,
- completed: false,
- });
- return state;
- });
- };
-
- // Rest of your component...
-}
-```
-
-### Using Context Provider
-
-```tsx
-import React, { useMemo } from 'react';
-import { LoroDoc } from 'loro-crdt';
-import { schema } from '@loro-mirror/core';
-import { createLoroContext } from '@loro-mirror/react';
-
-// Define your schema
-const todoSchema = schema({
- todos: schema.LoroList(
- schema.LoroMap({
- id: schema.String({ required: true }),
- text: schema.String({ required: true }),
- completed: schema.Boolean({ defaultValue: false }),
- })
- ),
-});
-
-// Create a context
-const {
- LoroProvider,
- useLoroContext,
- useLoroState,
- useLoroSelector,
- useLoroAction,
-} = createLoroContext(todoSchema);
-
-// Root component
-function App() {
- const doc = useMemo(() => new LoroDoc(), []);
-
- return (
- <LoroProvider doc={doc} initialState={{ todos: [] }}>
- <TodoList />
- <AddTodoForm />
- </LoroProvider>
- );
-}
-
-// Todo list component
-function TodoList() {
- // Subscribe only to the todos array
- const todos = useLoroSelector(state => state.todos);
-
- return (
- <ul>
- {todos.map(todo => (
- <TodoItem key={todo.id} todo={todo} />
- ))}
- </ul>
- );
-}
-
-// Todo item component
-function TodoItem({ todo }) {
- const toggleTodo = useLoroAction(state => {
- const todoIndex = state.todos.findIndex(t => t.id === todo.id);
- if (todoIndex !== -1) {
- state.todos[todoIndex].completed = !state.todos[todoIndex].completed;
- }
- });
-
- return (
- <li>
- <input
- type="checkbox"
- checked={todo.completed}
- onChange={toggleTodo}
- />
- <span>{todo.text}</span>
- </li>
- );
-}
-```
-
-## API Reference
-
-### `useLoroStore`
-
-Creates and manages a Loro Mirror store.
-
-```tsx
-const { state, setState, sync, syncFromLoro, syncToLoro, store } = useLoroStore({
- doc,
- schema,
- initialState,
- validateUpdates,
- throwOnValidationError,
- debug,
-});
-```
-
-### `useLoroValue`
-
-Subscribes to a specific value from a Loro Mirror store.
-
-```tsx
-const todos = useLoroValue(store, state => state.todos);
-```
-
-### `useLoroCallback`
-
-Creates a callback that updates a Loro Mirror store.
-
-```tsx
-const addTodo = useLoroCallback(
- store,
- (state, text) => {
- state.todos.push({
- id: Date.now().toString(),
- text,
- completed: false,
- });
- },
- [/* dependencies */]
-);
-
-// Usage
-addTodo('New todo');
-```
-
-### `createLoroContext`
-
-Creates a context provider and hooks for a Loro Mirror store.
-
-```tsx
-const {
- LoroContext,
- LoroProvider,
- useLoroContext,
- useLoroState,
- useLoroSelector,
- useLoroAction,
-} = createLoroContext(schema);
-```
-
-#### `LoroProvider`
-
-Provider component for the Loro Mirror context.
-
-```tsx
-<LoroProvider
- doc={loroDoc}
- initialState={initialState}
- validateUpdates={true}
- throwOnValidationError={false}
- debug={false}
->
- {children}
-</LoroProvider>
-```
-
-#### `useLoroContext`
-
-Hook to access the Loro Mirror store from context.
-
-```tsx
-const store = useLoroContext();
-```
-
-#### `useLoroState`
-
-Hook to access and update the full state.
-
-```tsx
-const [state, setState] = useLoroState();
-```
-
-#### `useLoroSelector`
-
-Hook to select a specific value from the state.
-
-```tsx
-const todos = useLoroSelector(state => state.todos);
-```
-
-#### `useLoroAction`
-
-Hook to create an action that updates the state.
-
-```tsx
-const addTodo = useLoroAction(
- (state, text) => {
- state.todos.push({
- id: Date.now().toString(),
- text,
- completed: false,
- });
- },
- [/* dependencies */]
-);
-
-// Usage
-addTodo('New todo');
-```
-
-## License
-
-MIT
diff --git a/js/loro-mirror/packages/react/package.json b/js/loro-mirror/packages/react/package.json
deleted file mode 100644
index 861a779f7d..0000000000
--- a/js/loro-mirror/packages/react/package.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "@loro-mirror/react",
- "version": "0.1.0",
- "description": "React integration for Loro Mirror - a state management library with Loro CRDT synchronization",
- "main": "dist/index.js",
- "module": "dist/index.esm.js",
- "types": "dist/index.d.ts",
- "files": [
- "dist"
- ],
- "scripts": {
- "build": "rollup -c",
- "test": "vitest run",
- "test:watch": "vitest",
- "lint": "eslint src --ext .ts,.tsx",
- "typecheck": "tsc --noEmit"
- },
- "keywords": [
- "loro",
- "crdt",
- "state",
- "management",
- "sync",
- "mirror",
- "react",
- "hooks"
- ],
- "author": "",
- "license": "MIT",
- "dependencies": {
- "@loro-mirror/core": "workspace:*"
- },
- "peerDependencies": {
- "loro-crdt": "^1.4.4",
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
- },
- "devDependencies": {
- "@types/node": "^20.10.5",
- "@types/react": "^18.2.45",
- "loro-crdt": "^1.4.4",
- "react": "^18.2.0",
- "typescript": "^5.3.3"
- }
-}
diff --git a/js/loro-mirror/packages/react/rollup.config.js b/js/loro-mirror/packages/react/rollup.config.js
deleted file mode 100644
index 0f208a61f6..0000000000
--- a/js/loro-mirror/packages/react/rollup.config.js
+++ /dev/null
@@ -1,41 +0,0 @@
-const typescript = require('rollup-plugin-typescript2');
-const { nodeResolve } = require('@rollup/plugin-node-resolve');
-const commonjs = require('@rollup/plugin-commonjs');
-const pkg = require('./package.json');
-
-module.exports = {
- input: 'src/index.ts',
- output: [
- {
- file: pkg.main,
- format: 'cjs',
- sourcemap: true,
- },
- {
- file: pkg.module,
- format: 'esm',
- sourcemap: true,
- },
- ],
- external: [
- ...Object.keys(pkg.dependencies || {}),
- ...Object.keys(pkg.peerDependencies || {}),
- 'react',
- 'react-dom',
- ],
- plugins: [
- nodeResolve(),
- commonjs(),
- typescript({
- useTsconfigDeclarationDir: true,
- tsconfigOverride: {
- compilerOptions: {
- declaration: true,
- declarationDir: 'dist',
- jsx: 'react',
- },
- exclude: ['**/*.test.ts', '**/*.test.tsx', 'tests'],
- },
- }),
- ],
-};
diff --git a/js/loro-mirror/packages/react/src/hooks.tsx b/js/loro-mirror/packages/react/src/hooks.tsx
deleted file mode 100644
index 5c4cfdcf16..0000000000
--- a/js/loro-mirror/packages/react/src/hooks.tsx
+++ /dev/null
@@ -1,360 +0,0 @@
-import type { InferType, SchemaType, Store } from '@loro-mirror/core';
-import type { LoroDoc } from 'loro-crdt';
-/**
- * React hooks for Loro Mirror
- */
-import type React from 'react';
-import {
- type PropsWithChildren,
- createContext,
- useCallback,
- useContext,
- useEffect,
- useRef,
- useState,
-} from 'react';
-
-/**
- * Context options for creating a Loro Mirror store
- */
-export interface UseLoroStoreOptions<S extends SchemaType> {
- /**
- * The Loro document to sync with
- */
- doc: LoroDoc;
-
- /**
- * The schema definition for the state
- */
- schema: S;
-
- /**
- * Initial state (optional)
- */
- initialState?: Partial<InferType<S>>;
-
- /**
- * Whether to validate state updates against the schema
- * @default true
- */
- validateUpdates?: boolean;
-
- /**
- * Whether to throw errors on validation failures
- * @default false
- */
- throwOnValidationError?: boolean;
-
- /**
- * Debug mode - logs operations
- * @default false
- */
- debug?: boolean;
-}
-
-/**
- * Hook to create and use a Loro Mirror store
- *
- * @example
- * ```tsx
- * const todoSchema = schema({
- * todos: schema.LoroList(schema.LoroMap({
- * id: schema.String({ required: true }),
- * text: schema.String({ required: true }),
- * completed: schema.Boolean({ defaultValue: false }),
- * })),
- * });
- *
- * function TodoApp() {
- * const doc = useMemo(() => new LoroDoc(), []);
- * const { state, setState } = useLoroStore({
- * doc,
- * schema: todoSchema,
- * initialState: { todos: [] },
- * });
- *
- * // Use state and setState to interact with the store
- * }
- * ```
- */
-export function useLoroStore<S extends SchemaType>(
- options: UseLoroStoreOptions<S>
-) {
- // Create a stable reference to the store
- const storeRef = useRef<Store<S> | null>(null);
-
- // Initialize the store and get initial state
- const getStore = useCallback((): Store<S> => {
- if (!storeRef.current) {
- // We need to dynamically import the core package to avoid circular dependencies
- const coreModule = require('@loro-mirror/core');
- storeRef.current = coreModule.createStore(options);
- }
- return storeRef.current!;
- }, [options]);
-
- // Get the current state
- const [state, setLocalState] = useState<InferType<S>>(() => {
- return getStore().getState();
- });
-
- // Subscribe to state changes
- useEffect(() => {
- const store = getStore();
-
- // Update local state when the store changes
- const unsubscribe = store.subscribe((newState: InferType<S>) => {
- setLocalState(newState);
- });
-
- // Initial sync
- store.sync();
-
- return unsubscribe;
- }, [getStore]);
-
- // Create a stable setState function
- const setState = useCallback(
- (
- updater: ((state: InferType<S>) => InferType<S>) | Partial<InferType<S>>
- ) => {
- getStore().setState(updater);
- },
- [getStore]
- );
-
- // Create a stable sync function
- const sync = useCallback(() => {
- return getStore().sync();
- }, [getStore]);
-
- // Create a stable syncFromLoro function
- const syncFromLoro = useCallback(() => {
- return getStore().syncFromLoro();
- }, [getStore]);
-
- // Create a stable syncToLoro function
- const syncToLoro = useCallback(() => {
- getStore().syncToLoro();
- }, [getStore]);
-
- return {
- state,
- setState,
- sync,
- syncFromLoro,
- syncToLoro,
- store: getStore(),
- };
-}
-
-/**
- * Hook to subscribe to a specific value from a Loro Mirror store
- *
- * @example
- * ```tsx
- * function TodoList({ store }) {
- * // Subscribe only to the todos array
- * const todos = useLoroValue(store, state => state.todos);
- *
- * return (
- * <ul>
- * {todos.map(todo => (
- * <li key={todo.id}>{todo.text}</li>
- * ))}
- * </ul>
- * );
- * }
- * ```
- */
-export function useLoroValue<S extends SchemaType, R>(
- store: Store<S>,
- selector: (state: InferType<S>) => R
-): R {
- // Get the initial value
- const [value, setValue] = useState<R>(() => selector(store.getState()));
-
- // Subscribe to changes
- useEffect(() => {
- const unsubscribe = store.subscribe((state: InferType<S>) => {
- const newValue = selector(state);
- setValue(newValue);
- });
-
- return unsubscribe;
- }, [store, selector]);
-
- return value;
-}
-
-/**
- * Hook to create a callback that updates a Loro Mirror store
- *
- * @example
- * ```tsx
- * function AddTodo({ store }) {
- * const [text, setText] = useState('');
- *
- * const addTodo = useLoroCallback(
- * store,
- * (state) => {
- * state.todos.push({
- * id: Date.now().toString(),
- * text,
- * completed: false,
- * });
- * },
- * [text]
- * );
- *
- * return (
- * <form onSubmit={(e) => {
- * e.preventDefault();
- * addTodo();
- * setText('');
- * }}>
- * <input value={text} onChange={e => setText(e.target.value)} />
- * <button type="submit">Add</button>
- * </form>
- * );
- * }
- * ```
- */
-export function useLoroCallback<S extends SchemaType, Args extends any[]>(
- store: Store<S>,
- updater: (state: InferType<S>, ...args: Args) => void,
- deps: React.DependencyList = []
-): (...args: Args) => void {
- return useCallback(
- (...args: Args) => {
- store.setState((state: InferType<S>) => {
- // Use immer's produce to create a new state with the updates
- const newState = { ...state };
- updater(newState, ...args);
- return newState;
- });
- },
- [store, updater, ...deps]
- );
-}
-
-/**
- * Hook to create a Loro Mirror context provider and hooks
- *
- * @example
- * ```tsx
- * // In a shared file:
- * const todoSchema = schema({
- * todos: schema.LoroList(schema.LoroMap({
- * id: schema.String({ required: true }),
- * text: schema.String({ required: true }),
- * completed: schema.Boolean({ defaultValue: false }),
- * })),
- * });
- *
- * export const {
- * LoroProvider,
- * useLoroContext,
- * useLoroState,
- * useLoroSelector,
- * useLoroAction,
- * } = createLoroContext(todoSchema);
- *
- * // In your app:
- * function App() {
- * const doc = useMemo(() => new LoroDoc(), []);
- *
- * return (
- * <LoroProvider doc={doc} initialState={{ todos: [] }}>
- * <TodoList />
- * <AddTodo />
- * </LoroProvider>
- * );
- * }
- * ```
- */
-export function createLoroContext<S extends SchemaType>(schema: S) {
- // Create a React context
- const LoroContext = createContext<Store<S> | null>(null);
-
- // Create a provider component
- function LoroProvider({
- children,
- doc,
- initialState,
- validateUpdates,
- throwOnValidationError,
- debug,
- }: PropsWithChildren<Omit<UseLoroStoreOptions<S>, 'schema'>>) {
- const { store } = useLoroStore({
- doc,
- schema,
- initialState,
- validateUpdates,
- throwOnValidationError,
- debug,
- });
-
- return (
- <LoroContext.Provider value={store}>{children}</LoroContext.Provider>
- );
- }
-
- // Hook to access the context
- function useLoroContext() {
- const context = useContext(LoroContext);
- if (!context) {
- throw new Error('useLoroContext must be used within a LoroProvider');
- }
- return context;
- }
-
- // Hook to access the full state
- function useLoroState() {
- const store = useLoroContext();
- const [state, setState] = useState(store.getState());
-
- useEffect(() => {
- const unsubscribe = store.subscribe((newState: InferType<S>) => {
- setState(newState);
- });
-
- return unsubscribe;
- }, [store]);
-
- const updateState = useCallback(
- (
- updater: ((state: InferType<S>) => InferType<S>) | Partial<InferType<S>>
- ) => {
- store.setState(updater);
- },
- [store]
- );
-
- return [state, updateState] as const;
- }
-
- // Hook to select a specific value from the state
- function useLoroSelector<R>(selector: (state: InferType<S>) => R): R {
- const store = useLoroContext();
- return useLoroValue(store, selector);
- }
-
- // Hook to create an action that updates the state
- function useLoroAction<Args extends any[]>(
- updater: (state: InferType<S>, ...args: Args) => void,
- deps: React.DependencyList = []
- ): (...args: Args) => void {
- const store = useLoroContext();
- return useLoroCallback(store, updater, deps);
- }
-
- return {
- LoroContext,
- LoroProvider,
- useLoroContext,
- useLoroState,
- useLoroSelector,
- useLoroAction,
- };
-}
diff --git a/js/loro-mirror/packages/react/src/index.ts b/js/loro-mirror/packages/react/src/index.ts
deleted file mode 100644
index d2a8a1cf48..0000000000
--- a/js/loro-mirror/packages/react/src/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/**
- * React integration for Loro Mirror
- */
-
-export * from "./hooks";
diff --git a/js/loro-mirror/packages/react/tsconfig.json b/js/loro-mirror/packages/react/tsconfig.json
deleted file mode 100644
index cc4e671747..0000000000
--- a/js/loro-mirror/packages/react/tsconfig.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "extends": "../../tsconfig.json",
- "compilerOptions": {
- "outDir": "./dist",
- "rootDir": "./src",
- "composite": true,
- "noEmit": false,
- "jsx": "react-jsx"
- },
- "include": [
- "src/**/*"
- ],
- "exclude": [
- "node_modules",
- "dist",
- "**/*.test.ts",
- "**/*.test.tsx"
- ],
- "references": [
- {
- "path": "../core"
- }
- ]
-}
diff --git a/js/loro-mirror/packages/react/vitest.config.ts b/js/loro-mirror/packages/react/vitest.config.ts
deleted file mode 100644
index 0429da71ef..0000000000
--- a/js/loro-mirror/packages/react/vitest.config.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { defineConfig } from "vitest/config";
-
-export default defineConfig({
- test: {
- environment: "jsdom",
- include: ["tests/**/*.test.ts", "tests/**/*.test.tsx"],
- globals: true,
- },
-});
diff --git a/js/loro-mirror/pnpm-lock.yaml b/js/loro-mirror/pnpm-lock.yaml
index 0aa9abd4ee..0d8dd70bf0 100644
--- a/js/loro-mirror/pnpm-lock.yaml
+++ b/js/loro-mirror/pnpm-lock.yaml
@@ -68,28 +68,6 @@ importers:
specifier: ^5.3.3
version: 5.7.3
- packages/react:
- dependencies:
- '@loro-mirror/core':
- specifier: workspace:*
- version: link:../core
- devDependencies:
- '@types/node':
- specifier: ^20.10.5
- version: 20.17.19
- '@types/react':
- specifier: ^18.2.45
- version: 18.3.18
- loro-crdt:
- specifier: ^1.4.4
- version: 1.4.4
- react:
- specifier: ^18.2.0
- version: 18.3.1
- typescript:
- specifier: ^5.3.3
- version: 5.7.3
-
packages:
'@esbuild/[email protected]':
@@ -501,12 +479,6 @@ packages:
resolution: {integrity: sha512-LEwC7o1ifqg/6r2gn9Dns0f1rhK+fPFDoMiceTJ6kWmVk6bgXBI/9IOWfVan4WiAavK9pIVWdX0/e3J+eEUh5A==}
- '@types/[email protected]':
- resolution: {integrity: sha512-gNMvNH49DJ7OJYv+KAKn0Xp45p8PLl6zo2YnvDIbTd4J6MER2BmWN49TG7n9LvkyihINxeKW8+3bfS2yDC9dzQ==}
-
- '@types/[email protected]':
- resolution: {integrity: sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==}
-
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
@@ -672,9 +644,6 @@ packages:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
- resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
-
resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==}
engines: {node: '>=6.0'}
@@ -913,9 +882,6 @@ packages:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
- resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
-
resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
hasBin: true
@@ -950,10 +916,6 @@ packages:
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
- resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
- hasBin: true
-
resolution: {integrity: sha512-4kGyBJ97FWJTaXzSECD7sq6b2+t65EKUGmfcKh+YCHNMSZvv6ZoqME+JpLzAjKyWbBhIGp0mzFyf/5EYZcDBxw==}
@@ -1069,10 +1031,6 @@ packages:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
- resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
@@ -1580,13 +1538,6 @@ snapshots:
dependencies:
undici-types: 6.19.8
- '@types/[email protected]': {}
-
- '@types/[email protected]':
- dependencies:
- '@types/prop-types': 15.7.14
- csstype: 3.1.3
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -1781,8 +1732,6 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
-
dependencies:
ms: 2.1.3
@@ -2038,8 +1987,6 @@ snapshots:
-
dependencies:
argparse: 2.0.1
@@ -2075,10 +2022,6 @@ snapshots:
- dependencies:
- js-tokens: 4.0.0
-
@@ -2173,10 +2116,6 @@ snapshots:
- dependencies:
- loose-envify: 1.4.0
-
diff --git a/js/loro-mirror/tsconfig.json b/js/loro-mirror/tsconfig.json
index aa4cfada98..ff513cf757 100644
--- a/js/loro-mirror/tsconfig.json
+++ b/js/loro-mirror/tsconfig.json
@@ -13,7 +13,6 @@
"outDir": "./dist",
"rootDir": ".",
"composite": true,
- "jsx": "react",
"lib": [
"DOM",
"DOM.Iterable",
@@ -28,15 +27,11 @@
"node_modules",
"dist",
"**/dist",
- "**/*.test.ts",
- "**/*.test.tsx"
+ "**/*.test.ts"
],
"references": [
{
"path": "./packages/core"
- },
- {
- "path": "./packages/react"
}
]
}