Debian Codegraph @

addons/html_editor/static/src/others/embedded_components/backend/caption/caption.js

raw
1 import {
2 applyObjectPropertyDifference,
3 getEmbeddedProps,
4 StateChangeManager,
5 } from "@html_editor/others/embedded_component_utils";
6 import { Component, useState, useRef, onMounted, onWillDestroy } from "@odoo/owl";
7
8 export class EmbeddedCaptionComponent extends Component {
9 static template = "html_editor.EmbeddedCaption";
10
11 static props = {
12 image: { type: Element },
13 onUpdateCaption: { type: Function },
14 onEditorHistoryApply: { type: Function },
15 focusInput: { type: Boolean },
16 host: { type: Object },
17 };
18
19 setup() {
20 super.setup();
21 this.state = useState({
22 caption: "",
23 host: this.props.host,
24 });
25 this.captionInput = useRef("captionInput");
26 if (this.props.focusInput) {
27 onMounted(() => {
28 this.captionInput.el.focus();
29 });
30 }
31 // Ensure the state, the attribute and the placeholder are in sync.
32 this.updateCaption();
33 const observer = new MutationObserver((mutations) => {
34 for (const mutation of mutations) {
35 if (mutation.type === "attributes" && mutation.attributeName === "data-caption") {
36 this.updateCaption();
37 }
38 }
39 });
40 observer.observe(this.props.image, { attributes: true });
41 onWillDestroy(() => {
42 observer.disconnect();
43 });
44 }
45
46 updateCaption(caption = this.props.image.getAttribute("data-caption")) {
47 if (caption !== this.state.caption) {
48 this.state.caption = caption;
49 this.props.onUpdateCaption(caption);
50 }
51 }
52
53 onInputBlur() {
54 // This is triggered before the selection changes. Wait before updating
55 // so when the history step triggers a normalization, it restores that
56 // new selection and not the old one.
57 setTimeout(() => {
58 if (this.captionInput.el) {
59 this.updateCaption(this.captionInput.el.value || "");
60 }
61 });
62 }
63
64 onInputKeyup(ev) {
65 if (ev.key === "z" && ev.ctrlKey && !this._appliedNativeHistory) {
66 this.props.onEditorHistoryApply(ev.shiftKey);
67 }
68 this._appliedNativeHistory = false;
69 }
70
71 onInputBeforeInput(ev) {
72 this._appliedNativeHistory = false;
73 if (ev.inputType === "historyUndo" || ev.inputType === "historyRedo") {
74 // Input elements handle their own history, but this event is not
75 // triggered if no changes were made to the input. So we handle the
76 // editor history on keyup in those cases, but let the browser do
77 // its thing otherwise.
78 this._appliedNativeHistory = true;
79 }
80 }
81 }
82
83 export const captionEmbedding = {
84 name: "caption",
85 Component: EmbeddedCaptionComponent,
86 getProps: (host) => ({ host, ...getEmbeddedProps(host) }),
87 getStateChangeManager: (config) =>
88 new StateChangeManager(
89 Object.assign(config, {
90 propertyUpdater: {
91 caption: (state, previous, next) => {
92 applyObjectPropertyDifference(
93 state,
94 "caption",
95 previous.caption,
96 next.caption
97 );
98 },
99 },
100 })
101 ),
102 };