@crdt-sync/react 0.1.0
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.
- package/README.md +98 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -0
- package/dist/useCrdtState.d.ts +8 -0
- package/dist/useCrdtState.js +105 -0
- package/package.json +26 -0
package/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# @crdt-sync/react
|
|
2
|
+
|
|
3
|
+
A high-level React adapter for `crdt-sync`. This package exposes the `useCrdtState` hook, which allows you to bind CRDT-powered, collaborative state directly to your React components.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
You need both the framework-agnostic core and the React adapter. The Wasm binaries are bundled within the `@crdt-sync/core` package.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @crdt-sync/core @crdt-sync/react
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start: `useCrdtState`
|
|
14
|
+
|
|
15
|
+
The `useCrdtState` hook magically handles:
|
|
16
|
+
- **Wasm Initialization**: Bootstraps the rust-generated `crdt-sync` bindings automatically.
|
|
17
|
+
- **Networking**: Connects via WebSocket out-of-the-box.
|
|
18
|
+
- **State Proxying**: Wraps your state with JavaScript proxies that automatically broadcast operations seamlessly upon assignment.
|
|
19
|
+
- **Reactivity**: Automatically hooks up to React's lifecycle to re-render when remote changes are received.
|
|
20
|
+
|
|
21
|
+
### Example
|
|
22
|
+
|
|
23
|
+
Here's how to create a simple connected component:
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import { useCrdtState } from '@crdt-sync/react';
|
|
27
|
+
|
|
28
|
+
// Define the shape of your state
|
|
29
|
+
type MyState = {
|
|
30
|
+
robot: {
|
|
31
|
+
speed: number;
|
|
32
|
+
active: boolean;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function RobotDashboard() {
|
|
37
|
+
// Bind the Wasm engine and network directly to React state
|
|
38
|
+
const { state, proxy, status } = useCrdtState<MyState>(
|
|
39
|
+
'wss://api.example.com/sync',
|
|
40
|
+
{
|
|
41
|
+
robot: { speed: 0, active: true } // Initial State
|
|
42
|
+
}
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
if (status === 'connecting') {
|
|
46
|
+
return <p>Connecting to sync engine...</p>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (status === 'error') {
|
|
50
|
+
return <p>Failed to connect to the sync server!</p>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return (
|
|
54
|
+
<div>
|
|
55
|
+
<h1>Robot Speed: {state.robot.speed}</h1>
|
|
56
|
+
{/*
|
|
57
|
+
Direct mutation is intercepted, applied as a CRDT operation,
|
|
58
|
+
broadcast over WebSocket, and triggers a local React re-render.
|
|
59
|
+
*/}
|
|
60
|
+
<button
|
|
61
|
+
onClick={() => {
|
|
62
|
+
// Mutate the state using the returned proxy wrapper
|
|
63
|
+
if (proxy) {
|
|
64
|
+
proxy.state.robot.speed += 10;
|
|
65
|
+
}
|
|
66
|
+
}}
|
|
67
|
+
>
|
|
68
|
+
Increase Speed
|
|
69
|
+
</button>
|
|
70
|
+
|
|
71
|
+
<button
|
|
72
|
+
onClick={() => {
|
|
73
|
+
if (proxy) {
|
|
74
|
+
proxy.state.robot.active = !proxy.state.robot.active;
|
|
75
|
+
}
|
|
76
|
+
}}
|
|
77
|
+
>
|
|
78
|
+
Toggle Active Status ({state.robot.active ? 'Active' : 'Idle'})
|
|
79
|
+
</button>
|
|
80
|
+
</div>
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## API Reference
|
|
86
|
+
|
|
87
|
+
### `useCrdtState<T>(url: string, initialState: T)`
|
|
88
|
+
|
|
89
|
+
Accepts a TypeScript generic `T` that extends `Record<string, unknown>`.
|
|
90
|
+
|
|
91
|
+
#### Parameters:
|
|
92
|
+
- `url` (`string`): The WebSocket URL to connect to the backend sync service.
|
|
93
|
+
- `initialState` (`T`): The default state to build the proxy structure over.
|
|
94
|
+
|
|
95
|
+
#### Returns (`UseCrdtStateResult<T>`):
|
|
96
|
+
- `state`: The plain Javascript object representation of your state. You should use `state` for reading values when rendering.
|
|
97
|
+
- `proxy`: The `CrdtStateProxy` object. You **must** perform all mutations on `proxy.state`. Mutating `state` directly will not trigger network events.
|
|
98
|
+
- `status`: Connective status indicator (`'connecting'` | `'open'` | `'error'`).
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useCrdtState = void 0;
|
|
4
|
+
var useCrdtState_1 = require("./useCrdtState");
|
|
5
|
+
Object.defineProperty(exports, "useCrdtState", { enumerable: true, get: function () { return useCrdtState_1.useCrdtState; } });
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { CrdtStateProxy } from '@crdt-sync/core';
|
|
2
|
+
export type CrdtStatus = 'connecting' | 'open' | 'error';
|
|
3
|
+
export interface UseCrdtStateResult<T> {
|
|
4
|
+
state: T;
|
|
5
|
+
proxy: CrdtStateProxy | null;
|
|
6
|
+
status: CrdtStatus;
|
|
7
|
+
}
|
|
8
|
+
export declare function useCrdtState<T extends Record<string, unknown>>(url: string, initialState: T): UseCrdtStateResult<T>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.useCrdtState = useCrdtState;
|
|
37
|
+
const react_1 = require("react");
|
|
38
|
+
const core_1 = require("@crdt-sync/core");
|
|
39
|
+
// @ts-ignore: Wasm module will be generated during the full build
|
|
40
|
+
const crdt_sync_js_1 = __importStar(require("@crdt-sync/core/pkg/web/crdt_sync.js"));
|
|
41
|
+
function useCrdtState(url, initialState) {
|
|
42
|
+
const [proxy, setProxy] = (0, react_1.useState)(null);
|
|
43
|
+
const [status, setStatus] = (0, react_1.useState)('connecting');
|
|
44
|
+
const [, setTick] = (0, react_1.useState)(0);
|
|
45
|
+
// Note: we're ignoring initialState updates (this behaves like useState).
|
|
46
|
+
const [initialRef] = (0, react_1.useState)(initialState);
|
|
47
|
+
(0, react_1.useEffect)(() => {
|
|
48
|
+
let active = true;
|
|
49
|
+
let manager = null;
|
|
50
|
+
let currentProxy = null;
|
|
51
|
+
async function setup() {
|
|
52
|
+
try {
|
|
53
|
+
await (0, crdt_sync_js_1.default)();
|
|
54
|
+
if (!active)
|
|
55
|
+
return;
|
|
56
|
+
// Create a unique client ID
|
|
57
|
+
const clientId = 'client-' + Math.random().toString(36).substring(2, 11);
|
|
58
|
+
const store = new crdt_sync_js_1.WasmStateStore(clientId);
|
|
59
|
+
currentProxy = new core_1.CrdtStateProxy(store);
|
|
60
|
+
// Initialize state
|
|
61
|
+
for (const [key, value] of Object.entries(initialRef)) {
|
|
62
|
+
currentProxy.state[key] = value;
|
|
63
|
+
}
|
|
64
|
+
if (!active)
|
|
65
|
+
return;
|
|
66
|
+
setProxy(currentProxy);
|
|
67
|
+
const ws = new WebSocket(url);
|
|
68
|
+
ws.onopen = () => {
|
|
69
|
+
if (active)
|
|
70
|
+
setStatus('open');
|
|
71
|
+
};
|
|
72
|
+
ws.onerror = () => {
|
|
73
|
+
if (active)
|
|
74
|
+
setStatus('error');
|
|
75
|
+
};
|
|
76
|
+
ws.onclose = () => {
|
|
77
|
+
if (active)
|
|
78
|
+
setStatus('connecting');
|
|
79
|
+
};
|
|
80
|
+
manager = new core_1.WebSocketManager(store, currentProxy, ws);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
console.error('Failed to initialize CRDT sync:', err);
|
|
84
|
+
if (active)
|
|
85
|
+
setStatus('error');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
setup();
|
|
89
|
+
return () => {
|
|
90
|
+
active = false;
|
|
91
|
+
if (manager)
|
|
92
|
+
manager.disconnect();
|
|
93
|
+
};
|
|
94
|
+
}, [url, initialRef]);
|
|
95
|
+
(0, react_1.useEffect)(() => {
|
|
96
|
+
if (!proxy)
|
|
97
|
+
return;
|
|
98
|
+
// Subscribe to proxy updates to trigger React re-renders.
|
|
99
|
+
return proxy.onUpdate(() => {
|
|
100
|
+
setTick(t => t + 1);
|
|
101
|
+
});
|
|
102
|
+
}, [proxy]);
|
|
103
|
+
const state = proxy ? proxy.state : initialRef;
|
|
104
|
+
return { state, proxy, status };
|
|
105
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crdt-sync/react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React hook adapter for crdt-sync",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc"
|
|
12
|
+
},
|
|
13
|
+
"peerDependencies": {
|
|
14
|
+
"react": ">=16.8",
|
|
15
|
+
"react-dom": ">=16.8"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@crdt-sync/core": "*"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@types/react": "^18.0.0",
|
|
22
|
+
"@types/react-dom": "^18.0.0",
|
|
23
|
+
"typescript": "^5.4.5"
|
|
24
|
+
},
|
|
25
|
+
"license": "MIT"
|
|
26
|
+
}
|