Debian Codegraph @

addons/html_editor/static/src/main/media/media_dialog/media_dialog.js

raw
1 import { _t } from "@web/core/l10n/translation";
2 import { useService, useChildRef } from "@web/core/utils/hooks";
3 import { Dialog } from "@web/core/dialog/dialog";
4 import { Notebook } from "@web/core/notebook/notebook";
5 import { ImageSelector } from "./image_selector";
6 import { IconSelector } from "./icon_selector";
7
8 import { Component, useState, useRef, useEffect } from "@odoo/owl";
9 import { iconClasses } from "@html_editor/utils/dom_info";
10
11 export const TABS = {
12 IMAGES: {
13 id: "IMAGES",
14 title: _t("Images"),
15 Component: ImageSelector,
16 sequence: 10,
17 },
18 ICONS: {
19 id: "ICONS",
20 title: _t("Icons"),
21 Component: IconSelector,
22 sequence: 20,
23 },
24 };
25
26 const DEFAULT_SEQUENCE = 50;
27 const sequence = (tab) => tab.sequence ?? DEFAULT_SEQUENCE;
28
29 export class MediaDialog extends Component {
30 static template = "html_editor.MediaDialog";
31 static defaultProps = {
32 useMediaLibrary: true,
33 extraTabs: [],
34 };
35 static components = {
36 Dialog,
37 Notebook,
38 };
39 static props = {
40 extraTabs: { type: Array, optional: true, element: Object },
41 visibleTabs: { type: Array, optional: true, element: String },
42 activeTab: { type: String, optional: true },
43 "*": true,
44 };
45
46 setup() {
47 this.size = "xl";
48 this.contentClass = "o_select_media_dialog h-100";
49 this.title = _t("Select a media");
50 this.modalRef = useChildRef();
51
52 this.orm = useService("orm");
53 this.notificationService = useService("notification");
54
55 this.selectedMedia = useState({});
56
57 this.addButtonRef = useRef("add-button");
58
59 this.initialIconClasses = [];
60
61 this.notebookPages = [];
62 this.addTabs();
63 this.notebookPages.sort((a, b) => sequence(a) - sequence(b));
64 this.tabs = Object.fromEntries(this.notebookPages.map((tab) => [tab.id, tab]));
65
66 this.errorMessages = {};
67
68 this.state = useState({
69 activeTab: this.initialActiveTab,
70 isSaving: false,
71 });
72
73 useEffect(
74 (nbSelectedAttachments) => {
75 // Disable/enable the add button depending on whether some media
76 // are selected or not.
77 this.addButtonRef.el.toggleAttribute(
78 "disabled",
79 !nbSelectedAttachments || this.state.isSaving
80 );
81 },
82 () => [this.selectedMedia[this.state.activeTab].length, this.state.isSaving]
83 );
84 }
85
86 get initialActiveTab() {
87 if (this.props.activeTab) {
88 return this.props.activeTab;
89 }
90 if (this.props.media) {
91 const correspondingTab = Object.keys(this.tabs).find((id) =>
92 this.tabs[id].Component.tagNames.includes(this.props.media.tagName)
93 );
94 if (correspondingTab) {
95 return correspondingTab;
96 }
97 }
98 return this.notebookPages[0].id;
99 }
100
101 addTab(tab, additionalProps = {}) {
102 if (this.props.visibleTabs && !this.props.visibleTabs.includes(tab.id)) {
103 return;
104 }
105 this.selectedMedia[tab.id] = [];
106 this.notebookPages.push({
107 ...tab,
108 props: {
109 ...tab.props,
110 ...additionalProps,
111 id: tab.id,
112 resModel: this.props.resModel,
113 resId: this.props.resId,
114 media: this.props.media,
115 // multiImages: this.props.multiImages,
116 selectedMedia: this.selectedMedia,
117 selectMedia: (...args) =>
118 this.selectMedia(...args, tab.id, additionalProps.multiSelect),
119 save: this.save.bind(this),
120 onAttachmentChange: this.props.onAttachmentChange,
121 errorMessages: (errorMessage) => (this.errorMessages[tab.id] = errorMessage),
122 modalRef: this.modalRef,
123 },
124 });
125 }
126
127 addTabs() {
128 const onlyImages =
129 this.props.onlyImages ||
130 (this.props.media &&
131 this.props.media.parentElement &&
132 (this.props.media.parentElement.dataset.oeField === "image" ||
133 this.props.media.parentElement.dataset.oeType === "image"));
134
135 if (!this.props.noImages) {
136 this.addTab(TABS.IMAGES, {
137 useMediaLibrary: this.props.useMediaLibrary,
138 multiSelect: this.props.multiImages,
139 addFieldImage: this.props.addFieldImage,
140 });
141 }
142 if (onlyImages) {
143 return;
144 }
145 const addIcons = !this.props.visibleTabs || this.props.visibleTabs.includes(TABS.ICONS.id);
146 if (addIcons) {
147 const fonts = TABS.ICONS.Component.initFonts();
148 this.addTab(TABS.ICONS, {
149 fonts,
150 });
151
152 if (
153 this.props.media &&
154 TABS.ICONS.Component.tagNames.includes(this.props.media.tagName)
155 ) {
156 const classes = this.props.media.className.split(/\s+/);
157 const predefinedMediaFont = fonts.find((font) => classes.includes(font.base));
158 if (predefinedMediaFont) {
159 const selectedIcon = predefinedMediaFont.icons.find((icon) =>
160 icon.names.some((name) => classes.includes(name))
161 );
162 if (selectedIcon) {
163 this.initialIconClasses.push(...selectedIcon.names);
164 this.selectMedia(selectedIcon, TABS.ICONS.id);
165 }
166 } else {
167 const iconRegex = new RegExp(`\\b(?:${iconClasses.join("|")})(?:-\\S+)?\\b`);
168 const fallbackIconClasses = classes.filter((cls) => iconRegex.test(cls));
169 this.initialIconClasses.push(...fallbackIconClasses);
170 }
171 }
172 }
173 this.props.extraTabs.forEach((tab) => this.addTab(tab));
174 }
175
176 /**
177 * Render the selected media for insertion in the editor
178 *
179 * @param {Array<Object>} selectedMedia
180 * @returns {Array<HTMLElement>}
181 */
182 async renderMedia(selectedMedia) {
183 const elements = await this.tabs[this.state.activeTab].Component.createElements(
184 selectedMedia,
185 { orm: this.orm }
186 );
187 elements.forEach((element) => {
188 if (this.props.media) {
189 element.classList.add(...this.props.media.classList);
190 const style = this.props.media.getAttribute("style");
191 if (style) {
192 element.setAttribute("style", style);
193 }
194 if (this.state.activeTab === TABS.IMAGES.id) {
195 if (this.props.media.dataset.shape) {
196 element.dataset.shape = this.props.media.dataset.shape;
197 }
198 if (this.props.media.dataset.shapeColors) {
199 element.dataset.shapeColors = this.props.media.dataset.shapeColors;
200 }
201 if (this.props.media.dataset.shapeFlip) {
202 element.dataset.shapeFlip = this.props.media.dataset.shapeFlip;
203 }
204 if (this.props.media.dataset.shapeRotate) {
205 element.dataset.shapeRotate = this.props.media.dataset.shapeRotate;
206 }
207 if (this.props.media.dataset.hoverEffect) {
208 element.dataset.hoverEffect = this.props.media.dataset.hoverEffect;
209 }
210 if (this.props.media.dataset.hoverEffectColor) {
211 element.dataset.hoverEffectColor =
212 this.props.media.dataset.hoverEffectColor;
213 }
214 if (this.props.media.dataset.hoverEffectStrokeWidth) {
215 element.dataset.hoverEffectStrokeWidth =
216 this.props.media.dataset.hoverEffectStrokeWidth;
217 }
218 if (this.props.media.dataset.hoverEffectIntensity) {
219 element.dataset.hoverEffectIntensity =
220 this.props.media.dataset.hoverEffectIntensity;
221 }
222 }
223 }
224 for (const otherTab of Object.keys(this.tabs).filter(
225 (key) => key !== this.state.activeTab
226 )) {
227 for (const property of this.tabs[otherTab].Component.mediaSpecificStyles) {
228 element.style.removeProperty(property);
229 }
230 element.classList.remove(...this.tabs[otherTab].Component.mediaSpecificClasses);
231 const extraClassesToRemove = [];
232 for (const name of this.tabs[otherTab].Component.mediaExtraClasses) {
233 if (typeof name === "string") {
234 extraClassesToRemove.push(name);
235 } else {
236 // Regex
237 for (const className of element.classList) {
238 if (className.match(name)) {
239 extraClassesToRemove.push(className);
240 }
241 }
242 }
243 }
244 // Remove classes that do not also exist in the target type.
245 element.classList.remove(
246 ...extraClassesToRemove.filter((candidateName) => {
247 for (const name of this.tabs[this.state.activeTab].Component
248 .mediaExtraClasses) {
249 if (typeof name === "string") {
250 if (candidateName === name) {
251 return false;
252 }
253 } else {
254 // Regex
255 if (candidateName.match(name)) {
256 return false;
257 }
258 }
259 }
260 return true;
261 })
262 );
263 }
264 element.classList.remove(...this.initialIconClasses);
265 element.classList.remove("o_modified_image_to_save");
266 element.classList.remove("oe_edited_link");
267 element.classList.add(
268 ...this.tabs[this.state.activeTab].Component.mediaSpecificClasses
269 );
270 });
271 return elements;
272 }
273
274 selectMedia(media, tabId, multiSelect) {
275 if (media && !Object.keys(media).length) {
276 // Clear media selection when an empty object is passed
277 this.selectedMedia[tabId] = [];
278 return;
279 }
280 if (multiSelect) {
281 const isMediaSelected = this.selectedMedia[tabId]
282 .map(({ id }) => id)
283 .includes(media.id);
284 if (!isMediaSelected) {
285 this.selectedMedia[tabId].push(media);
286 } else {
287 this.selectedMedia[tabId] = this.selectedMedia[tabId].filter(
288 (m) => m.id !== media.id
289 );
290 }
291 } else {
292 this.selectedMedia[tabId] = [media];
293 }
294 }
295
296 async save() {
297 if (this.errorMessages[this.state.activeTab]) {
298 this.notificationService.add(this.errorMessages[this.state.activeTab], {
299 type: "danger",
300 });
301 return;
302 }
303 const selectedMedia = this.selectedMedia[this.state.activeTab];
304 // TODO In master: clean the save method so it performs the specific
305 // adaptation before saving from the active media selector and find a
306 // way to simply close the dialog if the media element remains the same.
307 const saveSelectedMedia =
308 selectedMedia.length &&
309 (this.state.activeTab !== TABS.ICONS.id ||
310 selectedMedia[0].initialIconChanged ||
311 !this.props.media);
312 this.state.isSaving = true;
313 if (saveSelectedMedia) {
314 const elements = await this.renderMedia(selectedMedia);
315 if (this.props.multiImages) {
316 await this.props.save(elements, selectedMedia, this.state.activeTab);
317 } else {
318 await this.props.save(elements[0], selectedMedia, this.state.activeTab);
319 }
320 }
321 this.props.close();
322 this.state.isSaving = false;
323 }
324
325 onTabChange(tab) {
326 this.state.activeTab = tab;
327 }
328 }