-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
268 lines (236 loc) · 7.64 KB
/
index.js
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
/* eslint-disable max-classes-per-file */
import {
EditorState,
EditorView,
Schema,
baseSchema,
history,
buildKeymap,
keymap,
addListNodes,
baseKeymap,
tableEditing,
columnResizing,
goToNextCell,
tableNodes,
fixTables,
liftListItem,
sinkListItem,
gapCursor,
Y,
WebsocketProvider,
ySyncPlugin,
yCursorPlugin,
yUndoPlugin,
yUndo,
yRedo,
} from 'da-y-wrapper';
// DA
import prose2aem from '../../shared/prose2aem.js';
import menu from './plugins/menu.js';
import imageDrop from './plugins/imageDrop.js';
import linkConverter from './plugins/linkConverter.js';
import { COLLAB_ORIGIN, getDaAdmin } from '../../shared/constants.js';
import { addLocNodes, getLocClass } from './loc-utils.js';
const DA_ORIGIN = getDaAdmin();
function addCustomMarks(marks) {
const sup = {
parseDOM: [{ tag: 'sup' }, { clearMark: (m) => m.type.name === 'sup' }],
toDOM() { return ['sup', 0]; },
};
const sub = {
parseDOM: [{ tag: 'sub' }, { clearMark: (m) => m.type.name === 'sub' }],
toDOM() { return ['sub', 0]; },
};
const contextHighlight = { toDOM: () => ['span', { class: 'highlighted-context' }, 0] };
return marks
.addToEnd('sup', sup)
.addToEnd('sub', sub)
.addToEnd('contextHighlightingMark', contextHighlight);
}
// Note: until getSchema() is separated in its own module, this function needs to be kept in-sync
// with the getSchema() function in da-collab src/collab.js
export function getSchema() {
const { marks, nodes: baseNodes } = baseSchema.spec;
const withLocNodes = addLocNodes(baseNodes);
const withListnodes = addListNodes(withLocNodes, 'block+', 'block');
const nodes = withListnodes.append(tableNodes({ tableGroup: 'block', cellContent: 'block+' }));
return new Schema({ nodes, marks: addCustomMarks(marks) });
}
let sendUpdates = false;
let hasChanged = 0;
function dispatchTransaction(transaction) {
if (transaction.docChanged) {
hasChanged += 1;
sendUpdates = true;
}
const newState = window.view.state.apply(transaction);
window.view.updateState(newState);
}
function setPreviewBody(daPreview, proseEl) {
const clone = proseEl.cloneNode(true);
const body = prose2aem(clone, true);
daPreview.body = body;
}
function pollForUpdates() {
const daContent = document.querySelector('da-content');
const daPreview = daContent.shadowRoot.querySelector('da-preview');
const proseEl = window.view.root.querySelector('.ProseMirror');
if (!daPreview) return;
setInterval(() => {
if (sendUpdates) {
if (hasChanged > 0) {
hasChanged = 0;
return;
}
setPreviewBody(daPreview, proseEl);
sendUpdates = false;
}
}, 500);
}
function handleAwarenessUpdates(wsProvider, daTitle, win) {
const users = new Set();
wsProvider.awareness.on('update', (delta) => {
delta.added.forEach((u) => users.add(u));
delta.updated.forEach((u) => users.add(u));
delta.removed.forEach((u) => users.delete(u));
// Don't show the current user
users.delete(wsProvider.awareness.clientID);
const awarenessStates = wsProvider.awareness.getStates();
const userMap = new Map();
[...users].forEach((u) => {
const userInfo = awarenessStates.get(u)?.user;
if (!userInfo?.id) {
userMap.set(`anonymous-${u}`, 'Anonymous');
} else if (userInfo.id !== wsProvider.awareness.getLocalState().user?.id) {
userMap.set(userInfo.id, userInfo.name);
}
});
daTitle.collabUsers = [...userMap.values()].sort();
});
wsProvider.on('status', (st) => { daTitle.collabStatus = st.status; });
win.addEventListener('online', () => { daTitle.collabStatus = 'online'; });
win.addEventListener('offline', () => { daTitle.collabStatus = 'offline'; });
}
export function createAwarenessStatusWidget(wsProvider, win) {
const daTitle = win.document.querySelector('da-title');
handleAwarenessUpdates(wsProvider, daTitle, win);
return daTitle;
}
function registerErrorHandler(ydoc) {
ydoc.on('update', () => {
const errorMap = ydoc.getMap('error');
if (errorMap && errorMap.size > 0) {
// eslint-disable-next-line no-console
console.log('Error from server', JSON.stringify(errorMap));
errorMap.clear();
}
});
}
function generateColor(name, hRange = [0, 360], sRange = [60, 80], lRange = [40, 60]) {
let hash = 0;
for (let i = 0; i < name.length; i += 1) {
// eslint-disable-next-line no-bitwise
hash = name.charCodeAt(i) + ((hash << 5) - hash);
}
hash = Math.abs(hash);
const normalizeHash = (min, max) => Math.floor((hash % (max - min)) + min);
const h = normalizeHash(hRange[0], hRange[1]);
const s = normalizeHash(sRange[0], sRange[1]);
const l = normalizeHash(lRange[0], lRange[1]) / 100;
const a = (s * Math.min(l, 1 - l)) / 100;
const f = (n) => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0');
};
return `#${f(0)}${f(8)}${f(4)}`;
}
export default function initProse({ editor, path }) {
const schema = getSchema();
const ydoc = new Y.Doc();
const server = COLLAB_ORIGIN;
const roomName = `${DA_ORIGIN}${new URL(path).pathname}`;
const opts = {};
if (window.adobeIMS?.isSignedInUser()) {
opts.params = { Authorization: `Bearer ${window.adobeIMS.getAccessToken().token}` };
}
const wsProvider = new WebsocketProvider(server, roomName, ydoc, opts);
createAwarenessStatusWidget(wsProvider, window);
registerErrorHandler(ydoc);
const yXmlFragment = ydoc.getXmlFragment('prosemirror');
if (window.adobeIMS?.isSignedInUser()) {
window.adobeIMS.getProfile().then(
(profile) => {
wsProvider.awareness.setLocalStateField(
'user',
{
color: generateColor(profile.email || profile.userId),
name: profile.displayName,
id: profile.userId,
},
);
},
);
} else {
wsProvider.awareness.setLocalStateField(
'user',
{
color: generateColor(`${wsProvider.awareness.clientID}`),
name: 'Anonymous',
id: `anonymous-${wsProvider.awareness.clientID}}`,
},
);
}
let state = EditorState.create({
schema,
plugins: [
ySyncPlugin(yXmlFragment, {
onFirstRender: () => {
pollForUpdates();
},
}),
yCursorPlugin(wsProvider.awareness),
yUndoPlugin(),
menu,
imageDrop(schema),
linkConverter(schema),
columnResizing(),
tableEditing(),
keymap(buildKeymap(schema)),
keymap(baseKeymap),
keymap({
'Mod-z': yUndo,
'Mod-y': yRedo,
'Mod-Shift-z': yRedo,
}),
keymap({
Tab: goToNextCell(1),
'Shift-Tab': goToNextCell(-1),
}),
keymap({ 'Shift-Tab': liftListItem(schema.nodes.list_item) }),
keymap({ Tab: sinkListItem(schema.nodes.list_item) }),
gapCursor(),
history(),
],
});
const fix = fixTables(state);
if (fix) state = state.apply(fix.setMeta('addToHistory', false));
window.view = new EditorView(editor, {
state,
dispatchTransaction,
nodeViews: {
loc_added(node, view, getPos) {
const LocAddedView = getLocClass('da-loc-added', getSchema, dispatchTransaction, { isLangstore: false });
return new LocAddedView(node, view, getPos);
},
loc_deleted(node, view, getPos) {
const LocDeletedView = getLocClass('da-loc-deleted', getSchema, dispatchTransaction, { isLangstore: true });
return new LocDeletedView(node, view, getPos);
},
},
});
document.execCommand('enableObjectResizing', false, 'false');
document.execCommand('enableInlineTableEditing', false, 'false');
return wsProvider;
}