@yorkie-js/sdk 0.6.37 → 0.6.38

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/dist/quill.html CHANGED
@@ -3,359 +3,546 @@
3
3
  <head>
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <title>Yorkie + Quill Example</title>
6
+ <title>Quill Example</title>
7
7
  <link
8
- href="https://cdn.quilljs.com/1.3.6/quill.snow.css"
8
+ href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css"
9
9
  rel="stylesheet"
10
10
  />
11
11
  <link rel="stylesheet" href="style.css" />
12
- <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
13
- <script src="https://cdn.jsdelivr.net/npm/quill-cursors@3.1.0/dist/quill-cursors.min.js"></script>
12
+ <link rel="stylesheet" href="quill.css" />
13
+ <script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
14
+ <script src="https://cdn.jsdelivr.net/npm/quill-cursors@4.0.3/dist/quill-cursors.js"></script>
14
15
  <script src="https://cdn.jsdelivr.net/npm/color-hash@1.0.3/dist/color-hash.js"></script>
15
16
  </head>
16
17
  <body>
17
- <div id="network-status"></div>
18
- <div id="online-clients"></div>
19
- <div id="editor"></div>
20
- <div id="document"></div>
21
- <div id="document-text"></div>
18
+ <div class="client-container">
19
+ <div id="client-a">
20
+ Client A ( id:<span class="client-id"></span>)
21
+ <span class="network-status"></span>
22
+ <div class="syncmode-option">
23
+ <span>SyncMode: </span>
24
+ <div class="realtime-sync">
25
+ <span class="realtime-sync-title">Realtime Sync</span>
26
+ <div class="option">
27
+ <input
28
+ type="radio"
29
+ id="realtime-pushpull-a"
30
+ name="syncMode-a"
31
+ value="pushpull"
32
+ checked
33
+ />
34
+ <label for="realtime-pushpull-a">PushPull</label>
35
+ </div>
36
+ <div class="option">
37
+ <input
38
+ type="radio"
39
+ id="realtime-pushonly-a"
40
+ name="syncMode-a"
41
+ value="pushonly"
42
+ />
43
+ <label for="realtime-pushonly-a">PushOnly</label>
44
+ </div>
45
+ <div class="option">
46
+ <input
47
+ type="radio"
48
+ id="realtime-syncoff-a"
49
+ name="syncMode-a"
50
+ value="syncoff"
51
+ />
52
+ <label for="realtime-syncoff-a">SyncOff</label>
53
+ </div>
54
+ </div>
55
+ <div class="option">
56
+ <input
57
+ type="radio"
58
+ id="manual-a"
59
+ name="syncMode-a"
60
+ value="manual"
61
+ />
62
+ <label for="manual-a">Manual Sync</label>
63
+ <button class="manual-sync">sync</button>
64
+ </div>
65
+ </div>
66
+ <div class="editor"></div>
67
+ <div class="online-clients"></div>
68
+ </div>
69
+ <div id="client-b">
70
+ Client B ( id:<span class="client-id"></span>)
71
+ <span class="network-status"></span>
72
+ <div class="syncmode-option">
73
+ <span>SyncMode: </span>
74
+ <div class="realtime-sync">
75
+ <span class="realtime-sync-title">Realtime Sync</span>
76
+ <div class="option">
77
+ <input
78
+ type="radio"
79
+ id="realtime-pushpull-b"
80
+ name="syncMode-b"
81
+ value="pushpull"
82
+ checked
83
+ />
84
+ <label for="realtime-pushpull-b">PushPull</label>
85
+ </div>
86
+ <div class="option">
87
+ <input
88
+ type="radio"
89
+ id="realtime-pushonly-b"
90
+ name="syncMode-b"
91
+ value="pushonly"
92
+ />
93
+ <label for="realtime-pushonly-b">PushOnly</label>
94
+ </div>
95
+ <div class="option">
96
+ <input
97
+ type="radio"
98
+ id="realtime-syncoff-b"
99
+ name="syncMode-b"
100
+ value="syncoff"
101
+ />
102
+ <label for="realtime-syncoff-b">SyncOff</label>
103
+ </div>
104
+ </div>
105
+ <div class="option">
106
+ <input
107
+ type="radio"
108
+ id="manual-b"
109
+ name="syncMode-b"
110
+ value="manual"
111
+ />
112
+ <label for="manual-b">Manual Sync</label>
113
+ <button class="manual-sync">sync</button>
114
+ </div>
115
+ </div>
116
+ <div class="editor"></div>
117
+ <div class="online-clients"></div>
118
+ </div>
119
+ </div>
22
120
  <script type="module">
