Debian Codegraph @

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

raw
1 import { nodeToTree } from "@html_editor/core/history_plugin";
2 import { Plugin } from "@html_editor/plugin";
3 import { withSequence } from "@html_editor/utils/resource";
4 import { memoize } from "@web/core/utils/functions";
5 import { renderToElement } from "@web/core/utils/render";
6
7 /**
8 * @typedef { Object } EmbeddedComponentShared
9 * @property { EmbeddedComponentPlugin['renderBlueprintToElement'] } renderBlueprintToElement
10 */
11
12 /**
13 * @typedef {((arg: { name, env, props }) => void)[]} mount_component_handlers
14 * @typedef {(() => void)[]} post_mount_component_handlers
15 */
16
17 /**
18 * This plugin is responsible with providing the API to manipulate/insert
19 * sub components in an editor.
20 */
21 export class EmbeddedComponentPlugin extends Plugin {
22 static id = "embeddedComponents";
23 static dependencies = ["history", "protectedNode", "selection"];
24 static shared = ["renderBlueprintToElement"];
25 /** @type {import("plugins").EditorResources} */
26 resources = {
27 /** Handlers */
28 normalize_handlers: withSequence(0, this.normalize.bind(this)),
29 clean_for_save_handlers: ({ root }) => this.cleanForSave(root),
30 attribute_change_handlers: this.onChangeAttribute.bind(this),
31 restore_savepoint_handlers: () => this.handleComponents(this.editable),
32 history_reset_handlers: () => this.handleComponents(this.editable),
33 history_reset_from_steps_handlers: () => this.handleComponents(this.editable),
34 step_added_handlers: ({ stepCommonAncestor }) => this.handleComponents(stepCommonAncestor),
35 external_step_added_handlers: () => this.handleComponents(this.editable),
36
37 serializable_descendants_processors: this.processDescendantsToSerialize.bind(this),
38 attribute_change_processors: this.onChangeAttribute.bind(this),
39 savable_mutation_record_predicates: this.isMutationRecordSavable.bind(this),
40 move_node_whitelist_selectors: "[data-embedded]",
41 };
42
43 setup() {
44 this.components = new Set();
45 // map from node to component info
46 this.nodeMap = new WeakMap();
47 this.app = this.config.embeddedComponentInfo.app;
48 this.env = this.config.embeddedComponentInfo.env ?? {};
49 this.hostToStateChangeManagerMap = new WeakMap();
50 this.hostToOnComponentInsertedMap = new WeakMap();
51 this.embeddedComponents = memoize((embeddedComponents = []) => {
52 const result = {};
53 for (const embedding of embeddedComponents) {
54 // TODO ABD: Any embedding with the same name as another will overwrite it.
55 // File currently relies on this system. Change it ?
56 result[embedding.name] = embedding;
57 }
58 return result;
59 });
60 // First mount is done during history_reset_handlers which happens
61 // when start_edition_handlers are called.
62 }
63
64 isMutationRecordSavable(record) {
65 const info = this.nodeMap.get(record.target);
66 if (
67 info &&
68 record.type === "attributes" &&
69 record.attributeName === "data-embedded-props"
70 ) {
71 // This attribute is determined independently for each user
72 // through `data-embedded-state` attribute mutations.
73 return false;
74 }
75 return true;
76 }
77
78 /**
79 * @typedef {import("@html_editor/core/history_plugin").Tree} Tree
80 *
81 * @param {Node} elem
82 * @param {Tree[]} serializableDescendants
83 * @returns {Tree[]}
84 */
85 processDescendantsToSerialize(elem, serializableDescendants) {
86 const embedding = this.getEmbedding(elem);
87 if (!embedding) {
88 return serializableDescendants;
89 }
90 return Object.values(embedding.getEditableDescendants?.(elem) || {}).map(nodeToTree);
91 }
92
93 handleComponents(elem) {
94 this.destroyRemovedComponents([...this.components]);
95 this.forEachEmbeddedComponentHost(elem, (host, embedding) => {
96 const info = this.nodeMap.get(host);
97 if (!info) {
98 this.mountComponent(host, embedding);
99 }
100 });
101 }
102
103 forEachEmbeddedComponentHost(elem, callback) {
104 const selector = `[data-embedded]`;
105 const targets = [...elem.querySelectorAll(selector)];
106 if (elem.matches(selector)) {
107 targets.unshift(elem);
108 }
109 for (const host of targets) {
110 const embedding = this.getEmbedding(host);
111 if (!embedding) {
112 continue;
113 }
114 callback(host, embedding);
115 }
116 }
117
118 getEmbedding(host) {
119 return this.embeddedComponents(this.getResource("embedded_components"))[
120 host.dataset.embedded
121 ];
122 }
123
124 /**
125 * Apply an embedded state change received from `data-embedded-state`
126 * attribute. In some cases (undo/redo/revertStepsUntil history operations),
127 * the attribute has to be set to a new value, computed by the
128 * stateChangeManager.
129 *
130 * @param {Object} attributeChange @see HistoryPlugin
131 * @param { Object } options
132 * @param { boolean } options.forNewStep whether the mutation is being used
133 * to create a new step
134 * @returns {string} new attribute value to set on the node, which might be
135 * unchanged
136 */
137 onChangeAttribute(attributeChange, { forNewStep = false } = {}) {
138 const attributeValue = attributeChange.value;
139 let newAttributeValue;
140 if (attributeChange.attributeName === "data-embedded-state") {
141 const attrState = attributeChange.reverse
142 ? attributeChange.oldValue
143 : attributeChange.value;
144 const stateChangeManager = this.getStateChangeManager(attributeChange.target);
145 if (stateChangeManager) {
146 // onStateChanged returns undefined if no change is needed for
147 // the attribute value
148 newAttributeValue = stateChangeManager.onStateChanged(attrState, {
149 reverse: attributeChange.reverse,
150 forNewStep,
151 });
152 }
153 }
154 return newAttributeValue || attributeValue;
155 }
156
157 getStateChangeManager(host) {
158 const embedding = this.getEmbedding(host);
159 if (!("getStateChangeManager" in embedding)) {
160 return null;
161 }
162 if (!this.hostToStateChangeManagerMap.has(host)) {
163 const config = {
164 host,
165 commitStateChanges: () => this.dependencies.history.addStep(),
166 };
167 const stateChangeManager = embedding.getStateChangeManager(config);
168 stateChangeManager.setup();
169 this.hostToStateChangeManagerMap.set(host, stateChangeManager);
170 }
171 return this.hostToStateChangeManagerMap.get(host);
172 }
173
174 mountComponent(
175 host,
176 { Component, getEditableDescendants, getProps, name, getStateChangeManager }
177 ) {
178 const props = getProps?.(host) || {};
179 const env = Object.create(this.env);
180 env.editorShared = {};
181 if (getStateChangeManager) {
182 env.getStateChangeManager = this.getStateChangeManager.bind(this);
183 }
184 if (getEditableDescendants) {
185 env.getEditableDescendants = getEditableDescendants;
186 // Enable the automatic selection restoration feature in @see useEditableDescendants
187 Object.assign(env.editorShared, {
188 selection: { ...this.dependencies.selection },
189 });
190 }
191 this.dispatchTo("mount_component_handlers", { name, env, props });
192 const root = this.app.createRoot(Component, {
193 props,
194 env,
195 });
196 root.mount(host);
197 // Patch mount fiber to hook into the exact call stack where root is
198 // mounted (but before). This will remove host children synchronously
199 // just before adding the root rendered html.
200 const fiber = root.node.fiber;
201 const fiberComplete = fiber.complete;
202 fiber.complete = () => {
203 host.replaceChildren();
204 fiberComplete.call(fiber);
205 this.dispatchTo("post_mount_component_handlers");
206 };
207 const onComponentInserted = this.extractOnComponentInserted(host);
208 if (onComponentInserted) {
209 // If a pending operation should be executed after the first mount
210 // of an inserted blueprint, add it as the last `onMounted` callback
211 root.node.mounted.push(onComponentInserted);
212 }
213 const info = {
214 root,
215 host,
216 };
217 this.components.add(info);
218 this.nodeMap.set(host, info);
219 }
220
221 destroyRemovedComponents(infos) {
222 // Avoid registering mutations if removed hosts are handled in
223 // the same microtask as when they were removed.
224 this.dependencies.history.ignoreDOMMutations(() => {
225 for (const info of infos) {
226 if (!this.editable.contains(info.host)) {
227 const host = info.host;
228 const display = host.style.display;
229 const parentNode = host.parentNode;
230 const clone = host.cloneNode(false);
231 if (parentNode) {
232 parentNode.replaceChild(clone, host);
233 }
234 host.style.display = "none";
235 this.editable.after(host);
236 this.destroyComponent(info);
237 if (parentNode) {
238 parentNode.replaceChild(host, clone);
239 } else {
240 host.remove();
241 }
242 host.style.display = display;
243 if (!host.getAttribute("style")) {
244 host.removeAttribute("style");
245 }
246 }
247 }
248 });
249 }
250
251 deepDestroyComponent({ host }) {
252 const removed = [];
253 this.forEachEmbeddedComponentHost(host, (containedHost) => {
254 const info = this.nodeMap.get(containedHost);
255 if (info) {
256 if (this.editable.contains(containedHost)) {
257 this.destroyComponent(info);
258 } else {
259 removed.push(info);
260 }
261 }
262 });
263 this.destroyRemovedComponents(removed);
264 }
265
266 /**
267 * Should not be called directly as it will not handle recursivity and
268 * removed components @see deepDestroyComponent
269 */
270 destroyComponent({ root, host }) {
271 const { getEditableDescendants } = this.getEmbedding(host);
272 const editableDescendants = getEditableDescendants?.(host) || {};
273 root.destroy();
274 this.components.delete(arguments[0]);
275 this.nodeMap.delete(host);
276 host.append(...Object.values(editableDescendants));
277 }
278
279 destroy() {
280 super.destroy();
281 for (const info of [...this.components]) {
282 if (this.components.has(info)) {
283 this.deepDestroyComponent(info);
284 }
285 }
286 }
287
288 /**
289 * @param {String} template blueprint for the embedded Component
290 * @param {Object} [context] rendering context
291 * @param {Function} [onComponentInserted] function to be executed when
292 * it is first mounted after it was inserted in the DOM. It will not
293 * be executed if the blueprint is removed from the DOM before the
294 * first mount nor if the component is mounted again afterwards.
295 * @returns {HTMLElement} host
296 */
297 renderBlueprintToElement(template, context = {}, onComponentInserted = undefined) {
298 const host = renderToElement(template, context);
299 if (onComponentInserted) {
300 this.hostToOnComponentInsertedMap.set(host, onComponentInserted);
301 }
302 return host;
303 }
304
305 extractOnComponentInserted(host) {
306 const onComponentInserted = this.hostToOnComponentInsertedMap.get(host);
307 this.hostToOnComponentInsertedMap.delete(host);
308 return onComponentInserted;
309 }
310
311 normalize(elem) {
312 this.forEachEmbeddedComponentHost(elem, (host, { getEditableDescendants }) => {
313 this.dependencies.protectedNode.setProtectingNode(host, true);
314 const editableDescendants = getEditableDescendants?.(host) || {};
315 for (const editableDescendant of Object.values(editableDescendants)) {
316 this.dependencies.protectedNode.setProtectingNode(editableDescendant, false);
317 }
318 });
319 }
320
321 cleanForSave(clone) {
322 this.forEachEmbeddedComponentHost(clone, (host, { getEditableDescendants }) => {
323 // In this case, host is a cloned element, there is no OWL root
324 // attached to it.
325 const editableDescendants = getEditableDescendants?.(host) || {};
326 host.replaceChildren();
327 for (const editableDescendant of Object.values(editableDescendants)) {
328 delete editableDescendant.dataset.oeProtected;
329 host.append(editableDescendant);
330 }
331 delete host.dataset.oeProtected;
332 delete host.dataset.embeddedState;
333 });
334 }
335 }