Debian Codegraph @

addons/html_editor/static/src/others/embedded_component_utils.js

raw
1 import {
2 onMounted,
3 onRendered,
4 onPatched,
5 onWillDestroy,
6 reactive,
7 toRaw,
8 useComponent,
9 useRef,
10 useState,
11 } from "@odoo/owl";
12
13 /**
14 * @typedef {HTMLElement} HostElement host element for an embedded component
15 * @typedef {Object} State state obtained from `useState` usage
16 * @typedef {Record<string, HTMLElement>} EditableDescendants
17 * @typedef {(state, previous, next) => void} PropertyUpdate function applying
18 * a state change which can be computed from `previous` and `next`
19 * to `state`.
20 * @typedef {Record<string, PropertyUpdate>} PropertyUpdater
21 *
22 * @typedef {Object} StateChangeManagerConfig
23 * @property {PropertyUpdater} [propertyUpdater] object mapping a key of the
24 * state to a function which will compute how values from a stateChange
25 * are applied to the current state. Defined in the embedding definition
26 * of a component.
27 * @property {function(HostElement):State} [getEmbeddedState]
28 * custom function to get the first embedded state (the one used during
29 * setup), in case not all embedded props should be part of the state, or
30 * if more properties should be added to it.
31 * @property {function(HostElement, State):Object} [stateToEmbeddedProps]
32 * custom function to compute the props, i.e. in case the entire state
33 * should not be converted to props.
34 *
35 * @typedef {Object} Embedding object provided to the instance which mounts
36 * Embedded components (EmbeddedComponentPlugin, HtmlViewer, ...)
37 * @property {String} name
38 * @property {Component} Component
39 * @property {function(HostElement):Object} getProps props for the given
40 * Component class instance.
41 * @property {function(HostElement):EditableDescendants} [getEditableDescendants]
42 * @see useEditableDescendants
43 * @property {function(StateChangeManagerConfig):StateChangeManager} [getStateChangeManager]
44 * @see useEmbeddedState
45 */
46
47 /**
48 * Get all element children with `data-embedded-editable` attribute which are
49 * descendants of the host's own embedded component and not part of another
50 * embedded component descendant (an embedded component can contain others).
51 * If multiple elements have the same `data-embedded-editable`, only the last
52 * one is considered.
53 * @param {HostElement} host
54 * @returns {EditableDescendants} editableDescendants
55 */
56 export function getEditableDescendants(host) {
57 const editableDescendants = {};
58 for (const candidate of host.querySelectorAll("[data-embedded-editable]")) {
59 if (candidate.closest("[data-embedded]") === host) {
60 editableDescendants[candidate.dataset.embeddedEditable] = candidate;
61 }
62 }
63 return editableDescendants;
64 }
65
66 /**
67 * Handle the rendering of editableDescendants:
68 * It is a node owned by the editor, which will be inserted under a ref of
69 * the same name as the attribute `data-embedded-editable` of that node, in the
70 * component's template. This allows to use editor features inside an embedded
71 * component. EditableDescendants are shared in collaboration and are saved
72 * between edition sessions.
73 *
74 * Warning: there must be a ref in the template for every editableDescendants,
75 * available at all times no matter the component state to guarantee that the
76 * editor can save their values at any given time, synchronously.
77 *
78 * @param {HostElement} host
79 * @returns {EditableDescendants} (HTMLElement) by the value of their
80 * `data-embedded-editable` attribute.
81 */
82 export function useEditableDescendants(host) {
83 const component = useComponent();
84 if (!component.env.getEditableDescendants) {
85 throw new Error(
86 "Missing `getEditableDescendants` function in the `embedding` provided to the `EmbeddedComponentPlugin`."
87 );
88 }
89 const editableDescendants = Object.freeze(component.env.getEditableDescendants(host));
90 const refs = {};
91 const renders = {};
92 for (const name of Object.keys(editableDescendants)) {
93 refs[name] = useRef(name);
94 renders[name] = () => refs[name].el.replaceChildren(editableDescendants[name]);
95 }
96 let _restoreSelection;
97 const restoreSelection = () => {
98 if (_restoreSelection) {
99 _restoreSelection();
100 _restoreSelection = undefined;
101 }
102 };
103 if (component.env.editorShared?.selection) {
104 onRendered(() => {
105 _restoreSelection = component.env.editorShared.selection.preserveSelection().restore;
106 });
107 }
108 onMounted(() => {
109 for (const render of Object.values(renders)) {
110 render();
111 }
112 restoreSelection();
113 });
114 onPatched(() => {
115 for (const [name, render] of Object.entries(renders)) {
116 // Handle partial patch
117 if (!host.contains(editableDescendants[name])) {
118 render();
119 }
120 }
121 restoreSelection();
122 });
123 return editableDescendants;
124 }
125
126 /**
127 * Create a ProxyHandler to manage a serializable "buffer" (Proxy target) for
128 * changes. The buffer must be a @see reactive which should update state
129 * with its callback (commit).
130 * @see useEmbeddedState
131 * The Proxy target and state must be serializable through JSON.stringify.
132 *
133 * @param {Object} state
134 * @param {Object} stateChangeManager
135 * @param {Object} stateChangeManager.previousEmbeddedState null, or a deep copy
136 * of the target used as a reference point for comparison
137 * (before <-> after) so that multiple synchronous changes can be handled
138 * at once.
139 * @returns {ProxyHandler}
140 */
141 function embeddedStateProxyHandler(state, stateChangeManager) {
142 return {
143 // Write operations are always done on the target ("buffer").
144 // During the first write operation before a commit, keep a deep copy of
145 // the target through serialization, which will be used as a reference
146 // point for a comparison (before <-> after).
147 set(target, key, value, receiver) {
148 if (
149 value !== Reflect.get(target, key, receiver) &&
150 !stateChangeManager.previousEmbeddedState
151 ) {
152 stateChangeManager.previousEmbeddedState = JSON.parse(
153 JSON.stringify(stateChangeManager.embeddedState)
154 );
155 }
156 return Reflect.set(target, key, value, receiver);
157 },
158 deleteProperty(target, key) {
159 if (Reflect.has(target, key) && !stateChangeManager.previousEmbeddedState) {
160 stateChangeManager.previousEmbeddedState = JSON.parse(
161 JSON.stringify(stateChangeManager.embeddedState)
162 );
163 }
164 return Reflect.deleteProperty(target, key);
165 },
166 // Read operations should also be done on state to register the
167 // rendering callback.
168 get(target, key, receiver) {
169 Reflect.get(state, key, state);
170 return Reflect.get(target, key, receiver);
171 },
172 ownKeys(target) {
173 Reflect.ownKeys(state);
174 return Reflect.ownKeys(target);
175 },
176 has(target, key) {
177 Reflect.has(state, key);
178 return Reflect.has(target, key);
179 },
180 };
181 }
182
183 function observeAllKeys(reactive) {
184 for (const key in reactive) {
185 const prop = reactive[key];
186 if (prop instanceof Object) {
187 observeAllKeys(prop);
188 }
189 }
190 }
191
192 /**
193 * Extract props serialized in `data-embedded-props` attribute.
194 *
195 * @param {HostElement} host
196 * @returns {Object} props
197 */
198 export function getEmbeddedProps(host) {
199 return host.dataset.embeddedProps ? JSON.parse(host.dataset.embeddedProps) : {};
200 }
201
202 function sortedCopy(obj) {
203 const result = {};
204 const propNames = Object.keys(obj).sort();
205 for (const propName of propNames) {
206 result[propName] = obj[propName];
207 }
208 return result;
209 }
210
211 /**
212 * Compute the difference between next and previous, and apply that difference
213 * to container[key]. Comparison is done through JSON.stringify, so all values
214 * must be serializable.
215 *
216 * @param {Object} container
217 * @param {string} key
218 * @param {Object} previous
219 * @param {Object} next
220 */
221 export function applyObjectPropertyDifference(container, key, previous, next) {
222 if (!container[key]) {
223 container[key] = {};
224 }
225 const obj1 = { ...(previous || {}) };
226 const obj2 = { ...(next || {}) };
227 const dest = container[key];
228 for (const key in obj2) {
229 if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
230 dest[key] = obj2[key];
231 }
232 delete obj1[key];
233 }
234 for (const key in obj1) {
235 delete dest[key];
236 }
237 if (!Object.keys(dest).length && !next) {
238 delete container[key];
239 }
240 }
241
242 /**
243 * Overwrite container[key] with value.
244 *
245 * @param {Object} container
246 * @param {string} key
247 * @param {Object} value
248 */
249 export function replaceProperty(container, key, value) {
250 if (value === undefined) {
251 delete container[key];
252 } else {
253 container[key] = value;
254 }
255 }
256
257 export class StateChangeManager {
258 /**
259 * @param {StateChangeManagerConfig} config
260 * @param {HostElement} config.host
261 * @param {Function} config.commitChanges notify the host that we can commit
262 * changes
263 */
264 constructor(config) {
265 this.config = config;
266 }
267 setup() {
268 const defaultState = sortedCopy(this.getEmbeddedState());
269 const defaultStateChange = {
270 stateChangeId: null,
271 previous: defaultState,
272 next: defaultState,
273 };
274 // Used in case `data-embedded-state` is removed (i.e. when reverting
275 // the first mutation setting that attribute)
276 this.defaultStateChange = defaultStateChange;
277 // Used to keep track of the last applied stateChange, to avoid
278 // applying it multiple times (i.e. revertMutations + stageRecords
279 // during undo)
280 this.previousStateChange = defaultStateChange;
281 // Used to discard batch changes when a component is destroyed,
282 // pending state changes should not be applied
283 this.batchId = 0;
284 this.setupUnmounted();
285 }
286
287 /**
288 * Called at setup and when an embedded component is destroyed. This resets
289 * state values related to the mounted component. State changes will be
290 * handled differently when unmounted.
291 */
292 setupUnmounted() {
293 this.previousEmbeddedState = null;
294 this.state = null;
295 this.embeddedState = null;
296 this.embeddedStateProxy = null;
297 this.isLiveComponent = false;
298 this.batchId += 1;
299 }
300
301 /**
302 * Construct the proxy object to use inside an embedded component. It can
303 * be read on to register for rendering updates in the component template,
304 * and written on to trigger a re-rendering, sharing changes in
305 * collaboration and registering them for the history.
306 * @param {Object} state
307 * @returns {Proxy} embeddedStateProxy
308 */
309 constructEmbeddedState(state) {
310 this.state = state;
311 this.embeddedState = reactive(
312 this.assignDeepProxyCopy({}, state),
313 this.batchedChangeState()
314 );
315 this.embeddedStateProxy = new Proxy(
316 this.embeddedState,
317 embeddedStateProxyHandler(state, this)
318 );
319 // First subscription to changes.
320 observeAllKeys(this.embeddedStateProxy);
321 this.isLiveComponent = true;
322 return this.embeddedStateProxy;
323 }
324
325 /**
326 * Depending on whether the component is destroyed or started mounting,
327 * return its effective state.
328 * @returns {Object} state
329 */
330 getState() {
331 let state = this.state;
332 if (!this.isLiveComponent) {
333 state = this.getEmbeddedState();
334 }
335 return state;
336 }
337
338 /**
339 * Called when `data-embedded-state` attribute is being changed. This
340 * will update the state, the embedded state, the embedded props and
341 * recompute a new expression when necessary.
342 * @param {string} attrState JSON representation of a stateChange
343 * @param { Object } options
344 * @param {boolean} options.reverse whether to read the stateChange from
345 * next to previous
346 * @param {boolean} options.forNewStep whether the attribute change is being
347 * used to create a new step.
348 * @returns {string} new JSON representation of a stateChange, in case
349 * it needs to be represented under another form to be shared
350 * in collaboration (a local peer doing revertMutations implies
351 * that collaborators will do applyMutations, so the stateChange
352 * must be expressed with another form for them).
353 */
354 onStateChanged(attrState, { reverse = false, forNewStep = false } = {}) {
355 const stateChange = attrState ? JSON.parse(attrState) : this.defaultStateChange;
356 const state = this.getState();
357 if (reverse) {
358 this.reverseStateChange(stateChange);
359 }
360 if (!this.areStateChangesEqual(this.previousStateChange, stateChange)) {
361 const previous = JSON.stringify(sortedCopy(state));
362 this.commitStateChange(state, stateChange.previous, stateChange.next);
363 const sortedState = sortedCopy(state);
364 this.config.host.dataset.embeddedProps = JSON.stringify(
365 this.stateToEmbeddedProps(this.config.host, sortedState)
366 );
367 if (this.isLiveComponent && !this.previousEmbeddedState) {
368 // Update the embeddedState only if there is no pending change.
369 // If there is a pending change, it will be updated when the
370 // pending change is applied in `changeState`.
371 this.assignDeepProxyCopy(toRaw(this.embeddedState), sortedState);
372 }
373 if (!forNewStep) {
374 this.previousStateChange = stateChange;
375 } else {
376 // If mutations are being applied to create a new step, the
377 // state change must be expressed under another form for
378 // collaborators, since the collaborator will always
379 // "applyMutations" and never "revertMutations" when receiving
380 // external steps.
381 const next = JSON.stringify(sortedState);
382 if (previous !== next) {
383 this.previousStateChange = {
384 stateChangeId: this.generateId(),
385 previous: JSON.parse(previous),
386 next: JSON.parse(next),
387 };
388 return JSON.stringify(this.previousStateChange);
389 }
390 }
391 }
392 }
393
394 /**
395 * Allow to write on the embeddedState multiple times synchronously
396 * and batch all changes at once afterwards. A batch is discarded as soon
397 * as the component is destroyed.
398 * @returns {Function} batched changeState
399 */
400 batchedChangeState() {
401 let scheduled = false;
402 const batchId = this.batchId;
403 return async () => {
404 if (this.isLiveComponent && !scheduled) {
405 scheduled = true;
406 await Promise.resolve();
407 scheduled = false;
408 if (batchId === this.batchId) {
409 this.changeState();
410 }
411 }
412 };
413 }
414
415 /**
416 * Apply a stateChange that was done on the embeddedState to the state,
417 * to trigger a re-rendering, and write the stateChange in
418 * `data-embedded-state` for the history and collaboration. Also
419 * recompute `data-embedded-props` for the next mounting operation.
420 */
421 changeState() {
422 if (!this.previousEmbeddedState) {
423 // If there is no previousEmbeddedState, it means that no
424 // effective change was performed, so there is nothing to commit.
425 return;
426 }
427 const previousEmbeddedState = this.previousEmbeddedState;
428 this.previousEmbeddedState = null;
429 const previous = JSON.stringify(sortedCopy(this.state));
430 this.commitStateChange(
431 this.state,
432 previousEmbeddedState,
433 JSON.parse(JSON.stringify(this.embeddedState))
434 );
435 const sortedState = sortedCopy(this.state);
436 const next = JSON.stringify(sortedState);
437 this.assignDeepProxyCopy(toRaw(this.embeddedState), sortedState);
438 if (previous !== next) {
439 this.previousStateChange = {
440 stateChangeId: this.generateId(),
441 previous: JSON.parse(previous),
442 next: JSON.parse(next),
443 };
444 this.config.host.dataset.embeddedState = JSON.stringify(this.previousStateChange);
445 this.config.host.dataset.embeddedProps = JSON.stringify(
446 this.stateToEmbeddedProps(this.config.host, sortedState)
447 );
448 this.config.commitStateChanges();
449 }
450 observeAllKeys(this.embeddedStateProxy);
451 }
452
453 areStateChangesEqual(sc1, sc2) {
454 return (
455 sc1.stateChangeId === sc2.stateChangeId &&
456 JSON.stringify(sc1.previous) === JSON.stringify(sc2.previous) &&
457 JSON.stringify(sc1.next) === JSON.stringify(sc2.next)
458 );
459 }
460
461 reverseStateChange(stateChange) {
462 const previous = stateChange.previous;
463 stateChange.previous = stateChange.next;
464 stateChange.next = previous;
465 }
466
467 /**
468 * Replace every key of target with deep proxy copies of source.
469 * This will make it so that any change at any level will pass by the
470 * embeddedStateProxyHandler traps.
471 * @param {Object} target
472 * @param {Object} source
473 * @returns {Object} copy with proxies as keys
474 */
475 assignDeepProxyCopy(target, source) {
476 for (const key of Object.keys(target)) {
477 delete target[key];
478 }
479 for (const key of Object.keys(source)) {
480 target[key] = this.deepProxyCopy(source[key]);
481 }
482 return target;
483 }
484
485 /**
486 * Create a deep proxy copy of value ensuring that any change at any level
487 * will pass by the embeddedStateProxyHandler traps.
488 * @param {Object} value
489 * @returns {Proxy} deep proxy copy of value
490 */
491 deepProxyCopy(value) {
492 if (value instanceof Object) {
493 const copy = value instanceof Array ? [] : {};
494 for (const prop in value) {
495 copy[prop] = this.deepProxyCopy(value[prop]);
496 }
497 return new Proxy(copy, embeddedStateProxyHandler(value, this));
498 }
499 return value;
500 }
501
502 generateId() {
503 return Math.floor(Math.random() * Math.pow(2, 52));
504 }
505
506 /**
507 * Apply a transaction to the active state. `previous` is the state
508 * before the transaction, and `next` is the state after the
509 * transaction was done. Keep in mind that the current state may have
510 * been changed after the transaction was done, but before it was
511 * applied. By default, will always accept nextState as
512 * the final state. `propertyUpdater` should be provided in the config
513 * to handle some keys differently, i.e. object composition.
514 * @see applyObjectPropertyDifference
515 * @param {Object} state current state
516 * @param {Object} previous state before the transaction
517 * @param {Object} next state after the transaction
518 */
519 commitStateChange(state, previous, next) {
520 const currentKeys = new Set([
521 ...Object.keys(state),
522 ...Object.keys(previous),
523 ...Object.keys(next),
524 ]);
525 for (const key of currentKeys) {
526 if (key in (this.config.propertyUpdater || {})) {
527 this.config.propertyUpdater[key](state, previous, next);
528 } else if (JSON.stringify(previous[key]) !== JSON.stringify(next[key])) {
529 replaceProperty(state, key, next[key]);
530 }
531 }
532 }
533
534 /**
535 * Extract values to be used as the first embedded state (used for setup)
536 * from the host.
537 * Extract all values from `data-embedded-props` by default.
538 * @returns {Object} state
539 */
540 getEmbeddedState() {
541 const host = this.config.host;
542 return this.config.getEmbeddedState?.(host) || getEmbeddedProps(host);
543 }
544
545 /**
546 * Convert a state to an object containing the props to be
547 * saved in `data-embedded-props`, which will be used for the next mount
548 * operation, and saved in the database. The returned object should be
549 * serializable using JSON.
550 * Return the entire state by default.
551 * @param {HostElement} host
552 * @param {Object} state
553 * @returns {Object} props
554 */
555 stateToEmbeddedProps(host, state) {
556 const props = this.config.stateToEmbeddedProps?.(host, state) || state;
557 // Clean undefined values to save space
558 for (const key of Object.keys(props)) {
559 if (props[key] === undefined) {
560 delete props[key];
561 }
562 }
563 return props;
564 }
565 }
566
567 /**
568 * Manage updates to `data-embedded-props` (To change props given to an
569 * embedded component when it will be mounted in the future), through history
570 * and collaborative operations.
571 * This is done through a special `embeddedState` which can be used externally
572 * as a normal state.
573 * That state can be modified through 2 channels:
574 * - By the component itself, as with any normal state.
575 * - By the embedded_component_plugin, during history or collaborative
576 * operations (undo/redo/resetStepsUntil/addExternalStep). The attribute
577 * `data-embedded-state` will be used to contain a serialized representation
578 * of a state change.
579 *
580 * While the embedded state evolves, the `data-embedded-props` attribute is
581 * always maintained to its relative value.
582 *
583 * `data-embedded-state` and `data-embedded-props` attributes are maintained
584 * even if the related component is in a destroyed state, in order to prepare
585 * the next mount operation if the host is re-inserted in the DOM through an
586 * history operation.
587 * If the component is currently mounted/being mounted, state changes are
588 * applied to the attribute and the embeddedState object.
589 *
590 * By default, a property change in the state is handled by replacing the
591 * previous value with the new one (overwrite). To change this behavior,
592 * provide a config extension in `getStateChangeManager` in the embedding
593 * definition, with a @see propertyUpdater mapping each state key to a change
594 * handler function.
595 *
596 * @param {HostElement} host
597 * @returns {Proxy} embeddedState state which can be used for rendering, and
598 * which is tied to the saved embedded props. Can only contain
599 * JSON serializable values.
600 */
601 export function useEmbeddedState(host) {
602 const component = useComponent();
603 if (!component.env.getStateChangeManager) {
604 throw new Error(
605 "Missing `getStateChangeManager` function in the `embedding` provided to the `EmbeddedComponentPlugin`."
606 );
607 }
608 const stateChangeManager = component.env.getStateChangeManager(host);
609 onWillDestroy(() => stateChangeManager.setupUnmounted());
610 const state = useState(stateChangeManager.getEmbeddedState());
611 return stateChangeManager.constructEmbeddedState(state);
612 }