Rich Text Editor
This demo shows the real-time collaborative version of the Quill editor with Yorkie and Vite.
main.ts
1import yorkie, { DocEventType, Indexable, OpInfo } from '@yorkie-js/sdk';2import Quill, { Delta, type Op } from 'quill';3import QuillCursors from 'quill-cursors';4import 'quill/dist/quill.snow.css';5import { displayError, displayStatus, statusListener } from './network';6import './style.css';7import { YorkieDoc, YorkiePresence } from './type';8import {9 createPeer,10 displayPeers,11 getDocKey,12 linkToDoc,13 peerColor,14} from './utils';1516type TextValueType = {17 attributes?: Indexable;18 content?: string;19};2021const statusElem = document.getElementById('network-status')!;22const peersElem = document.getElementById('peers')!;23const errorElem = document.getElementById('error')!;24const noticeElem = document.getElementById('notice')!;25const shareLinkElem = document.getElementById(26 'share-link',27) as HTMLAnchorElement;2829const rpcAddr = import.meta.env.VITE_YORKIE_API_ADDR;30const documentKey = getDocKey('vanilla-quill');31linkToDoc(shareLinkElem, documentKey);3233// Filter out null values from attributes34function filterNullAttrs(attributes?: Indexable): Indexable | undefined {35 if (!attributes) return;3637 const filtered: Indexable = {};38 let hasNonNullValue = false;3940 for (const [key, value] of Object.entries(attributes)) {41 if (value !== null) {42 filtered[key] = value;43 hasNonNullValue = true;44 }45 }4647 return hasNonNullValue ? filtered : undefined;48}4950function toDeltaOperation<T extends TextValueType>(51 textValue: T,52 filterNull: boolean = false,53): Op {54 const { embed, ...restAttributes } = textValue.attributes ?? {};55 if (embed) {56 return {57 insert: JSON.parse(embed.toString()),58 attributes: filterNull ? filterNullAttrs(restAttributes) : restAttributes,59 };60 }6162 return {63 insert: textValue.content || '',64 attributes: filterNull65 ? filterNullAttrs(textValue.attributes)66 : textValue.attributes,67 };68}6970async function main() {71 displayStatus(statusElem, 'connecting');7273 // 01-1. create client with RPCAddr then activate it.74 const client = new yorkie.Client({75 rpcAddr,76 apiKey: import.meta.env.VITE_YORKIE_API_KEY,77 });78 await client.activate();7980 // 02-1. create a document then attach it into the client.81 const doc = new yorkie.Document<YorkieDoc, YorkiePresence>(documentKey, {82 enableDevtools: import.meta.env.DEV,83 });84 doc.subscribe('connection', statusListener(statusElem));85 doc.subscribe('presence', (event) => {86 // Names and colours never change, so only joins and leaves redraw the87 // avatars. Presences are keyed by the client's actor ID.88 if (event.type !== DocEventType.PresenceChanged) {89 displayPeers(peersElem, doc.getPresences(), client.getActorID()!);90 }91 });9293 await client.attach(doc, {94 initialPresence: createPeer(client.getActorID()!),95 });9697 doc.update((root) => {98 if (!root.content) {99 root.content = new yorkie.Text();100 root.content.edit(0, 0, '\n');101 }102 }, 'create content if not exists');103104 function updateCursor(user: { clientID: string; presence: YorkiePresence }) {105 const { clientID, presence } = user;106 if (clientID === client.getActorID()) return;107108 const { username, color, selection } = presence;109 if (!selection) return;110 // A peer's selection can point at text this client hasn't received yet;111 // skip that peer until it arrives instead of failing every peer.112 let range: [number, number];113 try {114 range = doc.getRoot().content.posRangeToIndexRange(selection);115 } catch {116 return;117 }118 cursors.createCursor(clientID, username, peerColor(color));119 cursors.moveCursor(clientID, {120 index: range[0],121 length: range[1] - range[0],122 });123 }124125 function updateAllCursors() {126 for (const user of doc.getPresences()) {127 updateCursor(user);128 }129 }130131 await client.sync();132133 // 03. create an instance of Quill134 // Track composition state to prevent selection updates during IME input135 let isComposing = false;136137 Quill.register('modules/cursors', QuillCursors);138 const quill = new Quill('#editor', {139 modules: {140 // Simplified toolbar: keep only core formatting features.141 // Add or remove items easily by editing this array.142 toolbar: {143 container: [144 ['bold', 'italic', 'underline'],145 [{ header: 1 }, { header: 2 }],146 [{ list: 'ordered' }, { list: 'bullet' }],147 ['blockquote', 'code-block'],148 ['image', 'video'],149 ['clean'],150 ],151 handlers: {152 image: imageHandler,153 },154 },155 cursors: true,156 history: {157 maxStack: 0, // Disable Quill's built-in undo/redo in favor of Yorkie's158 },159 },160 theme: 'snow',161 });162 const cursors = quill.getModule('cursors') as QuillCursors;163164 // 03-1. subscribe document event, now that the editor exists to apply165 // remote changes and cursors to.166 doc.subscribe((event) => {167 if (event.type === 'snapshot') {168 // The text is replaced to snapshot and must be re-synced.169 syncText();170 }171 });172173 doc.subscribe('$.content', (event) => {174 if (event.type === 'remote-change') {175 handleOperations(event.value.operations);176 } else if (event.source === 'undoredo') {177 handleOperations(event.value.operations, true);178 }179 updateAllCursors();180 });181 doc.subscribe('others', (event) => {182 if (event.type === DocEventType.Unwatched) {183 cursors.removeCursor(event.value.clientID);184 } else if (event.type === DocEventType.PresenceChanged) {185 updateCursor(event.value);186 }187 });188189 // Custom image handler to check file size (max 1MB)190 function imageHandler() {191 const input = document.createElement('input');192 input.setAttribute('type', 'file');193 input.setAttribute('accept', 'image/*');194 input.click();195196 input.onchange = () => {197 const file = input.files?.[0];198 if (!file) return;199200 // Images are stored inline in the document, so keep them small.201 const maxSize = 1 * 1024 * 1024; // 1MB in bytes202 noticeElem.hidden = file.size <= maxSize;203 if (file.size > maxSize) {204 const size = (file.size / 1024 / 1024).toFixed(2);205 noticeElem.textContent = `That image is ${size} MB. Pick one under 1 MB.`;206 return;207 }208209 const reader = new FileReader();210 reader.onload = (e) => {211 const range = quill.getSelection(true);212 const imageData = e.target?.result;213214 // Insert image in Quill editor first215 quill.insertEmbed(range.index, 'image', imageData, 'user');216 quill.setSelection(range.index + 1, 0, 'silent');217 };218 reader.readAsDataURL(file);219 };220 }221222 // 04. bind the document with the Quill.223 // Track composition events to prevent selection updates during IME input224 const editorElement = quill.root;225 editorElement.addEventListener('compositionstart', () => {226 isComposing = true;227 });228 editorElement.addEventListener('compositionend', () => {229 isComposing = false;230 });231232 // 04-0. bind Yorkie undo/redo to keyboard shortcuts.233 editorElement.addEventListener('keydown', (e) => {234 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {235 if (e.shiftKey) {236 if (doc.history.canRedo()) {237 doc.history.redo();238 }239 } else {240 if (doc.history.canUndo()) {241 doc.history.undo();242 }243 }244 e.preventDefault();245 }246 });247248 // 04-1. Quill to Document.249 quill250 .on('text-change', (delta, _, source) => {251 if (source === 'api' || !delta.ops) {252 return;253 }254255 let from = 0,256 to = 0;257 try {258 doc.update((root, presence) => {259 for (const op of delta.ops) {260 if (op.attributes !== undefined || op.insert !== undefined) {261 if (op.retain !== undefined && typeof op.retain === 'number') {262 to = from + op.retain;263 }264 let range;265 if (op.attributes !== undefined && op.insert === undefined) {266 root.content.setStyle(from, to, op.attributes as Indexable);267 from = to;268 } else if (op.insert !== undefined) {269 if (to < from) {270 to = from;271 }272273 if (typeof op.insert === 'object') {274 range = root.content.edit(from, to, ' ', {275 embed: JSON.stringify(op.insert),276 ...op.attributes,277 });278 } else {279 range = root.content.edit(280 from,281 to,282 op.insert,283 op.attributes as Indexable,284 );285 }286 from =287 to + (typeof op.insert === 'string' ? op.insert.length : 1);288 to = from;289 }290291 if (range) {292 presence.set({293 selection: root.content.indexRangeToPosRange(range),294 });295 }296 } else if (op.delete !== undefined) {297 to = from + op.delete;298 const range = root.content.edit(from, to, '');299 if (range) {300 presence.set({301 selection: root.content.indexRangeToPosRange(range),302 });303 }304 // After delete, 'to' should stay at 'from' since content was removed305 to = from;306 } else if (307 op.retain !== undefined &&308 typeof op.retain === 'number'309 ) {310 from += op.retain;311 to = from;312 }313 }314 });315 } catch (err) {316 // `Text.edit` refuses an index that splits a UTF-16 surrogate pair,317 // and content carrying a lone half of one, so a local Quill change is318 // not guaranteed to reach the document. `doc.update` discarded the319 // whole delta, so rebuild the editor from the document instead of320 // leaving the two silently diverged.321 console.error('local edit rejected, re-syncing editor:', err);322 syncText();323 updateAllCursors();324 }325 })326 .on('selection-change', (range, _, source) => {327 if (!range) {328 return;329 }330331 // Ignore selection changes during composition (e.g., Korean IME input)332 // to prevent cursor position from being broadcast incorrectly to other users333 if (isComposing) {334 return;335 }336337 // NOTE(chacha912): If the selection in the Quill editor does not match the range computed by yorkie,338 // additional updates are necessary. This condition addresses situations where Quill's selection behaves339 // differently, such as when inserting text before a range selection made by another user, causing340 // the second character onwards to be included in the selection.341 if (source === 'api') {342 const { selection } = doc.getMyPresence();343 if (selection) {344 const [from, to] = doc345 .getRoot()346 .content.posRangeToIndexRange(selection);347 const { index, length } = range;348 if (from === index && to === index + length) {349 return;350 }351 }352 }353354 doc.update((root, presence) => {355 presence.set({356 selection: root.content.indexRangeToPosRange([357 range.index,358 range.index + range.length,359 ]),360 });361 }, `update selection by ${client.getID()}`);362 });363364 // Handle selection changes when mouse is released outside the editor.365 // Only write presence when the selection actually moved, so a click366 // elsewhere on the page doesn't send an update to every peer.367 document.addEventListener('mouseup', () => {368 // Ignore selection changes during composition369 if (isComposing) {370 return;371 }372373 const range = quill.getSelection();374 if (!range) return;375 const { selection } = doc.getMyPresence();376 if (selection) {377 const [from, to] = doc.getRoot().content.posRangeToIndexRange(selection);378 if (from === range.index && to === range.index + range.length) return;379 }380 doc.update((root, presence) => {381 presence.set({382 selection: root.content.indexRangeToPosRange([383 range.index,384 range.index + range.length,385 ]),386 });387 }, `update selection by ${client.getID()}`);388 });389390 // 04-2. document to Quill(remote and undo/redo).391 function handleOperations(ops: Array<OpInfo>, moveCursor: boolean = false) {392 const hasFocus = quill.hasFocus();393394 // On Safari, DOM mutations in a contenteditable element can steal focus395 // from other iframes. Temporarily disable contenteditable for remote396 // updates when this editor doesn't have focus.397 if (!hasFocus) {398 quill.root.setAttribute('contenteditable', 'false');399 }400401 let cursorPosition = -1;402 for (const op of ops) {403 if (op.type === 'edit') {404 const from = op.from;405 const to = op.to;406 const { insert, attributes } = toDeltaOperation(op.value!, true);407408 const deltaOperations: Op[] = [];409410 if (from > 0) {411 deltaOperations.push({ retain: from });412 }413414 const deleteLength = to - from;415 if (deleteLength > 0) {416 deltaOperations.push({ delete: deleteLength });417 }418419 if (insert) {420 const op: Op = { insert };421 if (attributes) {422 op.attributes = attributes;423 }424 deltaOperations.push(op);425 }426427 if (deltaOperations.length > 0) {428 const delta = new Delta(deltaOperations);429 quill.updateContents(delta, 'api');430 }431432 if (moveCursor) {433 const insertLength =434 typeof insert === 'string' ? insert.length : insert ? 1 : 0;435 cursorPosition = from + insertLength;436 }437 } else if (op.type === 'style') {438 const from = op.from;439 const to = op.to;440 const { attributes } = toDeltaOperation(op.value!, false);441442 if (attributes) {443 const deltaOperations: Op[] = [];444445 if (from > 0) {446 deltaOperations.push({ retain: from });447 }448449 const op: Op = { attributes };450 const retainLength = to - from;451 if (retainLength > 0) {452 op.retain = retainLength;453 }454 deltaOperations.push(op);455456 const delta = new Delta(deltaOperations);457 quill.updateContents(delta, 'api');458 }459460 if (moveCursor) {461 cursorPosition = to;462 }463 }464 }465466 // Move cursor to the changed position for undo/redo467 if (moveCursor && cursorPosition >= 0) {468 quill.setSelection(cursorPosition, 0, 'api');469 }470471 if (!hasFocus) {472 quill.root.setAttribute('contenteditable', 'true');473 }474 }475476 // 05. synchronize text of document and Quill.477 function syncText() {478 const hasFocus = quill.hasFocus();479 if (!hasFocus) {480 quill.root.setAttribute('contenteditable', 'false');481 }482483 const text = doc.getRoot().content;484 const delta = new Delta(485 text.values().map((value) => toDeltaOperation(value, true)),486 );487 quill.setContents(delta, 'api');488489 if (!hasFocus) {490 quill.root.setAttribute('contenteditable', 'true');491 }492 }493494 syncText();495 updateAllCursors();496}497498main().catch(() => {499 displayError(statusElem, errorElem, rpcAddr);500});
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1