Debian Codegraph @

addons/html_editor/static/src/others/collaboration/collaboration_plugin.js

raw
1 import { Plugin } from "@html_editor/plugin";
2
3 // 60 seconds
4 export const HISTORY_SNAPSHOT_INTERVAL = 1000 * 60;
5 // 10 seconds
6 const HISTORY_SNAPSHOT_BUFFER_TIME = 1000 * 10;
7
8 /**
9 * @typedef { Object } CollaborationPluginConfig
10 * @property { string } peerId
11 *
12 * @typedef { import("../../core/history_plugin").HistoryStep } HistoryStep
13 */
14
15 /**
16 * @typedef { Object } CollaborationShared
17 * @property { CollaborationPlugin['getBranchIds'] } getBranchIds
18 * @property { CollaborationPlugin['getSnapshotSteps'] } getSnapshotSteps
19 * @property { CollaborationPlugin['historyGetMissingSteps'] } historyGetMissingSteps
20 * @property { CollaborationPlugin['onExternalHistorySteps'] } onExternalHistorySteps
21 * @property { CollaborationPlugin['resetFromSteps'] } resetFromSteps
22 * @property { CollaborationPlugin['setInitialBranchStepId'] } setInitialBranchStepId
23 */
24
25 /**
26 * @typedef {(() => void)[]} external_history_step_handlers
27 */
28
29 export class CollaborationPlugin extends Plugin {
30 static id = "collaboration";
31 static dependencies = ["history", "selection", "sanitize"];
32 /** @type {import("plugins").EditorResources} */
33 resources = {
34 /** Handlers */
35 history_cleaned_handlers: this.onHistoryClean.bind(this),
36 history_reset_handlers: this.onHistoryReset.bind(this),
37 step_added_handlers: ({ step }) => this.onStepAdded(step),
38
39 /** Overrides */
40 set_attribute_overrides: this.setAttribute.bind(this),
41
42 history_step_processors: this.processHistoryStep.bind(this),
43 unreversible_step_predicates: this.isUnreversibleStep.bind(this),
44 };
45 static shared = [
46 "getBranchIds",
47 "getSnapshotSteps",
48 "historyGetMissingSteps",
49 "onExternalHistorySteps",
50 "resetFromSteps",
51 "setInitialBranchStepId",
52 ];
53
54 /** @type { CollaborationPluginConfig['peerId'] } */
55 peerId = null;
56
57 setup() {
58 this.peerId = this.config.collaboration.peerId;
59 if (!this.peerId) {
60 throw new Error("The collaboration plugin requires a peerId");
61 }
62 this._snapshotInterval = setInterval(() => {
63 this.makeSnapshot();
64 }, HISTORY_SNAPSHOT_INTERVAL);
65 }
66
67 destroy() {
68 super.destroy();
69 clearInterval(this._snapshotInterval);
70 this._snapshotInterval = false;
71 }
72
73 onHistoryClean() {
74 this.branchStepIds = [];
75 }
76 onHistoryReset() {
77 const firstStep = this.dependencies.history.getHistorySteps()[0];
78 this.snapshots = [{ step: firstStep }];
79 }
80 /**
81 * @param {HistoryStep} step
82 */
83 isUnreversibleStep(step) {
84 return step.peerId !== this.peerId;
85 }
86 /**
87 * @param {Node} node
88 * @param {string} attributeName
89 * @param {string} attributeValue
90 */
91 setAttribute(node, attributeName, attributeValue) {
92 if (attributeValue) {
93 this.safeSetAttribute(node, attributeName, attributeValue);
94 return true;
95 }
96 }
97
98 /**
99 * Get all the history ids for the current history branch.
100 */
101 getBranchIds() {
102 const steps = this.dependencies.history.getHistorySteps();
103 return (this.initialBranchStepId || "")
104 .split(",")
105 .concat(this.branchStepIds)
106 .concat(steps.map((s) => s.id));
107 }
108 /**
109 * Safely set an attribute on a node.
110 * @param {HTMLElement} node
111 * @param {string} attributeName
112 * @param {string} attributeValue
113 */
114 safeSetAttribute(node, attributeName, attributeValue) {
115 const clone = this.document.createElement(node.tagName);
116 clone.setAttribute(attributeName, attributeValue);
117 this.dependencies.sanitize.sanitize(clone);
118 if (clone.hasAttribute(attributeName)) {
119 node.setAttribute(attributeName, clone.getAttribute(attributeName));
120 } else {
121 node.removeAttribute(attributeName);
122 }
123 }
124
125 /**
126 * Apply external steps coming from the collaboration.
127 *
128 * @param {Object} newSteps External steps to be applied
129 */
130 onExternalHistorySteps(newSteps) {
131 let stepIndex = 0;
132 const selectionData = this.dependencies.selection.getSelectionData();
133
134 const steps = this.dependencies.history.getHistorySteps();
135 for (const newStep of newSteps) {
136 // todo: add a test that no 2 history_missing_parent_step_handlers
137 // are called in same stack.
138 const insertIndex = this.getInsertStepIndex(steps, newStep);
139 if (typeof insertIndex === "undefined") {
140 continue;
141 }
142 this.dependencies.history.addExternalStep(newStep, insertIndex);
143 stepIndex++;
144 }
145 if (selectionData.documentSelectionIsInEditable) {
146 this.dependencies.selection.rectifySelection(selectionData.editableSelection);
147 }
148
149 this.dispatchTo("external_history_step_handlers");
150
151 // todo: ensure that if the selection was not in the editable before the
152 // reset, it remains where it was after applying the snapshot.
153
154 if (stepIndex) {
155 this.config.onChange?.();
156 }
157 }
158
159 /**
160 * @param {HistoryStep[]} steps
161 * @param {HistoryStep} newStep
162 */
163 getInsertStepIndex(steps, newStep) {
164 let index = steps.length - 1;
165 while (index >= 0 && steps[index].id !== newStep.previousStepId) {
166 // Skip steps that are already in the list.
167 if (steps[index].id === newStep.id) {
168 return;
169 }
170 index--;
171 }
172
173 // When the previousStepId is not present in the steps it
174 // could be either:
175 // - the previousStepId is before a snapshot of the same history
176 // - the previousStepId has not been received because peers were
177 // disconnected at that time
178 // - the previousStepId is in another history (in case two totally
179 // differents `steps` (but it should not arise)).
180 if (index < 0) {
181 const historySteps = steps;
182 let index = historySteps.length - 1;
183 // Get the last known step that we are sure the missing step
184 // peer has. It could either be a step that has the same
185 // peerId or the first step.
186 while (index !== 0) {
187 if (historySteps[index].peerId === newStep.peerId) {
188 break;
189 }
190 index--;
191 }
192 const fromStepId = historySteps[index].id;
193 this.dispatchTo("history_missing_parent_step_handlers", {
194 step: newStep,
195 fromStepId: fromStepId,
196 });
197 return;
198 }
199
200 let concurentSteps = [];
201 index++;
202 while (index < steps.length) {
203 if (steps[index].previousStepId === newStep.previousStepId) {
204 if (steps[index].id.localeCompare(newStep.id) === 1) {
205 break;
206 } else {
207 concurentSteps = [steps[index].id];
208 }
209 } else {
210 if (concurentSteps.includes(steps[index].previousStepId)) {
211 concurentSteps.push(steps[index].id);
212 } else {
213 break;
214 }
215 }
216 index++;
217 }
218
219 return index;
220 }
221
222 /**
223 * @param {Object} params
224 * @param {string} params.fromStepId
225 * @param {string} [params.toStepId]
226 */
227 historyGetMissingSteps({ fromStepId, toStepId }) {
228 const steps = this.dependencies.history.getHistorySteps();
229 const fromIndex = steps.findIndex((x) => x.id === fromStepId);
230 const toIndex = toStepId ? steps.findIndex((x) => x.id === toStepId) : steps.length;
231 if (fromIndex === -1 || toIndex === -1) {
232 return -1;
233 }
234 return steps.slice(fromIndex + 1, toIndex);
235 }
236
237 getSnapshotSteps() {
238 const historySteps = this.dependencies.history.getHistorySteps();
239 // If the current snapshot has no time, it means that there is the no
240 // other snapshot that have been made (either it is the one created upon
241 // initialization or reseted by history's resetFromSteps).
242 if (!this.snapshots[0].time) {
243 return { steps: historySteps, historyIds: this.getBranchIds() };
244 }
245 const snapshotSteps = [];
246 let snapshot;
247 if (this.snapshots[0].time + HISTORY_SNAPSHOT_BUFFER_TIME < Date.now()) {
248 snapshot = this.snapshots[0];
249 } else {
250 // this.snapshots[1] has being created at least 1 minute ago
251 // (HISTORY_SNAPSHOT_INTERVAL) or it is the first step.
252 snapshot = this.snapshots[1];
253 }
254 let index = historySteps.length - 1;
255 while (historySteps[index].id !== snapshot.step.id) {
256 snapshotSteps.push(historySteps[index]);
257 index--;
258 }
259 snapshotSteps.push(snapshot.step);
260 snapshotSteps.reverse();
261
262 return { steps: snapshotSteps, historyIds: this.getBranchIds() };
263 }
264 setInitialBranchStepId(stepId) {
265 this.initialBranchStepId = stepId;
266 }
267 resetFromSteps(steps, branchStepIds) {
268 this.dependencies.selection.resetSelection();
269 this.dependencies.history.resetFromSteps(steps);
270 this.snapshots = [{ step: steps[0] }];
271 this.branchStepIds = branchStepIds;
272
273 // @todo @phoenix: test that the hint are proprely handeled
274 // this._handleCommandHint();
275 // @todo @phoenix: make the multiselection
276 // this.multiselectionRefresh();
277 // @todo @phoenix: check it is still relevant
278 // this.dispatchEvent(new Event("resetFromSteps"));
279 }
280
281 makeSnapshot() {
282 const historyLength = this.dependencies.history.getHistorySteps().length;
283 if (!this.lastSnapshotLength || this.lastSnapshotLength < historyLength) {
284 this.lastSnapshotLength = historyLength;
285 const step = this.dependencies.history.makeSnapshotStep();
286 const snapshot = {
287 time: Date.now(),
288 step: step,
289 };
290 this.snapshots = [snapshot, this.snapshots[0]];
291 }
292 }
293
294 /**
295 * @param {HistoryStep} step
296 */
297 onStepAdded(step) {
298 step.peerId = this.peerId;
299 this.dispatchTo("collaboration_step_added_handlers", step);
300 }
301 /**
302 * @param {HistoryStep} step
303 */
304 processHistoryStep(step) {
305 step.peerId = this.peerId;
306 return step;
307 }
308 }