23
121
  import './src/yorkie.ts';
24
122
  import Network from './devtool/network.js';
25
123
 
26
- const onlineClientsElem = document.getElementById('online-clients');
27
- const documentElem = document.getElementById('document');
28
- const documentTextElem = document.getElementById('document-text');
29
- const networkStatusElem = document.getElementById('network-status');
30
124
  const colorHash = new ColorHash();
31
- const documentKey = 'quill';
125
+ const clientAElem = document.getElementById('client-a');
126
+ const clientBElem = document.getElementById('client-b');
127
+ const documentKey = 'quill-two-clients';
32
128
 
33
- function displayLog(elem, textElem, doc) {
34
- elem.innerText = doc.toJSON();
35
- textElem.innerText = doc.getRoot().content.toTestString();
129
+ function filterNullAttrs(attributes) {
130
+ if (!attributes) return undefined;
131
+
132
+ const filtered = {};
133
+ let hasNonNullValue = false;
134
+
135
+ for (const [key, value] of Object.entries(attributes)) {
136
+ if (value !== null) {
137
+ filtered[key] = value;
138
+ hasNonNullValue = true;
139
+ }
140
+ }
141
+
142
+ return hasNonNullValue ? filtered : undefined;
36
143
  }
37
144
 
38
- function toDeltaOperation(textValue) {
145
+ function toDeltaOperation(textValue, filterNull = false) {
39
146
  const { embed, ...restAttributes } = textValue.attributes ?? {};
40
-
41
147
  if (embed) {
42
- return { insert: embed, attributes: restAttributes };
148
+ return {
149
+ insert: JSON.parse(embed.toString()),
150
+ attributes: filterNull
151
+ ? filterNullAttrs(restAttributes)
152
+ : restAttributes,
153
+ };
43
154
  }
44
155
 
45
156
  return {
46
157
  insert: textValue.content || '',
47
- attributes: textValue.attributes,
158
+ attributes: filterNull
159
+ ? filterNullAttrs(textValue.attributes)
160
+ : textValue.attributes,
48
161
  };
49
162
  }
50
163
 
51
- function displayOnlineClients(presences, myClientID) {
52
- const clients = [];
53
- for (const { clientID, presence } of presences) {
54
- const clientElem = `<span class="client" style='background: ${presence.color}; color: white; margin-right:2px; padding:2px;'>${presence.name}</span>`;
55
- if (myClientID === clientID) {
56
- clients.unshift(clientElem);
57
- continue;
58
- }
59
- clients.push(clientElem);
60
- }
61
- onlineClientsElem.innerHTML = clients.join('');
62
- }
63
-
64
164
  async function main() {
65
165
  try {
66
- // 01. create client with RPCAddr then activate it.
67
- const client = new yorkie.Client({
68
- rpcAddr: 'http://localhost:8080',
69
- });
70
- await client.activate();
71
-
72
- // 02. create a document then attach it into the client.
73
- const doc = new yorkie.Document(documentKey, {
74
- enableDevtools: true,
75
- });
76
- doc.subscribe(
77
- 'connection',
78
- new Network(networkStatusElem).statusListener,
79
- );
80
- doc.subscribe('presence', (event) => {
81
- if (event.type === 'presence-changed') return;
82
- displayOnlineClients(doc.getPresences(), client.getID());
83
- });
84
-
85
- await client.attach(doc, {
86
- initialPresence: {
87
- name: client.getID().slice(-2),
88
- color: colorHash.hex(client.getID().slice(-2)),
89
- },
90
- });
91
-
92
- doc.update((root) => {
93
- if (!root.content) {
94
- root.content = new yorkie.Text();
95
- root.content.edit(0, 0, '\n');
96
- }
97
- }, 'create content if not exists');
166
+ async function initializeRealtimeEditor(clientElem) {
167
+ // 01. create client with RPCAddr(envoy) then activate it.
168
+ const client = new yorkie.Client({
169
+ rpcAddr: 'http://localhost:8080',
170
+ });
171
+ await client.activate();
172
+ const clientID = client.getID().slice(-2);
173
+ clientElem.querySelector('.client-id').textContent = clientID;
98
174
 
99
- // 02-2. subscribe document event.
100
- doc.subscribe((event) => {
101
- if (event.type === 'snapshot') {
102
- // The text is replaced to snapshot and must be re-synced.
103
- syncText();
104
- }
105
- displayLog(documentElem, documentTextElem, doc);
106
- });
175
+ // 02. create a document then attach it into the client.
176
+ const doc = new yorkie.Document(documentKey, {
177
+ enableDevtools: true,
178
+ });
179
+ doc.subscribe(
180
+ 'connection',
181
+ new Network(clientElem.querySelector('.network-status'))
182
+ .statusListener,
183
+ );
184
+ const onlineClients = clientElem.querySelector('.online-clients');
185
+ doc.subscribe('presence', (event) => {
186
+ // Update online clients list
187
+ if (event.type !== 'presence-changed') {
188
+ const clientIDs = doc
189
+ .getPresences()
190
+ .map(({ clientID }) => clientID)
191
+ .join(', ');
192
+ onlineClients.textContent = clientIDs;
193
+ }
107
194
 
108
- doc.subscribe('$.content', (event) => {
109
- if (event.type === 'remote-change') {
110
- const { actor, message, operations } = event.value;
111
- handleOperations(operations, actor);
112
- }
113
- updateAllCursors();
114
- });
195
+ console.warn(
196
+ `%c${clientID}`,
197
+ `color:white; padding: 2px 4px; border-radius: 3px;
198
+ background: ${colorHash.hex(clientID)}; `,
199
+ event.type,
200
+ );
201
+ });
115
202
 
116
- doc.subscribe('others', (event) => {
117
- if (event.type === 'unwatched') {
118
- cursors.removeCursor(event.value.clientID);
119
- } else if (event.type === 'presence-changed') {
120
- updateCursor(event.value);
121
- }
122
- });
123
-
124
- await client.sync();
125
-
126
- // 03. create an instance of Quill
127
- Quill.register('modules/cursors', QuillCursors);
128
- const quill = new Quill('#editor', {
129
- modules: {
130
- toolbar: [
131
- ['bold', 'italic', 'underline', 'strike'],
132
- ['blockquote', 'code-block'],
133
- [{ header: 1 }, { header: 2 }],
134
- [{ list: 'ordered' }, { list: 'bullet' }],
135
- [{ script: 'sub' }, { script: 'super' }],
136
- [{ indent: '-1' }, { indent: '+1' }],
137
- [{ direction: 'rtl' }],
138
- [{ size: ['small', false, 'large', 'huge'] }],
139
- [{ header: [1, 2, 3, 4, 5, 6, false] }],
140
- [{ color: [] }, { background: [] }],
141
- [{ font: [] }],
142
- [{ align: [] }],
143
- ['image', 'video'],
144
- ['clean'],
145
- ],
146
- cursors: true,
147
- },
148
- theme: 'snow',
149
- });
150
- const cursors = quill.getModule('cursors');
151
-
152
- function updateCursor(user) {
153
- const { clientID, presence } = user;
154
- if (clientID === client.getID()) return;
155
- // TODO(chacha912): After resolving the presence initialization issue(#608),
156
- // remove the following check.
157
- if (!presence) return;
158
-
159
- const { name, color, selection } = presence;
160
- if (!selection) return;
161
- const range = doc.getRoot().content.posRangeToIndexRange(selection);
162
- cursors.createCursor(clientID, name, color);
163
- cursors.moveCursor(clientID, {
164
- index: range[0],
165
- length: range[1] - range[0],
203
+ await client.attach(doc, {
204
+ initialPresence: { name: clientID },
166
205
  });
167
- }
168
206
 
169
- function updateAllCursors() {
170
- for (const user of doc.getPresences()) {
171
- updateCursor(user);
172
- }
173
- }
207
+ doc.update((root) => {
208
+ if (!root.content) {
209
+ root.content = new yorkie.Text();
210
+ root.content.edit(0, 0, '\n');
211
+ }
212
+ }, 'create content if not exists');
174
213
 
175
- // 04. bind the document with the Quill.
176
- // 04-1. Quill to Document.
177
- quill
178
- .on('text-change', (delta, _, source) => {
179
- if (source === 'api' || !delta.ops) {
180
- return;
214
+ // 02-2. subscribe document event.
215
+ doc.subscribe((event) => {
216
+ if (event.type === 'snapshot') {
217
+ // The text is replaced to snapshot and must be re-synced.
218
+ syncText(doc, quill);
181
219
  }
182
220
 
183
- let from = 0,
184
- to = 0;
185
- console.log(
186
- `%c quill: ${JSON.stringify(delta.ops)}`,
187
- 'color: green',
221
+ console.warn(
222
+ `%c${clientID}`,
223
+ `color:white; padding: 2px 4px; border-radius: 3px;
224
+ background: ${colorHash.hex(clientID)}; `,
225
+ event.type,
188
226
  );
189
- for (const op of delta.ops) {
190
- if (op.attributes !== undefined || op.insert !== undefined) {
191
- if (op.retain !== undefined) {
192
- to = from + op.retain;
193
- }
194
- console.log(
195
- `%c local: ${from}-${to}: ${op.insert} ${
196
- op.attributes ? JSON.stringify(op.attributes) : '{}'
197
- }`,
198
- 'color: green',
199
- );
200
-
201
- doc.update((root, presence) => {
202
- let range;
203
- if (
204
- op.attributes !== undefined &&
205
- op.insert === undefined
206
- ) {
207
- root.content.setStyle(from, to, op.attributes);
208
- } else if (op.insert !== undefined) {
209
- if (to < from) {
210
- to = from;
211
- }
227
+ });
212
228
 
213
- if (typeof op.insert === 'object') {
214
- range = root.content.edit(from, to, ' ', {
215
- embed: op.insert,
216
- ...op.attributes,
217
- });
218
- } else {
219
- range = root.content.edit(
220
- from,
221
- to,
222
- op.insert,
223
- op.attributes,
224
- );
225
- }
226
- from = to + op.insert.length;
227
- }
229
+ doc.subscribe('$.content', (event) => {
230
+ if (event.type === 'remote-change') {
231
+ const { message, operations } = event.value;
232
+ handleOperations(quill, operations);
233
+ }
234
+ updateAllCursors();
235
+ });
228
236
 
229
- if (range) {
230
- presence.set({
231
- selection: root.content.indexRangeToPosRange(range),
232
- });
233
- }
234
- }, `update style by ${client.getID()}`);
235
- } else if (op.delete !== undefined) {
236
- to = from + op.delete;
237
- console.log(`%c local: ${from}-${to}: ''`, 'color: green');
238
-
239
- doc.update((root, presence) => {
240
- const range = root.content.edit(from, to, '');
241
- if (range) {
242
- presence.set({
243
- selection: root.content.indexRangeToPosRange(range),
244
- });
245
- }
246
- }, `update content by ${client.getID()}`);
247
- } else if (op.retain !== undefined) {
248
- from = to + op.retain;
249
- to = from;
250
- }
237
+ doc.subscribe('presence', (event) => {
238
+ // Update cursors
239
+ if (event.type === 'initialized') {
240
+ updateAllCursors();
241
+ } else if (event.type === 'unwatched') {
242
+ cursors.removeCursor(event.value.clientID);
243
+ } else {
244
+ updateCursor(event.value);
251
245
  }
252
- })
253
- .on('selection-change', (range, _, source) => {
254
- if (!range) {
255
- return;
246
+ });
247
+
248
+ // 03. create an instance of Quill
249
+ const editorElem = clientElem?.getElementsByClassName('editor')[0];
250
+ Quill.register('modules/cursors', QuillCursors);
251
+ const quill = new Quill(editorElem, {
252
+ modules: {
253
+ toolbar: [
254
+ ['bold', 'italic', 'underline'],
255
+ [{ header: 1 }, { header: 2 }],
256
+ [{ list: 'ordered' }, { list: 'bullet' }],
257
+ ['blockquote', 'code-block'],
258
+ ['image', 'video'],
259
+ ['clean'],
260
+ ],
261
+ cursors: {
262
+ hideDelayMs: Number.MAX_VALUE,
263
+ },
264
+ },
265
+ theme: 'snow',
266
+ });
267
+ const cursors = quill.getModule('cursors');
268
+
269
+ function updateCursor(user) {
270
+ const { clientID, presence } = user;
271
+ // TODO(chacha912): After resolving the presence initialization issue(#608),
272
+ // remove the following check.
273
+ if (!presence) return;
274
+
275
+ const { name, selection } = presence;
276
+ if (!selection) return;
277
+ const range = doc
278
+ .getRoot()
279
+ .content.posRangeToIndexRange(selection);
280
+ cursors.createCursor(clientID, name, colorHash.hex(name));
281
+ cursors.moveCursor(clientID, {
282
+ index: range[0],
283
+ length: range[1] - range[0],
284
+ });
285
+ }
286
+
287
+ function updateAllCursors() {
288
+ cursors.clearCursors();
289
+ for (const user of doc.getPresences()) {
290
+ updateCursor(user);
256
291
  }
257
- // NOTE(chacha912): If the selection in the Quill editor does not match the range computed by yorkie,
258
- // additional updates are necessary. This condition addresses situations where Quill's selection behaves
259
- // differently, such as when inserting text before a range selection made by another user, causing
260
- // the second character onwards to be included in the selection.
261
- if (source === 'api') {
262
- const [from, to] = doc
263
- .getRoot()
264
- .content.posRangeToIndexRange(doc.getMyPresence().selection);
265
- const { index, length } = range;
266
- if (from === index && to === index + length) {
292
+ }
293
+
294
+ // 04. bind the document with the Quill.
295
+ // 04-1. Quill to Document.
296
+ quill
297
+ .on('text-change', (delta, _, source) => {
298
+ if (source === 'api' || !delta.ops) {
267
299
  return;
268
300
  }
269
- }
270
301
 
271
- doc.update((root, presence) => {
272
- presence.set({
273
- selection: root.content.indexRangeToPosRange([
274
- range.index,
275
- range.index + range.length,
276
- ]),
277
- });
278
- }, `update selection by ${client.getID()}`);
279
- });
280
-
281
- // 04-2. document to Quill(remote).
282
- function handleOperations(ops, actor) {
283
- const deltaOperations = [];
284
- let prevTo = 0;
285
- for (const op of ops) {
286
- const from = op.from;
287
- const to = op.to;
288
- const retainFrom = from - prevTo;
289
- const retainTo = to - from;
290
-
291
- if (op.type === 'edit') {
292
- const { insert, attributes } = toDeltaOperation(op.value);
302
+ let from = 0,
303
+ to = 0;
293
304
  console.log(
294
- `%c remote: ${from}-${to}: ${insert}`,
295
- 'color: skyblue',
305
+ `%c quill: ${JSON.stringify(delta.ops)}`,
306
+ 'color: green',
296
307
  );
308
+ doc.update((root, presence) => {
309
+ for (const op of delta.ops) {
310
+ if (
311
+ op.attributes !== undefined ||
312
+ op.insert !== undefined
313
+ ) {
314
+ if (
315
+ op.retain !== undefined &&
316
+ typeof op.retain === 'number'
317
+ ) {
318
+ to = from + op.retain;
319
+ }
320
+ console.log(
321
+ `%c local: ${from}-${to}: ${op.insert} ${
322
+ op.attributes ? JSON.stringify(op.attributes) : '{}'
323
+ }`,
324
+ 'color: green',
325
+ );
326
+
327
+ let range;
328
+ if (
329
+ op.attributes !== undefined &&
330
+ op.insert === undefined
331
+ ) {
332
+ root.content.setStyle(from, to, op.attributes);
333
+ from = to;
334
+ } else if (op.insert !== undefined) {
335
+ if (to < from) {
336
+ to = from;
337
+ }
338
+
339
+ if (typeof op.insert === 'object') {
340
+ range = root.content.edit(from, to, ' ', {
341
+ embed: JSON.stringify(op.insert),
342
+ ...op.attributes,
343
+ });
344
+ } else {
345
+ range = root.content.edit(
346
+ from,
347
+ to,
348
+ op.insert,
349
+ op.attributes,
350
+ );
351
+ }
352
+ from =
353
+ to +
354
+ (typeof op.insert === 'string'
355
+ ? op.insert.length
356
+ : 1);
357
+ }
297
358
 
298
- if (retainFrom) {
299
- deltaOperations.push({ retain: retainFrom });
300
- }
301
- if (retainTo) {
302
- deltaOperations.push({ delete: retainTo });
303
- }
304
- if (insert) {
305
- const deltaOp = { insert };
306
- if (attributes) {
307
- deltaOp.attributes = attributes;
359
+ if (range) {
360
+ presence.set({
361
+ selection: root.content.indexRangeToPosRange(range),
362
+ });
363
+ }
364
+ } else if (op.delete !== undefined) {
365
+ to = from + op.delete;
366
+ console.log(
367
+ `%c local: ${from}-${to}: ''`,
368
+ 'color: green',
369
+ );
370
+
371
+ const range = root.content.edit(from, to, '');
372
+ if (range) {
373
+ presence.set({
374
+ selection: root.content.indexRangeToPosRange(range),
375
+ });
376
+ }
377
+ // After delete, 'to' should stay at 'from' since content was removed
378
+ to = from;
379
+ } else if (
380
+ op.retain !== undefined &&
381
+ typeof op.retain === 'number'
382
+ ) {
383
+ from = to + op.retain;
384
+ to = from;
385
+ }
308
386
  }
309
- deltaOperations.push(deltaOp);
387
+ });
388
+ })
389
+ .on('selection-change', (range, _, source) => {
390
+ if (!range) {
391
+ return;
310
392
  }
311
- } else if (op.type === 'style') {
312
- const { attributes } = toDeltaOperation(op.value);
313
- console.log(
314
- `%c remote: ${from}-${to}: ${JSON.stringify(attributes)}`,
315
- 'color: skyblue',
316
- );
317
393
 
318
- if (retainFrom) {
319
- deltaOperations.push({ retain: retainFrom });
394
+ // NOTE(chacha912): If the selection in the Quill editor does not match the range computed by yorkie,
395
+ // additional updates are necessary. This condition addresses situations where Quill's selection behaves
396
+ // differently, such as when inserting text before a range selection made by another user, causing
397
+ // the second character onwards to be included in the selection.
398
+ if (source === 'api') {
399
+ const { selection } = doc.getMyPresence();
400
+ if (selection) {
401
+ const [from, to] = doc
402
+ .getRoot()
403
+ .content.posRangeToIndexRange(selection);
404
+ const { index, length } = range;
405
+ if (from === index && to === index + length) {
406
+ return;
407
+ }
408
+ }
320
409
  }
321
- if (attributes) {
322
- const deltaOp = { attributes };
410
+
411
+ doc.update((root, presence) => {
412
+ presence.set({
413
+ selection: root.content.indexRangeToPosRange([
414
+ range.index,
415
+ range.index + range.length,
416
+ ]),
417
+ });
418
+ }, `update selection by ${client.getID()}`);
419
+ });
420
+
421
+ // 04-2. document to Quill(remote).
422
+ function handleOperations(quill, ops) {
423
+ const deltaOperations = [];
424
+ let prevTo = 0;
425
+ for (const op of ops) {
426
+ if (op.type === 'edit') {
427
+ const from = op.from;
428
+ const to = op.to;
429
+ const retainFrom = from - prevTo;
430
+ const retainTo = to - from;
431
+
432
+ const { insert, attributes } = toDeltaOperation(
433
+ op.value,
434
+ true,
435
+ );
436
+ console.log(
437
+ `%c remote: ${from}-${to}: ${insert}`,
438
+ 'color: skyblue',
439
+ );
440
+
441
+ if (retainFrom) {
442
+ deltaOperations.push({ retain: retainFrom });
443
+ }
323
444
  if (retainTo) {
324
- deltaOp.retain = retainTo;
445
+ deltaOperations.push({ delete: retainTo });
325
446
  }
447
+ const insertLength =
448
+ typeof insert === 'string' ? insert.length : 0;
449
+ if (insert) {
450
+ const op = { insert };
451
+ if (attributes) {
452
+ op.attributes = attributes;
453
+ }
454
+ deltaOperations.push(op);
455
+ }
456
+ // Update prevTo considering the actual text change:
457
+ // from + length of inserted text (delete is already handled by retainTo)
458
+ prevTo = from + insertLength;
459
+ } else if (op.type === 'style') {
460
+ const from = op.from;
461
+ const to = op.to;
462
+ const retainFrom = from - prevTo;
463
+ const retainTo = to - from;
464
+ const { attributes } = toDeltaOperation(op.value, false);
465
+ console.log(
466
+ `%c remote: ${from}-${to}: ${JSON.stringify(attributes)}`,
467
+ 'color: skyblue',
468
+ );
326
469
 
327
- deltaOperations.push(deltaOp);
470
+ if (retainFrom) {
471
+ deltaOperations.push({ retain: retainFrom });
472
+ }
473
+ if (attributes) {
474
+ const op = { attributes };
475
+ if (retainTo) {
476
+ op.retain = retainTo;
477
+ }
478
+
479
+ deltaOperations.push(op);
480
+ }
481
+ prevTo = to;
328
482
  }
329
483
  }
330
484
 
331
- prevTo = to;
485
+ if (deltaOperations.length) {
486
+ console.log(
487
+ `%c to quill: ${JSON.stringify(deltaOperations)}`,
488
+ 'color: green',
489
+ );
490
+ const delta = new Quill.imports.delta(deltaOperations);
491
+ quill.updateContents(delta, 'api');
492
+ }
332
493
  }
333
494
 
334
- if (deltaOperations.length) {
335
- console.log(
336
- `%c to quill: ${JSON.stringify(deltaOperations)}`,
337
- 'color: green',
495
+ // 05. synchronize text of document and Quill.
496
+ function syncText(doc, quill) {
497
+ const text = doc.getRoot().content;
498
+ const delta = new Quill.imports.delta(
499
+ text.values().map((val) => toDeltaOperation(val, true)),
338
500
  );
339
- quill.updateContents({ ops: deltaOperations }, 'api');
501
+ quill.setContents(delta, 'api');
340
502
  }
341
- }
342
503
 
343
- // 05. synchronize text of document and Quill.
344
- function syncText() {
345
- const text = doc.getRoot().content;
346
- const delta = {
347
- ops: text.values().map((val) => toDeltaOperation(val)),
348
- };
349
- quill.setContents(delta, 'api');
504
+ // 06. sync option
505
+ const option = clientElem.querySelector('.syncmode-option');
506
+ option.addEventListener('change', async (e) => {
507
+ if (!event.target.matches('input[type="radio"]')) {
508
+ return;
509
+ }
510
+ const syncMode = event.target.value;
511
+ switch (syncMode) {
512
+ case 'pushpull':
513
+ await client.changeSyncMode(doc, 'realtime');
514
+ break;
515
+ case 'pushonly':
516
+ await client.changeSyncMode(doc, 'realtime-pushonly');
517
+ break;
518
+ case 'syncoff':
519
+ await client.changeSyncMode(doc, 'realtime-syncoff');
520
+ break;
521
+ case 'manual':
522
+ await client.changeSyncMode(doc, 'manual');
523
+ break;
524
+ default:
525
+ break;
526
+ }
527
+ });
528
+ const syncButton = clientElem.querySelector('.manual-sync');
529
+ syncButton.addEventListener('click', async () => {
530
+ await client.sync(doc);
531
+ });
532
+
533
+ syncText(doc, quill);
534
+ updateAllCursors();
535
+
536
+ return { client, doc, quill };
350
537
  }
351
538
 
352
- syncText();
353
- updateAllCursors();
354
- displayLog(documentElem, documentTextElem, doc);
539
+ await initializeRealtimeEditor(clientAElem);
540
+ await initializeRealtimeEditor(clientBElem);
355
541
  } catch (e) {
356
542
  console.error(e);
357
543
  }
358
544
  }
545
+
359
546
  main();
360
547
  </script>
361
548
  </body>