diff --git a/addons/hr_timesheet/models/ir_http.py b/addons/hr_timesheet/models/ir_http.py index cc687a513c4..b7d031ff8d4 100644 --- a/addons/hr_timesheet/models/ir_http.py +++ b/addons/hr_timesheet/models/ir_http.py @@ -13,7 +13,7 @@ class Http(models.AbstractModel): widget to apply, depending on the current company. """ result = super(Http, self).session_info() - if self.env.user.has_group('base.group_user'): + if request.env.user.has_group('base.group_user'): company_ids = request.env.user.company_ids for company in company_ids: diff --git a/addons/mail/models/mail_ice_server.py b/addons/mail/models/mail_ice_server.py index 1ab3a674432..043b34d63e0 100644 --- a/addons/mail/models/mail_ice_server.py +++ b/addons/mail/models/mail_ice_server.py @@ -36,8 +36,8 @@ class MailIceServer(models.Model): """ To be overridable if we need to obtain credentials from another source. :return: tuple """ - account_sid = self.env['ir.config_parameter'].get_param('mail.twilio_account_sid') - auth_token = self.env['ir.config_parameter'].get_param('mail.twilio_account_token') + account_sid = self.env['ir.config_parameter'].sudo().get_param('mail.twilio_account_sid') + auth_token = self.env['ir.config_parameter'].sudo().get_param('mail.twilio_account_token') return account_sid, auth_token def _get_ice_servers(self): @@ -45,7 +45,7 @@ class MailIceServer(models.Model): :return: List of dict, each of which representing a stun or turn server, formatted as expected by the specifications of RTCConfiguration.iceServers """ - if self.env['ir.config_parameter'].get_param('mail.use_twilio_rtc_servers'): + if self.env['ir.config_parameter'].sudo().get_param('mail.use_twilio_rtc_servers'): (account_sid, auth_token) = self._get_twilio_credentials() if account_sid and auth_token: url = f'https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Tokens.json' diff --git a/addons/web_editor/__manifest__.py b/addons/web_editor/__manifest__.py index fdc7013ffad..418c6278ff5 100644 --- a/addons/web_editor/__manifest__.py +++ b/addons/web_editor/__manifest__.py @@ -9,7 +9,7 @@ Odoo Web Editor widget. ========================== """, - 'depends': ['web'], + 'depends': ['web', 'mail'], 'data': [ 'security/ir.model.access.csv', 'data/editor_assets.xml', @@ -42,6 +42,7 @@ Odoo Web Editor widget. 'web_editor/static/lib/odoo-editor/src/utils/sanitize.js', 'web_editor/static/lib/odoo-editor/src/utils/serialize.js', 'web_editor/static/lib/odoo-editor/src/utils/utils.js', + 'web_editor/static/lib/odoo-editor/src/utils/DOMPurify.js', 'web_editor/static/lib/odoo-editor/src/tablepicker/TablePicker.js', 'web_editor/static/lib/odoo-editor/src/powerbox/patienceDiff.js', 'web_editor/static/lib/odoo-editor/src/powerbox/Powerbox.js', @@ -57,6 +58,7 @@ Odoo Web Editor widget. # utils 'web_editor/static/src/js/wysiwyg/wysiwyg_utils.js', + 'web_editor/static/src/js/wysiwyg/PeerToPeer.js', # odoo utils ('include', 'web._assets_helpers'), diff --git a/addons/web_editor/controllers/__init__.py b/addons/web_editor/controllers/__init__.py index 5d4b25db9c0..bb87d678c16 100644 --- a/addons/web_editor/controllers/__init__.py +++ b/addons/web_editor/controllers/__init__.py @@ -2,3 +2,4 @@ # Part of Odoo. See LICENSE file for full copyright and licensing details. from . import main +from . import bus diff --git a/addons/web_editor/controllers/bus.py b/addons/web_editor/controllers/bus.py new file mode 100644 index 00000000000..67e329119cb --- /dev/null +++ b/addons/web_editor/controllers/bus.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +import re + +from odoo.http import request +from odoo.addons.bus.controllers.main import BusController +from odoo.exceptions import AccessDenied + + +class EditorCollaborationController(BusController): + # --------------------------- + # Extends BUS Controller Poll + # --------------------------- + def _poll(self, dbname, channels, last, options): + if request.session.uid: + # Do not alter original list. + channels = list(channels) + for channel in channels: + if isinstance(channel, str): + match = re.match(r'editor_collaboration:(\w+(?:.\w+)*):(\w+):([\d]+)', channel) + if (match): + model_name = match[1] + field_name = match[2] + res_id = int(match[3]) + + # Verify access to the edition channel. + if not request.env.user.has_group('base.group_user'): + raise AccessDenied() + + document = request.env[model_name].browse([res_id]) + + document.check_access_rights('read') + document.check_field_access_rights('read', [field_name]) + document.check_access_rule('read') + document.check_access_rights('write') + document.check_field_access_rights('write', [field_name]) + document.check_access_rule('write') + + channels.append((request.db, 'editor_collaboration', model_name, field_name, res_id)) + return super(EditorCollaborationController, self)._poll(dbname, channels, last, options) diff --git a/addons/web_editor/controllers/main.py b/addons/web_editor/controllers/main.py index ab8e583c5a0..a02e3e5d2c7 100644 --- a/addons/web_editor/controllers/main.py +++ b/addons/web_editor/controllers/main.py @@ -687,3 +687,21 @@ class Web_Editor(http.Controller): attachments.append(attachment._get_media_info()) return attachments + + @http.route("/web_editor/get_ice_servers", type='json', auth="user") + def get_ice_servers(self): + return request.env['mail.ice.server']._get_ice_servers() + + @http.route("/web_editor/bus_broadcast", type="json", auth="user") + def bus_broadcast(self, model_name, field_name, res_id, bus_data): + document = request.env[model_name].browse([res_id]) + + document.check_access_rights('read') + document.check_field_access_rights('read', [field_name]) + document.check_access_rule('read') + document.check_access_rights('write') + document.check_field_access_rights('write', [field_name]) + document.check_access_rule('write') + + channel = (request.db, 'editor_collaboration', model_name, field_name, int(res_id)) + request.env['bus.bus'].sendone(channel, bus_data) diff --git a/addons/web_editor/static/lib/odoo-editor/src/OdooEditor.js b/addons/web_editor/static/lib/odoo-editor/src/OdooEditor.js index b68c4a95467..2580f8665ee 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/OdooEditor.js +++ b/addons/web_editor/static/lib/odoo-editor/src/OdooEditor.js @@ -11,7 +11,7 @@ import './commands/toggleList.js'; import './commands/align.js'; import { sanitize } from './utils/sanitize.js'; -import { nodeToObject, objectToNode } from './utils/serialize.js'; +import { serializeNode, unserializeNode, serializeSelection } from './utils/serialize.js'; import { closestBlock, commonParentGet, @@ -25,7 +25,7 @@ import { isColorGradient, nodeSize, preserveCursor, - setCursor, + setSelection, startPos, toggleClass, closestElement, @@ -45,6 +45,7 @@ import { isBold, YOUTUBE_URL_GET_VIDEO_ID, unwrapContents, + peek, } from './utils/utils.js'; import { editorCommands } from './commands/commands.js'; import { Powerbox } from './powerbox/Powerbox.js'; @@ -56,6 +57,11 @@ import { UNBREAKABLE_ROLLBACK_CODE, UNREMOVABLE_ROLLBACK_CODE } from './utils/co const BACKSPACE_ONLY_COMMANDS = ['oDeleteBackward', 'oDeleteForward']; const BACKSPACE_FIRST_COMMANDS = BACKSPACE_ONLY_COMMANDS.concat(['oEnter', 'oShiftEnter']); +// 60 seconds +const HISTORY_SNAPSHOT_INTERVAL = 1000 * 60; +// 10 seconds +const HISTORY_SNAPSHOT_BUFFER_TIME = 1000 * 10; + const KEYBOARD_TYPES = { VIRTUAL: 'VIRTUAL', PHYSICAL: 'PHYSICAL', UNKNOWN: 'UKNOWN' }; const IS_KEYBOARD_EVENT_UNDO = ev => ev.key === 'z' && (ev.ctrlKey || ev.metaKey); @@ -133,7 +139,6 @@ function defaultOptions(defaultObject, object) { } return newObject; } - export class OdooEditor extends EventTarget { constructor(editable, options = {}) { super(); @@ -178,9 +183,6 @@ export class OdooEditor extends EventTarget { // All dom listeners currently active. this._domListeners = []; - this.resetHistory(); - this._historyStepsActive = true; - // Set of labels that which prevent the automatic step mechanism if // it contains at least one element. this._observerTimeoutUnactive = new Set(); @@ -193,9 +195,6 @@ export class OdooEditor extends EventTarget { this._onKeyupResetContenteditableNodes = []; - this._isCollaborativeActive = false; - this._collaborativeLastSynchronisedId = null; - // Track if we need to rollback mutations in case unbreakable or unremovable are being added or removed. this._toRollback = false; @@ -210,15 +209,30 @@ export class OdooEditor extends EventTarget { editable.innerHTML = '


'; } - // Convention: root node is ID 1. - editable.oid = 1; + // Convention: root node is ID root. + editable.oid = 'root'; this._idToNodeMap.set(1, editable); this.editable = this.options.toSanitize ? sanitize(editable) : editable; // Set contenteditable before clone as FF updates the content at this point. this._activateContenteditable(); + this._collabClientId = this.options.collaborationClientId; + + // Colaborator selection and caret display. + this._collabSelectionInfos = new Map(); + this._collabSelectionColor = `hsl(${(Math.random() * 360).toFixed(0)}, 75%, 50%)`; + this._collabSelectionsContainer = this.document.createElement('div'); + this._collabSelectionsContainer.classList.add('oe-collaboration-selections-container'); + this.editable.before(this._collabSelectionsContainer); + this.idSet(editable); + this.historyReset(); + this._historyStepsActive = true; + const firstStep = this._historyGetSnapshotStep(); + this._firstStepId = firstStep.id; + this._historySnapshots = [{ step: firstStep }]; + this._historySteps.push(firstStep); this._createCommandBar(); @@ -251,6 +265,16 @@ export class OdooEditor extends EventTarget { this.addDomListener(this.document, 'mousedown', this._onDoumentMousedown); this.addDomListener(this.document, 'mouseup', this._onDoumentMouseup); + this.multiselectionRefresh = this.multiselectionRefresh.bind(this); + this._resizeObserver = new ResizeObserver(this.multiselectionRefresh); + this._resizeObserver.observe(this.document.body); + this._resizeObserver.observe(this.editable); + this.addDomListener(this.editable, 'scroll', this.multiselectionRefresh); + + this._snapshotInterval = setInterval(() => { + this._historyMakeSnapshot(); + }, HISTORY_SNAPSHOT_INTERVAL); + // ------- // Toolbar // ------- @@ -304,15 +328,16 @@ export class OdooEditor extends EventTarget { this._removeDomListener(); this.commandBar.destroy(); this.commandbarTablePicker.el.remove(); + this._collabSelectionsContainer.remove(); + this._resizeObserver.disconnect(); + clearInterval(this._snapshotInterval); } sanitize() { this.observerFlush(); - // find common ancestror in this.history[-1] - const step = this._historySteps[this._historySteps.length - 1]; let commonAncestor, record; - for (record of step.mutations) { + for (record of this._currentStep.mutations) { const node = this.idFind(record.parentId || record.id) || this.editable; commonAncestor = commonAncestor ? commonParentGet(commonAncestor, node, this.editable) @@ -332,12 +357,18 @@ export class OdooEditor extends EventTarget { element.addEventListener(eventName, boundCallback); } + _generateId() { + // No need for secure random number. + return Math.floor(Math.random() * Math.pow(2,52)).toString(); + } + // Assign IDs to src, and dest if defined idSet(node, testunbreak = false) { if (!node.oid) { - node.oid = (Math.random() * 2 ** 31) | 0; // TODO: uuid4 or higher number - this._idToNodeMap.set(node.oid, node); + node.oid = this._generateId(); } + // In case the id was created by another collaboration client. + this._idToNodeMap.set(node.oid, node); // Rollback if node.ouid changed. This ensures that nodes never change // unbreakable ancestors. node.ouid = node.ouid || getOuid(node, true); @@ -359,14 +390,12 @@ export class OdooEditor extends EventTarget { return this._idToNodeMap.get(id); } - // Observer that syncs doms - - // if not in collaboration mode, no need to serialize / unserialize - serialize(node) { - return this._isCollaborativeActive ? nodeToObject(node) : node; + serializeNode(node, mutatedNodes) { + return this._collabClientId ? serializeNode(node, mutatedNodes) : node; } - unserialize(obj) { - return this._isCollaborativeActive ? objectToNode(obj) : obj; + + unserializeNode(node) { + return this._collabClientId ? unserializeNode(node) : node; } automaticStepActive(label) { @@ -416,10 +445,28 @@ export class OdooEditor extends EventTarget { } observerApply(records) { + // There is a case where node A is added and node B is a descendant of + // node A where node B was not in the observed tree) then node B is + // added into another node. In that case, we need to keep track of node + // B so when serializing node A, we strip node B from the node A tree to + // avoid the duplication of node A. + const mutatedNodes = new Set(); + for (const record of records) { + if (record.type === 'childList') { + for (const node of record.addedNodes) { + this.idSet(node, this._checkStepUnbreakable); + mutatedNodes.add(node.oid); + } + for (const node of record.removedNodes) { + this.idSet(node, this._checkStepUnbreakable); + mutatedNodes.delete(node.oid); + } + } + } for (const record of records) { switch (record.type) { case 'characterData': { - this._historySteps[this._historySteps.length - 1].mutations.push({ + this._currentStep.mutations.push({ 'type': 'characterData', 'id': record.target.oid, 'text': record.target.textContent, @@ -428,7 +475,7 @@ export class OdooEditor extends EventTarget { break; } case 'attributes': { - this._historySteps[this._historySteps.length - 1].mutations.push({ + this._currentStep.mutations.push({ 'type': 'attributes', 'id': record.target.oid, 'attributeName': record.attributeName, @@ -456,20 +503,19 @@ export class OdooEditor extends EventTarget { } else { return false; } - this.idSet(added, this._checkStepUnbreakable); mutation.id = added.oid; - mutation.node = this.serialize(added); - this._historySteps[this._historySteps.length - 1].mutations.push(mutation); + mutation.node = this.serializeNode(added, mutatedNodes); + this._currentStep.mutations.push(mutation); }); record.removedNodes.forEach(removed => { if (!this._toRollback && containsUnremovable(removed)) { this._toRollback = UNREMOVABLE_ROLLBACK_CODE; } - this._historySteps[this._historySteps.length - 1].mutations.push({ + this._currentStep.mutations.push({ 'type': 'remove', 'id': removed.oid, 'parentId': record.target.oid, - 'node': this.serialize(removed), + 'node': this.serializeNode(removed), 'nextId': record.nextSibling ? record.nextSibling.oid : undefined, 'previousId': record.previousSibling ? record.previousSibling.oid @@ -512,25 +558,74 @@ export class OdooEditor extends EventTarget { return filteredRecords; } - resetHistory() { - this._historySteps = [ - { - cursor: { - // cursor at beginning of step - anchorNode: undefined, - anchorOffset: undefined, - focusNode: undefined, - focusOffset: undefined, - }, - mutations: [], - id: undefined, + // History + // ------------------------------------------------------------------------- + + historyReset() { + this._historySteps = []; + this._currentStep = { + selection: { + anchorNodeOid: undefined, + anchorOffset: undefined, + focusNodeOid: undefined, + focusOffset: undefined, }, - ]; + mutations: [], + id: undefined, + clientId: undefined, + }; this._historyStepsStates = new Map(); } - // - // History - // + historyGetSnapshotSteps() { + // If the current snapshot has no time, it means that there is the no + // other snapshot that have been made (either it is the one created upon + // initialization or reseted by historyResetFromSteps). + if (!this._historySnapshots[0].time) { + return this._historySteps; + } + const steps = []; + let snapshot; + if (this._historySnapshots[0].time + HISTORY_SNAPSHOT_BUFFER_TIME < Date.now()) { + snapshot = this._historySnapshots[0]; + } else { + // this._historySnapshots[1] has being created at least 1 minute ago + // (HISTORY_SNAPSHOT_INTERVAL) or it is the first step. + snapshot = this._historySnapshots[1]; + } + let index = this._historySteps.length - 1; + while (this._historySteps[index].id !== snapshot.step.id) { + steps.push(this._historySteps[index]); + index--; + } + steps.push(snapshot.step); + steps.reverse(); + + return steps; + } + historyResetFromSteps(steps) { + this.observerUnactive(); + for (const node of [...this.editable.childNodes]) { + node.remove(); + } + this.historyReset(); + for (const step of steps) { + this.historyApply(step.mutations); + } + this._historySnapshots = [{ step: steps[0] }]; + this._historySteps = steps; + + this._handleCommandHint(); + this.multiselectionRefresh(); + this.observerActive(); + } + historyGetMissingSteps({fromStepId, toStepId}) { + const fromIndex = this._historySteps.findIndex(x => x.id === fromStepId); + const toIndex = this._historySteps.findIndex(x => x.id === toStepId); + if (fromIndex === -1 || toIndex === -1) { + return -1; + } + return this._historySteps.slice(fromIndex + 1, toIndex); + } // One step completed: apply to vDOM, setup next history step historyStep(skipRollback = false) { @@ -545,22 +640,29 @@ export class OdooEditor extends EventTarget { } // push history - const latest = this._historySteps[this._historySteps.length - 1]; - if (!latest.mutations.length) { + const currentStep = this._currentStep; + if (!currentStep.mutations.length) { return false; } - latest.id = (Math.random() * 2 ** 31) | 0; // TODO: replace by uuid4 generator - this.historySend(latest); - this._historySteps.push({ - cursor: {}, - mutations: [], - }); - this._checkStepUnbreakable = true; - this._recordHistoryCursor(); - this.dispatchEvent(new Event('historyStep')); - } + currentStep.id = this._generateId(); + const previousStep = peek(this._historySteps); + currentStep.clientId = this._collabClientId; + currentStep.previousStepId = previousStep.id; + this._historySteps.push(currentStep); + if (this.options.onHistoryStep) { + this.options.onHistoryStep(currentStep); + } + this._currentStep = { + selection: {}, + mutations: [], + }; + this._checkStepUnbreakable = true; + this._recordHistorySelection(); + this.dispatchEvent(new Event('historyStep')); + this.multiselectionRefresh(); + } // apply changes according to some records historyApply(records) { for (const record of records) { @@ -572,7 +674,7 @@ export class OdooEditor extends EventTarget { } else if (record.type === 'attributes') { const node = this.idFind(record.id); if (node) { - node.setAttribute(record.attributeName, record.value); + this._safeSetAttribute(node, record.attributeName, record.value); } } else if (record.type === 'remove') { const toremove = this.idFind(record.id); @@ -580,135 +682,49 @@ export class OdooEditor extends EventTarget { toremove.remove(); } } else if (record.type === 'add') { - const node = this.unserialize(record.node); - const newnode = node.cloneNode(1); - // preserve oid after the clone - this.idSet(node, newnode); - - const destnode = this.idFind(record.node.oid); - if (destnode && record.node.parentNode.oid === destnode.parentNode.oid) { - // TODO: optimization: remove record from the history to reduce collaboration bandwidth + let node = this.idFind(record.oid) || this.unserializeNode(record.node); + const fakeNode = document.createElement('fake-el'); + fakeNode.appendChild(node); + DOMPurify.sanitize(fakeNode, { IN_PLACE: true }); + node = fakeNode.childNodes[0]; + if (!node) { continue; } + this.idSet(node, true); + if (record.append && this.idFind(record.append)) { - this.idFind(record.append).append(newnode); + this.idFind(record.append).append(node); } else if (record.before && this.idFind(record.before)) { - this.idFind(record.before).before(newnode); + this.idFind(record.before).before(node); } else if (record.after && this.idFind(record.after)) { - this.idFind(record.after).after(newnode); + this.idFind(record.after).after(node); } else { continue; } } } } - - // send changes to server - historyFetch() { - if (!this._isCollaborativeActive) { - return; - } - window - .fetch(`/history-get/${this._collaborativeLastSynchronisedId || 0}`, { - headers: { 'Content-Type': 'application/json;charset=utf-8' }, - method: 'GET', - }) - .then(response => { - if (!response.ok) { - return Promise.reject(); - } - return response.json(); - }) - .then(result => { - if (!result.length) { - return false; - } - this.observerUnactive(); - - let index = this._historySteps.length; - let updated = false; - while ( - index && - this._historySteps[index - 1].id !== this._collaborativeLastSynchronisedId - ) { - index--; - } - - for (let residx = 0; residx < result.length; residx++) { - const record = result[residx]; - this._collaborativeLastSynchronisedId = record.id; - if ( - index < this._historySteps.length && - record.id === this._historySteps[index].id - ) { - index++; - continue; - } - updated = true; - - // we are not synched with the server anymore, rollback and replay - while (this._historySteps.length > index) { - this.historyRollback(); - this._historySteps.pop(); - } - - if (record.id === 1) { - this.editable.innerHTML = ''; - } - this.historyApply(record.mutations); - - record.mutations = record.id === 1 ? [] : record.mutations; - this._historySteps.push(record); - index++; - } - if (updated) { - this._historySteps.push({ - cursor: {}, - mutations: [], - }); - } - this.observerActive(); - this.historyFetch(); - }) - .catch(() => { - // TODO: change that. currently: if error on fetch, fault back to non collaborative mode. - this._isCollaborativeActive = false; - }); - } - - historySend(item) { - if (!this._isCollaborativeActive) { - return; - } - window.fetch('/history-push', { - body: JSON.stringify(item), - headers: { 'Content-Type': 'application/json;charset=utf-8' }, - method: 'POST', - }); - } - historyRollback(until = 0) { - const step = this._historySteps[this._historySteps.length - 1]; + const step = this._currentStep; this.observerFlush(); - this.historyRevert(step, until); + this.historyRevert(step, { until }); this.observerFlush(); step.mutations = step.mutations.slice(0, until); this._toRollback = false; } - /** * Undo a step of the history. * * this._historyStepsState is a map from it's location (index) in this.history to a state. * The state can be on of: * undefined: the position has never been undo or redo. - * 0: The position is considered as a redo of another. - * 1: The position is considered as a undo of another. - * 2: The position has been undone and is considered consumed. + * "redo": The position is considered as a redo of another. + * "undo": The position is considered as a undo of another. + * "consumed": The position has been undone and is considered consumed. */ historyUndo() { // The last step is considered an uncommited draft so always revert it. - const lastStep = this._historySteps[this._historySteps.length - 1]; + const lastStep = this._currentStep; this.historyRevert(lastStep); // Clean the last step otherwise if no other step is created after, the // mutations of the revert itself will be added to the same step and @@ -716,17 +732,17 @@ export class OdooEditor extends EventTarget { lastStep.mutations = []; const pos = this._getNextUndoIndex(); - if (pos >= 0) { + if (pos > 0) { // Consider the position consumed. - this._historyStepsStates.set(pos, 2); + this._historyStepsStates.set(this._historySteps[pos].id, 'consumed'); this.historyRevert(this._historySteps[pos]); - // Consider the last position of the history as an undo. - this._historyStepsStates.set(this._historySteps.length - 1, 1); this.historyStep(true); + // Consider the last position of the history as an undo. + const undoStep = this._historySteps[this._historySteps.length - 1]; + this._historyStepsStates.set(undoStep.id, 'undo'); this.dispatchEvent(new Event('historyUndo')); } } - /** * Redo a step of the history. * @@ -734,12 +750,13 @@ export class OdooEditor extends EventTarget { */ historyRedo() { const pos = this._getNextRedoIndex(); - if (pos >= 0) { - this._historyStepsStates.set(pos, 2); + if (pos > 0) { + this._historyStepsStates.set(this._historySteps[pos].id, 'consumed'); this.historyRevert(this._historySteps[pos]); - this._historyStepsStates.set(this._historySteps.length - 1, 0); - this.historySetCursor(this._historySteps[pos]); + this.historySetSelection(this._historySteps[pos]); this.historyStep(true); + const lastStep = this._historySteps[this._historySteps.length - 1]; + this._historyStepsStates.set(lastStep.id, 'redo'); this.dispatchEvent(new Event('historyRedo')); } } @@ -747,19 +764,19 @@ export class OdooEditor extends EventTarget { * Check wether undoing is possible. */ historyCanUndo() { - return this._getNextUndoIndex() >= 0; + return this._getNextUndoIndex() > 0; } /** * Check wether redoing is possible. */ historyCanRedo() { - return this._getNextRedoIndex() >= 0; + return this._getNextRedoIndex() > 0; } historySize() { return this._historySteps.length; } - historyRevert(step, until = 0) { + historyRevert(step, { until = 0, sideEffect = true } = {} ) { // apply dom changes by reverting history steps for (let i = step.mutations.length - 1; i >= until; i--) { const mutation = step.mutations[i]; @@ -776,7 +793,7 @@ export class OdooEditor extends EventTarget { const node = this.idFind(mutation.id); if (node) { if (mutation.oldValue) { - node.setAttribute(mutation.attributeName, mutation.oldValue); + this._safeSetAttribute(node, mutation.attributeName, mutation.oldValue); } else { node.removeAttribute(mutation.attributeName); } @@ -784,7 +801,18 @@ export class OdooEditor extends EventTarget { break; } case 'remove': { - const nodeToRemove = this.unserialize(mutation.node); + let nodeToRemove = this.idFind(mutation.id); + if (!nodeToRemove) { + nodeToRemove = this.unserializeNode(mutation.node); + const fakeNode = document.createElement('fake-el'); + fakeNode.appendChild(nodeToRemove); + DOMPurify.sanitize(fakeNode, { IN_PLACE: true }); + nodeToRemove = fakeNode.childNodes[0]; + if (!nodeToRemove) { + continue; + } + this.idSet(nodeToRemove); + } if (mutation.nextId && this.idFind(mutation.nextId)) { const node = this.idFind(mutation.nextId); node && node.before(nodeToRemove); @@ -805,39 +833,44 @@ export class OdooEditor extends EventTarget { } } } - this._activateContenteditable(); - this.historySetCursor(step); - this.dispatchEvent(new Event('historyRevert')); + if (sideEffect) { + this._activateContenteditable(); + this.historySetSelection(step); + this.dispatchEvent(new Event('historyRevert')); + } } - /** - * Place the cursor on the last known cursor position from the history steps. + * Place the selection on the last known selection position from the history + * steps. * * @returns {boolean} */ - resetCursorOnLastHistoryCursor() { - const lastHistoryStep = this._historySteps[this._historySteps.length - 1]; - if (lastHistoryStep && lastHistoryStep.cursor && lastHistoryStep.cursor.anchorNode) { - this.historySetCursor(lastHistoryStep); - return true; - } - return false; - } - - historySetCursor(step) { - if (step.cursor && step.cursor.anchorNode) { - const anchorNode = this.idFind(step.cursor.anchorNode); - const focusNode = step.cursor.focusNode - ? this.idFind(step.cursor.focusNode) - : anchorNode; + historyResetLatestComputedSelection() { + if (this._latestComputedSelection && this._latestComputedSelection.anchorNode) { + const anchorNode = this.idFind(this._latestComputedSelection.anchorNode.oid); + const focusNode = this.idFind(this._latestComputedSelection.focusNode.oid) || anchorNode; if (anchorNode) { - setCursor( + setSelection( anchorNode, - step.cursor.anchorOffset, + this._latestComputedSelection.anchorOffset, focusNode, - step.cursor.focusOffset !== undefined - ? step.cursor.focusOffset - : step.cursor.anchorOffset, + this._latestComputedSelection.focusOffset, + ); + } + } + } + historySetSelection(step) { + if (step.selection && step.selection.anchorNodeOid) { + const anchorNode = this.idFind(step.selection.anchorNodeOid); + const focusNode = this.idFind(step.selection.focusNodeOid) || anchorNode; + if (anchorNode) { + setSelection( + anchorNode, + step.selection.anchorOffset, + focusNode, + step.selection.focusOffset !== undefined + ? step.selection.focusOffset + : step.selection.anchorOffset, false, ); } @@ -854,6 +887,248 @@ export class OdooEditor extends EventTarget { historyUnpauseSteps() { this._historyStepsActive = true; } + _historyGetSnapshotStep() { + return { + selection: { + anchorNode: undefined, + anchorOffset: undefined, + focusNode: undefined, + focusOffset: undefined, + }, + mutations: Array.from(this.editable.childNodes).map(node => ({ + type: 'add', + append: 1, + id: node.oid, + node: serializeNode(node), + })), + id: this._generateId(), + clientId: this.clientId, + previousStepId: undefined, + }; + } + _historyMakeSnapshot() { + if ( + !this._lastSnapshotHistoryLength || + this._lastSnapshotHistoryLength < this._historySteps.length + ) { + this._lastSnapshotHistoryLength = this._historySteps.length; + const step = this._historyGetSnapshotStep(); + step.id = this._historySteps[this._historySteps.length - 1].id; + const snapshot = { + time: Date.now(), + step: step, + }; + this._historySnapshots = [snapshot, this._historySnapshots[0]]; + } + } + /** + * Insert a step from another collaborator. + */ + _historyAddExternalStep(newStep) { + let index = this._historySteps.length - 1; + while (index >= 0 && this._historySteps[index].id !== newStep.previousStepId) { + // Skip steps that are already in the list. + if (this._historySteps[index].id === newStep.id) { + return; + } + index--; + } + + // When the previousStepId is not present in the this._historySteps it + // could be either: + // - the previousStepId is before a snapshot of the same history + // - the previousStepId has not been received because clients were + // disconnected at that time + // - the previousStepId is in another history (in case two totally + // differents this._historySteps (but it should not arise)). + if (index < 0) { + if (this.options.onHistoryMissingParentSteps) { + const historySteps = this._historySteps; + let index = historySteps.length - 1; + // Get the last known step that we are sure the missing step + // client has. It could either be a step that has the same + // clientId or the first step. + while(index !== 0) { + if (historySteps[index].clientId === newStep.clientId) { + break; + } + index--; + } + const fromStepId = historySteps[index].id; + this.options.onHistoryMissingParentSteps({ + step: newStep, + fromStepId: fromStepId, + }); + } + return; + } + + let currentIndex; + let concurentSteps = []; + index++; + while (index < this._historySteps.length) { + if (this._historySteps[index].previousStepId === newStep.previousStepId) { + if (this._historySteps[index].id.localeCompare(newStep.id) === 1) { + currentIndex = index; + break; + } else { + concurentSteps = [this._historySteps[index].id]; + } + } else { + if (concurentSteps.includes(this._historySteps[index].previousStepId)) { + concurentSteps.push(this._historySteps[index].id); + } else { + currentIndex = index; + break; + } + } + index++; + } + currentIndex = typeof currentIndex !== 'undefined' ? currentIndex : index; + + const stepsAfterNewStep = this._historySteps.slice(index); + + for (const stepToRevert of stepsAfterNewStep.slice().reverse()) { + this.historyRevert(stepToRevert, { sideEffect: false }); + } + this.historyApply(newStep.mutations); + this._historySteps.splice(index, 0, newStep); + for (const stepToApply of stepsAfterNewStep) { + this.historyApply(stepToApply.mutations); + } + } + + onExternalHistorySteps(newSteps) { + this.observerUnactive(); + this._computeHistorySelection(); + + for (const newStep of newSteps) { + this._historyAddExternalStep(newStep); + } + + this.observerActive(); + this.historyResetLatestComputedSelection(); + this._handleCommandHint(); + this.multiselectionRefresh(); + } + + // Multi selection + // ------------------------------------------------------------------------- + + onExternalMultiselectionUpdate(selection) { + this._multiselectionDisplayClient(selection); + const { clientId } = selection; + if (this._collabSelectionInfos.has(clientId)) { + this._collabSelectionInfos.get(clientId).selection = selection; + } else { + this._collabSelectionInfos.set(clientId, { selection }); + } + } + + multiselectionRefresh() { + this._collabSelectionsContainer.innerHTML = ''; + for (const { selection } of this._collabSelectionInfos.values()) { + this._multiselectionDisplayClient(selection); + } + } + + _multiselectionDisplayClient({ selection, color, clientId, clientName = 'Anonyme' }) { + let clientRects; + + const anchorNode = this.idFind(selection.anchorNodeOid); + const focusNode = this.idFind(selection.focusNodeOid); + if (!anchorNode || !focusNode) { + return; + } + + const direction = getCursorDirection( + anchorNode, + selection.anchorOffset, + focusNode, + selection.focusOffset, + ); + const range = new Range(); + try { + if (direction === DIRECTIONS.RIGHT) { + range.setStart(anchorNode, selection.anchorOffset); + range.setEnd(focusNode, selection.focusOffset); + } else { + range.setStart(focusNode, selection.focusOffset); + range.setEnd(anchorNode, selection.anchorOffset); + } + + clientRects = Array.from(range.getClientRects()); + } catch (e) { + // Changes in the dom might prevent the range to be instantiated + // (because of a removed node for example), in which case we ignore + // the range. + clientRects = []; + } + if (!clientRects.length) { + return; + } + + // Draw rects (in case the selection is not collapsed). + const containerRect = this._collabSelectionsContainer.getBoundingClientRect(); + const indicators = clientRects.map(({ x, y, width, height }) => { + const rectElement = this.document.createElement('div'); + rectElement.style = ` + position: absolute; + top: ${y - containerRect.y}px; + left: ${x - containerRect.x}px; + width: ${width}px; + height: ${height}px; + background-color: ${color}; + opacity: 0.25; + pointer-events: none; + `; + rectElement.setAttribute('data-selection-client-id', clientId); + return rectElement; + }); + + // Draw carret. + const caretElement = this.document.createElement('div'); + caretElement.style = `border-left: 2px solid ${color}; position: absolute;`; + caretElement.setAttribute('data-selection-client-id', clientId); + caretElement.className = 'oe-collaboration-caret'; + + // Draw carret top square. + const caretTopSquare = this.document.createElement('div'); + caretTopSquare.className = 'oe-collaboration-caret-top-square'; + caretTopSquare.style['background-color'] = color; + caretTopSquare.setAttribute('data-client-name', clientName); + caretElement.append(caretTopSquare); + + if (clientRects.length) { + if (direction === DIRECTIONS.LEFT) { + const rect = clientRects[0]; + caretElement.style.height = `${rect.height * 1.2}px`; + caretElement.style.top = `${rect.y - containerRect.y}px`; + caretElement.style.left = `${rect.x - containerRect.x}px`; + } else { + const rect = peek(clientRects); + caretElement.style.height = `${rect.height * 1.2}px`; + caretElement.style.top = `${rect.y - containerRect.y}px`; + caretElement.style.left = `${rect.right - containerRect.x}px`; + } + } + this._multiselectionRemoveClient(clientId); + this._collabSelectionsContainer.append(caretElement, ...indicators); + } + + multiselectionRemove(clientId) { + this._collabSelectionInfos.delete(clientId); + this._multiselectionRemoveClient(clientId); + } + + _multiselectionRemoveClient(clientId) { + const elements = this._collabSelectionsContainer.querySelectorAll( + `[data-selection-client-id="${clientId}"]`, + ); + for (const element of elements) { + element.remove(); + } + } /** * Same as @see _applyCommand, except that also simulates all the @@ -870,7 +1145,7 @@ export class OdooEditor extends EventTarget { * @returns {?} */ execCommand(...args) { - this._computeHistoryCursor(); + this._computeHistorySelection(); return this._applyCommand(...args); } @@ -922,7 +1197,7 @@ export class OdooEditor extends EventTarget { let next = nextLeaf(end, this.editable); const splitEndTd = closestElement(end, 'td') && end.nextSibling; const contents = range.extractContents(); - setCursor(start, nodeSize(start)); + setSelection(start, nodeSize(start)); range = getDeepRange(this.editable, { sel }); // Restore unremovables removed by extractContents. [...contents.querySelectorAll('*')].filter(isUnremovable).forEach(n => { @@ -982,7 +1257,7 @@ export class OdooEditor extends EventTarget { const shouldPreserveSpace = (doJoin || hasSpaceAfter) && joinWith && oldText.endsWith(' '); if (shouldPreserveSpace) { joinWith.textContent = oldText.replace(/ $/, '\u00A0'); - setCursor(joinWith, nodeSize(joinWith)); + setSelection(joinWith, nodeSize(joinWith)); } // Rejoin blocks that extractContents may have split in two. while ( @@ -1000,7 +1275,7 @@ export class OdooEditor extends EventTarget { } else { next = firstLeaf(next); } - }, this._historySteps[this._historySteps.length - 1].mutations.length); + }, this._currentStep.mutations.length); if ([UNBREAKABLE_ROLLBACK_CODE, UNREMOVABLE_ROLLBACK_CODE].includes(res)) { restore(); break; @@ -1013,13 +1288,13 @@ export class OdooEditor extends EventTarget { ) { // Restore the text we modified in order to preserve trailing space. joinWith.textContent = oldText; - setCursor(joinWith, nodeSize(joinWith)); + setSelection(joinWith, nodeSize(joinWith)); } if (joinWith) { const el = closestElement(joinWith); const { zws } = fillEmpty(el); if (zws) { - setCursor(zws, 0, zws, nodeSize(zws)); + setSelection(zws, 0, zws, nodeSize(zws)); } } } @@ -1144,7 +1419,7 @@ export class OdooEditor extends EventTarget { * @returns {?} */ _applyCommand(...args) { - this._recordHistoryCursor(true); + this._recordHistorySelection(true); const result = this._protect(() => this._applyRawCommand(...args)); this.sanitize(); this.historyStep(); @@ -1216,56 +1491,80 @@ export class OdooEditor extends EventTarget { * @private * @returns {Object} */ - _computeHistoryCursor() { + _computeHistorySelection() { const sel = this.document.getSelection(); if (!sel.anchorNode) { - return this._latestComputedCursor; + return this._latestComputedSelection; } - this._latestComputedCursor = { - anchorNode: sel.anchorNode.oid, + this._latestComputedSelection = { + anchorNode: sel.anchorNode, anchorOffset: sel.anchorOffset, - focusNode: sel.focusNode.oid, + focusNode: sel.focusNode, focusOffset: sel.focusOffset, }; - return this._latestComputedCursor; + return this._latestComputedSelection; } /** * @private * @param {boolean} [useCache=false] */ - _recordHistoryCursor(useCache = false) { - const latest = this._historySteps[this._historySteps.length - 1]; - latest.cursor = - (useCache ? this._latestComputedCursor : this._computeHistoryCursor()) || {}; + _recordHistorySelection(useCache = false) { + this._currentStep.selection = + serializeSelection( + useCache ? this._latestComputedSelection : this._computeHistorySelection(), + ) || {}; } /** * Get the step index in the history to undo. * Return -1 if no undo index can be found. */ _getNextUndoIndex() { - let index = this._historySteps.length - 2; - // go back to first step that can be undoed (0 or undefined) - while (this._historyStepsStates.get(index)) { - index--; + // Go back to first step that can be undone ("redo" or undefined). + for (let index = this._historySteps.length - 1; index >= 0; index--) { + if ( + this._historySteps[index] && + this._historySteps[index].clientId === this._collabClientId + ) { + const state = this._historyStepsStates.get(this._historySteps[index].id); + if (state === 'redo' || !state) { + return index; + } + } } - return index; + // There is no steps left to be undone, return an index that does not + // point to any step + return -1; } /** * Get the step index in the history to redo. * Return -1 if no redo index can be found. */ _getNextRedoIndex() { - let pos = this._historySteps.length - 2; // We cannot redo more than what is consumed. - // Check if we have no more 2 than 0 until we get to a 1 + // Check if we have no more "consumed" than "redo" until we get to an + // "undo" let totalConsumed = 0; - while (this._historyStepsStates.has(pos) && this._historyStepsStates.get(pos) !== 1) { - // here ._historyStepsState.get(pos) can only be 2 (consumed) or 0 (undoed). - totalConsumed += this._historyStepsStates.get(pos) === 2 ? 1 : -1; - pos--; + for (let index = this._historySteps.length - 1; index >= 0; index--) { + if ( + this._historySteps[index] && + this._historySteps[index].clientId === this._collabClientId + ) { + const state = this._historyStepsStates.get(this._historySteps[index].id); + switch (state) { + case 'undo': + return totalConsumed <= 0 ? index : -1; + case 'redo': + totalConsumed -= 1; + break; + case 'consumed': + totalConsumed += 1; + break; + default: + return -1; + } + } } - const canRedo = this._historyStepsStates.get(pos) === 1 && totalConsumed <= 0; - return canRedo ? pos : -1; + return -1; } // COMMAND BAR @@ -1275,16 +1574,18 @@ export class OdooEditor extends EventTarget { this.options.noScrollSelector = this.options.noScrollSelector || 'body'; const revertHistoryBeforeCommandbar = () => { + const lastStep = this._currentStep; + this.historyRevert(lastStep); let stepIndex = this._historySteps.length - 1; - while (stepIndex >= this._beforeCommandbarStepIndex) { - const stepState = this._historyStepsStates.get(stepIndex); - if (stepState !== 2) { + while (stepIndex > this._beforeCommandbarStepIndex) { + const step = this._historySteps[stepIndex]; + const stepState = this._historyStepsStates.get(step.id); + if (step.clientId === this._collabClientId && stepState !== 'consumed') { this.historyRevert(this._historySteps[stepIndex]); + this._historyStepsStates.set(step.id, 'consumed'); } - this._historyStepsStates.set(stepIndex, 2); stepIndex--; } - this._historyStepsStates.set(this._historySteps.length - 1, 1); this.historyStep(true); setTimeout(() => { this.editable.focus(); @@ -1714,6 +2015,22 @@ export class OdooEditor extends EventTarget { node.matches([].concat(...Object.values(CLIPBOARD_BLACKLISTS)).join(',')) ); } + _safeSetAttribute(node, attributeName, attributeValue) { + const parent = node.parentNode; + const next = node.nextSibling; + this.observerFlush(); + node.remove(); + this.observer.takeRecords(); + node.setAttribute(attributeName, attributeValue); + this.observerFlush(); + DOMPurify.sanitize(node, { IN_PLACE: true }); + if (next) { + next.before(node); + } else if (parent) { + parent.append(node); + } + this.observer.takeRecords(); + } //-------------------------------------------------------------------------- // Handlers @@ -1730,12 +2047,13 @@ export class OdooEditor extends EventTarget { * @private */ _onInput(ev) { - // Record the cursor position that was computed on keydown or before + // Record the selection position that was computed on keydown or before // contentEditable execCommand (whatever preceded the 'input' event) - this._recordHistoryCursor(true); - const cursor = this._historySteps[this._historySteps.length - 1].cursor; - const { focusOffset, focusNode, anchorNode, anchorOffset } = cursor || {}; - const wasCollapsed = !cursor || (focusNode === anchorNode && focusOffset === anchorOffset); + this._recordHistorySelection(true); + const selection = this._currentStep.selection; + const { anchorNodeOid, anchorOffset, focusNodeOid, focusOffset } = selection || {}; + const wasCollapsed = + !selection || (focusNodeOid === anchorNodeOid && focusOffset === anchorOffset); // Sometimes google chrome wrongly triggers an input event with `data` // being `null` on `deleteContentForward` `insertParagraph`. Luckily, @@ -1768,12 +2086,12 @@ export class OdooEditor extends EventTarget { const selection = this.document.getSelection(); // Detect that text was selected and change behavior only if it is the case, // since it is the only text insertion case that may cause problems. - if (anchorNode !== focusNode || anchorOffset !== focusOffset) { + if (anchorNodeOid !== focusNodeOid || anchorOffset !== focusOffset) { ev.preventDefault(); this._applyRawCommand('oDeleteBackward'); insertText(selection, ev.data); const range = selection.getRangeAt(0); - setCursor(range.endContainer, range.endOffset); + setSelection(range.endContainer, range.endOffset); } // Check for url after user insert a space so we won't transform an incomplete url. if ( @@ -1818,8 +2136,8 @@ export class OdooEditor extends EventTarget { if (ev.key === 'Backspace' && !ev.ctrlKey && !ev.metaKey) { // backspace // We need to hijack it because firefox doesn't trigger a - // deleteBackward input event with a collapsed cursor in front of a - // contentEditable="false" (eg: font awesome) + // deleteBackward input event with a collapsed selection in front of + // a contentEditable="false" (eg: font awesome). const selection = this.document.getSelection(); if (selection.isCollapsed) { ev.preventDefault(); @@ -1860,9 +2178,9 @@ export class OdooEditor extends EventTarget { * @private */ _onSelectionChange() { - // Compute the current cursor on selectionchange but do not record it. Leave + // Compute the current selection on selectionchange but do not record it. Leave // that to the command execution or the 'input' event handler. - this._computeHistoryCursor(); + this._computeHistorySelection(); const selection = this.document.getSelection(); const isSelectionInEditable = @@ -1874,6 +2192,23 @@ export class OdooEditor extends EventTarget { if (this._currentMouseState === 'mouseup') { this._fixFontAwesomeSelection(); } + if ( + selection.rangeCount && + selection.getRangeAt(0) && + this.options.onCollaborativeSelectionChange + ) { + this.options.onCollaborativeSelectionChange(this.getCurrentCollaborativeSelection()); + } + } + + getCurrentCollaborativeSelection() { + const selection = this._latestComputedSelection || this._computeHistorySelection(); + if (!selection) return; + return Object.assign({ + selection: serializeSelection(selection), + color: this._collabSelectionColor, + clientId: this._collabClientId, + }); } clean() { @@ -2062,7 +2397,6 @@ export class OdooEditor extends EventTarget { // To avoid this problem, we make all editable zone become uneditable // except the link. Then when cliking outside the link, reset the // editable zones. - this.automaticStepSkipStack(); const link = closestElement(ev.target, 'a'); this._resetContenteditableLinks(); if ( @@ -2092,6 +2426,8 @@ export class OdooEditor extends EventTarget { } else { this._activateContenteditable(); } + // Ignore any changes that might have happened before this point. + this.observer.takeRecords(); const node = ev.target; // handle checkbox lists @@ -2099,6 +2435,7 @@ export class OdooEditor extends EventTarget { if (ev.offsetX < 0) { toggleClass(node, 'o_checked'); ev.preventDefault(); + this.historyStep(); } } } @@ -2363,10 +2700,10 @@ export class OdooEditor extends EventTarget { } if (this.document.caretPositionFromPoint) { const range = this.document.caretPositionFromPoint(ev.clientX, ev.clientY); - setCursor(range.offsetNode, range.offset); + setSelection(range.offsetNode, range.offset); } else if (this.document.caretRangeFromPoint) { const range = this.document.caretRangeFromPoint(ev.clientX, ev.clientY); - setCursor(range.startContainer, range.startOffset); + setSelection(range.startContainer, range.startOffset); } this.execCommand('insertHTML', this._prepareClipboardData(pastedText)); }); @@ -2386,7 +2723,7 @@ export class OdooEditor extends EventTarget { const cursorDestination = tds[tds.findIndex(td => closestTd === td) + (direction === DIRECTIONS.LEFT ? -1 : 1)]; if (cursorDestination) { - setCursor(...startPos(cursorDestination), ...endPos(cursorDestination), true); + setSelection(...startPos(cursorDestination), ...endPos(cursorDestination), true); } else if (direction === DIRECTIONS.RIGHT) { this._addRowBelow(); this._onTabulationInTable(ev); @@ -2450,7 +2787,7 @@ export class OdooEditor extends EventTarget { } } if (shouldUpdateSelection) { - setCursor( + setSelection( fixedSelection.anchorNode, fixedSelection.anchorOffset, fixedSelection.focusNode, diff --git a/addons/web_editor/static/lib/odoo-editor/src/commands/commands.js b/addons/web_editor/static/lib/odoo-editor/src/commands/commands.js index d2c5cb96443..0f4b8010c56 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/commands/commands.js +++ b/addons/web_editor/static/lib/odoo-editor/src/commands/commands.js @@ -26,7 +26,7 @@ import { leftLeafFirstPath, preserveCursor, rightPos, - setCursor, + setSelection, setCursorStart, setTagName, splitElement, @@ -256,9 +256,9 @@ export function applyInlineStyle(editor, applyStyle) { const firstNode = selectedTextNodes[0]; const lastNode = selectedTextNodes[selectedTextNodes.length - 1]; if (direction === DIRECTIONS.RIGHT) { - setCursor(firstNode, 0, lastNode, lastNode.length); + setSelection(firstNode, 0, lastNode, lastNode.length); } else { - setCursor(lastNode, lastNode.length, firstNode, 0); + setSelection(lastNode, lastNode.length, firstNode, 0); } } function addColumn(editor, beforeOrAfter) { @@ -285,7 +285,7 @@ function deleteTable(editor, table) { p.appendChild(document.createElement('br')); table.before(p); table.remove(); - setCursor(p, 0); + setSelection(p, 0); } // This is a whitelist of the commands that are implemented by the @@ -307,7 +307,7 @@ export const editorCommands = { const insertedNode = editorCommands.insertHTML(editor, '')[0]; insertedNode.className = faClass; const position = rightPos(insertedNode); - setCursor(...position, ...position, false); + setSelection(...position, ...position, false); }, // History @@ -324,7 +324,7 @@ export const editorCommands = { block.nodeName, ) ) { - setCursor(block, 0, block, nodeSize(block)); + setSelection(block, 0, block, nodeSize(block)); editor.historyPauseSteps(); editor.document.execCommand('removeFormat'); editor.historyUnpauseSteps(); @@ -394,13 +394,13 @@ export const editorCommands = { link = link || prompt('URL or Email', (currentLink && currentLink.href) || 'http://'); const res = editor.document.execCommand('createLink', false, link); if (res) { - setCursor(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); + setSelection(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); const node = findNode(closestPath(sel.focusNode), node => node.tagName === 'A'); for (const [param, value] of Object.entries(editor.options.defaultLinkAttributes)) { node.setAttribute(param, `${value}`); } const pos = [node.parentElement, childNodeIndex(node) + 1]; - setCursor(...pos, ...pos, false); + setSelection(...pos, ...pos, false); } }, unlink: editor => { @@ -415,12 +415,12 @@ export const editorCommands = { if (sel.isCollapsed) { const cr = preserveCursor(editor.document); const node = closestElement(sel.focusNode, 'a'); - setCursor(node, 0, node, node.childNodes.length, false); + setSelection(node, 0, node, node.childNodes.length, false); editor.document.execCommand('unlink'); cr(); } else { editor.document.execCommand('unlink'); - setCursor(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); + setSelection(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); } }, @@ -561,7 +561,7 @@ export const editorCommands = { ? splitTextNode(anchorNode, sel.anchorOffset, DIRECTIONS.LEFT) + 1 && anchorNode : splitElement(anchorNode, sel.anchorOffset).shift(); const newPosition = rightPos(newAnchorNode); - setCursor(...newPosition, ...newPosition, false); + setSelection(...newPosition, ...newPosition, false); } const [table] = editorCommands.insertHTML(editor, tableHtml); setCursorStart(table.querySelector('td')); @@ -587,7 +587,7 @@ export const editorCommands = { const index = cells.findIndex(td => td === cell); const siblingCell = cells[index - 1] || cells[index + 1]; table.querySelectorAll(`tr td:nth-of-type(${index + 1})`).forEach(td => td.remove()); - siblingCell ? setCursor(...startPos(siblingCell)) : deleteTable(editor, table); + siblingCell ? setSelection(...startPos(siblingCell)) : deleteTable(editor, table); }, removeRow: editor => { getDeepRange(editor.editable, { select: true }); // Ensure deep range for finding tr. @@ -598,7 +598,7 @@ export const editorCommands = { const rowIndex = rows.findIndex(tr => tr === row); const siblingRow = rows[rowIndex - 1] || rows[rowIndex + 1]; row.remove(); - siblingRow ? setCursor(...startPos(siblingRow)) : deleteTable(editor, table); + siblingRow ? setSelection(...startPos(siblingRow)) : deleteTable(editor, table); }, deleteTable: (editor, table) => deleteTable(editor, table), insertHorizontalRule(editor) { diff --git a/addons/web_editor/static/lib/odoo-editor/src/commands/deleteBackward.js b/addons/web_editor/static/lib/odoo-editor/src/commands/deleteBackward.js index 18bef0adbfc..828b891c956 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/commands/deleteBackward.js +++ b/addons/web_editor/static/lib/odoo-editor/src/commands/deleteBackward.js @@ -18,7 +18,7 @@ import { moveNodes, nodeSize, prepareUpdate, - setCursor, + setSelection, splitTextNode, isUnbreakable, isMediaElement, @@ -56,7 +56,7 @@ Text.prototype.oDeleteBackward = function (offset, alreadyMoved = false) { } fillEmpty(parentNode); - setCursor(parentNode, firstSplitOffset); + setSelection(parentNode, firstSplitOffset); }; HTMLElement.prototype.oDeleteBackward = function (offset, alreadyMoved = false) { @@ -127,7 +127,7 @@ HTMLElement.prototype.oDeleteBackward = function (offset, alreadyMoved = false) // TODO this handle BR/IMG/etc removals../ to see if we // prefer to have a dedicated handler for every possible // HTML element or if we let this generic code handle it. - setCursor(parentEl, parentOffset); + setSelection(parentEl, parentOffset); return; } } @@ -158,7 +158,7 @@ HTMLElement.prototype.oDeleteBackward = function (offset, alreadyMoved = false) firstBlockIndex++; } let [cursorNode, cursorOffset] = moveNodes(...moveDest, this, offset, firstBlockIndex); - setCursor(cursorNode, cursorOffset); + setSelection(cursorNode, cursorOffset); // Propagate if this is still a block on the left of where the nodes were // moved. diff --git a/addons/web_editor/static/lib/odoo-editor/src/commands/shiftEnter.js b/addons/web_editor/static/lib/odoo-editor/src/commands/shiftEnter.js index fd42a8812bd..3b106e124f2 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/commands/shiftEnter.js +++ b/addons/web_editor/static/lib/odoo-editor/src/commands/shiftEnter.js @@ -5,7 +5,7 @@ import { isFakeLineBreak, prepareUpdate, rightPos, - setCursor, + setSelection, getState, leftPos, splitTextNode, @@ -35,7 +35,7 @@ HTMLElement.prototype.oShiftEnter = function (offset) { for (const el of brEls) { if (el.parentNode) { - setCursor(...rightPos(el)); + setSelection(...rightPos(el)); break; } } diff --git a/addons/web_editor/static/lib/odoo-editor/src/commands/toggleList.js b/addons/web_editor/static/lib/odoo-editor/src/commands/toggleList.js index 6c60ebe7832..c1417ccb5c1 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/commands/toggleList.js +++ b/addons/web_editor/static/lib/odoo-editor/src/commands/toggleList.js @@ -23,8 +23,7 @@ HTMLElement.prototype.oToggleList = function (offset, mode = 'UL') { return inLI.oToggleList(0, mode); } const restoreCursor = preserveCursor(this.ownerDocument); - // if `this` is the root editable - if (this.oid === 1) { + if (this.oid === 'root') { const callingNode = this.childNodes[offset]; const group = getAdjacents(callingNode, n => !isBlock(n)); insertListAfter(callingNode, mode, [group]); diff --git a/addons/web_editor/static/lib/odoo-editor/src/style.css b/addons/web_editor/static/lib/odoo-editor/src/style.css index 84120fecb9a..f54edeb88c0 100644 --- a/addons/web_editor/static/lib/odoo-editor/src/style.css +++ b/addons/web_editor/static/lib/odoo-editor/src/style.css @@ -301,3 +301,30 @@ i.oe-commandbar-commandImg { text-align: inherit; width: 100%; } + +/* Collaboration cursor */ +.oe-collaboration-selections-container { + position: absolute; + isolation: isolate; + height: 0; + width: 0; + z-index: 1; +} +.oe-collaboration-caret-top-square { + min-height: 5px; + min-width: 5px; + color: #fff; + text-shadow: 0 0 5px #000; + position: absolute; + bottom: 100%; + left: -4px; + white-space: nowrap; +} + +.oe-collaboration-caret-top-square:hover::before { + content: attr(data-client-name); +} +.oe-collaboration-caret-top-square:hover { + border-radius: 2px; + padding: 0.3em 0.6em; +} diff --git a/addons/web_editor/static/lib/odoo-editor/src/utils/DOMPurify.js b/addons/web_editor/static/lib/odoo-editor/src/utils/DOMPurify.js new file mode 100644 index 00000000000..388dc1e84b9 --- /dev/null +++ b/addons/web_editor/static/lib/odoo-editor/src/utils/DOMPurify.js @@ -0,0 +1,1376 @@ +/*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.DOMPurify = factory()); +}(this, function () { 'use strict'; + + function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + var hasOwnProperty = Object.hasOwnProperty, + setPrototypeOf = Object.setPrototypeOf, + isFrozen = Object.isFrozen, + getPrototypeOf = Object.getPrototypeOf, + getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + var freeze = Object.freeze, + seal = Object.seal, + create = Object.create; // eslint-disable-line import/no-mutable-exports + + var _ref = typeof Reflect !== 'undefined' && Reflect, + apply = _ref.apply, + construct = _ref.construct; + + if (!apply) { + apply = function apply(fun, thisValue, args) { + return fun.apply(thisValue, args); + }; + } + + if (!freeze) { + freeze = function freeze(x) { + return x; + }; + } + + if (!seal) { + seal = function seal(x) { + return x; + }; + } + + if (!construct) { + construct = function construct(Func, args) { + return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))(); + }; + } + + var arrayForEach = unapply(Array.prototype.forEach); + var arrayPop = unapply(Array.prototype.pop); + var arrayPush = unapply(Array.prototype.push); + + var stringToLowerCase = unapply(String.prototype.toLowerCase); + var stringMatch = unapply(String.prototype.match); + var stringReplace = unapply(String.prototype.replace); + var stringIndexOf = unapply(String.prototype.indexOf); + var stringTrim = unapply(String.prototype.trim); + + var regExpTest = unapply(RegExp.prototype.test); + + var typeErrorCreate = unconstruct(TypeError); + + function unapply(func) { + return function (thisArg) { + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return apply(func, thisArg, args); + }; + } + + function unconstruct(func) { + return function () { + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + return construct(func, args); + }; + } + + /* Add properties to a lookup table */ + function addToSet(set, array) { + if (setPrototypeOf) { + // Make 'in' and truthy checks like Boolean(set.constructor) + // independent of any properties defined on Object.prototype. + // Prevent prototype setters from intercepting set as a this value. + setPrototypeOf(set, null); + } + + var l = array.length; + while (l--) { + var element = array[l]; + if (typeof element === 'string') { + var lcElement = stringToLowerCase(element); + if (lcElement !== element) { + // Config presets (e.g. tags.js, attrs.js) are immutable. + if (!isFrozen(array)) { + array[l] = lcElement; + } + + element = lcElement; + } + } + + set[element] = true; + } + + return set; + } + + /* Shallow clone an object */ + function clone(object) { + var newObject = create(null); + + var property = void 0; + for (property in object) { + if (apply(hasOwnProperty, object, [property])) { + newObject[property] = object[property]; + } + } + + return newObject; + } + + /* IE10 doesn't support __lookupGetter__ so lets' + * simulate it. It also automatically checks + * if the prop is function or getter and behaves + * accordingly. */ + function lookupGetter(object, prop) { + while (object !== null) { + var desc = getOwnPropertyDescriptor(object, prop); + if (desc) { + if (desc.get) { + return unapply(desc.get); + } + + if (typeof desc.value === 'function') { + return unapply(desc.value); + } + } + + object = getPrototypeOf(object); + } + + function fallbackValue(element) { + console.warn('fallback value for', element); + return null; + } + + return fallbackValue; + } + + var html = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); + + // SVG + var svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']); + + var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); + + // List of SVG elements that are disallowed by default. + // We still need to know them so that we can do namespace + // checks properly in case one wants to add them to + // allow-list. + var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']); + + var mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); + + // Similarly to SVG, we want to know all MathML elements, + // even those that we disallow by default. + var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']); + + var text = freeze(['#text']); + + var html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']); + + var svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']); + + var mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']); + + var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']); + + // eslint-disable-next-line unicorn/better-regex + var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode + var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm); + var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape + var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape + var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape + ); + var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); + var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex + ); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + + var getGlobal = function getGlobal() { + return typeof window === 'undefined' ? null : window; + }; + + /** + * Creates a no-op policy for internal use only. + * Don't export this function outside this module! + * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory. + * @param {Document} document The document object (to determine policy name suffix) + * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types + * are not supported). + */ + var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) { + if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') { + return null; + } + + // Allow the callers to control the unique policy name + // by adding a data-tt-policy-suffix to the script element with the DOMPurify. + // Policy creation with duplicate names throws in Trusted Types. + var suffix = null; + var ATTR_NAME = 'data-tt-policy-suffix'; + if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) { + suffix = document.currentScript.getAttribute(ATTR_NAME); + } + + var policyName = 'dompurify' + (suffix ? '#' + suffix : ''); + + try { + return trustedTypes.createPolicy(policyName, { + createHTML: function createHTML(html$$1) { + return html$$1; + } + }); + } catch (_) { + // Policy creation failed (most likely another DOMPurify script has + // already run). Skip creating the policy, as this will only cause errors + // if TT are enforced. + console.warn('TrustedTypes policy ' + policyName + ' could not be created.'); + return null; + } + }; + + function createDOMPurify() { + var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal(); + + var DOMPurify = function DOMPurify(root) { + return createDOMPurify(root); + }; + + /** + * Version label, exposed for easier checks + * if DOMPurify is up to date or not + */ + DOMPurify.version = '2.3.1'; + + /** + * Array of elements that DOMPurify removed during sanitation. + * Empty if nothing was removed. + */ + DOMPurify.removed = []; + + if (!window || !window.document || window.document.nodeType !== 9) { + // Not running in a browser, provide a factory function + // so that you can pass your own Window + DOMPurify.isSupported = false; + + return DOMPurify; + } + + var originalDocument = window.document; + + var document = window.document; + var DocumentFragment = window.DocumentFragment, + HTMLTemplateElement = window.HTMLTemplateElement, + Node = window.Node, + Element = window.Element, + NodeFilter = window.NodeFilter, + _window$NamedNodeMap = window.NamedNodeMap, + NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, + Text = window.Text, + Comment = window.Comment, + DOMParser = window.DOMParser, + trustedTypes = window.trustedTypes; + + + var ElementPrototype = Element.prototype; + + var cloneNode = lookupGetter(ElementPrototype, 'cloneNode'); + var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling'); + var getChildNodes = lookupGetter(ElementPrototype, 'childNodes'); + var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); + + // As per issue #47, the web-components registry is inherited by a + // new document created via createHTMLDocument. As per the spec + // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries) + // a new empty registry is used when creating a template contents owner + // document, so we use that as our parent document to ensure nothing + // is inherited. + if (typeof HTMLTemplateElement === 'function') { + var template = document.createElement('template'); + if (template.content && template.content.ownerDocument) { + document = template.content.ownerDocument; + } + } + + var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument); + var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : ''; + + var _document = document, + implementation = _document.implementation, + createNodeIterator = _document.createNodeIterator, + createDocumentFragment = _document.createDocumentFragment, + getElementsByTagName = _document.getElementsByTagName; + var importNode = originalDocument.importNode; + + + var documentMode = {}; + try { + documentMode = clone(document).documentMode ? document.documentMode : {}; + } catch (_) {} + + var hooks = {}; + + /** + * Expose whether this browser supports running the full DOMPurify. + */ + DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9; + + var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR, + ERB_EXPR$$1 = ERB_EXPR, + DATA_ATTR$$1 = DATA_ATTR, + ARIA_ATTR$$1 = ARIA_ATTR, + IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA, + ATTR_WHITESPACE$$1 = ATTR_WHITESPACE; + var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI; + + /** + * We consider the elements and attributes below to be safe. Ideally + * don't add any new ones but feel free to remove unwanted ones. + */ + + /* allowed element names */ + + var ALLOWED_TAGS = null; + var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text))); + + /* Allowed attribute names */ + var ALLOWED_ATTR = null; + var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml))); + + /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */ + var FORBID_TAGS = null; + + /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */ + var FORBID_ATTR = null; + + /* Decide if ARIA attributes are okay */ + var ALLOW_ARIA_ATTR = true; + + /* Decide if custom data attributes are okay */ + var ALLOW_DATA_ATTR = true; + + /* Decide if unknown protocols are okay */ + var ALLOW_UNKNOWN_PROTOCOLS = false; + + /* Output should be safe for common template engines. + * This means, DOMPurify removes data attributes, mustaches and ERB + */ + var SAFE_FOR_TEMPLATES = false; + + /* Decide if document with ... should be returned */ + var WHOLE_DOCUMENT = false; + + /* Track whether config is already set on this instance of DOMPurify. */ + var SET_CONFIG = false; + + /* Decide if all elements (e.g. style, script) must be children of + * document.body. By default, browsers might move them to document.head */ + var FORCE_BODY = false; + + /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html + * string (or a TrustedHTML object if Trusted Types are supported). + * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead + */ + var RETURN_DOM = false; + + /* Decide if a DOM `DocumentFragment` should be returned, instead of a html + * string (or a TrustedHTML object if Trusted Types are supported) */ + var RETURN_DOM_FRAGMENT = false; + + /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM + * `Node` is imported into the current `Document`. If this flag is not enabled the + * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by + * DOMPurify. + * + * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false` + * might cause XSS from attacks hidden in closed shadowroots in case the browser + * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/ + */ + var RETURN_DOM_IMPORT = true; + + /* Try to return a Trusted Type object instead of a string, return a string in + * case Trusted Types are not supported */ + var RETURN_TRUSTED_TYPE = false; + + /* Output should be free from DOM clobbering attacks? */ + var SANITIZE_DOM = true; + + /* Keep element content when removing element? */ + var KEEP_CONTENT = true; + + /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead + * of importing it into a new Document and returning a sanitized copy */ + var IN_PLACE = false; + + /* Allow usage of profiles like html, svg and mathMl */ + var USE_PROFILES = {}; + + /* Tags to ignore content of when KEEP_CONTENT is true */ + var FORBID_CONTENTS = null; + var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']); + + /* Tags that are safe for data: URIs */ + var DATA_URI_TAGS = null; + var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']); + + /* Attributes safe for values like "javascript:" */ + var URI_SAFE_ATTRIBUTES = null; + var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']); + + var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; + var SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; + var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; + /* Document namespace */ + var NAMESPACE = HTML_NAMESPACE; + var IS_EMPTY_INPUT = false; + + /* Keep a reference to config to pass to hooks */ + var CONFIG = null; + + /* Ideally, do not touch anything below this line */ + /* ______________________________________________ */ + + var formElement = document.createElement('form'); + + /** + * _parseConfig + * + * @param {Object} cfg optional config literal + */ + // eslint-disable-next-line complexity + var _parseConfig = function _parseConfig(cfg) { + if (CONFIG && CONFIG === cfg) { + return; + } + + /* Shield configuration object from tampering */ + if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') { + cfg = {}; + } + + /* Shield configuration object from prototype pollution */ + cfg = clone(cfg); + + /* Set configuration parameters */ + ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS; + ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR; + URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES; + DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS; + FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS; + FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {}; + FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {}; + USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false; + ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true + ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true + ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false + SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false + WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false + RETURN_DOM = cfg.RETURN_DOM || false; // Default false + RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false + RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true + RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false + FORCE_BODY = cfg.FORCE_BODY || false; // Default false + SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true + KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true + IN_PLACE = cfg.IN_PLACE || false; // Default false + IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1; + NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; + if (SAFE_FOR_TEMPLATES) { + ALLOW_DATA_ATTR = false; + } + + if (RETURN_DOM_FRAGMENT) { + RETURN_DOM = true; + } + + /* Parse profile info */ + if (USE_PROFILES) { + ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text))); + ALLOWED_ATTR = []; + if (USE_PROFILES.html === true) { + addToSet(ALLOWED_TAGS, html); + addToSet(ALLOWED_ATTR, html$1); + } + + if (USE_PROFILES.svg === true) { + addToSet(ALLOWED_TAGS, svg); + addToSet(ALLOWED_ATTR, svg$1); + addToSet(ALLOWED_ATTR, xml); + } + + if (USE_PROFILES.svgFilters === true) { + addToSet(ALLOWED_TAGS, svgFilters); + addToSet(ALLOWED_ATTR, svg$1); + addToSet(ALLOWED_ATTR, xml); + } + + if (USE_PROFILES.mathMl === true) { + addToSet(ALLOWED_TAGS, mathMl); + addToSet(ALLOWED_ATTR, mathMl$1); + addToSet(ALLOWED_ATTR, xml); + } + } + + /* Merge configuration parameters */ + if (cfg.ADD_TAGS) { + if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { + ALLOWED_TAGS = clone(ALLOWED_TAGS); + } + + addToSet(ALLOWED_TAGS, cfg.ADD_TAGS); + } + + if (cfg.ADD_ATTR) { + if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { + ALLOWED_ATTR = clone(ALLOWED_ATTR); + } + + addToSet(ALLOWED_ATTR, cfg.ADD_ATTR); + } + + if (cfg.ADD_URI_SAFE_ATTR) { + addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR); + } + + if (cfg.FORBID_CONTENTS) { + if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { + FORBID_CONTENTS = clone(FORBID_CONTENTS); + } + + addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS); + } + + /* Add #text in case KEEP_CONTENT is set to true */ + if (KEEP_CONTENT) { + ALLOWED_TAGS['#text'] = true; + } + + /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */ + if (WHOLE_DOCUMENT) { + addToSet(ALLOWED_TAGS, ['html', 'head', 'body']); + } + + /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */ + if (ALLOWED_TAGS.table) { + addToSet(ALLOWED_TAGS, ['tbody']); + delete FORBID_TAGS.tbody; + } + + // Prevent further manipulation of configuration. + // Not available in IE8, Safari 5, etc. + if (freeze) { + freeze(cfg); + } + + CONFIG = cfg; + }; + + var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']); + + var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); + + /* Keep track of all possible SVG and MathML tags + * so that we can perform the namespace checks + * correctly. */ + var ALL_SVG_TAGS = addToSet({}, svg); + addToSet(ALL_SVG_TAGS, svgFilters); + addToSet(ALL_SVG_TAGS, svgDisallowed); + + var ALL_MATHML_TAGS = addToSet({}, mathMl); + addToSet(ALL_MATHML_TAGS, mathMlDisallowed); + + /** + * + * + * @param {Element} element a DOM element whose namespace is being checked + * @returns {boolean} Return false if the element has a + * namespace that a spec-compliant parser would never + * return. Return true otherwise. + */ + var _checkValidNamespace = function _checkValidNamespace(element) { + var parent = getParentNode(element); + + // In JSDOM, if we're inside shadow DOM, then parentNode + // can be null. We just simulate parent in this case. + if (!parent || !parent.tagName) { + parent = { + namespaceURI: HTML_NAMESPACE, + tagName: 'template' + }; + } + + var tagName = stringToLowerCase(element.tagName); + var parentTagName = stringToLowerCase(parent.tagName); + + if (element.namespaceURI === SVG_NAMESPACE) { + // The only way to switch from HTML namespace to SVG + // is via . If it happens via any other tag, then + // it should be killed. + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === 'svg'; + } + + // The only way to switch from MathML to SVG is via + // svg if parent is either or MathML + // text integration points. + if (parent.namespaceURI === MATHML_NAMESPACE) { + return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); + } + + // We only allow elements that are defined in SVG + // spec. All others are disallowed in SVG namespace. + return Boolean(ALL_SVG_TAGS[tagName]); + } + + if (element.namespaceURI === MATHML_NAMESPACE) { + // The only way to switch from HTML namespace to MathML + // is via . If it happens via any other tag, then + // it should be killed. + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === 'math'; + } + + // The only way to switch from SVG to MathML is via + // and HTML integration points + if (parent.namespaceURI === SVG_NAMESPACE) { + return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName]; + } + + // We only allow elements that are defined in MathML + // spec. All others are disallowed in MathML namespace. + return Boolean(ALL_MATHML_TAGS[tagName]); + } + + if (element.namespaceURI === HTML_NAMESPACE) { + // The only way to switch from SVG to HTML is via + // HTML integration points, and from MathML to HTML + // is via MathML text integration points + if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { + return false; + } + + if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { + return false; + } + + // Certain elements are allowed in both SVG and HTML + // namespace. We need to specify them explicitly + // so that they don't get erronously deleted from + // HTML namespace. + var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']); + + // We disallow tags that are specific for MathML + // or SVG and should never appear in HTML namespace + return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]); + } + + // The code should never reach this place (this means + // that the element somehow got namespace that is not + // HTML, SVG or MathML). Return false just in case. + return false; + }; + + /** + * _forceRemove + * + * @param {Node} node a DOM node + */ + var _forceRemove = function _forceRemove(node) { + arrayPush(DOMPurify.removed, { element: node }); + try { + // eslint-disable-next-line unicorn/prefer-dom-node-remove + node.parentNode.removeChild(node); + } catch (_) { + try { + node.outerHTML = emptyHTML; + } catch (_) { + node.remove(); + } + } + }; + + /** + * _removeAttribute + * + * @param {String} name an Attribute name + * @param {Node} node a DOM node + */ + var _removeAttribute = function _removeAttribute(name, node) { + try { + arrayPush(DOMPurify.removed, { + attribute: node.getAttributeNode(name), + from: node + }); + } catch (_) { + arrayPush(DOMPurify.removed, { + attribute: null, + from: node + }); + } + + node.removeAttribute(name); + + // We void attribute values for unremovable "is"" attributes + if (name === 'is' && !ALLOWED_ATTR[name]) { + if (RETURN_DOM || RETURN_DOM_FRAGMENT) { + try { + _forceRemove(node); + } catch (_) {} + } else { + try { + node.setAttribute(name, ''); + } catch (_) {} + } + } + }; + + /** + * _initDocument + * + * @param {String} dirty a string of dirty markup + * @return {Document} a DOM, filled with the dirty markup + */ + var _initDocument = function _initDocument(dirty) { + /* Create a HTML document */ + var doc = void 0; + var leadingWhitespace = void 0; + + if (FORCE_BODY) { + dirty = '' + dirty; + } else { + /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */ + var matches = stringMatch(dirty, /^[\r\n\t ]+/); + leadingWhitespace = matches && matches[0]; + } + + var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; + /* + * Use the DOMParser API by default, fallback later if needs be + * DOMParser not work for svg when has multiple root element. + */ + if (NAMESPACE === HTML_NAMESPACE) { + try { + doc = new DOMParser().parseFromString(dirtyPayload, 'text/html'); + } catch (_) {} + } + + /* Use createHTMLDocument in case DOMParser is not available */ + if (!doc || !doc.documentElement) { + doc = implementation.createDocument(NAMESPACE, 'template', null); + try { + doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload; + } catch (_) { + // Syntax error if dirtyPayload is invalid xml + } + } + + var body = doc.body || doc.documentElement; + + if (dirty && leadingWhitespace) { + body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null); + } + + /* Work on whole document or just its body */ + if (NAMESPACE === HTML_NAMESPACE) { + return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0]; + } + + return WHOLE_DOCUMENT ? doc.documentElement : body; + }; + + /** + * _createIterator + * + * @param {Document} root document/fragment to create iterator for + * @return {Iterator} iterator instance + */ + var _createIterator = function _createIterator(root) { + return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false); + }; + + /** + * _isClobbered + * + * @param {Node} elm element to check for clobbering attacks + * @return {Boolean} true if clobbered, false if safe + */ + var _isClobbered = function _isClobbered(elm) { + if (elm instanceof Text || elm instanceof Comment) { + return false; + } + + if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function') { + return true; + } + + return false; + }; + + /** + * _isNode + * + * @param {Node} obj object to check whether it's a DOM node + * @return {Boolean} true is object is a DOM node + */ + var _isNode = function _isNode(object) { + return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'; + }; + + /** + * _executeHook + * Execute user configurable hooks + * + * @param {String} entryPoint Name of the hook's entry point + * @param {Node} currentNode node to work on with the hook + * @param {Object} data additional hook parameters + */ + var _executeHook = function _executeHook(entryPoint, currentNode, data) { + if (!hooks[entryPoint]) { + return; + } + + arrayForEach(hooks[entryPoint], function (hook) { + hook.call(DOMPurify, currentNode, data, CONFIG); + }); + }; + + /** + * _sanitizeElements + * + * @protect nodeName + * @protect textContent + * @protect removeChild + * + * @param {Node} currentNode to check for permission to exist + * @return {Boolean} true if node was killed, false if left alive + */ + var _sanitizeElements = function _sanitizeElements(currentNode) { + var content = void 0; + + /* Execute a hook if present */ + _executeHook('beforeSanitizeElements', currentNode, null); + + /* Check if element is clobbered or can clobber */ + if (_isClobbered(currentNode)) { + _forceRemove(currentNode); + return true; + } + + /* Check if tagname contains Unicode */ + if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) { + _forceRemove(currentNode); + return true; + } + + /* Now let's check the element's type and name */ + var tagName = stringToLowerCase(currentNode.nodeName); + + /* Execute a hook if present */ + _executeHook('uponSanitizeElement', currentNode, { + tagName: tagName, + allowedTags: ALLOWED_TAGS + }); + + /* Detect mXSS attempts abusing namespace confusion */ + if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) { + _forceRemove(currentNode); + return true; + } + + /* Mitigate a problem with templates inside select */ + if (tagName === 'select' && regExpTest(/
+
diff --git a/addons/web_editor/static/lib/odoo-editor/test/editor-test.js b/addons/web_editor/static/lib/odoo-editor/test/editor-test.js index 7b2b15237e3..05904ba70ae 100644 --- a/addons/web_editor/static/lib/odoo-editor/test/editor-test.js +++ b/addons/web_editor/static/lib/odoo-editor/test/editor-test.js @@ -8,6 +8,7 @@ import './spec/insertHTML.test.js'; import './spec/fontAwesome.test.js'; import './spec/autostep.test.js'; import './spec/urlRegex.test.js'; +import './spec/collab.test.js'; mocha.run(failures => { if (failures) { diff --git a/addons/web_editor/static/lib/odoo-editor/test/spec/collab.test.js b/addons/web_editor/static/lib/odoo-editor/test/spec/collab.test.js new file mode 100644 index 00000000000..7eed71df836 --- /dev/null +++ b/addons/web_editor/static/lib/odoo-editor/test/spec/collab.test.js @@ -0,0 +1,572 @@ +import { OdooEditor } from '../../src/OdooEditor.js'; +import { + insertCharsAt, + parseMultipleTextualSelection, + setTestSelection, + targetDeepest, +} from '../utils.js'; + +const overridenDomClass = [ + 'HTMLBRElement', + 'HTMLHeadingElement', + 'HTMLParagraphElement', + 'HTMLPreElement', + 'HTMLQuoteElement', + 'HTMLTableCellElement', + 'Text', +]; + +const applyConcurentActions = (clientInfos, concurentActions) => { + const clientInfosList = Object.values(clientInfos); + for (const clientInfo of clientInfosList) { + if (typeof concurentActions[clientInfo.clientId] === 'function') { + concurentActions[clientInfo.clientId](clientInfo.editor); + } + } +}; + +const mergeClientsSteps = clientInfos => { + const clientInfosList = Object.values(clientInfos); + for (const clientInfoA of clientInfosList) { + for (const clientInfoB of clientInfosList) { + if (clientInfoA === clientInfoB) { + continue; + } + for (const step of clientInfoB.recordedHistorySteps) { + clientInfoA.editor.onExternalHistorySteps([JSON.parse(JSON.stringify(step))]); + } + } + } +}; + +const testSameHistory = clientInfos => { + const clientInfosList = Object.values(clientInfos); + + const firstClientInfo = clientInfosList[0]; + const historyLength = firstClientInfo.editor._historySteps.length; + + for (const clientInfo of clientInfosList.slice(1)) { + window.chai + .expect(firstClientInfo.editor._historySteps.length) + .to.be.equal(historyLength, 'The history size should be the same.'); + for (let i = 0; i < historyLength; i++) { + try { + window.chai + .expect(firstClientInfo.editor._historySteps[i].id) + .to.be.equal( + clientInfo.editor._historySteps[i].id, + `History steps are not consistent accross clients.`, + ); + } catch (e) { + console.log( + 'Clients steps:', + clientInfosList.map(x => x.editor._historySteps.map(y => `${y.id}`)), + ); + throw e; + } + } + } +}; + +const testMultiEditor = spec => { + const clientInfos = {}; + const concurentActions = spec.concurentActions || []; + const clientIds = spec.clientIds || Object.keys(concurentActions); + for (const clientId of clientIds) { + clientInfos[clientId] = { + clientId, + recordedHistorySteps: [], + }; + const clientInfo = clientInfos[clientId]; + clientInfo.iframe = document.createElement('iframe'); + if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { + // Firefox reset the page without this hack. + // With this hack, chrome does not render content. + clientInfo.iframe.setAttribute('src', ' javascript:void(0);'); + } + document.body.appendChild(clientInfo.iframe); + + clientInfo.editable = document.createElement('div'); + clientInfo.editable.setAttribute('contenteditable', 'true'); + clientInfo.editable.innerHTML = spec.contentBefore; + + const iframeWindow = clientInfo.iframe.contentWindow; + + for (const overridenClass of overridenDomClass) { + const windowClassPrototype = window[overridenClass].prototype; + const iframeWindowClassPrototype = iframeWindow[overridenClass].prototype; + const iframePrototypeMethodNames = Object.keys(iframeWindowClassPrototype); + + for (const methodName of Object.keys(windowClassPrototype)) { + if (!iframePrototypeMethodNames.includes(methodName)) { + iframeWindowClassPrototype[methodName] = windowClassPrototype[methodName]; + } + } + } + } + const clientInfosList = Object.values(clientInfos); + + let shouldListenSteps = false; + + // Init the editors + for (const clientInfo of clientInfosList) { + const selections = parseMultipleTextualSelection(clientInfo.editable); + const iframeWindow = clientInfo.iframe.contentWindow; + const iframeDocument = iframeWindow.document; + iframeDocument.body.appendChild(clientInfo.editable); + + // Insure all the client will have the same starting id. + let nextId = 1; + OdooEditor.prototype._generateId = () => 'fake_id_' + nextId++; + + clientInfo.editor = new OdooEditor(clientInfo.editable, { + toSanitize: false, + document: iframeDocument, + collaborationClientId: clientInfo.clientId, + onHistoryStep: step => { + if (shouldListenSteps) { + clientInfo.recordedHistorySteps.push(step); + } + }, + onHistoryMissingParentSteps: ({ step, fromStepId }) => { + const missingSteps = clientInfos[step.clientId].editor.historyGetMissingSteps({ + fromStepId, + toStepId: step.id, + }); + if (missingSteps === -1 || !missingSteps.length) { + throw new Error('Impossible to get the missing steps.'); + } + clientInfo.editor.onExternalHistorySteps(missingSteps.concat([step])); + }, + }); + clientInfo.editor.keyboardType = 'PHYSICAL_KEYBOARD'; + const selection = selections[clientInfo.clientId]; + if (selection) { + setTestSelection(selection, iframeDocument); + } else { + iframeDocument.getSelection().removeAllRanges(); + } + // Flush the history so that steps generated by the parsing of the + // selection and the editor loading are not recorded. + clientInfo.editor.observerFlush(); + } + + shouldListenSteps = true; + + // From now, any any step from a client must have a different ID. + let concurentNextId = 1; + OdooEditor.prototype._generateId = () => 'fake_concurent_id_' + concurentNextId++; + + if (spec.afterCreate) { + spec.afterCreate(clientInfos); + } + + shouldListenSteps = false; + + // Render textual selection. + + const cursorNodes = {}; + for (const clientInfo of clientInfosList) { + const iframeDocument = clientInfo.iframe.contentWindow.document; + const clientSelection = iframeDocument.getSelection(); + if (clientSelection.anchorNode === null) { + continue; + } + + const [anchorNode, anchorOffset] = targetDeepest( + clientSelection.anchorNode, + clientSelection.anchorOffset, + ); + const [focusNode, focusOffset] = targetDeepest( + clientSelection.focusNode, + clientSelection.focusOffset, + ); + + const clientId = clientInfo.clientId; + cursorNodes[focusNode.oid] = cursorNodes[focusNode.oid] || []; + cursorNodes[focusNode.oid].push({ type: 'focus', clientId, offset: focusOffset }); + cursorNodes[anchorNode.oid] = cursorNodes[anchorNode.oid] || []; + cursorNodes[anchorNode.oid].push({ type: 'anchor', clientId, offset: anchorOffset }); + } + + for (const nodeOid of Object.keys(cursorNodes)) { + cursorNodes[nodeOid] = cursorNodes[nodeOid].sort((a, b) => { + return b.offset - a.offset || b.clientId.localeCompare(a.clientId); + }); + } + + for (const clientInfo of clientInfosList) { + clientInfo.editor.observerUnactive(); + for (const [nodeOid, cursorsData] of Object.entries(cursorNodes)) { + const node = clientInfo.editor.idFind(nodeOid); + for (const cursorData of cursorsData) { + const cursorString = + cursorData.type === 'anchor' + ? `[${cursorData.clientId}}` + : `{${cursorData.clientId}]`; + insertCharsAt(cursorString, node, cursorData.offset); + } + } + } + + if (spec.contentAfter) { + for (const clientInfo of clientInfosList) { + const value = clientInfo.editable.innerHTML; + window.chai + .expect(value) + .to.be.equal(spec.contentAfter, `error with client ${clientInfo.clientId}`); + } + } + if (spec.afterCursorInserted) { + spec.afterCursorInserted(clientInfos); + } + for (const clientInfo of clientInfosList) { + clientInfo.editor.destroy(); + clientInfo.iframe.remove(); + } +}; + +describe('Collaboration', () => { + describe('Conflict resolution', () => { + it('all client steps should be on the same order', () => { + testMultiEditor({ + clientIds: ['c1', 'c2', 'c3'], + contentBefore: 'a[c1}{c1]e[c2}{c2]i[c3}{c3]', + afterCreate: clientInfos => { + applyConcurentActions(clientInfos, { + c1: editor => { + editor.execCommand('insertText', 'b'); + editor.execCommand('insertText', 'c'); + editor.execCommand('insertText', 'd'); + }, + c2: editor => { + editor.execCommand('insertText', 'f'); + editor.execCommand('insertText', 'g'); + editor.execCommand('insertText', 'h'); + }, + c3: editor => { + editor.execCommand('insertText', 'j'); + editor.execCommand('insertText', 'k'); + editor.execCommand('insertText', 'l'); + }, + }); + mergeClientsSteps(clientInfos); + testSameHistory(clientInfos); + }, + contentAfter: 'abcd[c1}{c1]efgh[c2}{c2]ijkl[c3}{c3]', + }); + }); + it('should 2 client insertText in 2 different paragraph', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: '

ab[c1}{c1]

cd[c2}{c2]

', + afterCreate: clientInfos => { + applyConcurentActions(clientInfos, { + c1: editor => { + editor.execCommand('insertText', 'e'); + }, + c2: editor => { + editor.execCommand('insertText', 'f'); + }, + }); + mergeClientsSteps(clientInfos); + testSameHistory(clientInfos); + }, + contentAfter: '

abe[c1}{c1]

cdf[c2}{c2]

', + }); + }); + it('should 2 client insertText twice in 2 different paragraph', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: '

ab[c1}{c1]

cd[c2}{c2]

', + afterCreate: clientInfos => { + applyConcurentActions(clientInfos, { + c1: editor => { + editor.execCommand('insertText', 'e'); + editor.execCommand('insertText', 'f'); + }, + c2: editor => { + editor.execCommand('insertText', 'g'); + editor.execCommand('insertText', 'h'); + }, + }); + mergeClientsSteps(clientInfos); + testSameHistory(clientInfos); + }, + contentAfter: '

abef[c1}{c1]

cdgh[c2}{c2]

', + }); + }); + it('should insertText with client 1 and deleteBackward with client 2', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'ab[c1}{c1][c2}{c2]c', + afterCreate: clientInfos => { + applyConcurentActions(clientInfos, { + c1: editor => { + editor.execCommand('insertText', 'd'); + }, + c2: editor => { + editor.execCommand('oDeleteBackward'); + }, + }); + mergeClientsSteps(clientInfos); + testSameHistory(clientInfos); + }, + contentAfter: 'a[c2}{c2]c[c1}{c1]dc', + }); + }); + it('should insertText twice with client 1 and deleteBackward twice with client 2', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'ab[c1}{c1][c2}{c2]c', + afterCreate: clientInfos => { + applyConcurentActions(clientInfos, { + c1: editor => { + editor.execCommand('insertText', 'd'); + editor.execCommand('insertText', 'e'); + }, + c2: editor => { + editor.execCommand('oDeleteBackward'); + editor.execCommand('oDeleteBackward'); + }, + }); + mergeClientsSteps(clientInfos); + testSameHistory(clientInfos); + }, + contentAfter: '[c2}{c2]cd[c1}{c1]ec', + }); + }); + }); + it('should reset from snapshot', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a[c1}{c1]', + afterCreate: clientInfos => { + clientInfos.c1.editor.execCommand('insertText', 'b'); + clientInfos.c1.editor._historyMakeSnapshot(); + // Insure the snapshot is considered to be older than 30 seconds. + clientInfos.c1.editor._historySnapshots[0].time = 1; + const steps = clientInfos.c1.editor.historyGetSnapshotSteps(); + clientInfos.c2.editor.historyResetFromSteps(steps); + + chai.expect(clientInfos.c2.editor._historySteps.map(x => x.id)).to.deep.equal([ + 'fake_concurent_id_2', + ]); + chai.expect( + clientInfos.c2.editor._historySteps[0].mutations.map(x => x.id), + ).to.deep.equal(['fake_id_1', 'fake_concurent_id_1']); + }, + contentAfter: 'ab[c1}{c1]', + }); + }); + describe('steps whith no parent in history', () => { + it('should be able to retreive steps when disconnected from clients that has send step', () => { + testMultiEditor({ + clientIds: ['c1', 'c2', 'c3'], + contentBefore: 'a[c1}{c1]b[c2}{c2]c[c3}{c3]', + afterCreate: clientInfos => { + clientInfos.c1.editor.execCommand('insertText', 'd'); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + clientInfos.c2.editor.execCommand('insertText', 'e'); + clientInfos.c1.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[2], + ]); + clientInfos.c3.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[2], + ]); + // receive step 1 after step 2 + clientInfos.c3.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + testSameHistory(clientInfos); + }, + contentAfter: 'ad[c1}{c1]be[c2}{c2]c[c3}{c3]', + }); + }); + it('should receive steps where parent was not received', () => { + testMultiEditor({ + clientIds: ['c1', 'c2', 'c3'], + contentBefore: 'a[c1}{c1]b[c2}{c2]', + afterCreate: clientInfos => { + clientInfos.c1.editor.execCommand('insertText', 'c'); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + + // Client 3 connect firt to client 1 that made a snapshot. + + clientInfos.c1.editor._historyMakeSnapshot(); + // Fake the time of the snapshot so it is considered to be + // older than 30 seconds. + clientInfos.c1.editor._historySnapshots[0].time = 1; + const steps = clientInfos.c1.editor.historyGetSnapshotSteps(); + clientInfos.c3.editor.historyResetFromSteps(steps); + + // In the meantime client 2 send the step to client 1 + clientInfos.c2.editor.execCommand('insertText', 'd'); + clientInfos.c2.editor.execCommand('insertText', 'e'); + clientInfos.c1.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[2], + ]); + clientInfos.c1.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[3], + ]); + + // Now client 2 is connected to client 3 and client 2 make a new step. + clientInfos.c2.editor.execCommand('insertText', 'f'); + clientInfos.c1.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[4], + ]); + clientInfos.c3.editor.onExternalHistorySteps([ + clientInfos.c2.editor._historySteps[4], + ]); + }, + contentAfter: 'ac[c1}{c1]bdef[c2}{c2]', + }); + }); + }); + describe('sanitize', () => { + it('should sanitize when adding a node', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a', + afterCreate: clientInfos => { + const script = document.createElement('script'); + script.innerHTML = 'console.log("xss")'; + clientInfos.c1.editable.append(script); + clientInfos.c1.editor.historyStep(); + window.chai.expect(clientInfos.c1.editor._historySteps[1]).is.not.undefined; + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + window.chai + .expect(clientInfos.c2.editor.editable.innerHTML) + .to.equal('a'); + }, + }); + }); + it('should sanitize when adding a script as descendant', async () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a[c1}{c1][c2}{c2]', + afterCreate: clientInfos => { + const i = document.createElement('i'); + i.innerHTML = 'b'; + clientInfos.c1.editable.appendChild(i); + clientInfos.c1.editor.historyStep(); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + }, + afterCursorInserted: clientInfos => { + chai.expect(clientInfos.c2.editable.innerHTML).to.equal( + 'a[c1}{c1][c2}{c2]b', + ); + }, + }); + }); + it('should sanitize when changing an attribute', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a', + afterCreate: clientInfos => { + const img = clientInfos.c1.editable.childNodes[0].childNodes[1]; + img.setAttribute('class', 'b'); + img.setAttribute('onerror', 'console.log("xss")'); + clientInfos.c1.editor.historyStep(); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + window.chai + .expect(clientInfos.c1.editor.editable.innerHTML) + .to.equal('a'); + window.chai + .expect(clientInfos.c2.editor.editable.innerHTML) + .to.equal('a'); + }, + }); + }); + + it('should sanitize when undo is adding a script node', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a', + afterCreate: clientInfos => { + const script = document.createElement('script'); + script.innerHTML = 'console.log("xss")'; + clientInfos.c1.editable.append(script); + clientInfos.c1.editor.historyStep(); + script.remove(); + clientInfos.c1.editor.historyStep(); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + // Change the client in order to be undone from client 2 + clientInfos.c1.editor._historySteps[2].clientId = 'c2'; + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[2], + ]); + clientInfos.c2.editor.historyUndo(); + window.chai + .expect(clientInfos.c2.editor.editable.innerHTML) + .to.equal('a'); + }, + }); + }); + it('should sanitize when undo is adding a descendant script node', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a', + afterCreate: clientInfos => { + const div = document.createElement('div'); + div.innerHTML = 'b'; + clientInfos.c1.editable.append(div); + clientInfos.c1.editor.historyStep(); + div.remove(); + clientInfos.c1.editor.historyStep(); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + // Change the client in order to be undone from client 2 + clientInfos.c1.editor._historySteps[2].clientId = 'c2'; + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[2], + ]); + clientInfos.c2.editor.historyUndo(); + window.chai + .expect(clientInfos.c2.editor.editable.innerHTML) + .to.equal('a
b
'); + }, + }); + }); + it('should sanitize when undo is changing an attribute', () => { + testMultiEditor({ + clientIds: ['c1', 'c2'], + contentBefore: 'a', + afterCreate: clientInfos => { + const img = clientInfos.c1.editable.childNodes[0].childNodes[1]; + img.setAttribute('class', 'b'); + img.setAttribute('onerror', 'console.log("xss")'); + clientInfos.c1.editor.historyStep(); + img.setAttribute('class', ''); + img.setAttribute('onerror', ''); + clientInfos.c1.editor.historyStep(); + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[1], + ]); + // Change the client in order to be undone from client 2 + clientInfos.c1.editor._historySteps[2].clientId = 'c2'; + clientInfos.c2.editor.onExternalHistorySteps([ + clientInfos.c1.editor._historySteps[2], + ]); + clientInfos.c2.editor.historyUndo(); + window.chai + .expect(clientInfos.c2.editor.editable.innerHTML) + .to.equal('a'); + }, + }); + }); + }); +}); diff --git a/addons/web_editor/static/lib/odoo-editor/test/spec/utils.test.js b/addons/web_editor/static/lib/odoo-editor/test/spec/utils.test.js index 10251324fd8..370b90d5d24 100644 --- a/addons/web_editor/static/lib/odoo-editor/test/spec/utils.test.js +++ b/addons/web_editor/static/lib/odoo-editor/test/spec/utils.test.js @@ -23,7 +23,7 @@ import { previousLeaf, rightPos, startPos, - setCursor, + setSelection, setCursorStart, setCursorEnd, getCursorDirection, @@ -707,7 +707,7 @@ describe('Utils', () => { describe('collapsed', () => { it('should collapse the cursor at the beginning of an element', () => { const [p] = insertTestHtml('

abc

'); - const result = setCursor(p.firstChild, 0); + const result = setSelection(p.firstChild, 0); window.chai.expect(result).to.eql([p.firstChild, 0, p.firstChild, 0]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -717,7 +717,7 @@ describe('Utils', () => { }); it('should collapse the cursor within an element', () => { const [p] = insertTestHtml('

abcd

'); - const result = setCursor(p.firstChild, 2); + const result = setSelection(p.firstChild, 2); window.chai.expect(result).to.eql([p.firstChild, 2, p.firstChild, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -727,7 +727,7 @@ describe('Utils', () => { }); it('should collapse the cursor at the end of an element', () => { const [p] = insertTestHtml('

abc

'); - const result = setCursor(p.firstChild, 3); + const result = setSelection(p.firstChild, 3); window.chai.expect(result).to.eql([p.firstChild, 3, p.firstChild, 3]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -738,7 +738,7 @@ describe('Utils', () => { it('should collapse the cursor before a nested inline element', () => { const [p] = insertTestHtml('

abcdefghij

'); const cd = p.childNodes[1].firstChild; - const result = setCursor(cd, 2); + const result = setSelection(cd, 2); window.chai.expect(result).to.eql([cd, 2, cd, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -749,7 +749,7 @@ describe('Utils', () => { it('should collapse the cursor at the beginning of a nested inline element', () => { const [p] = insertTestHtml('

abcdefghij

'); const ef = p.childNodes[1].childNodes[1].firstChild; - const result = setCursor(ef, 0); + const result = setSelection(ef, 0); window.chai.expect(result).to.eql([ef, 0, ef, 0]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -760,7 +760,7 @@ describe('Utils', () => { it('should collapse the cursor within a nested inline element', () => { const [p] = insertTestHtml('

abcdefghijkl

'); const efgh = p.childNodes[1].childNodes[1].firstChild; - const result = setCursor(efgh, 2); + const result = setSelection(efgh, 2); window.chai.expect(result).to.eql([efgh, 2, efgh, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -771,7 +771,7 @@ describe('Utils', () => { it('should collapse the cursor at the end of a nested inline element', () => { const [p] = insertTestHtml('

abcdefghij

'); const ef = p.childNodes[1].childNodes[1].firstChild; - const result = setCursor(ef, 2); + const result = setSelection(ef, 2); window.chai.expect(result).to.eql([ef, 2, ef, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -783,7 +783,7 @@ describe('Utils', () => { const [p] = insertTestHtml('

abcdefghij

'); const ef = p.childNodes[1].childNodes[1].firstChild; const gh = p.childNodes[1].lastChild; - const result = setCursor(gh, 0); + const result = setSelection(gh, 0); window.chai.expect(result).to.eql([ef, 2, ef, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -791,7 +791,7 @@ describe('Utils', () => { .expect([anchorNode, anchorOffset, focusNode, focusOffset]) .to.eql([ef, 2, ef, 2]); - const nonNormalizedResult = setCursor(gh, 0, gh, 0, false); + const nonNormalizedResult = setSelection(gh, 0, gh, 0, false); window.chai.expect(nonNormalizedResult).to.eql([gh, 0, gh, 0]); const sel = document.getSelection(); window.chai @@ -802,7 +802,7 @@ describe('Utils', () => { describe('forward', () => { it('should select the contents of an element', () => { const [p] = insertTestHtml('

abc

'); - const result = setCursor(p.firstChild, 0, p.firstChild, 3); + const result = setSelection(p.firstChild, 0, p.firstChild, 3); window.chai.expect(result).to.eql([p.firstChild, 0, p.firstChild, 3]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -817,7 +817,7 @@ describe('Utils', () => { const ef = p1.childNodes[1].childNodes[1].firstChild; const qr = p2.childNodes[1].childNodes[2]; const st = p2.childNodes[2]; - const result = setCursor(ef, 1, st, 0); + const result = setSelection(ef, 1, st, 0); window.chai.expect(result).to.eql([ef, 1, qr, 2]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -825,7 +825,7 @@ describe('Utils', () => { .expect([anchorNode, anchorOffset, focusNode, focusOffset]) .to.eql([ef, 1, qr, 2]); - const nonNormalizedResult = setCursor(ef, 1, st, 0, false); + const nonNormalizedResult = setSelection(ef, 1, st, 0, false); window.chai.expect(nonNormalizedResult).to.eql([ef, 1, st, 0]); const sel = document.getSelection(); window.chai @@ -836,7 +836,7 @@ describe('Utils', () => { describe('backward', () => { it('should select the contents of an element', () => { const [p] = insertTestHtml('

abc

'); - const result = setCursor(p.firstChild, 3, p.firstChild, 0); + const result = setSelection(p.firstChild, 3, p.firstChild, 0); window.chai.expect(result).to.eql([p.firstChild, 3, p.firstChild, 0]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -851,7 +851,7 @@ describe('Utils', () => { const ef = p1.childNodes[1].childNodes[1].firstChild; const qr = p2.childNodes[1].childNodes[2]; const st = p2.childNodes[2]; - const result = setCursor(st, 0, ef, 1); + const result = setSelection(st, 0, ef, 1); window.chai.expect(result).to.eql([qr, 2, ef, 1]); const { anchorNode, anchorOffset, focusNode, focusOffset } = document.getSelection(); @@ -859,7 +859,7 @@ describe('Utils', () => { .expect([anchorNode, anchorOffset, focusNode, focusOffset]) .to.eql([qr, 2, ef, 1]); - const nonNormalizedResult = setCursor(st, 0, ef, 1, false); + const nonNormalizedResult = setSelection(st, 0, ef, 1, false); window.chai.expect(nonNormalizedResult).to.eql([st, 0, ef, 1]); const sel = document.getSelection(); window.chai @@ -1217,7 +1217,7 @@ describe('Utils', () => {

`, ); const abc = p.childNodes[1].firstChild.firstChild.firstChild.firstChild; - setCursor(p, 2, p, 0, false); + setSelection(p, 2, p, 0, false); const result = getDeepRange(p.parentElement, { select: true }); const { startContainer, startOffset, endContainer, endOffset } = result; window.chai @@ -1240,7 +1240,7 @@ describe('Utils', () => { const span1 = p1.childNodes[1]; const ef = span1.childNodes[1].firstChild; const st = p2.childNodes[2]; - setCursor(p2, 2, span1, 1, false); + setSelection(p2, 2, span1, 1, false); const result = getDeepRange(p1.parentElement, { select: true }); const { startContainer, startOffset, endContainer, endOffset } = result; window.chai diff --git a/addons/web_editor/static/lib/odoo-editor/test/utils.js b/addons/web_editor/static/lib/odoo-editor/test/utils.js index cbc43deada6..53eb7f6b495 100644 --- a/addons/web_editor/static/lib/odoo-editor/test/utils.js +++ b/addons/web_editor/static/lib/odoo-editor/test/utils.js @@ -32,7 +32,7 @@ function _toDomLocation(node, index) { return [container, offset]; } -function _parseTextualSelection(testContainer) { +export function parseTextualSelection(testContainer) { let anchorNode; let anchorOffset; let focusNode; @@ -93,13 +93,83 @@ function _parseTextualSelection(testContainer) { } } +export function parseMultipleTextualSelection(testContainer) { + let currentNode = testContainer; + + const clients = {}; + while (currentNode) { + if (currentNode.nodeType === Node.TEXT_NODE) { + // Look for special characters in the text content and remove them. + let match; + const regex = new RegExp(/(?:\[(\w+)\})|(?:\{(\w+)])/, 'gd'); + while ((match = regex.exec(currentNode.textContent))) { + regex.lastIndex = 0; + const indexes = match.indices[0]; + + if (match[0].includes('}')) { + const clientId = match[1]; + clients[clientId] = clients[clientId] || {}; + clients[clientId].anchorNode = currentNode; + clients[clientId].anchorOffset = indexes[0]; + if (clients[clientId].focusNode) { + clients[clientId].direction = Direction.FORWARD; + } + } else { + const clientId = match[2]; + clients[clientId] = clients[clientId] || {}; + clients[clientId].focusNode = currentNode; + clients[clientId].focusOffset = indexes[0]; + if (clients[clientId].anchorNode) { + clients[clientId].direction = Direction.BACKWARD; + } + } + currentNode.textContent = + currentNode.textContent.slice(0, indexes[0]) + + currentNode.textContent.slice(indexes[1]); + } + } + currentNode = _nextNode(currentNode); + } + + return clients; +} + +/** + * Insert in the DOM: + * - `SELECTION_ANCHOR_CHAR` in place for the selection start + * - `SELECTION_FOCUS_CHAR` in place for the selection end + * + * This is used in the function `testEditor`. + */ +export function renderMultipleTextualSelection() { + const selection = document.getSelection(); + if (selection.rangeCount === 0) { + return; + } + + const anchor = targetDeepest(selection.anchorNode, selection.anchorOffset); + const focus = targetDeepest(selection.focusNode, selection.focusOffset); + + // If the range characters have to be inserted within the same parent and + // the anchor range character has to be before the focus range character, + // the focus offset needs to be adapted to account for the first insertion. + const [anchorNode, anchorOffset] = anchor; + const [focusNode, baseFocusOffset] = focus; + let focusOffset = baseFocusOffset; + if (anchorNode === focusNode && anchorOffset <= focusOffset) { + focusOffset++; + } + insertCharsAt('[', ...anchor); + insertCharsAt(']', focusNode, focusOffset); +} + /** * Set a range in the DOM. * * @param selection */ -export function setSelection(selection) { - const domRange = document.createRange(); +export function setTestSelection(selection, doc = document) { + const domRange = doc.createRange(); if (selection.direction === Direction.FORWARD) { domRange.setStart(selection.anchorNode, selection.anchorOffset); domRange.collapse(true); @@ -118,24 +188,24 @@ export function setSelection(selection) { } /** - * Inserts the given character at the given offset of the given node. + * Inserts the given characters at the given offset of the given node. * - * @param {string} char + * @param {string} chars * @param {Node} node * @param {number} offset */ -function _insertCharAt(char, node, offset) { +export function insertCharsAt(chars, node, offset) { if (node.nodeType === Node.TEXT_NODE) { const startValue = node.nodeValue; if (offset < 0 || offset > startValue.length) { - throw new Error(`Invalid ${char} insertion in text node`); + throw new Error(`Invalid ${chars} insertion in text node`); } - node.nodeValue = startValue.slice(0, offset) + char + startValue.slice(offset); + node.nodeValue = startValue.slice(0, offset) + chars + startValue.slice(offset); } else { if (offset < 0 || offset > node.childNodes.length) { - throw new Error(`Invalid ${char} insertion in non-text node`); + throw new Error(`Invalid ${chars} insertion in non-text node`); } - const textNode = document.createTextNode(char); + const textNode = document.createTextNode(chars); if (offset < node.childNodes.length) { node.insertBefore(textNode, node.childNodes[offset]); } else { @@ -211,24 +281,24 @@ export function renderTextualSelection() { if (anchorNode === focusNode && anchorOffset <= focusOffset) { focusOffset++; } - _insertCharAt('[', ...anchor); - _insertCharAt(']', focusNode, focusOffset); + insertCharsAt('[', ...anchor); + insertCharsAt(']', focusNode, focusOffset); } export async function testEditor(Editor = OdooEditor, spec) { const testNode = document.createElement('div'); - document.body.appendChild(testNode); + document.querySelector('#editor-test-container').appendChild(testNode); // Add the content to edit and remove the "[]" markers *before* initializing // the editor as otherwise those would genererate mutations the editor would // consider and the tests would make no sense. testNode.innerHTML = spec.contentBefore; - const selection = _parseTextualSelection(testNode); + const selection = parseTextualSelection(testNode); const editor = new Editor(testNode, { toSanitize: false }); editor.keyboardType = 'PHYSICAL_KEYBOARD'; if (selection) { - setSelection(selection); + setTestSelection(selection); } else { document.getSelection().removeAllRanges(); } diff --git a/addons/web_editor/static/src/js/backend/field_html.js b/addons/web_editor/static/src/js/backend/field_html.js index 26cf6983af7..faa3819344c 100644 --- a/addons/web_editor/static/src/js/backend/field_html.js +++ b/addons/web_editor/static/src/js/backend/field_html.js @@ -185,6 +185,11 @@ var FieldHtml = basic_fields.DebouncedField.extend(TranslatableFieldMixin, { res_id: this.res_id, }, placeholder: this.attrs && this.attrs.placeholder, + collaborationChannel: { + collaborationModelName: this.model, + collaborationFieldName: this.name, + collaborationResId: parseInt(this.res_id), + }, noAttachment: this.nodeOptions['no-attachment'], inIframe: !!this.nodeOptions.cssEdit, iframeCssAssets: this.nodeOptions.cssEdit, diff --git a/addons/web_editor/static/src/js/wysiwyg/PeerToPeer.js b/addons/web_editor/static/src/js/wysiwyg/PeerToPeer.js new file mode 100644 index 00000000000..db03ca0f8bc --- /dev/null +++ b/addons/web_editor/static/src/js/wysiwyg/PeerToPeer.js @@ -0,0 +1,570 @@ +/** @odoo-module */ + +const urlParams = new URLSearchParams(window.location.search); +const collaborationDebug = urlParams.get('collaborationDebug'); +const COLLABORATION_LOCALSTORAGE_KEY = 'odoo_editor_collaboration_debug'; +if (typeof collaborationDebug === 'string') { + if (collaborationDebug === 'false') { + localStorage.removeItem( + COLLABORATION_LOCALSTORAGE_KEY, + urlParams.get('collaborationDebug'), + ); + } else { + localStorage.setItem(COLLABORATION_LOCALSTORAGE_KEY, urlParams.get('collaborationDebug')); + } +} +const debugValue = localStorage.getItem(COLLABORATION_LOCALSTORAGE_KEY); + +const debugShowLog = ['', 'true', 'all'].includes(debugValue); +const debugShowNotifications = debugValue === 'all'; + +const baseNotificationMethods = { + ptp_request: async function(notification) { + const { requestId, requestName, requestPayload, requestTransport } = + notification.notificationPayload; + this._onRequest( + notification.fromClientId, + requestId, + requestName, + requestPayload, + requestTransport, + ); + }, + ptp_request_result: function(notification) { + const { requestId, result } = notification.notificationPayload; + // If not in _pendingRequestResolver, it means it has timeout. + if (this._pendingRequestResolver[requestId]) { + clearTimeout(this._pendingRequestResolver[requestId].rejectTimeout); + this._pendingRequestResolver[requestId].resolve(result); + delete this._pendingRequestResolver[requestId]; + } + }, + + ptp_join: async function (notification) { + this._createClient(notification.fromClientId); + }, + + rtc_signal_icecandidate: async function (notification) { + if (debugShowLog) console.log(`%creceive candidate`, 'background: darkgreen; color: white;'); + const clientInfos = this.clientsInfos[notification.fromClientId]; + if ( + !clientInfos || + !clientInfos.peerConnection || + clientInfos.peerConnection.connectionState === 'closed' + ) { + console.groupCollapsed('=== ERROR: Handle Ice Candidate from undefined|closed ==='); + console.trace(clientInfos); + console.groupEnd(); + return; + } + if (!clientInfos.peerConnection.remoteDescription) { + clientInfos.iceCandidateBuffer.push(notification.notificationPayload); + } else { + this._addIceCandidate(clientInfos, notification.notificationPayload); + } + }, + rtc_signal_description: async function (notification) { + const description = notification.notificationPayload; + if (debugShowLog) + console.log( + `%cdescription received:`, + 'background: blueviolet; color: white;', + description, + ); + + const clientInfos = + this.clientsInfos[notification.fromClientId] || + this._createClient(notification.fromClientId); + const pc = clientInfos.peerConnection; + + if (!pc || pc.connectionState === 'closed') { + if (debugShowLog) { + console.groupCollapsed('=== ERROR: handle offer ==='); + console.log( + 'An offer has been received for a non-existent peer connection - client: ' + + notification.fromClientId, + ); + console.trace(pc.connectionState); + console.groupEnd(); + } + return; + } + + // Skip if we already have an offer. + if (pc.signalingState === 'have-remote-offer') { + return; + } + + // If there is a racing conditing with the signaling offer (two + // being sent at the same time). We need one client that abort by + // rollbacking to a stable signaling state where the other is + // continuing the process. The client that is polite is the one that + // will rollback. + const isPolite = + ('' + notification.fromClientId).localeCompare('' + this._currentClientId) === 1; + if (debugShowLog) + console.log( + `%cisPolite: %c${isPolite}`, + 'background: deepskyblue;', + `background:${isPolite ? 'green' : 'red'}`, + ); + + const isOfferRacing = + description.type === 'offer' && + (clientInfos.makingOffer || pc.signalingState !== 'stable'); + // If there is a racing conditing with the signaling offer and the + // client is impolite, we must not process this offer and wait for + // the answer for the signaling process to continue. + if (isOfferRacing && !isPolite) { + if (debugShowLog) + console.log( + `%creturn because isOfferRacing && !isPolite. pc.signalingState: ${pc.signalingState}`, + 'background: red;', + ); + return; + } + if (debugShowLog) console.log(`%cisOfferRacing: ${isOfferRacing}`, 'background: red;'); + + if (isOfferRacing) { + if (debugShowLog) + console.log(`%c SETREMOTEDESCRIPTION 1`, 'background: navy; color:white;'); + await Promise.all([ + pc.setLocalDescription({ type: 'rollback' }), + pc.setRemoteDescription(description), + ]); + } else { + if (debugShowLog) + console.log(`%c SETREMOTEDESCRIPTION 2`, 'background: navy; color:white;'); + await pc.setRemoteDescription(description); + } + if (clientInfos.iceCandidateBuffer.length) { + for (const candidate of clientInfos.iceCandidateBuffer) { + await this._addIceCandidate(clientInfos, candidate); + clientInfos.iceCandidateBuffer.splice(0); + } + } + if (description.type === 'offer') { + const answerDescription = await pc.createAnswer(); + await pc.setLocalDescription(answerDescription); + this.notifyClient( + notification.fromClientId, + 'rtc_signal_description', + pc.localDescription, + ); + } + }, +}; + +export class PeerToPeer { + constructor(options) { + this.options = options; + this._currentClientId = this.options.currentClientId; + if (debugShowLog) + console.log( + `%c currentClientId:${this._currentClientId}`, + 'background: blue; color: white;', + ); + + // clientId -> ClientInfos + this.clientsInfos = {}; + this._lastRequestId = -1; + this._pendingRequestResolver = {}; + } + + getConnectedClientIds() { + return Object.entries(this.clientsInfos) + .filter( + ([id, infos]) => + infos.peerConnection.iceConnectionState === 'connected' && + infos.dataChannel.readyState === 'open', + ) + .map(([id]) => id); + } + + removeClient(clientId) { + if (debugShowLog) console.log(`%c REMOVE CLIENT ${clientId}`, 'background: chocolate;'); + this.notifySelf('ptp_remove', clientId); + const clientInfos = this.clientsInfos[clientId]; + if (!clientInfos) return; + clearTimeout(clientInfos.fallbackTimeout); + clearTimeout(clientInfos.zombieTimeout); + clientInfos.dataChannel.close(); + clientInfos.peerConnection.close(); + delete this.clientsInfos[clientId]; + } + + async closeAllConnections() { + for (const clientId of Object.keys(this.clientsInfos)) { + this.notifyAllClients('ptp_disconnect'); + this.removeClient(clientId); + } + } + + async notifyAllClients(notificationName, notificationPayload, { transport = 'server' } = {}) { + const transportPayload = { + fromClientId: this._currentClientId, + notificationName, + notificationPayload, + }; + if (transport === 'server') { + await this.options.broadcastAll(transportPayload); + } else if (transport === 'rtc') { + for (const cliendId of Object.keys(this.clientsInfos)) { + this._channelNotify(cliendId, transportPayload); + } + } else { + throw new Error( + `Transport "${transport}" is not supported. Use "server" or "rtc" transport.`, + ); + } + } + + notifyClient(clientId, notificationName, notificationPayload, { transport = 'server' } = {}) { + if (debugShowNotifications) { + if (notificationName === 'ptp_request_result') { + console.log( + `%c${Date.now()} - REQUEST RESULT SEND: %c${transport}:${ + notificationPayload.requestId + }:${this._currentClientId.slice('-5')}:${clientId.slice('-5')}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } else if (notificationName === 'ptp_request') { + console.log( + `%c${Date.now()} - REQUEST SEND: %c${transport}:${ + notificationPayload.requestName + }|${notificationPayload.requestId}:${this._currentClientId.slice( + '-5', + )}:${clientId.slice('-5')}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } else { + console.log( + `%c${Date.now()} - NOTIFICATION SEND: %c${transport}:${notificationName}:${this._currentClientId.slice( + '-5', + )}:${clientId.slice('-5')}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } + } + const transportPayload = { + fromClientId: this._currentClientId, + toClientId: clientId, + notificationName, + notificationPayload, + }; + if (transport === 'server') { + this.options.broadcastAll(transportPayload); + } else if (transport === 'rtc') { + this._channelNotify(clientId, transportPayload); + } else { + throw new Error( + `Transport "${transport}" is not supported. Use "server" or "rtc" transport.`, + ); + } + } + + notifySelf(notificationName, notificationPayload) { + this.handleNotification({ notificationName, notificationPayload }); + } + + handleNotification(notification) { + const isInternalNotification = + typeof notification.fromClientId === 'undefined' && + typeof notification.toClientId === 'undefined'; + if ( + isInternalNotification || + (notification.fromClientId !== this._currentClientId && !notification.toClientId) || + notification.toClientId === this._currentClientId + ) { + if (debugShowNotifications) { + if (notification.notificationName === 'ptp_request_result') { + console.log( + `%c${Date.now()} - REQUEST RESULT RECEIVE: %c${ + notification.notificationPayload.requestId + }:${notification.fromClientId.slice('-5')}:${notification.toClientId.slice( + '-5', + )}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } else if (notification.notificationName === 'ptp_request') { + console.log( + `%c${Date.now()} - REQUEST RECEIVE: %c${ + notification.notificationPayload.requestName + }|${ + notification.notificationPayload.requestId + }:${notification.fromClientId.slice('-5')}:${notification.toClientId.slice( + '-5', + )}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } else { + console.log( + `%c${Date.now()} - NOTIFICATION RECEIVE: %c${ + notification.notificationName + }:${notification.fromClientId}:${notification.toClientId}`, + 'color: #aaa;font-weight:bold;', + 'color: #aaa;font-weight:normal', + ); + } + } + const baseMethod = baseNotificationMethods[notification.notificationName]; + if (baseMethod) { + baseMethod.call(this, notification); + } + if (this.options.onNotification) { + this.options.onNotification(notification); + } + } + } + + requestClient(clientId, requestName, requestPayload, { transport = 'server' } = {}) { + return new Promise((resolve, reject) => { + const requestId = this._getRequestId(); + + const rejectTimeout = setTimeout(() => { + reject('Request took too long (more than 10 seconds).'); + delete this._pendingRequestResolver[requestId]; + }, 10000); + + this._pendingRequestResolver[requestId] = { + resolve, + rejectTimeout, + }; + + this.notifyClient( + clientId, + 'ptp_request', + { + requestId, + requestName, + requestPayload, + requestTransport: transport, + }, + { transport }, + ); + }); + } + + _createClient(clientId, { makeOffer = true } = {}) { + if (debugShowLog) console.log('CREATE CONNECTION with client id:', clientId); + this.clientsInfos[clientId] = { + makingOffer: false, + iceCandidateBuffer: [], + }; + const pc = new RTCPeerConnection(this.options.peerConnectionConfig); + + if (makeOffer) { + pc.onnegotiationneeded = async () => { + if (debugShowLog) + console.log( + `%c NEGONATION NEEDED: ${pc.connectionState}`, + 'background: deeppink;', + ); + try { + this.clientsInfos[clientId].makingOffer = true; + if (debugShowLog) + console.log( + `%ccreating and sending an offer`, + 'background: darkmagenta; color: white;', + ); + const offer = await pc.createOffer(); + // Avoid race condition. + if (pc.signalingState !== 'stable') { + return; + } + await pc.setLocalDescription(offer); + this.notifyClient(clientId, 'rtc_signal_description', pc.localDescription); + } catch (err) { + console.error(err); + } finally { + this.clientsInfos[clientId].makingOffer = false; + } + }; + } + pc.onicecandidate = async event => { + if (event.candidate) { + this.notifyClient(clientId, 'rtc_signal_icecandidate', event.candidate); + } + }; + pc.oniceconnectionstatechange = async () => { + if (debugShowLog) console.log('ICE STATE UPDATE: ' + pc.iceConnectionState); + + switch (pc.iceConnectionState) { + case 'failed': + case 'closed': + this.removeClient(clientId); + break; + case 'disconnected': + await this._recoverConnection(clientId, { + delay: 1000, + reason: 'ice connection disconnected', + }); + break; + } + }; + // This event does not work in FF. Let's try with oniceconnectionstatechange if it is sufficient. + pc.onconnectionstatechange = async () => { + if (debugShowLog) console.log('CONNECTION STATE UPDATE:' + pc.connectionState); + + switch (pc.connectionState) { + case 'failed': + case 'closed': + this.removeClient(clientId); + break; + case 'disconnected': + await this._recoverConnection(clientId, { + delay: 500, + reason: 'connection disconnected', + }); + break; + } + }; + pc.onicecandidateerror = async error => { + if (debugShowLog) { + console.groupCollapsed('=== ERROR: onIceCandidate ==='); + console.log( + 'connectionState: ' + + pc.connectionState + + ' - iceState: ' + + pc.iceConnectionState, + ); + console.trace(error); + console.groupEnd(); + } + this._recoverConnection(clientId, { delay: 15000, reason: 'ice candidate error' }); + }; + const dataChannel = pc.createDataChannel('notifications', { negotiated: true, id: 1 }); + let message = []; + dataChannel.onmessage = event => { + if (event.data !== '-') { + message.push(event.data); + } else { + this.handleNotification(JSON.parse(message.join(''))); + message = []; + } + }; + dataChannel.onopen = event => { + this.notifySelf('rtc_data_channel_open', { + connectionClientId: clientId, + }); + }; + + this.clientsInfos[clientId].peerConnection = pc; + this.clientsInfos[clientId].dataChannel = dataChannel; + + return this.clientsInfos[clientId]; + } + async _addIceCandidate(clientInfos, candidate) { + const rtcIceCandidate = new RTCIceCandidate(candidate); + try { + await clientInfos.peerConnection.addIceCandidate(rtcIceCandidate); + } catch (error) { + // Ignored. + console.groupCollapsed('=== ERROR: ADD ICE CANDIDATE ==='); + console.trace(error); + console.groupEnd(); + } + } + + _channelNotify(clientId, transportPayload) { + const clientInfo = this.clientsInfos[clientId]; + const dataChannel = clientInfo && clientInfo.dataChannel; + + if (!dataChannel || dataChannel.readyState !== 'open') { + if (clientInfo && !clientInfo.zombieTimeout) { + if (debugShowLog) console.warn( + `Impossible to communicate with client ${clientId}. The connection be killed in 10 seconds if the datachannel state has not changed.`, + ); + this._killPotentialZombie(clientId); + } + } else { + const str = JSON.stringify(transportPayload); + const size = str.length; + const maxStringLength = 5000; + let from = 0; + let to = maxStringLength; + while (from < size) { + dataChannel.send(str.slice(from, to)); + from = to; + to = to += maxStringLength; + } + dataChannel.send('-'); + } + } + + _getRequestId() { + this._lastRequestId++; + return this._lastRequestId; + } + + async _onRequest(fromClientId, requestId, requestName, requestPayload, requestTransport) { + const requestFunction = this.options.onRequest && this.options.onRequest[requestName]; + const result = await requestFunction({ + fromClientId, + requestId, + requestName, + requestPayload, + }); + this.notifyClient( + fromClientId, + 'ptp_request_result', + { requestId, result }, + { transport: requestTransport }, + ); + } + /** + * Attempts a connection recovery by updating the tracks, which will start a new transaction: + * negotiationneeded -> offer -> answer -> ... + * + * @private + * @param {Object} [param1] + * @param {number} [param1.delay] in ms + * @param {string} [param1.reason] + */ + _recoverConnection(clientId, { delay = 0, reason = '' } = {}) { + const clientInfos = this.clientsInfos[clientId]; + if (!clientInfos || clientInfos.fallbackTimeout) return; + + clientInfos.fallbackTimeout = setTimeout(async () => { + clientInfos.fallbackTimeout = undefined; + const pc = clientInfos.peerConnection; + if (!pc || pc.iceConnectionState === 'connected') { + return; + } + if (['connected', 'closed'].includes(pc.connectionState)) { + return; + } + // hard reset: recreating a RTCPeerConnection + if (debugShowLog) + console.log( + `%c RTC RECOVERY: calling back client ${clientId} to salvage the connection ${pc.iceConnectionState}, reason: ${reason}`, + 'background: darkorange; color: white;', + ); + this.removeClient(clientId); + await this._createClient(clientId); + }, delay); + } + // todo: do we try to salvage the connection after killing the zombie ? + // Maybe the salvage should be done when the connection is dropped. + _killPotentialZombie(clientId) { + const clientInfos = this.clientsInfos[clientId]; + if (!clientInfos || clientInfos.zombieTimeout) { + return; + } + + // If there is no connection after 10 seconds, terminate. + clientInfos.zombieTimeout = setTimeout(() => { + if (clientInfos && clientInfos.dataChannel.readyState !== 'open') { + if (debugShowLog) console.log(`%c KILL ZOMBIE ${clientId}`, 'background: red;'); + this.removeClient(clientId); + } else { + if (debugShowLog) console.log(`%c NOT A ZOMBIE ${clientId}`, 'background: green;'); + } + }, 10000); + } +} diff --git a/addons/web_editor/static/src/js/wysiwyg/widgets/link_tools.js b/addons/web_editor/static/src/js/wysiwyg/widgets/link_tools.js index e3845b5b53e..a4fe7f70c0e 100644 --- a/addons/web_editor/static/src/js/wysiwyg/widgets/link_tools.js +++ b/addons/web_editor/static/src/js/wysiwyg/widgets/link_tools.js @@ -5,7 +5,7 @@ const Link = require('wysiwyg.widgets.Link'); const OdooEditorLib = require('@web_editor/../lib/odoo-editor/src/OdooEditor'); const dom = require('web.dom'); -const setCursor = OdooEditorLib.setCursor; +const setSelection = OdooEditorLib.setSelection; /** * Allows to customize link content and style. @@ -48,7 +48,7 @@ const LinkTools = Link.extend({ this.$button.removeClass('active'); this.options.wysiwyg.odooEditor.observerActive(); this.applyLinkToDom(this._getData()); - setCursor(this.$link[0], 0, this.$link[0], 1); + setSelection(this.$link[0], 0, this.$link[0], 1); this.options.wysiwyg.odooEditor.historyStep(); this._super(...arguments); }, diff --git a/addons/web_editor/static/src/js/wysiwyg/wysiwyg.js b/addons/web_editor/static/src/js/wysiwyg/wysiwyg.js index a020e9de78e..16c584049d1 100644 --- a/addons/web_editor/static/src/js/wysiwyg/wysiwyg.js +++ b/addons/web_editor/static/src/js/wysiwyg/wysiwyg.js @@ -15,6 +15,8 @@ const Toolbar = require('web_editor.toolbar'); const weWidgets = require('wysiwyg.widgets'); const wysiwygUtils = require('@web_editor/js/wysiwyg/wysiwyg_utils'); const weUtils = require('web_editor.utils'); +const { PeerToPeer } = require('@web_editor/js/wysiwyg/PeerToPeer'); +const { Mutex } = require('web.concurrency'); var _t = core._t; @@ -72,7 +74,14 @@ const Wysiwyg = Widget.extend({ this.toolbar = new Toolbar(this, this.options.toolbarTemplate); await this.toolbar.appendTo(document.createElement('void')); const commands = this._getCommands(); - this.odooEditor = new OdooEditor(this.$editable[0], { + + let editorCollaborationOptions; + + if (options.collaborationChannel) { + editorCollaborationOptions = this.setupCollaboration(options.collaborationChannel); + } + + this.odooEditor = new OdooEditor(this.$editable[0], Object.assign({ _t: _t, toolbar: this.toolbar.$el[0], document: this.options.document, @@ -96,7 +105,18 @@ const Wysiwyg = Widget.extend({ }, noScrollSelector: 'body, .note-editable, .o_content, #wrapwrap', commands: commands, - }); + }, editorCollaborationOptions)); + + const $wrapwrap = $('#wrapwrap'); + if ($wrapwrap.length) { + $wrapwrap[0].addEventListener('scroll', this.odooEditor.multiselectionRefresh, { passive: true }); + } + + if (this._peerToPeerLoading) { + // Now that the editor is loaded, wait for the peerToPeer to be + // ready to join. + this._peerToPeerLoading.then(() => this.ptp.notifyAllClients('ptp_join')); + } this._observeOdooFieldChanges(); this.$editable.on( @@ -193,6 +213,219 @@ const Wysiwyg = Widget.extend({ } }); }, + + setupCollaboration(collaborationChannel) { + const modelName = collaborationChannel.collaborationModelName; + const fieldName = collaborationChannel.collaborationFieldName; + const resId = collaborationChannel.collaborationResId; + + if (!(modelName && fieldName && resId)) { + return; + } + + const startCollaborationTime = new Date().getTime(); + + // No need for secure random number. + const currentClientId = Math.floor(Math.random() * Math.pow(2, 52)).toString(); + + this._collaborationChannelName = `editor_collaboration:${modelName}:${fieldName}:${resId}`; + + this.call('bus_service', 'onNotification', this, (notifications) => { + for (const [channel, busData] of notifications) { + if ( + channel[1] == 'editor_collaboration' && + channel[2] === modelName && + channel[3] === fieldName && + channel[4] === resId + ) { + this._peerToPeerLoading.then(() => this.ptp.handleNotification(busData)); + } + } + }); + this.call('bus_service', 'addChannel', this._collaborationChannelName); + this.call('bus_service', 'startPolling'); + + // Wether or not the history has been sent or received at least once. + let historySyncAtLeastOnce = false; + let historySyncFinished = false; + // const syncHistory = async (fromClientId) => { + // } + // Check wether clientA is before clientB. + const isClientFirst = (clientA, clientB) => { + if (clientA.startTime === clientB.startTime) { + return clientA.id.localCompare(clientB.id) === -1; + } else { + return clientA.startTime < clientB.startTime; + } + } + const rpcMutex = new Mutex(); + + this._peerToPeerLoading = new Promise(async (resolve) => { + let iceServers = await this._rpc({route: '/web_editor/get_ice_servers'}); + if (!iceServers.length) { + iceServers = [ + { + urls: [ + 'stun:stun1.l.google.com:19302', + 'stun:stun2.l.google.com:19302', + ], + } + ]; + } + + this.ptp = new PeerToPeer({ + peerConnectionConfig: { iceServers }, + currentClientId: currentClientId, + broadcastAll: (rpcData) => { + return rpcMutex.exec(async () => { + return this._rpc({ + route: '/web_editor/bus_broadcast', + params: { + model_name: modelName, + field_name: fieldName, + res_id: resId, + bus_data: rpcData, + }, + }); + }) + }, + onRequest: { + get_start_time: () => startCollaborationTime, + get_client_name: async () => { + if (!this._userName) { + this._userName = (await this._rpc({ + model: "res.users", + method: "search_read", + args: [ + [['id', '=', this.getSession().user_id]], + ['name'] + ], + }))[0].name; + } + return this._userName; + }, + get_missing_steps: (params) => this.odooEditor.historyGetMissingSteps(params.requestPayload), + get_history_from_snapshot: () => this.odooEditor.historyGetSnapshotSteps(), + get_collaborative_selection: () => this.odooEditor.getCurrentCollaborativeSelection(), + }, + onNotification: async ({ fromClientId, notificationName, notificationPayload }) => { + switch (notificationName) { + case 'ptp_remove': + this.odooEditor.multiselectionRemove(notificationPayload); + break; + case 'ptp_disconnect': + this.ptp.removeClient(fromClientId); + this.odooEditor.multiselectionRemove(fromClientId); + break; + case 'rtc_data_channel_open': + fromClientId = notificationPayload.connectionClientId; + const remoteStartTime = await this.ptp.requestClient(fromClientId, 'get_start_time', undefined, { transport: 'rtc' }); + this.ptp.clientsInfos[fromClientId].startTime = remoteStartTime; + this.ptp.requestClient(fromClientId, 'get_client_name', undefined, { transport: 'rtc' }).then((clientName) => { + this.ptp.clientsInfos[fromClientId].clientName = clientName; + }); + + if (!historySyncAtLeastOnce) { + historySyncAtLeastOnce = true; + await editorCollaborationOptions.onHistoryNeedSync(); + historySyncFinished = true; + } else { + const remoteSelection = await this.ptp.requestClient(fromClientId, 'get_collaborative_selection', undefined, { transport: 'rtc' }); + if (remoteSelection) { + this.odooEditor.onExternalMultiselectionUpdate(remoteSelection); + } + } + break; + case 'oe_history_step': + // Avoid race condition where the step is received + // before the history has synced at least once. + if (historySyncFinished) { + this.odooEditor.onExternalHistorySteps([notificationPayload]); + } + break; + case 'oe_history_set_selection': + const client = this.ptp.clientsInfos[fromClientId]; + if (!client) { + return; + } + const selection = notificationPayload; + selection.clientName = client.clientName; + this.odooEditor.onExternalMultiselectionUpdate(selection); + break; + } + } + }); + resolve(); + }); + + const editorCollaborationOptions = { + collaborationClientId: currentClientId, + onHistoryStep: (historyStep) => { + if (!this.ptp) return; + this.ptp.notifyAllClients('oe_history_step', historyStep, { transport: 'rtc' }); + }, + onCollaborativeSelectionChange: _.throttle((collaborativeSelection) => { + if (!this.ptp) return; + this.ptp.notifyAllClients('oe_history_set_selection', collaborativeSelection, { transport: 'rtc' }); + }, 50), + onHistoryMissingParentSteps: async ({ step, fromStepId }) => { + if (!this.ptp) return; + const missingSteps = await this.ptp.requestClient( + step.clientId, + 'get_missing_steps', { + fromStepId: fromStepId, + toStepId: step.id + }, + { transport: 'rtc' } + ); + if (missingSteps === -1 || !missingSteps.length) { + // This case should never happen. + console.warn('Editor get_missing_steps result is erroneous.'); + return; + } + this.ptp && this.odooEditor.onExternalHistorySteps(missingSteps.concat([step])); + }, + onHistoryNeedSync: async () => { + if (!this.ptp) return; + let firstClientId = currentClientId; + let firstClientStartTime = startCollaborationTime; + const connectedClientIds = this.ptp.getConnectedClientIds(); + for (const clientId of connectedClientIds) { + const clientInfo = this.ptp.clientsInfos[clientId]; + // Ensure we already retreived remote client starting time. + if (!clientInfo.startTime) { + continue; + } + + const isCurrentClientFirst = isClientFirst( + { + startTime: clientInfo.startTime, + id: clientId, + }, + { + startTime: firstClientStartTime, + id: firstClientId, + } + ); + + if (isCurrentClientFirst) { + firstClientStartTime = clientInfo.startTime; + firstClientId = clientId; + } + } + + if (firstClientId !== currentClientId) { + const historySteps = await this.ptp.requestClient(firstClientId, 'get_history_from_snapshot', undefined, { transport: 'rtc' }); + this.odooEditor.historyResetFromSteps(historySteps); + const remoteSelection = await this.ptp.requestClient(firstClientId, 'get_collaborative_selection', undefined, { transport: 'rtc' }); + if (remoteSelection) { + this.odooEditor.onExternalMultiselectionUpdate(remoteSelection); + } + } + }, + } + return editorCollaborationOptions; + }, /** * @override */ @@ -200,11 +433,22 @@ const Wysiwyg = Widget.extend({ if (this.odooEditor) { this.odooEditor.destroy(); } + // If peer to peer is initializing, wait for properly closing it. + if (this._peerToPeerLoading) { + this._peerToPeerLoading.then(()=> { + this.call('bus_service', 'deleteChannel', this._collaborationChannelName); + this.ptp.closeAllConnections(); + }); + } this.$editable && this.$editable.off('blur', this._onBlur); document.removeEventListener('mousedown', this._onDocumentMousedown, true); const $body = $(document.body); $body.off('mousemove', this.resizerMousemove); $body.off('mouseup', this.resizerMouseup); + const $wrapwrap = $('#wrapwrap'); + if ($wrapwrap.length) { + $('#wrapwrap')[0].removeEventListener('scroll', this.odooEditor.multiselectionRefresh, { passive: true }); + } this._super(); }, /** @@ -442,7 +686,7 @@ const Wysiwyg = Widget.extend({ * Set cursor to the editor latest position before blur or to the last editable node, ready to type. */ focus: function () { - if(!this.odooEditor.resetCursorOnLastHistoryCursor()) { + if(!this.odooEditor.historyResetLatestComputedSelection()) { // If the editor don't have an history step to focus to, // We place the cursor after the end of the editor exiting content. const range = document.createRange(); @@ -805,11 +1049,11 @@ const Wysiwyg = Widget.extend({ setTimeout(() => { const scrollableContainer = this.$el.scrollParent(); if (!options.snippets && scrollableContainer.length) { - this.odooEditor.addDomListener( - scrollableContainer[0], - 'scroll', - this.odooEditor.updateToolbarPosition.bind(this.odooEditor), - ); + // this.odooEditor.addDomListener( + // scrollableContainer[0], + // 'scroll', + // this.odooEditor.updateToolbarPosition.bind(this.odooEditor), + // ); } }, 0); }, diff --git a/addons/web_editor/static/src/scss/web_editor.backend.scss b/addons/web_editor/static/src/scss/web_editor.backend.scss index 8bd21d289a3..b49b8990053 100644 --- a/addons/web_editor/static/src/scss/web_editor.backend.scss +++ b/addons/web_editor/static/src/scss/web_editor.backend.scss @@ -1,6 +1,7 @@ .oe_form_field_html { position: relative; word-wrap: break-word; + overflow: hidden; .odoo-editor #codeview-btn-group { position: absolute; diff --git a/addons/website/static/src/js/menu/edit.js b/addons/website/static/src/js/menu/edit.js index afa602645ed..1de78e484de 100644 --- a/addons/website/static/src/js/menu/edit.js +++ b/addons/website/static/src/js/menu/edit.js @@ -358,13 +358,27 @@ var EditPageMenu = websiteNavbarData.WebsiteNavbarActionWidget.extend({ * @private */ _wysiwygInstance: function () { + // todo: retrieve other config if there is no #wrap element on the page (eg. product, blog, ect.) + let collaborationConfig = {}; + // todo: To uncomment when enabling the collaboration on website. + // const $wrap = $('#wrapwrap #wrap[data-oe-model][data-oe-field][data-oe-id]'); + // if ($wrap.length) { + // collaborationConfig = { + // collaborationChannel: { + // collaborationModelName: $wrap.attr('data-oe-model'), + // collaborationFieldName: $wrap.attr('data-oe-field'), + // collaborationResId: parseInt($wrap.attr('data-oe-id')), + // } + // }; + // } + var context; this.trigger_up('context_get', { callback: function (ctx) { context = ctx; }, }); - const params = { + const params = Object.assign({ snippets: 'website.snippets', recordInfo: { context: context, @@ -379,7 +393,7 @@ var EditPageMenu = websiteNavbarData.WebsiteNavbarActionWidget.extend({ isRootEditable: false, controlHistoryFromDocument: true, getContentEditableAreas: this._getContentEditableAreas.bind(this), - }; + }, collaborationConfig); return wysiwygLoader.createWysiwyg(this, Object.assign(params, this.wysiwygOptions), ['website.compiled_assets_wysiwyg']