Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active November 18, 2023 18:22
Show Gist options
  • Save gvergnaud/bff3a31ffc7e299b7021f4828c25c235 to your computer and use it in GitHub Desktop.
Save gvergnaud/bff3a31ffc7e299b7021f4828c25c235 to your computer and use it in GitHub Desktop.
import { createLiveState, crdtSchema } from "@/lib/live-state";
export type NotebookJSON = {
title: string;
description: string;
cells: TextCell[];
};
const notebookCRDTSchema = {
title: crdtSchema.LiveText(),
cells: crdtSchema.LiveList({ content: crdtSchema.LiveText() }),
};
export const { RoomProvider, useActions, useLiveStateSelector } =
createLiveState<NotebookJSON>()(notebookCRDTSchema, (notebook) => ({
replaceTitle: (content: string) => {
const title = notebook.get("title");
title.delete(0, title.length);
title.insert(0, content);
},
replaceDescription: (content: string) => {
notebook.set("description", content);
},
insertTitle: (index: number, content: string) => {
notebook.get("title").insert(index, content);
},
deleteTitle: (index: number, length: number) => {
notebook.get("title").delete(index, length);
},
addCell: () => {
notebook.get("cells").push([{ content: new Y.Text("Default text") }]);
},
deleteCell: (index: number) => {
notebook.get("cells").delete(index);
},
insertCellText: (cellIndex: number, index: number, content: string) => {
notebook.get("cells").get(cellIndex).content.insert(index, content);
},
deleteCellText: (cellIndex: number, index: number, length: number) => {
notebook.get("cells").get(cellIndex).content.delete(index, length);
},
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment