Skip to content

feat: re-implement Y.js collaboration as BlockNote plugins #1638

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 0 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,6 @@
"@tiptap/core": "^2.11.5",
"@tiptap/extension-bold": "^2.11.5",
"@tiptap/extension-code": "^2.11.5",
"@tiptap/extension-collaboration": "^2.11.5",
"@tiptap/extension-collaboration-cursor": "^2.11.5",
"@tiptap/extension-gapcursor": "^2.11.5",
"@tiptap/extension-history": "^2.11.5",
"@tiptap/extension-horizontal-rule": "^2.11.5",
Expand Down
11 changes: 9 additions & 2 deletions packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ import { CodeBlockOptions } from "../blocks/CodeBlockContent/CodeBlockContent.js
import type { ThreadStore, User } from "../comments/index.js";
import "../style.css";
import { EventEmitter } from "../util/EventEmitter.js";
import { CursorPlugin } from "../extensions/Collaboration/CursorPlugin.js";

export type BlockNoteExtensionFactory = (
editor: BlockNoteEditor<any, any, any>
Expand All @@ -124,6 +125,7 @@ export type BlockNoteExtension =
| AnyExtension
| {
plugin: Plugin;
priority?: number;
};

export type BlockCache<
Expand Down Expand Up @@ -472,6 +474,8 @@ export class BlockNoteEditor<

private readonly showSelectionPlugin: ShowSelectionPlugin;

private readonly cursorPlugin: CursorPlugin;

/**
* The `uploadFile` method is what the editor uses when files need to be uploaded (for example when selecting an image to upload).
* This method should set when creating the editor as this is application-specific.
Expand Down Expand Up @@ -622,6 +626,7 @@ export class BlockNoteEditor<
this.tableHandles = this.extensions["tableHandles"] as any;
this.comments = this.extensions["comments"] as any;
this.showSelectionPlugin = this.extensions["showSelection"] as any;
this.cursorPlugin = this.extensions["yCursorPlugin"] as any;

if (newOptions.uploadFile) {
const uploadFile = newOptions.uploadFile;
Expand All @@ -643,7 +648,7 @@ export class BlockNoteEditor<
this.headless = newOptions._headless;

const collaborationEnabled =
"collaboration" in this.extensions ||
"ySyncPlugin" in this.extensions ||
"liveblocksExtension" in this.extensions;

if (collaborationEnabled && newOptions.initialContent) {
Expand Down Expand Up @@ -696,6 +701,7 @@ export class BlockNoteEditor<
// "blocknote" extensions (prosemirror plugins)
return Extension.create({
name: key,
priority: ext.priority,
addProseMirrorPlugins: () => [ext.plugin],
});
}),
Expand Down Expand Up @@ -1488,7 +1494,8 @@ export class BlockNoteEditor<
"Cannot update collaboration user info when collaboration is disabled."
);
}
this._tiptapEditor.commands.updateUser(user);

this.cursorPlugin.updateUser(user);
}

/**
Expand Down
19 changes: 14 additions & 5 deletions packages/core/src/editor/BlockNoteExtensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import { createDropFileExtension } from "../api/clipboard/fromClipboard/fileDrop
import { createPasteFromClipboardExtension } from "../api/clipboard/fromClipboard/pasteExtension.js";
import { createCopyToClipboardExtension } from "../api/clipboard/toClipboard/copyExtension.js";
import { BackgroundColorExtension } from "../extensions/BackgroundColor/BackgroundColorExtension.js";
import { createCollaborationExtensions } from "../extensions/Collaboration/createCollaborationExtensions.js";
import { CursorPlugin } from "../extensions/Collaboration/CursorPlugin.js";
import { UndoPlugin } from "../extensions/Collaboration/UndoPlugin.js";
import { SyncPlugin } from "../extensions/Collaboration/SyncPlugin.js";
import { CommentMark } from "../extensions/Comments/CommentMark.js";
import { CommentsPlugin } from "../extensions/Comments/CommentsPlugin.js";
import type { ThreadStore } from "../comments/index.js";
Expand Down Expand Up @@ -106,6 +108,15 @@ export const getBlockNoteExtensions = <
ret[ext.name] = ext;
}

if (opts.collaboration) {
ret["ySyncPlugin"] = new SyncPlugin(opts.collaboration.fragment);
ret["yUndoPlugin"] = new UndoPlugin();

if (opts.collaboration.provider?.awareness) {
ret["yCursorPlugin"] = new CursorPlugin(opts.collaboration);
}
}

// Note: this is pretty hardcoded and will break when user provides plugins with same keys.
// Define name on plugins instead and not make this a map?
ret["formattingToolbar"] = new FormattingToolbarProsemirrorPlugin(
Expand Down Expand Up @@ -285,10 +296,8 @@ const getTipTapExtensions = <

LINKIFY_INITIALIZED = true;

if (opts.collaboration) {
tiptapExtensions.push(...createCollaborationExtensions(opts.collaboration));
} else {
// disable history extension when collaboration is enabled as Yjs takes care of undo / redo
if (!opts.collaboration) {
// disable history extension when collaboration is enabled as y-prosemirror takes care of undo / redo
tiptapExtensions.push(History);
}

Expand Down
152 changes: 152 additions & 0 deletions packages/core/src/extensions/Collaboration/CursorPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { Plugin } from "prosemirror-state";
import { defaultSelectionBuilder, yCursorPlugin } from "y-prosemirror";
import { Awareness } from "y-protocols/awareness.js";
import * as Y from "yjs";

export type CollaborationUser = {
name: string;
color: string;
[key: string]: string;
};

export class CursorPlugin {
public plugin: Plugin;
private provider: { awareness: Awareness };
private recentlyUpdatedCursors: Map<
number,
{ element: HTMLElement; hideTimeout: NodeJS.Timeout | undefined }
>;
constructor(
private collaboration: {
fragment: Y.XmlFragment;
user: CollaborationUser;
provider: { awareness: Awareness };
renderCursor?: (user: CollaborationUser) => HTMLElement;
showCursorLabels?: "always" | "activity";
}
) {
this.provider = collaboration.provider;
this.recentlyUpdatedCursors = new Map();

this.provider.awareness.setLocalStateField("user", collaboration.user);

if (collaboration.showCursorLabels !== "always") {
this.provider.awareness.on(
"change",
({
updated,
}: {
added: Array<number>;
updated: Array<number>;
removed: Array<number>;
}) => {
for (const clientID of updated) {
const cursor = this.recentlyUpdatedCursors.get(clientID);

if (cursor) {
cursor.element.setAttribute("data-active", "");

if (cursor.hideTimeout) {
clearTimeout(cursor.hideTimeout);
}

this.recentlyUpdatedCursors.set(clientID, {
element: cursor.element,
hideTimeout: setTimeout(() => {
cursor.element.removeAttribute("data-active");
}, 2000),
});
}
}
}
);
}

this.plugin = yCursorPlugin(this.provider.awareness, {
selectionBuilder: defaultSelectionBuilder,
cursorBuilder: this.renderCursor,
});
}

public get priority() {
return 999;
}

private renderCursor = (user: CollaborationUser, clientID: number) => {
let cursorData = this.recentlyUpdatedCursors.get(clientID);

if (!cursorData) {
const cursorElement = (
this.collaboration.renderCursor ?? CursorPlugin.defaultCursorRender
)(user);

if (this.collaboration.showCursorLabels !== "always") {
cursorElement.addEventListener("mouseenter", () => {
const cursor = this.recentlyUpdatedCursors.get(clientID)!;
cursor.element.setAttribute("data-active", "");

if (cursor.hideTimeout) {
clearTimeout(cursor.hideTimeout);
this.recentlyUpdatedCursors.set(clientID, {
element: cursor.element,
hideTimeout: undefined,
});
}
});

cursorElement.addEventListener("mouseleave", () => {
const cursor = this.recentlyUpdatedCursors.get(clientID)!;

this.recentlyUpdatedCursors.set(clientID, {
element: cursor.element,
hideTimeout: setTimeout(() => {
cursor.element.removeAttribute("data-active");
}, 2000),
});
});
}

cursorData = {
element: cursorElement,
hideTimeout: undefined,
};

this.recentlyUpdatedCursors.set(clientID, cursorData);
}

return cursorData.element;
};

public updateUser = (user: {
name: string;
color: string;
[key: string]: string;
}) => {
this.provider.awareness.setLocalStateField("user", user);
};

public static defaultCursorRender = (user: CollaborationUser) => {
const cursorElement = document.createElement("span");

cursorElement.classList.add("bn-collaboration-cursor__base");

const caretElement = document.createElement("span");
caretElement.setAttribute("contentedEditable", "false");
caretElement.classList.add("bn-collaboration-cursor__caret");
caretElement.setAttribute("style", `background-color: ${user.color}`);

const labelElement = document.createElement("span");

labelElement.classList.add("bn-collaboration-cursor__label");
labelElement.setAttribute("style", `background-color: ${user.color}`);
labelElement.insertBefore(document.createTextNode(user.name), null);

caretElement.insertBefore(labelElement, null);

cursorElement.insertBefore(document.createTextNode("\u2060"), null); // Non-breaking space
cursorElement.insertBefore(caretElement, null);
cursorElement.insertBefore(document.createTextNode("\u2060"), null); // Non-breaking space

return cursorElement;
};
}
15 changes: 15 additions & 0 deletions packages/core/src/extensions/Collaboration/SyncPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Plugin } from "prosemirror-state";
import { ySyncPlugin } from "y-prosemirror";
import type * as Y from "yjs";

export class SyncPlugin {
public plugin: Plugin;

constructor(fragment: Y.XmlFragment) {
this.plugin = ySyncPlugin(fragment);
}

public get priority() {
return 1001;
}
}
14 changes: 14 additions & 0 deletions packages/core/src/extensions/Collaboration/UndoPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Plugin } from "prosemirror-state";
import { yUndoPlugin } from "y-prosemirror";

export class UndoPlugin {
public plugin: Plugin;

constructor() {
this.plugin = yUndoPlugin();
}

public get priority() {
return 1000;
}
}
Loading
Loading