-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathSuperDoc.js
More file actions
702 lines (598 loc) · 21.5 KB
/
SuperDoc.js
File metadata and controls
702 lines (598 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
// TODO: side-effect with styles
import '../style.css';
import '@harbour-enterprises/super-editor/style.css';
import EventEmitter from 'eventemitter3';
import { v4 as uuidv4 } from 'uuid';
import { HocuspocusProviderWebsocket } from '@hocuspocus/provider';
import { DOCX, PDF, HTML } from '@harbour-enterprises/common';
import { SuperToolbar, createZip } from '@harbour-enterprises/super-editor';
import { SuperComments } from '../components/CommentsLayer/commentsList/super-comments-list.js';
import { createSuperdocVueApp } from './create-app';
import { shuffleArray } from '@harbour-enterprises/common/collaboration/awareness.js';
import { Telemetry } from '@harbour-enterprises/common/Telemetry.js';
import { createDownload, cleanName } from './helpers/export.js';
import {
initSuperdocYdoc,
initCollaborationComments,
makeDocumentsCollaborative,
} from './collaboration/helpers.js';
/**
* @typedef {Object} User The current user of this superdoc
* @property {string} name The user's name
* @property {string} email The user's email
* @property {string | null} image The user's photo
*/
/**
* @typedef {Object} Telemetry Telemetry configuration
* @property {boolean} [enabled=true] Whether telemetry is enabled
* @property {string} [licenceKey] The licence key for telemetry
* @property {string} [endpoint] The endpoint for telemetry
*/
/**
* @typedef {Object} Document
* @property {string} id The ID of the document
* @property {string} type The type of the document
* @property {File | null} [data] The initial data of the document
*/
/**
* @typedef {Object} Modules
* @property {Object} [comments] Comments module configuration
* @property {Object} [ai] AI module configuration
* @property {string} [ai.apiKey] Harbour API key for AI features
* @property {string} [ai.endpoint] Custom endpoint URL for AI services
*/
/**
* @typedef {Object} Config
* @property {string} [superdocId] The ID of the SuperDoc
* @property {string} selector The selector to mount the SuperDoc into
* @property {'editing' | 'viewing' | 'suggesting'} documentMode The mode of the document
* @property {'editor' | 'viewer' | 'suggester'} [role] The role of the user in this SuperDoc
* @property {Object | string} [document] The document to load. If a string, it will be treated as a URL
* @property {Array<Document>} documents The documents to load
* @property {User} [user] The current user of this SuperDoc
* @property {Array<User>} [users] All users of this SuperDoc (can be used for "@"-mentions)
* @property {Array<string>} [colors] Colors to use for user awareness
* @property {Modules} [modules] Modules to load
* @property {boolean} [pagination] Whether to show pagination in SuperEditors
* @property {string} [toolbar] Optional DOM element to render the toolbar in
* @property {Array<string>} [toolbarGroups] Toolbar groups to show
* @property {Object} [toolbarIcons] Icons to show in the toolbar
* @property {boolean} [isDev] Whether the SuperDoc is in development mode
* @property {Telemetry} [telemetry] Telemetry configuration
* @property {(editor: Editor) => void} [onEditorBeforeCreate] Callback before an editor is created
* @property {(editor: Editor) => void} [onEditorCreate] Callback after an editor is created
* @property {() => void} [onEditorDestroy] Callback after an editor is destroyed
* @property {(params: { error: object, editor: Editor, documentId: string, file: File })} [onContentError] Callback when there is an error in the content
* @property {(editor: { superdoc: SuperDoc }) => void} [onReady] Callback when the SuperDoc is ready
* @property {(params: { type: string, data: object}) => void} [onCommentsUpdate] Callback when comments are updated
* @property {(params: { context: SuperDoc, states: Array }) => void} [onAwarenessUpdate] Callback when awareness is updated
* @property {(params: { isLocked: boolean, lockedBy: User }) => void} [onLocked] Callback when the SuperDoc is locked
* @property {() => void} [onPdfDocumentReady] Callback when the PDF document is ready
* @property {(isOpened: boolean) => void} [onSidebarToggle] Callback when the sidebar is toggled
* @property {(params: { editor: Editor }) => void} [onCollaborationReady] Callback when collaboration is ready
* @property {(params: { editor: Editor }) => void} [onEditorUpdate] Callback when document is updated
* @property {(params: { error: Exception }) => void} [onException] Callback when an exception is thrown
*/
/**
* SuperDoc class
* Expects a config object
* @class
*/
export class SuperDoc extends EventEmitter {
/** @type {Array<string>} */
static allowedTypes = [DOCX, PDF, HTML];
/** @type {number} */
version;
users;
/** @type {Config} */
config = {
superdocId: null,
selector: '#superdoc',
documentMode: 'editing',
role: 'editor',
document: {},
documents: [],
format: null,
editorExtensions: [],
colors: [],
user: { name: null, email: null },
users: [],
modules: {}, // Optional: Modules to load. Use modules.ai.{your_key} to pass in your key
title: 'SuperDoc',
conversations: [],
pagination: false, // Optional: Whether to show pagination in SuperEditors
isCollaborative: false,
isInternal: false,
// toolbar config
toolbar: null, // Optional DOM element to render the toolbar in
toolbarGroups: ['left', 'center', 'right'],
toolbarIcons: {},
isDev: false,
// telemetry config
telemetry: null,
pdfViewer: {},
// Events
onEditorBeforeCreate: () => null,
onEditorCreate: () => null,
onEditorDestroy: () => null,
onContentError: () => null,
onReady: () => null,
onCommentsUpdate: () => null,
onAwarenessUpdate: () => null,
onLocked: () => null,
onPdfDocumentReady: () => null,
onSidebarToggle: () => null,
onCollaborationReady: () => null,
onEditorUpdate: () => null,
onCommentsListChange: () => null,
onException: () => null,
// Image upload handler
// async (file) => url;
handleImageUpload: null,
};
/**
* @param {Config} config
*/
constructor(config) {
super();
this.#init(config);
}
async #init(config) {
this.config = {
...this.config,
...config,
};
this.config.colors = shuffleArray(this.config.colors);
this.userColorMap = new Map();
this.colorIndex = 0;
this.version = __APP_VERSION__;
console.debug('🦋 [superdoc] Using SuperDoc version:', this.version);
this.superdocId = config.superdocId || uuidv4();
this.colors = this.config.colors;
// Preprocess document
this.#initDocuments();
// Initialize collaboration if configured
await this.#initCollaboration(this.config.modules);
// this.#initTelemetry();
this.#initVueApp();
this.#initListeners();
this.user = this.config.user; // The current user
this.users = this.config.users || []; // All users who have access to this superdoc
this.socket = null;
this.isDev = this.config.isDev || false;
this.activeEditor = null;
this.comments = [];
this.app.mount(this.config.selector);
// Required editors
this.readyEditors = 0;
this.isLocked = this.config.isLocked || false;
this.lockedBy = this.config.lockedBy || null;
// If a toolbar element is provided, render a toolbar
this.#addToolbar(this);
}
get requiredNumberOfEditors() {
return this.superdocStore.documents.filter((d) => d.type === DOCX).length;
}
get state() {
return {
documents: this.superdocStore.documents,
users: this.users,
};
}
#initDocuments() {
const doc = this.config.document;
const hasDocumentConfig = !!doc && typeof doc === 'object' && Object.keys(this.config.document)?.length;
const hasDocumentUrl = !!doc && typeof doc === 'string' && doc.length > 0;
const hasDocumentFile = !!doc && doc instanceof File;
const hasListOfDocuments = this.config.documents && this.config.documents?.length;
if (hasDocumentConfig && hasListOfDocuments) {
console.warn('🦋 [superdoc] You can only provide one of document or documents');
};
if (hasDocumentConfig) {
this.config.documents = [this.config.document];
} else if (hasDocumentUrl) {
this.config.documents = [
{
type: DOCX,
url: this.config.document,
name: 'document.docx',
isNewFile: true,
},
];
} else if (hasDocumentFile) {
this.config.documents = [
{
type: this.config.document.type,
data: this.config.document,
name: this.config.document.name,
isNewFile: true,
},
];
}
}
#initVueApp() {
const { app, pinia, superdocStore, commentsStore } = createSuperdocVueApp(this);
this.app = app;
this.pinia = pinia;
this.app.config.globalProperties.$config = this.config;
this.app.config.globalProperties.$documentMode = this.config.documentMode;
this.app.config.globalProperties.$superdoc = this;
this.superdocStore = superdocStore;
this.commentsStore = commentsStore;
this.version = this.config.version;
this.superdocStore.init(this.config);
this.commentsStore.init(this.config.modules.comments);
}
#initListeners() {
this.on('editorBeforeCreate', this.config.onEditorBeforeCreate);
this.on('editorCreate', this.config.onEditorCreate);
this.on('editorDestroy', this.config.onEditorDestroy);
this.on('ready', this.config.onReady);
this.on('comments-update', this.config.onCommentsUpdate);
this.on('awareness-update', this.config.onAwarenessUpdate);
this.on('locked', this.config.onLocked);
this.on('pdf-document-ready', this.config.onPdfDocumentReady);
this.on('sidebar-toggle', this.config.onSidebarToggle);
this.on('collaboration-ready', this.config.onCollaborationReady);
this.on('editor-update', this.config.onEditorUpdate);
this.on('content-error', this.onContentError);
this.on('exception', this.config.onException);
}
/**
* Initialize collaboration if configured
* @param {Object} config
* @returns {Promise<Array>} The processed documents with collaboration enabled
*/
async #initCollaboration({ collaboration: collaborationModuleConfig } = {}) {
if (!collaborationModuleConfig) return this.config.documents;
// Flag this superdoc as collaborative
this.isCollaborative = true;
// Start a socket for all documents and general metaMap for this SuperDoc
this.config.socket = new HocuspocusProviderWebsocket({
url: collaborationModuleConfig.url,
});
// Initialize global superdoc sync - for comments, view, etc.
initSuperdocYdoc(this);
// Initialize comments sync, if enabled
initCollaborationComments(this);
// Initialize collaboration for documents
return makeDocumentsCollaborative(this);
};
/**
* Add a user to the shared users list
*
* @param {Object} user The user to add
* @returns {void}
*/
addSharedUser(user) {
if (this.users.some((u) => u.email === user.email)) return;
this.users.push(user);
}
/**
* Remove a user from the shared users list
*
* @param {String} email The email of the user to remove
* @returns {void}
*/
removeSharedUser(email) {
this.users = this.users.filter((u) => u.email !== email);
}
/**
* Initialize telemetry service.
*/
#initTelemetry() {
this.telemetry = new Telemetry({
enabled: this.config.telemetry?.enabled ?? true,
licenseKey: this.config.telemetry?.licenseKey,
endpoint: this.config.telemetry?.endpoint,
superdocId: this.superdocId,
superdocVersion: this.version,
});
}
onContentError({ error, editor }) {
const { documentId } = editor.options;
const doc = this.superdocStore.documents.find((d) => d.id === documentId);
this.config.onContentError({ error, editor, documentId: doc.id, file: doc.data });
}
broadcastPdfDocumentReady() {
this.emit('pdf-document-ready');
}
broadcastReady() {
if (this.readyEditors === this.requiredNumberOfEditors) {
this.emit('ready', { superdoc: this });
}
}
broadcastEditorBeforeCreate(editor) {
this.emit('editorBeforeCreate', { editor });
}
broadcastEditorCreate(editor) {
this.readyEditors++;
this.broadcastReady();
this.emit('editorCreate', { editor });
}
broadcastEditorDestroy() {
this.emit('editorDestroy');
}
broadcastSidebarToggle(isOpened) {
this.emit('sidebar-toggle', isOpened);
}
log(...args) {
console.debug('🦋 🦸♀️ [superdoc]', ...args);
}
setActiveEditor(editor) {
this.activeEditor = editor;
if (this.toolbar) this.toolbar.setActiveEditor(editor);
}
/**
* Toggle the ruler visibility for SuperEditors
*
* @returns {void}
*/
toggleRuler() {
this.config.rulers = !this.config.rulers;
this.superdocStore.documents.forEach((doc) => {
doc.rulers = this.config.rulers;
});
}
#addToolbar() {
const moduleConfig = this.config.modules?.toolbar || {};
this.toolbarElement = this.config.modules?.toolbar?.selector || this.config.toolbar;
this.toolbar = null;
const config = {
selector: this.toolbarElement || null,
isDev: this.isDev || false,
toolbarGroups: this.config.modules?.toolbar?.groups || this.config.toolbarGroups,
role: this.config.role,
pagination: this.config.pagination,
icons: this.config.toolbarIcons,
documentMode: this.config.documentMode,
superdoc: this,
aiApiKey: this.config.modules?.ai?.apiKey,
aiEndpoint: this.config.modules?.ai?.endpoint,
...moduleConfig,
};
this.toolbar = new SuperToolbar(config);
this.toolbar.on('superdoc-command', this.onToolbarCommand.bind(this));
// AI highlight is not related to document editing, should be separate events
this.toolbar.on('ai-highlight', ({ type, data }) => {
this.emit('ai-highlight', { type, data });
});
this.once('editorCreate', () => this.toolbar.updateToolbarState());
}
addCommentsList(element) {
if (!this.config?.modules?.comments || this.config.role === 'viewer') return;
console.debug('🦋 [superdoc] Adding comments list to:', element);
if (element) this.config.modules.comments.element = element;
this.commentsList = new SuperComments(this.config.modules?.comments, this);
if (this.config.onCommentsListChange) this.config.onCommentsListChange({ isRendered: true })
}
removeCommentsList() {
if (this.commentsList) {
this.commentsList.close();
this.commentsList = null;
if (this.config.onCommentsListChange) this.config.onCommentsListChange({ isRendered: false })
}
}
onToolbarCommand({ item, argument }) {
if (item.command === 'setDocumentMode') {
this.setDocumentMode(argument);
} else if (item.command === 'setZoom') {
this.superdocStore.activeZoom = argument;
}
}
setDocumentMode(type) {
if (!type) return;
type = type.toLowerCase();
this.config.documentMode = type;
const types = {
viewing: () => this.#setModeViewing(),
editing: () => this.#setModeEditing(),
suggesting: () => this.#setModeSuggesting(),
};
if (types[type]) types[type]();
}
#setModeEditing() {
if (this.config.role !== 'editor') return this.#setModeSuggesting();
if (this.superdocStore.documents.length > 0) {
const firstEditor = this.superdocStore.documents[0]?.getEditor();
if (firstEditor) this.setActiveEditor(firstEditor);
}
this.superdocStore.documents.forEach((doc) => {
doc.restoreComments();
const editor = doc.getEditor();
if (editor) editor.setDocumentMode('editing');
});
if (this.toolbar) {
this.toolbar.documentMode = 'editing';
this.toolbar.updateToolbarState();
}
}
#setModeSuggesting() {
if (!['editor', 'suggester'].includes(this.config.role)) return this.#setModeViewing();
if (this.superdocStore.documents.length > 0) {
const firstEditor = this.superdocStore.documents[0]?.getEditor();
if (firstEditor) this.setActiveEditor(firstEditor);
}
this.superdocStore.documents.forEach((doc) => {
doc.restoreComments();
const editor = doc.getEditor();
if (editor) editor.setDocumentMode('suggesting');
});
if (this.toolbar) {
this.toolbar.documentMode = 'suggesting';
this.toolbar.updateToolbarState();
}
}
#setModeViewing() {
this.toolbar.activeEditor = null;
this.superdocStore.documents.forEach((doc) => {
doc.removeComments();
const editor = doc.getEditor();
if (editor) editor.setDocumentMode('viewing');
});
if (this.toolbar) {
this.toolbar.documentMode = 'viewing';
this.toolbar.updateToolbarState();
}
}
search(text) {
return this.activeEditor?.commands.search(text);
}
goToSearchResult(match) {
return this.activeEditor?.commands.goToSearchResult(match);
}
/**
* Set the document to locked or unlocked
* @param {boolean} lock
*/
setLocked(lock = true) {
this.config.documents.forEach((doc) => {
const metaMap = doc.ydoc.getMap('meta');
doc.ydoc.transact(() => {
metaMap.set('locked', lock);
metaMap.set('lockedBy', this.user);
});
});
}
getHTML() {
const editors = [];
this.superdocStore.documents.forEach((doc) => {
const editor = doc.getEditor();
if (editor) {
editors.push(editor);
}
});
return editors.map((editor) => editor.getHTML());
}
/**
* Lock the current superdoc
* @param {Boolean} isLocked
* @param {User} lockedBy The user who locked the superdoc
*/
lockSuperdoc(isLocked = false, lockedBy) {
this.isLocked = isLocked;
this.lockedBy = lockedBy;
console.debug('🦋 [superdoc] Locking superdoc:', isLocked, lockedBy, '\n\n\n');
this.emit('locked', { isLocked, lockedBy });
}
async export({
exportType = ['docx'],
commentsType,
exportedName,
additionalFiles = [],
additionalFileNames = [],
isFinalDoc = false,
} = {}) {
// Get the docx files first
const baseFileName = exportedName ? cleanName(exportedName) : cleanName(this.config.title);
const docxFiles = await this.exportEditorsToDOCX({ commentsType, isFinalDoc });
const blobsToZip = [...additionalFiles];
const filenames = [...additionalFileNames];
// If we are exporting docx files, add them to the zip
if (exportType.includes('docx')) {
docxFiles.forEach((blob, index) => {
blobsToZip.push(blob);
filenames.push(`${baseFileName}.docx`);
});
}
// If we only have one blob, just download it. Otherwise, zip them up.
if (blobsToZip.length === 1) {
createDownload(blobsToZip[0], baseFileName, exportType[0]);
} else {
const zip = await createZip(blobsToZip, filenames);
createDownload(zip, baseFileName, 'zip');
}
};
async exportEditorsToDOCX({ commentsType, isFinalDoc } = {}) {
const comments = [];
if (commentsType !== 'clean') {
comments.push(...this.commentsStore?.translateCommentsForExport());
}
const docxPromises = [];
this.superdocStore.documents.forEach((doc) => {
const editor = doc.getEditor();
if (editor) {
docxPromises.push(editor.exportDocx({ isFinalDoc, comments, commentsType }));
}
});
return await Promise.all(docxPromises);
};
/**
* Request an immediate save from all collaboration documents
* @returns {Promise<void>} Resolves when all documents have saved
*/
async #triggerCollaborationSaves() {
console.debug('🦋 [superdoc] Triggering collaboration saves');
return new Promise((resolve, reject) => {
this.superdocStore.documents.forEach((doc) => {
this.pendingCollaborationSaves = 0;
if (doc.ydoc) {
this.pendingCollaborationSaves++;
const metaMap = doc.ydoc.getMap('meta');
metaMap.observe((event) => {
if (event.changes.keys.has('immediate-save-finished')) {
this.pendingCollaborationSaves--;
if (this.pendingCollaborationSaves <= 0) {
resolve();
}
}
});
metaMap.set('immediate-save', true);
}
});
});
}
async save() {
const savePromises = [
this.#triggerCollaborationSaves(),
// this.exportEditorsToDOCX(),
];
console.debug('🦋 [superdoc] Saving superdoc');
const result = await Promise.all(savePromises);
console.debug('🦋 [superdoc] Save complete:', result);
return result;
}
destroy() {
if (!this.app) {
return;
}
this.log('[superdoc] Unmounting app');
this.config.socket?.cancelWebsocketRetry();
this.config.socket?.disconnect();
this.config.socket?.destroy();
this.ydoc?.destroy();
this.provider?.disconnect();
this.provider?.destroy();
this.config.documents.forEach((doc) => {
if (doc.provider) {
doc.provider.disconnect();
doc.provider.destroy();
};
// Destroy the ydoc
doc.ydoc?.destroy();
});
this.superdocStore.reset();
// Clean up telemetry when editor is destroyed
this.telemetry?.destroy();
this.app.unmount();
this.removeAllListeners();
delete this.app.config.globalProperties.$config;
delete this.app.config.globalProperties.$superdoc;
}
/**
* Focus the active editor or the first editor in the superdoc
* @returns {void}
*/
focus() {
if (this.activeEditor) {
this.activeEditor.focus();
} else {
this.superdocStore.documents.find((doc) => {
const editor = doc.getEditor();
if (editor) {
editor.focus();
}
});
}
}
}