Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adds ability to use ContainerID to persist prosemirror document to. #20

Merged
merged 5 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 122 additions & 6 deletions examples/stories/src/stories/Editor.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { Meta } from "@storybook/react";

import { CursorAwareness, LoroDocType } from "loro-prosemirror";
import { useEffect, useRef } from "react";
import { Editor } from "./Editor";
import { LoroDoc } from "loro-crdt";
import { LoroDoc, VersionVector } from "loro-crdt";
import { useEffect, useRef, useState } from "react";
import { CursorAwareness, LoroDocType } from "loro-prosemirror";

const meta = {
title: "Editor/Basic",
Expand All @@ -27,6 +27,56 @@ export const Basic = () => {
);
};

type UpdateType = "ephemeral" | "awareness" | "crdt";
type UpdateMessage = {
type: "update";
updateType: UpdateType;
payload: Uint8Array;
};

function parseMessage(data: Uint8Array): UpdateMessage {
const messageType = data[0];
switch (messageType) {
case 1: {
// Update
const updateType = (() => {
switch (data[1]) {
case 0:
return "ephemeral";
case 1:
return "awareness";
case 2:
return "crdt";
default:
throw new Error(`Unknown update type: ${data[1]}`);
}
})();
return {
type: "update",
updateType,
payload: data.slice(2),
};
}
default:
throw new Error(`Unknown message type: ${messageType}`);
}
}

function encodeUpdateMessage(
updateType: UpdateType,
payload: Uint8Array,
): Uint8Array {
const message = new Uint8Array(2 + payload.length);
message[0] = 1;
message[1] = updateType === "ephemeral"
? 0
: updateType === "awareness"
? 1
: 2;
message.set(payload, 2);
return message;
}

export const Sync = () => {
const loroARef = useRef<LoroDocType>(new LoroDoc());
const idA = loroARef.current.peerIdStr;
Expand All @@ -38,14 +88,20 @@ export const Sync = () => {
loroARef.current.subscribe((event) => {
if (event.by === "local") {
loroBRef.current.import(
loroARef.current.exportFrom(loroBRef.current.oplogVersion()),
loroARef.current.export({
mode: "update",
from: loroBRef.current.oplogVersion(),
}),
);
}
});
loroBRef.current.subscribe((event) => {
if (event.by === "local") {
loroARef.current.import(
loroBRef.current.exportFrom(loroARef.current.oplogVersion()),
loroBRef.current.export({
mode: "update",
from: loroARef.current.oplogVersion(),
}),
);
}
});
Expand All @@ -63,10 +119,70 @@ export const Sync = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<div>
<Editor
loro={loroARef.current}
awareness={awarenessA.current}
containerId={loroARef.current?.getMap("doc")?.id}
/>
<Editor
loro={loroBRef.current}
awareness={awarenessB.current}
containerId={loroARef.current?.getMap("doc")?.id}
/>
</div>
);
};

export const BroadcastChannelExample = () => {
const bcA = useRef<BroadcastChannel>(new BroadcastChannel(`A`));
const loroARef = useRef<LoroDocType>(new LoroDoc());
const idA = loroARef.current.peerIdStr;
const awarenessA = useRef<CursorAwareness>(new CursorAwareness(idA));
const [lastStateA, setLastStateA] = useState<VersionVector | undefined>();
useEffect(() => {
bcA.current.onmessage = (event) => {
const parsedMessage = parseMessage(event.data);
if (parsedMessage.type === "update") {
// Handle different update types
switch (parsedMessage.updateType) {
case "ephemeral":
break;
case "awareness":
break;
case "crdt":
loroARef.current.import(parsedMessage.payload);
loroARef.current.commit({ origin: "sys:bc-update" });
break;
}
}
};
loroARef.current.subscribe((event) => {
if (event.by === "local") {
bcA.current.postMessage(
encodeUpdateMessage(
"crdt",
loroARef.current.export({ mode: "update", from: lastStateA }),
),
);
setLastStateA(loroARef.current.version());
}
});
awarenessA.current.addListener((_state, origin) => {
if (origin === "local") {
bcA.current.postMessage(
encodeUpdateMessage("awareness", awarenessA.current.encode([idA])),
);
}
});

// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return (
<div>
<Editor loro={loroARef.current} awareness={awarenessA.current} />
<Editor loro={loroBRef.current} awareness={awarenessB.current} />
</div>
);
};
22 changes: 14 additions & 8 deletions examples/stories/src/stories/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ import { useEffect, useRef } from "react";
import {
CursorAwareness,
LoroCursorPlugin,
LoroDocType,
LoroSyncPlugin,
LoroUndoPlugin,
undo,
redo,
LoroDocType,
undo,
} from "loro-prosemirror";
import "./Editor.css";
import { LoroDoc } from "loro-crdt";
import { ContainerID, LoroDoc } from "loro-crdt";
import { buildMenuItems } from "./menu";

const mySchema = new Schema({
Expand All @@ -27,16 +27,22 @@ const mySchema = new Schema({
const doc = DOMParser.fromSchema(mySchema).parse(document.createElement("div"));

/* eslint-disable */
const plugins = exampleSetup({ schema: mySchema, history: false, menuContent: buildMenuItems(mySchema).fullMenu as any });
const plugins = exampleSetup({
schema: mySchema,
history: false,
menuContent: buildMenuItems(mySchema).fullMenu as any,
});

export function Editor({
loro,
awareness,
onCreateLoro,
containerId,
}: {
loro?: LoroDocType;
awareness?: CursorAwareness;
onCreateLoro?: (loro: LoroDocType) => void;
containerId?: ContainerID;
}) {
const editorRef = useRef<null | EditorView>(null);
const editorDom = useRef(null);
Expand All @@ -56,12 +62,12 @@ export function Editor({

const all = [
...plugins,
LoroSyncPlugin({ doc: loroRef.current! }),
LoroSyncPlugin({ doc: loroRef.current!, containerId }),
LoroUndoPlugin({ doc: loroRef.current! }),
keymap({
"Mod-z": state => undo(state, () => {}),
"Mod-y": state => redo(state, () => {}),
"Mod-Shift-z": state => redo(state, () => {}),
"Mod-z": (state) => undo(state, () => {}),
"Mod-y": (state) => redo(state, () => {}),
"Mod-Shift-z": (state) => redo(state, () => {}),
}),
];
if (awareness) {
Expand Down
Loading