@intlayer/editor 9.5.12 → 9.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/ContentSelector.cjs +28 -11
- package/dist/cjs/components/ContentSelector.cjs.map +1 -1
- package/dist/cjs/components/ContentSelectorWrapper.cjs +31 -1
- package/dist/cjs/components/ContentSelectorWrapper.cjs.map +1 -1
- package/dist/cjs/components/isInteractiveClickTarget.cjs +66 -0
- package/dist/cjs/components/isInteractiveClickTarget.cjs.map +1 -0
- package/dist/cjs/core/EditorStateManager.cjs +16 -0
- package/dist/cjs/core/EditorStateManager.cjs.map +1 -1
- package/dist/cjs/core/IframeClickInterceptor.cjs +15 -7
- package/dist/cjs/core/IframeClickInterceptor.cjs.map +1 -1
- package/dist/cjs/core/getLocalEditorParentOrigin.cjs +33 -0
- package/dist/cjs/core/getLocalEditorParentOrigin.cjs.map +1 -0
- package/dist/cjs/core/initEditorClient.cjs +4 -1
- package/dist/cjs/core/initEditorClient.cjs.map +1 -1
- package/dist/cjs/core/selectionClick.cjs +25 -0
- package/dist/cjs/core/selectionClick.cjs.map +1 -0
- package/dist/cjs/messageKey.cjs +4 -0
- package/dist/cjs/messageKey.cjs.map +1 -1
- package/dist/esm/components/ContentSelector.mjs +28 -11
- package/dist/esm/components/ContentSelector.mjs.map +1 -1
- package/dist/esm/components/ContentSelectorWrapper.mjs +31 -1
- package/dist/esm/components/ContentSelectorWrapper.mjs.map +1 -1
- package/dist/esm/components/isInteractiveClickTarget.mjs +65 -0
- package/dist/esm/components/isInteractiveClickTarget.mjs.map +1 -0
- package/dist/esm/core/EditorStateManager.mjs +16 -0
- package/dist/esm/core/EditorStateManager.mjs.map +1 -1
- package/dist/esm/core/IframeClickInterceptor.mjs +15 -7
- package/dist/esm/core/IframeClickInterceptor.mjs.map +1 -1
- package/dist/esm/core/getLocalEditorParentOrigin.mjs +32 -0
- package/dist/esm/core/getLocalEditorParentOrigin.mjs.map +1 -0
- package/dist/esm/core/initEditorClient.mjs +4 -1
- package/dist/esm/core/initEditorClient.mjs.map +1 -1
- package/dist/esm/core/selectionClick.mjs +23 -0
- package/dist/esm/core/selectionClick.mjs.map +1 -0
- package/dist/esm/messageKey.mjs +4 -0
- package/dist/esm/messageKey.mjs.map +1 -1
- package/dist/types/components/ContentSelector.d.ts +9 -2
- package/dist/types/components/ContentSelector.d.ts.map +1 -1
- package/dist/types/components/ContentSelectorWrapper.d.ts.map +1 -1
- package/dist/types/components/isInteractiveClickTarget.d.ts +16 -0
- package/dist/types/components/isInteractiveClickTarget.d.ts.map +1 -0
- package/dist/types/core/EditorStateManager.d.ts +10 -0
- package/dist/types/core/EditorStateManager.d.ts.map +1 -1
- package/dist/types/core/IframeClickInterceptor.d.ts +8 -2
- package/dist/types/core/IframeClickInterceptor.d.ts.map +1 -1
- package/dist/types/core/getLocalEditorParentOrigin.d.ts +13 -0
- package/dist/types/core/getLocalEditorParentOrigin.d.ts.map +1 -0
- package/dist/types/core/initEditorClient.d.ts.map +1 -1
- package/dist/types/core/selectionClick.d.ts +17 -0
- package/dist/types/core/selectionClick.d.ts.map +1 -0
- package/dist/types/messageKey.d.ts +5 -1
- package/dist/types/messageKey.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_core_selectionClick = require('../core/selectionClick.cjs');
|
|
2
3
|
const require_components_ContentSelectorWrapper = require('./ContentSelectorWrapper.cjs');
|
|
4
|
+
const require_components_isInteractiveClickTarget = require('./isInteractiveClickTarget.cjs');
|
|
3
5
|
|
|
4
6
|
//#region src/components/ContentSelector.ts
|
|
5
7
|
const DEFAULT_PRESS_DURATION = 250;
|
|
@@ -29,9 +31,15 @@ const _HTMLElement = typeof HTMLElement !== "undefined" ? HTMLElement : class {}
|
|
|
29
31
|
* <intlayer-content-selector>
|
|
30
32
|
*
|
|
31
33
|
* A framework-agnostic web component that wraps content with Intlayer editor
|
|
32
|
-
* selection UI (hover outline,
|
|
34
|
+
* selection UI (hover outline, click to select, click-outside to deselect).
|
|
33
35
|
*
|
|
34
|
-
*
|
|
36
|
+
* Content is selected by:
|
|
37
|
+
* - a click, unless it lands on something the app handles (link, button,
|
|
38
|
+
* form control, clickable ancestor), which keeps its behavior
|
|
39
|
+
* - a long press, on any content
|
|
40
|
+
* - a ⌘ / Ctrl + click, on any content, cancelling the click's own action
|
|
41
|
+
*
|
|
42
|
+
* @fires intlayer:press - Fired when the content is selected. Bubbles.
|
|
35
43
|
* @fires intlayer:hover - Fired on mouseenter. Bubbles.
|
|
36
44
|
* @fires intlayer:unhover - Fired on mouseleave / mouseup. Bubbles.
|
|
37
45
|
* @fires intlayer:click-outside - Fired when a click occurs outside the element. Bubbles.
|
|
@@ -125,13 +133,15 @@ var IntlayerContentSelectorElement = class extends _HTMLElement {
|
|
|
125
133
|
composed: true
|
|
126
134
|
}));
|
|
127
135
|
}
|
|
136
|
+
_select() {
|
|
137
|
+
this._clearPressTimer();
|
|
138
|
+
this._isSelectingState = true;
|
|
139
|
+
this._updateActiveState();
|
|
140
|
+
this._dispatch("intlayer:press");
|
|
141
|
+
}
|
|
128
142
|
_handleMouseDown() {
|
|
129
143
|
this._clearPressTimer();
|
|
130
|
-
this._pressTimer = setTimeout(() =>
|
|
131
|
-
this._isSelectingState = true;
|
|
132
|
-
this._updateActiveState();
|
|
133
|
-
this._dispatch("intlayer:press");
|
|
134
|
-
}, this._pressDuration);
|
|
144
|
+
this._pressTimer = setTimeout(() => this._select(), this._pressDuration);
|
|
135
145
|
}
|
|
136
146
|
_handleMouseEnter() {
|
|
137
147
|
this._isHovered = true;
|
|
@@ -146,11 +156,18 @@ var IntlayerContentSelectorElement = class extends _HTMLElement {
|
|
|
146
156
|
this._clearPressTimer();
|
|
147
157
|
this._updateActiveState();
|
|
148
158
|
}
|
|
149
|
-
_handleClick(
|
|
150
|
-
if (
|
|
151
|
-
|
|
152
|
-
|
|
159
|
+
_handleClick(event) {
|
|
160
|
+
if (require_core_selectionClick.isSelectionClick(event)) return;
|
|
161
|
+
const isModifierClick = event.metaKey || event.ctrlKey;
|
|
162
|
+
if (this._isSelecting || this._isSelectingState || isModifierClick) {
|
|
163
|
+
event.preventDefault();
|
|
164
|
+
event.stopPropagation();
|
|
165
|
+
if (isModifierClick) this._select();
|
|
166
|
+
return;
|
|
153
167
|
}
|
|
168
|
+
if (require_components_isInteractiveClickTarget.isInteractiveClickTarget(event)) return;
|
|
169
|
+
require_core_selectionClick.markSelectionClick(event);
|
|
170
|
+
this._select();
|
|
154
171
|
}
|
|
155
172
|
_handleBlur() {
|
|
156
173
|
this._isSelectingState = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContentSelector.cjs","names":[],"sources":["../../../src/components/ContentSelector.ts"],"sourcesContent":["import { defineIntlayerContentSelectorWrapper } from './ContentSelectorWrapper';\n\nconst DEFAULT_PRESS_DURATION = 250;\n\nconst STYLES = `\n :host {\n display: contents;\n }\n\n .wrapper {\n display: inline-block;\n cursor: pointer;\n user-select: none;\n border-radius: 0.375rem;\n outline-width: 2px;\n outline-offset: 4px;\n outline-style: solid;\n outline-color: transparent;\n transition: all 100ms 50ms ease-in-out;\n }\n\n .wrapper[data-active] {\n outline-color: inherit;\n }\n`;\n\nconst _HTMLElement =\n typeof HTMLElement !== 'undefined'\n ? HTMLElement\n : (class {} as unknown as typeof HTMLElement);\n\n/**\n * <intlayer-content-selector>\n *\n * A framework-agnostic web component that wraps content with Intlayer editor\n * selection UI (hover outline, long-press to select, click-outside to deselect).\n *\n * @fires intlayer:press - Fired after a long press (pressDuration ms). Bubbles.\n * @fires intlayer:hover - Fired on mouseenter. Bubbles.\n * @fires intlayer:unhover - Fired on mouseleave / mouseup. Bubbles.\n * @fires intlayer:click-outside - Fired when a click occurs outside the element. Bubbles.\n *\n * @prop {boolean} isSelecting - Whether this element is currently selected (external state)\n * @prop {number} pressDuration - Long-press threshold in ms. Default: 250\n */\nexport class IntlayerContentSelectorElement extends _HTMLElement {\n private _isSelecting = false;\n private _pressDuration = DEFAULT_PRESS_DURATION;\n private _isHovered = false;\n private _isSelectingState = false;\n private _wrapper: HTMLSpanElement;\n private _pressTimer: ReturnType<typeof setTimeout> | null = null;\n private _clickOutsideHandler: ((e: MouseEvent) => void) | null = null;\n\n static get observedAttributes(): string[] {\n return ['is-selecting', 'press-duration'];\n }\n\n get isSelecting(): boolean {\n return this._isSelecting;\n }\n set isSelecting(v: boolean) {\n this._isSelecting = v;\n this._updateActiveState();\n }\n\n get pressDuration(): number {\n return this._pressDuration;\n }\n set pressDuration(v: number) {\n this._pressDuration = v;\n }\n\n constructor() {\n super();\n const shadow = this.attachShadow({ mode: 'open' });\n\n const style = document.createElement('style');\n style.textContent = STYLES;\n shadow.appendChild(style);\n\n const wrapper = document.createElement('span');\n wrapper.className = 'wrapper';\n wrapper.setAttribute('role', 'button');\n wrapper.setAttribute('tabindex', '0');\n wrapper.appendChild(document.createElement('slot'));\n shadow.appendChild(wrapper);\n this._wrapper = wrapper;\n\n wrapper.addEventListener('mousedown', () => this._handleMouseDown());\n wrapper.addEventListener('mouseup', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('mouseleave', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('mouseenter', () => this._handleMouseEnter());\n wrapper.addEventListener('click', (e) => this._handleClick(e));\n wrapper.addEventListener('touchstart', () => this._handleMouseDown());\n wrapper.addEventListener('touchend', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('touchcancel', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('blur', () => this._handleBlur());\n }\n\n attributeChangedCallback(\n name: string,\n _oldVal: string | null,\n newVal: string | null\n ): void {\n if (name === 'is-selecting') {\n this._isSelecting = newVal !== null;\n this._updateActiveState();\n } else if (name === 'press-duration') {\n this._pressDuration =\n newVal !== null ? parseInt(newVal, 10) : DEFAULT_PRESS_DURATION;\n }\n }\n\n connectedCallback(): void {\n this._clickOutsideHandler = (e: MouseEvent) => {\n // composedPath() pierces shadow boundaries\n if (!e.composedPath().includes(this)) {\n this._isSelectingState = false;\n this._dispatch('intlayer:click-outside');\n this._updateActiveState();\n }\n };\n document.addEventListener('mousedown', this._clickOutsideHandler);\n }\n\n disconnectedCallback(): void {\n if (this._clickOutsideHandler) {\n document.removeEventListener('mousedown', this._clickOutsideHandler);\n this._clickOutsideHandler = null;\n }\n this._clearPressTimer();\n }\n\n private _updateActiveState(): void {\n const isActive =\n this._isSelecting || this._isSelectingState || this._isHovered;\n if (isActive) {\n this._wrapper.setAttribute('data-active', '');\n } else {\n this._wrapper.removeAttribute('data-active');\n }\n }\n\n private _clearPressTimer(): void {\n if (this._pressTimer !== null) {\n clearTimeout(this._pressTimer);\n this._pressTimer = null;\n }\n }\n\n private _dispatch(eventName: string): void {\n this.dispatchEvent(\n new CustomEvent(eventName, { bubbles: true, composed: true })\n );\n }\n\n private _handleMouseDown(): void {\n this._clearPressTimer();\n this._pressTimer = setTimeout(() => {\n this._isSelectingState = true;\n this._updateActiveState();\n this._dispatch('intlayer:press');\n }, this._pressDuration);\n }\n\n private _handleMouseEnter(): void {\n this._isHovered = true;\n this._updateActiveState();\n this._dispatch('intlayer:hover');\n }\n\n private _handleMouseUpOrLeave(): void {\n if (this._isHovered) {\n this._isHovered = false;\n this._dispatch('intlayer:unhover');\n }\n this._clearPressTimer();\n this._updateActiveState();\n }\n\n private _handleClick(e: MouseEvent): void {\n if (this._isSelecting || this._isSelectingState) {\n e.preventDefault();\n e.stopPropagation();\n }\n }\n\n private _handleBlur(): void {\n this._isSelectingState = false;\n this._updateActiveState();\n }\n}\n\n/**\n * Register all Intlayer custom elements.\n * Call this once at application startup (inside IntlayerEditorProvider or similar).\n * Safe to call multiple times — only registers elements that are not yet defined.\n */\nexport const defineIntlayerElements = (): void => {\n if (typeof customElements === 'undefined') return;\n if (!customElements.get('intlayer-content-selector')) {\n customElements.define(\n 'intlayer-content-selector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Ac,iBAAiB;GAClC,KAAK,oBAAoB;GACzB,KAAK,mBAAmB;GACxB,KAAK,UAAU,gBAAgB;EACjC,GAAG,KAAK,cAAc;CACxB;CAEA,AAAQ,oBAA0B;EAChC,KAAK,aAAa;EAClB,KAAK,mBAAmB;EACxB,KAAK,UAAU,gBAAgB;CACjC;CAEA,AAAQ,wBAA8B;EACpC,IAAI,KAAK,YAAY;GACnB,KAAK,aAAa;GAClB,KAAK,UAAU,kBAAkB;EACnC;EACA,KAAK,iBAAiB;EACtB,KAAK,mBAAmB;CAC1B;CAEA,AAAQ,aAAa,GAAqB;EACxC,IAAI,KAAK,gBAAgB,KAAK,mBAAmB;GAC/C,EAAE,eAAe;GACjB,EAAE,gBAAgB;EACpB;CACF;CAEA,AAAQ,cAAoB;EAC1B,KAAK,oBAAoB;EACzB,KAAK,mBAAmB;CAC1B;AACF;;;;;;AAOA,MAAa,+BAAqC;CAChD,IAAI,OAAO,mBAAmB,aAAa;CAC3C,IAAI,CAAC,eAAe,IAAI,2BAA2B,GACjD,eAAe,OACb,6BACA,8BACF;CAEF,+EAAqC;AACvC"}
|
|
1
|
+
{"version":3,"file":"ContentSelector.cjs","names":["isSelectionClick","isInteractiveClickTarget"],"sources":["../../../src/components/ContentSelector.ts"],"sourcesContent":["import { isSelectionClick, markSelectionClick } from '../core/selectionClick';\nimport { defineIntlayerContentSelectorWrapper } from './ContentSelectorWrapper';\nimport { isInteractiveClickTarget } from './isInteractiveClickTarget';\n\nconst DEFAULT_PRESS_DURATION = 250;\n\nconst STYLES = `\n :host {\n display: contents;\n }\n\n .wrapper {\n display: inline-block;\n cursor: pointer;\n user-select: none;\n border-radius: 0.375rem;\n outline-width: 2px;\n outline-offset: 4px;\n outline-style: solid;\n outline-color: transparent;\n transition: all 100ms 50ms ease-in-out;\n }\n\n .wrapper[data-active] {\n outline-color: inherit;\n }\n`;\n\nconst _HTMLElement =\n typeof HTMLElement !== 'undefined'\n ? HTMLElement\n : (class {} as unknown as typeof HTMLElement);\n\n/**\n * <intlayer-content-selector>\n *\n * A framework-agnostic web component that wraps content with Intlayer editor\n * selection UI (hover outline, click to select, click-outside to deselect).\n *\n * Content is selected by:\n * - a click, unless it lands on something the app handles (link, button,\n * form control, clickable ancestor), which keeps its behavior\n * - a long press, on any content\n * - a ⌘ / Ctrl + click, on any content, cancelling the click's own action\n *\n * @fires intlayer:press - Fired when the content is selected. Bubbles.\n * @fires intlayer:hover - Fired on mouseenter. Bubbles.\n * @fires intlayer:unhover - Fired on mouseleave / mouseup. Bubbles.\n * @fires intlayer:click-outside - Fired when a click occurs outside the element. Bubbles.\n *\n * @prop {boolean} isSelecting - Whether this element is currently selected (external state)\n * @prop {number} pressDuration - Long-press threshold in ms. Default: 250\n */\nexport class IntlayerContentSelectorElement extends _HTMLElement {\n private _isSelecting = false;\n private _pressDuration = DEFAULT_PRESS_DURATION;\n private _isHovered = false;\n private _isSelectingState = false;\n private _wrapper: HTMLSpanElement;\n private _pressTimer: ReturnType<typeof setTimeout> | null = null;\n private _clickOutsideHandler: ((e: MouseEvent) => void) | null = null;\n\n static get observedAttributes(): string[] {\n return ['is-selecting', 'press-duration'];\n }\n\n get isSelecting(): boolean {\n return this._isSelecting;\n }\n set isSelecting(v: boolean) {\n this._isSelecting = v;\n this._updateActiveState();\n }\n\n get pressDuration(): number {\n return this._pressDuration;\n }\n set pressDuration(v: number) {\n this._pressDuration = v;\n }\n\n constructor() {\n super();\n const shadow = this.attachShadow({ mode: 'open' });\n\n const style = document.createElement('style');\n style.textContent = STYLES;\n shadow.appendChild(style);\n\n const wrapper = document.createElement('span');\n wrapper.className = 'wrapper';\n wrapper.setAttribute('role', 'button');\n wrapper.setAttribute('tabindex', '0');\n wrapper.appendChild(document.createElement('slot'));\n shadow.appendChild(wrapper);\n this._wrapper = wrapper;\n\n wrapper.addEventListener('mousedown', () => this._handleMouseDown());\n wrapper.addEventListener('mouseup', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('mouseleave', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('mouseenter', () => this._handleMouseEnter());\n wrapper.addEventListener('click', (e) => this._handleClick(e));\n wrapper.addEventListener('touchstart', () => this._handleMouseDown());\n wrapper.addEventListener('touchend', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('touchcancel', () => this._handleMouseUpOrLeave());\n wrapper.addEventListener('blur', () => this._handleBlur());\n }\n\n attributeChangedCallback(\n name: string,\n _oldVal: string | null,\n newVal: string | null\n ): void {\n if (name === 'is-selecting') {\n this._isSelecting = newVal !== null;\n this._updateActiveState();\n } else if (name === 'press-duration') {\n this._pressDuration =\n newVal !== null ? parseInt(newVal, 10) : DEFAULT_PRESS_DURATION;\n }\n }\n\n connectedCallback(): void {\n this._clickOutsideHandler = (e: MouseEvent) => {\n // composedPath() pierces shadow boundaries\n if (!e.composedPath().includes(this)) {\n this._isSelectingState = false;\n this._dispatch('intlayer:click-outside');\n this._updateActiveState();\n }\n };\n document.addEventListener('mousedown', this._clickOutsideHandler);\n }\n\n disconnectedCallback(): void {\n if (this._clickOutsideHandler) {\n document.removeEventListener('mousedown', this._clickOutsideHandler);\n this._clickOutsideHandler = null;\n }\n this._clearPressTimer();\n }\n\n private _updateActiveState(): void {\n const isActive =\n this._isSelecting || this._isSelectingState || this._isHovered;\n if (isActive) {\n this._wrapper.setAttribute('data-active', '');\n } else {\n this._wrapper.removeAttribute('data-active');\n }\n }\n\n private _clearPressTimer(): void {\n if (this._pressTimer !== null) {\n clearTimeout(this._pressTimer);\n this._pressTimer = null;\n }\n }\n\n private _dispatch(eventName: string): void {\n this.dispatchEvent(\n new CustomEvent(eventName, { bubbles: true, composed: true })\n );\n }\n\n private _select(): void {\n this._clearPressTimer();\n this._isSelectingState = true;\n this._updateActiveState();\n this._dispatch('intlayer:press');\n }\n\n private _handleMouseDown(): void {\n this._clearPressTimer();\n this._pressTimer = setTimeout(() => this._select(), this._pressDuration);\n }\n\n private _handleMouseEnter(): void {\n this._isHovered = true;\n this._updateActiveState();\n this._dispatch('intlayer:hover');\n }\n\n private _handleMouseUpOrLeave(): void {\n if (this._isHovered) {\n this._isHovered = false;\n this._dispatch('intlayer:unhover');\n }\n this._clearPressTimer();\n this._updateActiveState();\n }\n\n private _handleClick(event: MouseEvent): void {\n // A nested selector already selected its own content\n if (isSelectionClick(event)) return;\n\n const isModifierClick = event.metaKey || event.ctrlKey;\n\n // Selected content (by a long press, or from the editor) and modifier\n // clicks never reach the app, so a link or button doesn't fire\n if (this._isSelecting || this._isSelectingState || isModifierClick) {\n event.preventDefault();\n event.stopPropagation();\n\n if (isModifierClick) this._select();\n return;\n }\n\n if (isInteractiveClickTarget(event)) return;\n\n // Left to propagate: the app's own handlers still run\n markSelectionClick(event);\n this._select();\n }\n\n private _handleBlur(): void {\n this._isSelectingState = false;\n this._updateActiveState();\n }\n}\n\n/**\n * Register all Intlayer custom elements.\n * Call this once at application startup (inside IntlayerEditorProvider or similar).\n * Safe to call multiple times — only registers elements that are not yet defined.\n */\nexport const defineIntlayerElements = (): void => {\n if (typeof customElements === 'undefined') return;\n if (!customElements.get('intlayer-content-selector')) {\n customElements.define(\n 'intlayer-content-selector',\n IntlayerContentSelectorElement\n );\n }\n defineIntlayerContentSelectorWrapper();\n};\n"],"mappings":";;;;;;AAIA,MAAM,yBAAyB;AAE/B,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;AAsBf,MAAM,eACJ,OAAO,gBAAgB,cACnB,cACC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;AAsBd,IAAa,iCAAb,cAAoD,aAAa;CAC/D,AAAQ,eAAe;CACvB,AAAQ,iBAAiB;CACzB,AAAQ,aAAa;CACrB,AAAQ,oBAAoB;CAC5B,AAAQ;CACR,AAAQ,cAAoD;CAC5D,AAAQ,uBAAyD;CAEjE,WAAW,qBAA+B;EACxC,OAAO,CAAC,gBAAgB,gBAAgB;CAC1C;CAEA,IAAI,cAAuB;EACzB,OAAO,KAAK;CACd;CACA,IAAI,YAAY,GAAY;EAC1B,KAAK,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AAgB,KAAK,qBAAqB,iBAAiB;GAClE,MAAM,eAAe;GACrB,MAAM,gBAAgB;GAEtB,IAAI,iBAAiB,KAAK,QAAQ;GAClC;EACF;EAEA,IAAIC,qEAAyB,KAAK,GAAG;EAGrC,+CAAmB,KAAK;EACxB,KAAK,QAAQ;CACf;CAEA,AAAQ,cAAoB;EAC1B,KAAK,oBAAoB;EACzB,KAAK,mBAAmB;CAC1B;AACF;;;;;;AAOA,MAAa,+BAAqC;CAChD,IAAI,OAAO,mBAAmB,aAAa;CAC3C,IAAI,CAAC,eAAe,IAAI,2BAA2B,GACjD,eAAe,OACb,6BACA,8BACF;CAEF,+EAAqC;AACvC"}
|
|
@@ -37,6 +37,34 @@ const getPendingRevealOffset = (element) => {
|
|
|
37
37
|
}
|
|
38
38
|
return offset;
|
|
39
39
|
};
|
|
40
|
+
/**
|
|
41
|
+
* Reveal callbacks of the wrappers selected by the current focus change, keyed
|
|
42
|
+
* by wrapper. A focus matches every wrapper under its key path (list items,
|
|
43
|
+
* content rendered twice…), so they are batched and only the first is revealed.
|
|
44
|
+
*/
|
|
45
|
+
const pendingReveals = /* @__PURE__ */ new Map();
|
|
46
|
+
/** Whether `element` comes after `reference` in document order. */
|
|
47
|
+
const isAfterInDocument = (element, reference) => {
|
|
48
|
+
const position = reference.compareDocumentPosition(element);
|
|
49
|
+
if (position & Node.DOCUMENT_POSITION_DISCONNECTED) return true;
|
|
50
|
+
return Boolean(position & Node.DOCUMENT_POSITION_FOLLOWING);
|
|
51
|
+
};
|
|
52
|
+
/** Reveals the first wrapper, in document order, among the pending ones. */
|
|
53
|
+
const flushPendingReveals = () => {
|
|
54
|
+
let firstWrapper = null;
|
|
55
|
+
for (const wrapper of pendingReveals.keys()) {
|
|
56
|
+
if (!wrapper.isConnected) continue;
|
|
57
|
+
if (!firstWrapper || !isAfterInDocument(wrapper, firstWrapper)) firstWrapper = wrapper;
|
|
58
|
+
}
|
|
59
|
+
const reveal = firstWrapper ? pendingReveals.get(firstWrapper) : void 0;
|
|
60
|
+
pendingReveals.clear();
|
|
61
|
+
reveal?.();
|
|
62
|
+
};
|
|
63
|
+
/** Queues a wrapper to reveal once every wrapper handled the focus change. */
|
|
64
|
+
const scheduleReveal = (wrapper, reveal) => {
|
|
65
|
+
if (pendingReveals.size === 0) queueMicrotask(flushPendingReveals);
|
|
66
|
+
pendingReveals.set(wrapper, reveal);
|
|
67
|
+
};
|
|
40
68
|
const _HTMLElement = typeof HTMLElement !== "undefined" ? HTMLElement : class {};
|
|
41
69
|
/**
|
|
42
70
|
* <intlayer-content-selector-wrapper>
|
|
@@ -126,6 +154,7 @@ var IntlayerContentSelectorWrapperElement = class extends _HTMLElement {
|
|
|
126
154
|
_updateIsSelected(focusedContent) {
|
|
127
155
|
if (!focusedContent) {
|
|
128
156
|
this._isSelected = false;
|
|
157
|
+
pendingReveals.delete(this);
|
|
129
158
|
this._updateSelectorAttr();
|
|
130
159
|
return;
|
|
131
160
|
}
|
|
@@ -133,7 +162,8 @@ var IntlayerContentSelectorWrapperElement = class extends _HTMLElement {
|
|
|
133
162
|
const wasSelected = this._isSelected;
|
|
134
163
|
this._isSelected = focusedContent.dictionaryKey === this._dictionaryKey && (focusedContent.keyPath?.length ?? 0) > 0 && (0, _intlayer_core_utils.isSameKeyPath)(focusedContent.keyPath ?? [], keyPath);
|
|
135
164
|
this._updateSelectorAttr();
|
|
136
|
-
if (this._isSelected && !wasSelected) this._scrollIntoViewIfNeeded();
|
|
165
|
+
if (this._isSelected && !wasSelected) scheduleReveal(this, () => this._scrollIntoViewIfNeeded());
|
|
166
|
+
else if (!this._isSelected) pendingReveals.delete(this);
|
|
137
167
|
}
|
|
138
168
|
/**
|
|
139
169
|
* Scrolls the selected content to 30vh, unless it is already fully visible
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ContentSelectorWrapper.cjs","names":["getGlobalEditorManager","NodeTypes","node","isSameKeyPath","onGlobalEditorManagerChange"],"sources":["../../../src/components/ContentSelectorWrapper.ts"],"sourcesContent":["import { isSameKeyPath } from '@intlayer/core/utils';\n\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type { TypedNodeModel } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type {\n EditorStateManager,\n FileContent,\n} from '../core/EditorStateManager';\nimport {\n getGlobalEditorManager,\n onGlobalEditorManagerChange,\n} from '../core/globalManager';\nimport { MessageKey } from '../messageKey';\n\ntype RenderState = 'simple' | 'wrapped-slot' | 'wrapped-text';\n\n/**\n * Share of the viewport height left above content scrolled into view (30vh),\n * keeping it clear of fixed navbars.\n */\nconst SCROLL_TOP_OFFSET_RATIO = 0.3;\n\n/** Parent in the flattened tree, crossing shadow roots up to their host. */\nconst getComposedParent = (element: Element): Element | null =>\n element.parentElement ??\n ((element.getRootNode() as ShadowRoot).host as Element | undefined) ??\n null;\n\n/** Vertical translation applied to an element, by `transform` or `translate`. */\nconst getTranslateY = (style: CSSStyleDeclaration): number => {\n const transformOffset =\n style.transform && style.transform !== 'none'\n ? new DOMMatrixReadOnly(style.transform).m42\n : 0;\n // `translate: <x> <y>` — a single value only moves along x\n const translateOffset = Number.parseFloat(\n style.translate?.split(' ')[1] ?? ''\n );\n\n return (\n transformOffset + (Number.isNaN(translateOffset) ? 0 : translateOffset)\n );\n};\n\n/**\n * Vertical offset the element will lose once its reveal animations end.\n *\n * Scroll-reveal effects (`whileInView`, AOS…) keep off-screen content\n * transparent and shifted until it enters the viewport, then slide it into\n * place: measuring it as-is would scroll too far by that shift. Only\n * translucent ancestors are counted, so permanent transforms (centering…)\n * stay part of the position.\n */\nconst getPendingRevealOffset = (element: Element): number => {\n let offset = 0;\n\n for (\n let ancestor: Element | null = element;\n ancestor;\n ancestor = getComposedParent(ancestor)\n ) {\n const style = getComputedStyle(ancestor);\n\n if (Number.parseFloat(style.opacity) < 1) offset += getTranslateY(style);\n }\n\n return offset;\n};\n\nconst _HTMLElement =\n typeof HTMLElement !== 'undefined'\n ? HTMLElement\n : (class {} as unknown as typeof HTMLElement);\n\n/**\n * <intlayer-content-selector-wrapper>\n *\n * Framework-agnostic web component that wraps content with the Intlayer editor\n * selection UI. It replaces the per-framework ContentSelectorWrapper components\n * (Vue, Svelte, Solid, Preact).\n *\n * It reads from the global EditorStateManager singleton (set by initEditorClient)\n * and conditionally renders <intlayer-content-selector> around its slot content\n * when the editor is active and the app is running inside an iframe.\n *\n * @attr {string} key-path - JSON-serialized KeyPath[] for this content node\n * @attr {string} dictionary-key - The dictionary key owning this content node\n */\nexport class IntlayerContentSelectorWrapperElement extends _HTMLElement {\n private _keyPathJson = '[]';\n private _dictionaryKey = '';\n private _editorEnabled = false;\n private _isInIframe = false;\n private _isSelected = false;\n private _editedValue: ContentNode | undefined = undefined;\n\n private _renderState: RenderState | null = null;\n private _selector: HTMLElement | null = null;\n\n private _unsubManager: (() => void) | null = null;\n /** Removes the listeners attached to the current manager's states */\n private _unsubManagerState: (() => void) | null = null;\n\n static get observedAttributes(): string[] {\n return ['key-path', 'dictionary-key'];\n }\n\n constructor() {\n super();\n const shadow = this.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = ':host { display: contents; }';\n shadow.appendChild(style);\n }\n\n attributeChangedCallback(\n name: string,\n _oldValue: string | null,\n newValue: string | null\n ): void {\n if (name === 'key-path') {\n this._keyPathJson = newValue ?? '[]';\n } else {\n this._dictionaryKey = newValue ?? '';\n }\n\n const manager = getGlobalEditorManager();\n if (manager) this._updateEditedValue(manager);\n }\n\n connectedCallback(): void {\n if (typeof window !== 'undefined') {\n this._isInIframe = window.self !== window.top;\n }\n this._subscribeToManager();\n this._render();\n }\n\n disconnectedCallback(): void {\n this._unsubManager?.();\n this._unsubManager = null;\n this._unsubManagerState?.();\n this._unsubManagerState = null;\n }\n\n private _getRawKeyPath(): KeyPath[] {\n try {\n return JSON.parse(this._keyPathJson) as KeyPath[];\n } catch {\n return [];\n }\n }\n\n private _getFilteredKeyPath(): KeyPath[] {\n return this._getRawKeyPath().filter(\n (keyPath) => keyPath.type !== NodeTypes.TRANSLATION\n );\n }\n\n private _updateEditedValue(manager: EditorStateManager): void {\n const filteredKeyPath = this._getFilteredKeyPath();\n if (!this._dictionaryKey || filteredKeyPath.length === 0) {\n this._editedValue = undefined;\n this._render();\n return;\n }\n\n // Node types whose display requires framework-level rendering (markdown,\n // HTML, insertion, file): do not override the slot — the framework handles\n // those. Only plain / translated strings can be substituted here.\n const rawKeyPath = this._getRawKeyPath();\n const lastStepType = rawKeyPath[rawKeyPath.length - 1]?.type;\n if (\n lastStepType === NodeTypes.MARKDOWN ||\n lastStepType === NodeTypes.HTML ||\n lastStepType === NodeTypes.INSERTION ||\n lastStepType === NodeTypes.FILE\n ) {\n this._editedValue = undefined;\n this._render();\n return;\n }\n\n let value = manager.getContentValue(this._dictionaryKey, filteredKeyPath);\n\n // getContentNodeByKeyPath resolves translation nodes only at intermediate\n // steps, not the final leaf. Resolve manually when the returned value is\n // still a translation object (happens when Translation steps are filtered\n // out and the leaf IS the translation object).\n if (\n value !== null &&\n value !== undefined &&\n typeof value === 'object' &&\n (value as { nodeType?: unknown }).nodeType === NodeTypes.TRANSLATION\n ) {\n const locale = manager.currentLocale.value as string | undefined;\n // TypedNodeModel<Translation, …> structurally satisfies TypedNode<BaseNode>\n // (both have nodeType), so this narrowing cast is sound.\n const node = value as TypedNodeModel<\n typeof NodeTypes.TRANSLATION,\n Record<string, ContentNode>\n >;\n value = locale ? node[NodeTypes.TRANSLATION][locale] : undefined;\n }\n\n this._editedValue = value;\n this._render();\n }\n\n private _updateIsSelected(\n focusedContent: FileContent | null | undefined\n ): void {\n if (!focusedContent) {\n this._isSelected = false;\n this._updateSelectorAttr();\n return;\n }\n const keyPath = this._getFilteredKeyPath();\n const wasSelected = this._isSelected;\n this._isSelected =\n focusedContent.dictionaryKey === this._dictionaryKey &&\n (focusedContent.keyPath?.length ?? 0) > 0 &&\n isSameKeyPath(focusedContent.keyPath ?? [], keyPath);\n this._updateSelectorAttr();\n\n // Reveal content the editor focuses while it is off-screen in the app\n if (this._isSelected && !wasSelected) {\n this._scrollIntoViewIfNeeded();\n }\n }\n\n /**\n * Scrolls the selected content to 30vh, unless it is already fully visible\n * in this frame's viewport.\n */\n private _scrollIntoViewIfNeeded(): void {\n // `.wrapper` is the only real box: this host and the selector are\n // `display: contents`. No selector means the editor UI is inactive.\n const target = this._selector?.shadowRoot?.querySelector('.wrapper');\n if (!target) return;\n\n const rect = target.getBoundingClientRect();\n // Where the content settles once revealed\n const top = rect.top - getPendingRevealOffset(target);\n const bottom = top + rect.height;\n\n const isFullyVisible = top >= 0 && bottom <= window.innerHeight;\n if (\n isFullyVisible &&\n !this._isCoveredAt((rect.left + rect.right) / 2, top + 1)\n ) {\n return;\n }\n\n window.scrollBy({\n top: top - window.innerHeight * SCROLL_TOP_OFFSET_RATIO,\n behavior: 'smooth',\n });\n }\n\n /**\n * Whether another element (a fixed navbar, a sticky header…) is painted over\n * this content at the given viewport point.\n */\n private _isCoveredAt(x: number, y: number): boolean {\n // Query from this element's own root so apps rendered in a shadow root\n // (Lit…) don't get their outer host back\n const root = this.getRootNode() as Document | ShadowRoot;\n if (typeof root.elementFromPoint !== 'function') return false;\n\n const topElement = root.elementFromPoint(x, y);\n\n return Boolean(topElement) && !this.contains(topElement);\n }\n\n private _updateSelectorAttr(): void {\n if (!this._selector) return;\n if (this._isSelected) {\n this._selector.setAttribute('is-selecting', '');\n } else {\n this._selector.removeAttribute('is-selecting');\n }\n }\n\n private _subscribeToManager(): void {\n const manager = getGlobalEditorManager();\n if (manager) {\n this._setupManagerSubscriptions(manager);\n }\n // Keep listening for manager changes (handles stop + re-init cycles)\n this._unsubManager = onGlobalEditorManagerChange((nextManager) => {\n this._unsubManagerState?.();\n this._unsubManagerState = null;\n if (nextManager) {\n this._setupManagerSubscriptions(nextManager);\n } else {\n this._editorEnabled = false;\n this._isSelected = false;\n this._editedValue = undefined;\n this._render();\n }\n });\n }\n\n private _setupManagerSubscriptions(manager: EditorStateManager): void {\n this._editorEnabled = manager.editorEnabled.value ?? false;\n this._updateIsSelected(manager.focusedContent.value);\n this._updateEditedValue(manager);\n\n const handleEnabledChange = (e: Event) => {\n this._editorEnabled = (e as CustomEvent<boolean>).detail;\n this._render();\n };\n const handleFocusedChange = (e: Event) => {\n this._updateIsSelected((e as CustomEvent<FileContent | null>).detail);\n };\n const handleEditedContentChange = () => {\n this._updateEditedValue(manager);\n };\n\n manager.editorEnabled.addEventListener('change', handleEnabledChange);\n manager.focusedContent.addEventListener('change', handleFocusedChange);\n manager.editedContent.addEventListener('change', handleEditedContentChange);\n\n this._unsubManagerState = () => {\n manager.editorEnabled.removeEventListener('change', handleEnabledChange);\n manager.focusedContent.removeEventListener('change', handleFocusedChange);\n manager.editedContent.removeEventListener(\n 'change',\n handleEditedContentChange\n );\n };\n }\n\n private _handlePress(e: Event): void {\n // Stop propagation so nested wrappers don't also fire (composed + bubbles)\n e.stopPropagation();\n const manager = getGlobalEditorManager();\n if (!manager) return;\n manager.focusedContent.set({\n dictionaryKey: this._dictionaryKey,\n keyPath: this._getFilteredKeyPath(),\n });\n }\n\n private _handleHover(e: Event): void {\n e.stopPropagation();\n getGlobalEditorManager()?.messenger.send(\n `${MessageKey.INTLAYER_HOVERED_CONTENT_CHANGED}/post`,\n {\n dictionaryKey: this._dictionaryKey,\n keyPath: this._getFilteredKeyPath(),\n }\n );\n }\n\n private _handleUnhover(e: Event): void {\n e.stopPropagation();\n getGlobalEditorManager()?.messenger.send(\n `${MessageKey.INTLAYER_HOVERED_CONTENT_CHANGED}/post`,\n null\n );\n }\n\n private _render(): void {\n const useWrapper = this._isInIframe && this._editorEnabled;\n const editedValue = this._editedValue;\n const isSimpleValue =\n typeof editedValue === 'string' ||\n typeof editedValue === 'number' ||\n typeof editedValue === 'boolean';\n\n const newState: RenderState = !useWrapper\n ? 'simple'\n : isSimpleValue\n ? 'wrapped-text'\n : 'wrapped-slot';\n\n if (this._renderState !== newState) {\n this._rebuildContent(newState);\n return;\n }\n\n // Structure unchanged — update only dynamic parts\n if (newState !== 'simple' && this._selector) {\n this._updateSelectorAttr();\n if (\n newState === 'wrapped-text' &&\n this._selector.firstChild?.nodeType === Node.TEXT_NODE\n ) {\n (this._selector.firstChild as Text).data = String(editedValue);\n }\n }\n }\n\n private _rebuildContent(state: RenderState): void {\n const shadow = this.shadowRoot!;\n // Remove all nodes except the style element (first child)\n while (shadow.childNodes.length > 1) {\n shadow.removeChild(shadow.lastChild!);\n }\n this._selector = null;\n\n if (state === 'simple') {\n shadow.appendChild(document.createElement('slot'));\n } else {\n const selector = document.createElement('intlayer-content-selector');\n this._selector = selector;\n if (this._isSelected) selector.setAttribute('is-selecting', '');\n selector.addEventListener('intlayer:press', (e) => this._handlePress(e));\n selector.addEventListener('intlayer:hover', (e) => this._handleHover(e));\n selector.addEventListener('intlayer:unhover', (e) =>\n this._handleUnhover(e)\n );\n\n if (state === 'wrapped-text') {\n selector.appendChild(\n document.createTextNode(String(this._editedValue))\n );\n } else {\n selector.appendChild(document.createElement('slot'));\n }\n shadow.appendChild(selector);\n }\n\n this._renderState = state;\n }\n}\n\nexport const defineIntlayerContentSelectorWrapper = (): void => {\n if (typeof customElements === 'undefined') return;\n\n if (!customElements.get('intlayer-content-selector-wrapper')) {\n customElements.define(\n 'intlayer-content-selector-wrapper',\n IntlayerContentSelectorWrapperElement\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,MAAM,0BAA0B;;AAGhC,MAAM,qBAAqB,YACzB,QAAQ,iBACN,QAAQ,YAAY,CAAC,CAAgB,QACvC;;AAGF,MAAM,iBAAiB,UAAuC;CAC5D,MAAM,kBACJ,MAAM,aAAa,MAAM,cAAc,SACnC,IAAI,kBAAkB,MAAM,SAAS,CAAC,CAAC,MACvC;CAEN,MAAM,kBAAkB,OAAO,WAC7B,MAAM,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM,EACpC;CAEA,OACE,mBAAmB,OA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AU,YAAY,aAAa,KAAK,WAE7C,AAAC,KAAK,UAAU,WAAoB,OAAO,OAAO,WAAW;EAEjE;CACF;CAEA,AAAQ,gBAAgB,OAA0B;EAChD,MAAM,SAAS,KAAK;EAEpB,OAAO,OAAO,WAAW,SAAS,GAChC,OAAO,YAAY,OAAO,SAAU;EAEtC,KAAK,YAAY;EAEjB,IAAI,UAAU,UACZ,OAAO,YAAY,SAAS,cAAc,MAAM,CAAC;OAC5C;GACL,MAAM,WAAW,SAAS,cAAc,2BAA2B;GACnE,KAAK,YAAY;GACjB,IAAI,KAAK,aAAa,SAAS,aAAa,gBAAgB,EAAE;GAC9D,SAAS,iBAAiB,mBAAmB,MAAM,KAAK,aAAa,CAAC,CAAC;GACvE,SAAS,iBAAiB,mBAAmB,MAAM,KAAK,aAAa,CAAC,CAAC;GACvE,SAAS,iBAAiB,qBAAqB,MAC7C,KAAK,eAAe,CAAC,CACvB;GAEA,IAAI,UAAU,gBACZ,SAAS,YACP,SAAS,eAAe,OAAO,KAAK,YAAY,CAAC,CACnD;QAEA,SAAS,YAAY,SAAS,cAAc,MAAM,CAAC;GAErD,OAAO,YAAY,QAAQ;EAC7B;EAEA,KAAK,eAAe;CACtB;AACF;AAEA,MAAa,6CAAmD;CAC9D,IAAI,OAAO,mBAAmB,aAAa;CAE3C,IAAI,CAAC,eAAe,IAAI,mCAAmC,GACzD,eAAe,OACb,qCACA,qCACF;AAEJ"}
|
|
1
|
+
{"version":3,"file":"ContentSelectorWrapper.cjs","names":["getGlobalEditorManager","NodeTypes","node","isSameKeyPath","onGlobalEditorManagerChange"],"sources":["../../../src/components/ContentSelectorWrapper.ts"],"sourcesContent":["import { isSameKeyPath } from '@intlayer/core/utils';\n\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type { TypedNodeModel } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport type {\n EditorStateManager,\n FileContent,\n} from '../core/EditorStateManager';\nimport {\n getGlobalEditorManager,\n onGlobalEditorManagerChange,\n} from '../core/globalManager';\nimport { MessageKey } from '../messageKey';\n\ntype RenderState = 'simple' | 'wrapped-slot' | 'wrapped-text';\n\n/**\n * Share of the viewport height left above content scrolled into view (30vh),\n * keeping it clear of fixed navbars.\n */\nconst SCROLL_TOP_OFFSET_RATIO = 0.3;\n\n/** Parent in the flattened tree, crossing shadow roots up to their host. */\nconst getComposedParent = (element: Element): Element | null =>\n element.parentElement ??\n ((element.getRootNode() as ShadowRoot).host as Element | undefined) ??\n null;\n\n/** Vertical translation applied to an element, by `transform` or `translate`. */\nconst getTranslateY = (style: CSSStyleDeclaration): number => {\n const transformOffset =\n style.transform && style.transform !== 'none'\n ? new DOMMatrixReadOnly(style.transform).m42\n : 0;\n // `translate: <x> <y>` — a single value only moves along x\n const translateOffset = Number.parseFloat(\n style.translate?.split(' ')[1] ?? ''\n );\n\n return (\n transformOffset + (Number.isNaN(translateOffset) ? 0 : translateOffset)\n );\n};\n\n/**\n * Vertical offset the element will lose once its reveal animations end.\n *\n * Scroll-reveal effects (`whileInView`, AOS…) keep off-screen content\n * transparent and shifted until it enters the viewport, then slide it into\n * place: measuring it as-is would scroll too far by that shift. Only\n * translucent ancestors are counted, so permanent transforms (centering…)\n * stay part of the position.\n */\nconst getPendingRevealOffset = (element: Element): number => {\n let offset = 0;\n\n for (\n let ancestor: Element | null = element;\n ancestor;\n ancestor = getComposedParent(ancestor)\n ) {\n const style = getComputedStyle(ancestor);\n\n if (Number.parseFloat(style.opacity) < 1) offset += getTranslateY(style);\n }\n\n return offset;\n};\n\n/**\n * Reveal callbacks of the wrappers selected by the current focus change, keyed\n * by wrapper. A focus matches every wrapper under its key path (list items,\n * content rendered twice…), so they are batched and only the first is revealed.\n */\nconst pendingReveals = new Map<Element, () => void>();\n\n/** Whether `element` comes after `reference` in document order. */\nconst isAfterInDocument = (element: Element, reference: Element): boolean => {\n const position = reference.compareDocumentPosition(element);\n\n // Across unrelated trees the order is arbitrary: keep the earlier selection\n if (position & Node.DOCUMENT_POSITION_DISCONNECTED) return true;\n\n return Boolean(position & Node.DOCUMENT_POSITION_FOLLOWING);\n};\n\n/** Reveals the first wrapper, in document order, among the pending ones. */\nconst flushPendingReveals = (): void => {\n let firstWrapper: Element | null = null;\n\n for (const wrapper of pendingReveals.keys()) {\n if (!wrapper.isConnected) continue;\n if (!firstWrapper || !isAfterInDocument(wrapper, firstWrapper)) {\n firstWrapper = wrapper;\n }\n }\n\n const reveal = firstWrapper ? pendingReveals.get(firstWrapper) : undefined;\n pendingReveals.clear();\n reveal?.();\n};\n\n/** Queues a wrapper to reveal once every wrapper handled the focus change. */\nconst scheduleReveal = (wrapper: Element, reveal: () => void): void => {\n if (pendingReveals.size === 0) queueMicrotask(flushPendingReveals);\n pendingReveals.set(wrapper, reveal);\n};\n\nconst _HTMLElement =\n typeof HTMLElement !== 'undefined'\n ? HTMLElement\n : (class {} as unknown as typeof HTMLElement);\n\n/**\n * <intlayer-content-selector-wrapper>\n *\n * Framework-agnostic web component that wraps content with the Intlayer editor\n * selection UI. It replaces the per-framework ContentSelectorWrapper components\n * (Vue, Svelte, Solid, Preact).\n *\n * It reads from the global EditorStateManager singleton (set by initEditorClient)\n * and conditionally renders <intlayer-content-selector> around its slot content\n * when the editor is active and the app is running inside an iframe.\n *\n * @attr {string} key-path - JSON-serialized KeyPath[] for this content node\n * @attr {string} dictionary-key - The dictionary key owning this content node\n */\nexport class IntlayerContentSelectorWrapperElement extends _HTMLElement {\n private _keyPathJson = '[]';\n private _dictionaryKey = '';\n private _editorEnabled = false;\n private _isInIframe = false;\n private _isSelected = false;\n private _editedValue: ContentNode | undefined = undefined;\n\n private _renderState: RenderState | null = null;\n private _selector: HTMLElement | null = null;\n\n private _unsubManager: (() => void) | null = null;\n /** Removes the listeners attached to the current manager's states */\n private _unsubManagerState: (() => void) | null = null;\n\n static get observedAttributes(): string[] {\n return ['key-path', 'dictionary-key'];\n }\n\n constructor() {\n super();\n const shadow = this.attachShadow({ mode: 'open' });\n const style = document.createElement('style');\n style.textContent = ':host { display: contents; }';\n shadow.appendChild(style);\n }\n\n attributeChangedCallback(\n name: string,\n _oldValue: string | null,\n newValue: string | null\n ): void {\n if (name === 'key-path') {\n this._keyPathJson = newValue ?? '[]';\n } else {\n this._dictionaryKey = newValue ?? '';\n }\n\n const manager = getGlobalEditorManager();\n if (manager) this._updateEditedValue(manager);\n }\n\n connectedCallback(): void {\n if (typeof window !== 'undefined') {\n this._isInIframe = window.self !== window.top;\n }\n this._subscribeToManager();\n this._render();\n }\n\n disconnectedCallback(): void {\n this._unsubManager?.();\n this._unsubManager = null;\n this._unsubManagerState?.();\n this._unsubManagerState = null;\n }\n\n private _getRawKeyPath(): KeyPath[] {\n try {\n return JSON.parse(this._keyPathJson) as KeyPath[];\n } catch {\n return [];\n }\n }\n\n private _getFilteredKeyPath(): KeyPath[] {\n return this._getRawKeyPath().filter(\n (keyPath) => keyPath.type !== NodeTypes.TRANSLATION\n );\n }\n\n private _updateEditedValue(manager: EditorStateManager): void {\n const filteredKeyPath = this._getFilteredKeyPath();\n if (!this._dictionaryKey || filteredKeyPath.length === 0) {\n this._editedValue = undefined;\n this._render();\n return;\n }\n\n // Node types whose display requires framework-level rendering (markdown,\n // HTML, insertion, file): do not override the slot — the framework handles\n // those. Only plain / translated strings can be substituted here.\n const rawKeyPath = this._getRawKeyPath();\n const lastStepType = rawKeyPath[rawKeyPath.length - 1]?.type;\n if (\n lastStepType === NodeTypes.MARKDOWN ||\n lastStepType === NodeTypes.HTML ||\n lastStepType === NodeTypes.INSERTION ||\n lastStepType === NodeTypes.FILE\n ) {\n this._editedValue = undefined;\n this._render();\n return;\n }\n\n let value = manager.getContentValue(this._dictionaryKey, filteredKeyPath);\n\n // getContentNodeByKeyPath resolves translation nodes only at intermediate\n // steps, not the final leaf. Resolve manually when the returned value is\n // still a translation object (happens when Translation steps are filtered\n // out and the leaf IS the translation object).\n if (\n value !== null &&\n value !== undefined &&\n typeof value === 'object' &&\n (value as { nodeType?: unknown }).nodeType === NodeTypes.TRANSLATION\n ) {\n const locale = manager.currentLocale.value as string | undefined;\n // TypedNodeModel<Translation, …> structurally satisfies TypedNode<BaseNode>\n // (both have nodeType), so this narrowing cast is sound.\n const node = value as TypedNodeModel<\n typeof NodeTypes.TRANSLATION,\n Record<string, ContentNode>\n >;\n value = locale ? node[NodeTypes.TRANSLATION][locale] : undefined;\n }\n\n this._editedValue = value;\n this._render();\n }\n\n private _updateIsSelected(\n focusedContent: FileContent | null | undefined\n ): void {\n if (!focusedContent) {\n this._isSelected = false;\n pendingReveals.delete(this);\n this._updateSelectorAttr();\n return;\n }\n const keyPath = this._getFilteredKeyPath();\n const wasSelected = this._isSelected;\n this._isSelected =\n focusedContent.dictionaryKey === this._dictionaryKey &&\n (focusedContent.keyPath?.length ?? 0) > 0 &&\n isSameKeyPath(focusedContent.keyPath ?? [], keyPath);\n this._updateSelectorAttr();\n\n // Reveal content the editor focuses while it is off-screen in the app\n if (this._isSelected && !wasSelected) {\n scheduleReveal(this, () => this._scrollIntoViewIfNeeded());\n } else if (!this._isSelected) {\n pendingReveals.delete(this);\n }\n }\n\n /**\n * Scrolls the selected content to 30vh, unless it is already fully visible\n * in this frame's viewport.\n */\n private _scrollIntoViewIfNeeded(): void {\n // `.wrapper` is the only real box: this host and the selector are\n // `display: contents`. No selector means the editor UI is inactive.\n const target = this._selector?.shadowRoot?.querySelector('.wrapper');\n if (!target) return;\n\n const rect = target.getBoundingClientRect();\n // Where the content settles once revealed\n const top = rect.top - getPendingRevealOffset(target);\n const bottom = top + rect.height;\n\n const isFullyVisible = top >= 0 && bottom <= window.innerHeight;\n if (\n isFullyVisible &&\n !this._isCoveredAt((rect.left + rect.right) / 2, top + 1)\n ) {\n return;\n }\n\n window.scrollBy({\n top: top - window.innerHeight * SCROLL_TOP_OFFSET_RATIO,\n behavior: 'smooth',\n });\n }\n\n /**\n * Whether another element (a fixed navbar, a sticky header…) is painted over\n * this content at the given viewport point.\n */\n private _isCoveredAt(x: number, y: number): boolean {\n // Query from this element's own root so apps rendered in a shadow root\n // (Lit…) don't get their outer host back\n const root = this.getRootNode() as Document | ShadowRoot;\n if (typeof root.elementFromPoint !== 'function') return false;\n\n const topElement = root.elementFromPoint(x, y);\n\n return Boolean(topElement) && !this.contains(topElement);\n }\n\n private _updateSelectorAttr(): void {\n if (!this._selector) return;\n if (this._isSelected) {\n this._selector.setAttribute('is-selecting', '');\n } else {\n this._selector.removeAttribute('is-selecting');\n }\n }\n\n private _subscribeToManager(): void {\n const manager = getGlobalEditorManager();\n if (manager) {\n this._setupManagerSubscriptions(manager);\n }\n // Keep listening for manager changes (handles stop + re-init cycles)\n this._unsubManager = onGlobalEditorManagerChange((nextManager) => {\n this._unsubManagerState?.();\n this._unsubManagerState = null;\n if (nextManager) {\n this._setupManagerSubscriptions(nextManager);\n } else {\n this._editorEnabled = false;\n this._isSelected = false;\n this._editedValue = undefined;\n this._render();\n }\n });\n }\n\n private _setupManagerSubscriptions(manager: EditorStateManager): void {\n this._editorEnabled = manager.editorEnabled.value ?? false;\n this._updateIsSelected(manager.focusedContent.value);\n this._updateEditedValue(manager);\n\n const handleEnabledChange = (e: Event) => {\n this._editorEnabled = (e as CustomEvent<boolean>).detail;\n this._render();\n };\n const handleFocusedChange = (e: Event) => {\n this._updateIsSelected((e as CustomEvent<FileContent | null>).detail);\n };\n const handleEditedContentChange = () => {\n this._updateEditedValue(manager);\n };\n\n manager.editorEnabled.addEventListener('change', handleEnabledChange);\n manager.focusedContent.addEventListener('change', handleFocusedChange);\n manager.editedContent.addEventListener('change', handleEditedContentChange);\n\n this._unsubManagerState = () => {\n manager.editorEnabled.removeEventListener('change', handleEnabledChange);\n manager.focusedContent.removeEventListener('change', handleFocusedChange);\n manager.editedContent.removeEventListener(\n 'change',\n handleEditedContentChange\n );\n };\n }\n\n private _handlePress(e: Event): void {\n // Stop propagation so nested wrappers don't also fire (composed + bubbles)\n e.stopPropagation();\n const manager = getGlobalEditorManager();\n if (!manager) return;\n manager.focusedContent.set({\n dictionaryKey: this._dictionaryKey,\n keyPath: this._getFilteredKeyPath(),\n });\n }\n\n private _handleHover(e: Event): void {\n e.stopPropagation();\n getGlobalEditorManager()?.messenger.send(\n `${MessageKey.INTLAYER_HOVERED_CONTENT_CHANGED}/post`,\n {\n dictionaryKey: this._dictionaryKey,\n keyPath: this._getFilteredKeyPath(),\n }\n );\n }\n\n private _handleUnhover(e: Event): void {\n e.stopPropagation();\n getGlobalEditorManager()?.messenger.send(\n `${MessageKey.INTLAYER_HOVERED_CONTENT_CHANGED}/post`,\n null\n );\n }\n\n private _render(): void {\n const useWrapper = this._isInIframe && this._editorEnabled;\n const editedValue = this._editedValue;\n const isSimpleValue =\n typeof editedValue === 'string' ||\n typeof editedValue === 'number' ||\n typeof editedValue === 'boolean';\n\n const newState: RenderState = !useWrapper\n ? 'simple'\n : isSimpleValue\n ? 'wrapped-text'\n : 'wrapped-slot';\n\n if (this._renderState !== newState) {\n this._rebuildContent(newState);\n return;\n }\n\n // Structure unchanged — update only dynamic parts\n if (newState !== 'simple' && this._selector) {\n this._updateSelectorAttr();\n if (\n newState === 'wrapped-text' &&\n this._selector.firstChild?.nodeType === Node.TEXT_NODE\n ) {\n (this._selector.firstChild as Text).data = String(editedValue);\n }\n }\n }\n\n private _rebuildContent(state: RenderState): void {\n const shadow = this.shadowRoot!;\n // Remove all nodes except the style element (first child)\n while (shadow.childNodes.length > 1) {\n shadow.removeChild(shadow.lastChild!);\n }\n this._selector = null;\n\n if (state === 'simple') {\n shadow.appendChild(document.createElement('slot'));\n } else {\n const selector = document.createElement('intlayer-content-selector');\n this._selector = selector;\n if (this._isSelected) selector.setAttribute('is-selecting', '');\n selector.addEventListener('intlayer:press', (e) => this._handlePress(e));\n selector.addEventListener('intlayer:hover', (e) => this._handleHover(e));\n selector.addEventListener('intlayer:unhover', (e) =>\n this._handleUnhover(e)\n );\n\n if (state === 'wrapped-text') {\n selector.appendChild(\n document.createTextNode(String(this._editedValue))\n );\n } else {\n selector.appendChild(document.createElement('slot'));\n }\n shadow.appendChild(selector);\n }\n\n this._renderState = state;\n }\n}\n\nexport const defineIntlayerContentSelectorWrapper = (): void => {\n if (typeof customElements === 'undefined') return;\n\n if (!customElements.get('intlayer-content-selector-wrapper')) {\n customElements.define(\n 'intlayer-content-selector-wrapper',\n IntlayerContentSelectorWrapperElement\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,MAAM,0BAA0B;;AAGhC,MAAM,qBAAqB,YACzB,QAAQ,iBACN,QAAQ,YAAY,CAAC,CAAgB,QACvC;;AAGF,MAAM,iBAAiB,UAAuC;CAC5D,MAAM,kBACJ,MAAM,aAAa,MAAM,cAAc,SACnC,IAAI,kBAAkB,MAAM,SAAS,CAAC,CAAC,MACvC;CAEN,MAAM,kBAAkB,OAAO,WAC7B,MAAM,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM,EACpC;CAEA,OACE,mBAAmB,OAAO,MAAM,eAAe,IAAI,IAAI;AAE3D;;;;;;;;;;AAWA,MAAM,0BAA0B,YAA6B;CAC3D,IAAI,SAAS;CAEb,KACE,IAAI,WAA2B,SAC/B,UACA,WAAW,kBAAkB,QAAQ,GACrC;EACA,MAAM,QAAQ,iBAAiB,QAAQ;EAEvC,IAAI,OAAO,WAAW,MAAM,OAAO,IAAI,GAAG,UAAU,cAAc,KAAK;CACzE;CAEA,OAAO;AACT;;;;;;AAOA,MAAM,iCAAiB,IAAI,IAAyB;;AAGpD,MAAM,qBAAqB,SAAkB,cAAgC;CAC3E,MAAM,WAAW,UAAU,wBAAwB,OAAO;CAG1D,IAAI,WAAW,KAAK,gCAAgC,OAAO;CAE3D,OAAO,QAAQ,WAAW,KAAK,2BAA2B;AAC5D;;AAGA,MAAM,4BAAkC;CACtC,IAAI,eAA+B;CAEnC,KAAK,MAAM,WAAW,eAAe,KAAK,GAAG;EAC3C,IAAI,CAAC,QAAQ,aAAa;EAC1B,IAAI,CAAC,gBA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K,WAAW;GAC3C,KAAK,oBAAoB;GACzB,IACE,aAAa,kBACb,KAAK,UAAU,YAAY,aAAa,KAAK,WAE7C,AAAC,KAAK,UAAU,WAAoB,OAAO,OAAO,WAAW;EAEjE;CACF;CAEA,AAAQ,gBAAgB,OAA0B;EAChD,MAAM,SAAS,KAAK;EAEpB,OAAO,OAAO,WAAW,SAAS,GAChC,OAAO,YAAY,OAAO,SAAU;EAEtC,KAAK,YAAY;EAEjB,IAAI,UAAU,UACZ,OAAO,YAAY,SAAS,cAAc,MAAM,CAAC;OAC5C;GACL,MAAM,WAAW,SAAS,cAAc,2BAA2B;GACnE,KAAK,YAAY;GACjB,IAAI,KAAK,aAAa,SAAS,aAAa,gBAAgB,EAAE;GAC9D,SAAS,iBAAiB,mBAAmB,MAAM,KAAK,aAAa,CAAC,CAAC;GACvE,SAAS,iBAAiB,mBAAmB,MAAM,KAAK,aAAa,CAAC,CAAC;GACvE,SAAS,iBAAiB,qBAAqB,MAC7C,KAAK,eAAe,CAAC,CACvB;GAEA,IAAI,UAAU,gBACZ,SAAS,YACP,SAAS,eAAe,OAAO,KAAK,YAAY,CAAC,CACnD;QAEA,SAAS,YAAY,SAAS,cAAc,MAAM,CAAC;GAErD,OAAO,YAAY,QAAQ;EAC7B;EAEA,KAAK,eAAe;CACtB;AACF;AAEA,MAAa,6CAAmD;CAC9D,IAAI,OAAO,mBAAmB,aAAa;CAE3C,IAAI,CAAC,eAAe,IAAI,mCAAmC,GACzD,eAAe,OACb,qCACA,qCACF;AAEJ"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
//#region src/components/isInteractiveClickTarget.ts
|
|
3
|
+
/** Elements whose click already does something in the application. */
|
|
4
|
+
const INTERACTIVE_ELEMENT_SELECTOR = [
|
|
5
|
+
"a[href]",
|
|
6
|
+
"button",
|
|
7
|
+
"input",
|
|
8
|
+
"select",
|
|
9
|
+
"textarea",
|
|
10
|
+
"label",
|
|
11
|
+
"summary",
|
|
12
|
+
"option",
|
|
13
|
+
"video[controls]",
|
|
14
|
+
"audio[controls]",
|
|
15
|
+
"[contenteditable=\"\"]",
|
|
16
|
+
"[contenteditable=\"true\"]",
|
|
17
|
+
"[onclick]",
|
|
18
|
+
...[
|
|
19
|
+
"button",
|
|
20
|
+
"link",
|
|
21
|
+
"checkbox",
|
|
22
|
+
"radio",
|
|
23
|
+
"switch",
|
|
24
|
+
"tab",
|
|
25
|
+
"menuitem",
|
|
26
|
+
"menuitemcheckbox",
|
|
27
|
+
"menuitemradio",
|
|
28
|
+
"option",
|
|
29
|
+
"combobox",
|
|
30
|
+
"slider",
|
|
31
|
+
"spinbutton",
|
|
32
|
+
"textbox"
|
|
33
|
+
].map((role) => `[role="${role}"]`)
|
|
34
|
+
].join(",");
|
|
35
|
+
/** Tag prefix of the editor's own elements, which are never app controls. */
|
|
36
|
+
const EDITOR_ELEMENT_PREFIX = "intlayer-";
|
|
37
|
+
const isEditorElement = (element) => {
|
|
38
|
+
if (element.localName.startsWith(EDITOR_ELEMENT_PREFIX)) return true;
|
|
39
|
+
const root = element.getRootNode();
|
|
40
|
+
return root instanceof ShadowRoot && root.host.localName.startsWith(EDITOR_ELEMENT_PREFIX);
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Whether a click on editable content lands on something the application
|
|
44
|
+
* handles itself: a link, a button, a form control, or an ancestor rendered as
|
|
45
|
+
* clickable (`cursor: pointer`, the mark of delegated handlers such as React
|
|
46
|
+
* `onClick`). Such clicks keep their behavior; the content is then selected
|
|
47
|
+
* with a long press or a modifier click instead.
|
|
48
|
+
*
|
|
49
|
+
* The cursor is only read on ancestors of the editor elements: content inside
|
|
50
|
+
* them inherits the selector's own pointer cursor.
|
|
51
|
+
*
|
|
52
|
+
* @param event - Click event, read through its composed path
|
|
53
|
+
*/
|
|
54
|
+
const isInteractiveClickTarget = (event) => {
|
|
55
|
+
const elements = event.composedPath().filter((node) => node instanceof Element);
|
|
56
|
+
const outermostEditorIndex = elements.findLastIndex(isEditorElement);
|
|
57
|
+
return elements.some((element, index) => {
|
|
58
|
+
if (isEditorElement(element)) return false;
|
|
59
|
+
if (element.matches(INTERACTIVE_ELEMENT_SELECTOR)) return true;
|
|
60
|
+
return index > outermostEditorIndex && getComputedStyle(element).cursor === "pointer";
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
//#endregion
|
|
65
|
+
exports.isInteractiveClickTarget = isInteractiveClickTarget;
|
|
66
|
+
//# sourceMappingURL=isInteractiveClickTarget.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isInteractiveClickTarget.cjs","names":[],"sources":["../../../src/components/isInteractiveClickTarget.ts"],"sourcesContent":["/** Elements whose click already does something in the application. */\nconst INTERACTIVE_ELEMENT_SELECTOR = [\n 'a[href]',\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'label',\n 'summary',\n 'option',\n 'video[controls]',\n 'audio[controls]',\n '[contenteditable=\"\"]',\n '[contenteditable=\"true\"]',\n '[onclick]',\n ...[\n 'button',\n 'link',\n 'checkbox',\n 'radio',\n 'switch',\n 'tab',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'combobox',\n 'slider',\n 'spinbutton',\n 'textbox',\n ].map((role) => `[role=\"${role}\"]`),\n].join(',');\n\n/** Tag prefix of the editor's own elements, which are never app controls. */\nconst EDITOR_ELEMENT_PREFIX = 'intlayer-';\n\nconst isEditorElement = (element: Element): boolean => {\n if (element.localName.startsWith(EDITOR_ELEMENT_PREFIX)) return true;\n\n const root = element.getRootNode();\n\n // Internals of the editor elements (their `role=\"button\"` wrapper, slots…)\n return (\n root instanceof ShadowRoot &&\n root.host.localName.startsWith(EDITOR_ELEMENT_PREFIX)\n );\n};\n\n/**\n * Whether a click on editable content lands on something the application\n * handles itself: a link, a button, a form control, or an ancestor rendered as\n * clickable (`cursor: pointer`, the mark of delegated handlers such as React\n * `onClick`). Such clicks keep their behavior; the content is then selected\n * with a long press or a modifier click instead.\n *\n * The cursor is only read on ancestors of the editor elements: content inside\n * them inherits the selector's own pointer cursor.\n *\n * @param event - Click event, read through its composed path\n */\nexport const isInteractiveClickTarget = (event: Event): boolean => {\n const elements = event\n .composedPath()\n .filter((node): node is Element => node instanceof Element);\n\n const outermostEditorIndex = elements.findLastIndex(isEditorElement);\n\n return elements.some((element, index) => {\n if (isEditorElement(element)) return false;\n if (element.matches(INTERACTIVE_ELEMENT_SELECTOR)) return true;\n\n const isAncestorOfEditorElement = index > outermostEditorIndex;\n\n return (\n isAncestorOfEditorElement &&\n getComputedStyle(element).cursor === 'pointer'\n );\n });\n};\n"],"mappings":";;;AACA,MAAM,+BAA+B;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,SAAS,UAAU,KAAK,GAAG;AACpC,CAAC,CAAC,KAAK,GAAG;;AAGV,MAAM,wBAAwB;AAE9B,MAAM,mBAAmB,YAA8B;CACrD,IAAI,QAAQ,UAAU,WAAW,qBAAqB,GAAG,OAAO;CAEhE,MAAM,OAAO,QAAQ,YAAY;CAGjC,OACE,gBAAgB,cAChB,KAAK,KAAK,UAAU,WAAW,qBAAqB;AAExD;;;;;;;;;;;;;AAcA,MAAa,4BAA4B,UAA0B;CACjE,MAAM,WAAW,MACd,aAAa,CAAC,CACd,QAAQ,SAA0B,gBAAgB,OAAO;CAE5D,MAAM,uBAAuB,SAAS,cAAc,eAAe;CAEnE,OAAO,SAAS,MAAM,SAAS,UAAU;EACvC,IAAI,gBAAgB,OAAO,GAAG,OAAO;EACrC,IAAI,QAAQ,QAAQ,4BAA4B,GAAG,OAAO;EAI1D,OAFkC,QAAQ,wBAIxC,iBAAiB,OAAO,CAAC,CAAC,WAAW;CAEzC,CAAC;AACH"}
|
|
@@ -127,6 +127,22 @@ var EditorStateManager = class {
|
|
|
127
127
|
this.messenger.send("INTLAYER_ARE_YOU_THERE");
|
|
128
128
|
this.messenger.send(`${"INTLAYER_EDITOR_ENABLED"}/post`, true);
|
|
129
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* EDITOR mode: asks the client to switch locale. Covers applications whose
|
|
132
|
+
* locale is held in memory or storage only (no locale segment in the URL).
|
|
133
|
+
*/
|
|
134
|
+
requestLocaleChange(locale) {
|
|
135
|
+
if (this._mode !== "editor") return;
|
|
136
|
+
this.messenger.send("INTLAYER_LOCALE_CHANGE_REQUESTED", locale);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* CLIENT mode: subscribes to the locale changes requested by the editor.
|
|
140
|
+
* Returns an unsubscribe function.
|
|
141
|
+
*/
|
|
142
|
+
onLocaleChangeRequested(handler) {
|
|
143
|
+
if (this._mode !== "client") return () => {};
|
|
144
|
+
return this.messenger.subscribe("INTLAYER_LOCALE_CHANGE_REQUESTED", handler);
|
|
145
|
+
}
|
|
130
146
|
setFocusedContentKeyPath(keyPath) {
|
|
131
147
|
const filtered = keyPath.filter((key) => key.type !== _intlayer_types_nodeType.TRANSLATION);
|
|
132
148
|
const prev = this.focusedContent.value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EditorStateManager.cjs","names":["createSharedWindowState","CrossFrameMessenger","CrossFrameStateManager","UrlStateManager","IframeClickInterceptor","NodeTypes","getContentNodeByKeyPath","editDictionaryByKeyPath","renameContentNodeByKeyPath"],"sources":["../../../src/core/EditorStateManager.ts"],"sourcesContent":["import {\n editDictionaryByKeyPath,\n getContentNodeByKeyPath,\n renameContentNodeByKeyPath,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { MessageKey } from '../messageKey';\nimport {\n CrossFrameMessenger,\n type MessengerConfig,\n} from './CrossFrameMessenger';\nimport { CrossFrameStateManager } from './CrossFrameStateManager';\nimport { IframeClickInterceptor } from './IframeClickInterceptor';\nimport {\n createSharedWindowState,\n type SharedWindowState,\n} from './sharedWindowState';\nimport { UrlStateManager } from './UrlStateManager';\n\nexport type DictionaryContent = Record<LocalDictionaryId, Dictionary>;\n\ntype EditorConfig = Pick<IntlayerConfig, 'editor'>;\n\nconst sharedEditedContent =\n createSharedWindowState<DictionaryContent>('edited_content');\nconst sharedFocusedContent = createSharedWindowState<FileContent | null>(\n 'focused_content'\n);\n\nexport type FileContent = {\n dictionaryKey: string;\n dictionaryLocalId?: LocalDictionaryId;\n keyPath?: KeyPath[];\n};\n\nexport type EditorStateManagerConfig = {\n /** 'client' = the app running inside the iframe; 'editor' = the editor wrapping the app */\n mode: 'editor' | 'client';\n /** Cross-frame messaging configuration */\n messenger: MessengerConfig;\n /** Optional initial Intlayer configuration to broadcast */\n configuration?: EditorConfig;\n};\n\n/**\n * EditorStateManager is the single entry point for all Intlayer editor state.\n * It is framework-agnostic: instantiate one instance at the root of the application\n * and subscribe to its EventTarget-based events from any framework adapter.\n *\n * Replaces all context providers, hooks and store files across React, Preact,\n * Solid, Svelte, and Vue integrations.\n */\nexport class EditorStateManager {\n readonly messenger: CrossFrameMessenger;\n readonly editorEnabled: CrossFrameStateManager<boolean>;\n readonly focusedContent: CrossFrameStateManager<FileContent | null>;\n readonly localeDictionaries: CrossFrameStateManager<DictionaryContent>;\n readonly editedContent: CrossFrameStateManager<DictionaryContent>;\n readonly configuration: CrossFrameStateManager<EditorConfig>;\n readonly currentLocale: CrossFrameStateManager<Locale | undefined>;\n readonly displayedDictionaryKeys: CrossFrameStateManager<string[]>;\n\n private readonly _urlManager: UrlStateManager;\n private readonly _iframeInterceptor: IframeClickInterceptor;\n private readonly _mode: 'editor' | 'client';\n private readonly _configuration: EditorConfig | undefined;\n\n // Client-mode handshake subscribers\n private _unsubAreYouThere: (() => void) | null = null;\n private _unsubActivate: (() => void) | null = null;\n // Editor-mode handshake subscriber\n private _unsubClientReady: (() => void) | null = null;\n\n // Client-mode displayed-keys tracking\n private _displayedKeysObserver: MutationObserver | null = null;\n private _displayedKeysTimer: ReturnType<typeof setTimeout> | null = null;\n private _displayedKeysListeners: Array<[string, EventListener]> = [];\n\n // Sync with the other managers of this window\n private _stopSharedStateSyncs: Array<() => void> = [];\n\n constructor(config: EditorStateManagerConfig) {\n this._mode = config.mode;\n this._configuration = config.configuration;\n\n this.messenger = new CrossFrameMessenger(config.messenger);\n\n this.editorEnabled = new CrossFrameStateManager<boolean>(\n MessageKey.INTLAYER_EDITOR_ENABLED,\n this.messenger,\n { emit: false, receive: true, initialValue: false }\n );\n\n this.focusedContent = new CrossFrameStateManager<FileContent | null>(\n MessageKey.INTLAYER_FOCUSED_CONTENT_CHANGED,\n this.messenger,\n { emit: true, receive: true, initialValue: null }\n );\n\n this.localeDictionaries = new CrossFrameStateManager<DictionaryContent>(\n MessageKey.INTLAYER_LOCALE_DICTIONARIES_CHANGED,\n this.messenger\n );\n\n this.editedContent = new CrossFrameStateManager<DictionaryContent>(\n MessageKey.INTLAYER_EDITED_CONTENT_CHANGED,\n this.messenger\n );\n\n this.configuration = new CrossFrameStateManager<EditorConfig>(\n MessageKey.INTLAYER_CONFIGURATION,\n this.messenger,\n {\n emit: true,\n receive: false,\n ...(config.configuration ? { initialValue: config.configuration } : {}),\n }\n );\n\n // Client emits its locale to the editor; editor receives it.\n this.currentLocale = new CrossFrameStateManager<Locale>(\n MessageKey.INTLAYER_CURRENT_LOCALE,\n this.messenger,\n {\n emit: config.mode === 'client',\n receive: config.mode === 'editor',\n }\n );\n\n // Client emits displayed dictionary keys; editor receives them.\n this.displayedDictionaryKeys = new CrossFrameStateManager<string[]>(\n MessageKey.INTLAYER_DISPLAYED_DICTIONARY_KEYS,\n this.messenger,\n {\n emit: config.mode === 'client',\n receive: config.mode === 'editor',\n initialValue: [],\n }\n );\n\n this._urlManager = new UrlStateManager(this.messenger);\n this._iframeInterceptor = new IframeClickInterceptor(this.messenger);\n }\n\n start(): void {\n this.messenger.start();\n this.editorEnabled.start();\n this.focusedContent.start();\n this.localeDictionaries.start();\n this.editedContent.start();\n this.configuration.start();\n this.currentLocale.start();\n this.displayedDictionaryKeys.start();\n this._stopSharedStateSyncs = [\n this._syncWithSharedState(\n this.editedContent,\n sharedEditedContent,\n // An empty record carries no edit worth broadcasting to the client\n (content) => Object.keys(content).length > 0\n ),\n this._syncWithSharedState(this.focusedContent, sharedFocusedContent),\n ];\n\n if (this._mode === 'client') {\n this._urlManager.start();\n this._iframeInterceptor.startInterceptor();\n this._loadDictionaries();\n this._startDisplayedDictionariesTracking();\n // Request current edited content from the editor\n this.messenger.send(`${MessageKey.INTLAYER_EDITED_CONTENT_CHANGED}/get`);\n // Activation handshake: only participate if editor.enabled !== false\n if (this._configuration?.editor?.enabled !== false) {\n this._setupActivationHandshake();\n }\n } else {\n this._iframeInterceptor.startMerger();\n this._setupEditorHandshake();\n }\n }\n\n stop(): void {\n this._unsubAreYouThere?.();\n this._unsubActivate?.();\n this._unsubClientReady?.();\n this._unsubAreYouThere = null;\n this._unsubActivate = null;\n this._unsubClientReady = null;\n this.messenger.stop();\n this.editorEnabled.stop();\n this.focusedContent.stop();\n this.localeDictionaries.stop();\n this.editedContent.stop();\n this.configuration.stop();\n this.currentLocale.stop();\n this.displayedDictionaryKeys.stop();\n this._stopDisplayedDictionariesTracking();\n for (const stopSync of this._stopSharedStateSyncs) stopSync();\n this._stopSharedStateSyncs = [];\n this._urlManager.stop();\n this._iframeInterceptor.stopInterceptor();\n this._iframeInterceptor.stopMerger();\n }\n\n // ─── Handshake helpers ───────────────────────────────────────────────────────\n\n /**\n * EDITOR mode: re-send ARE_YOU_THERE to attempt re-connection with the client.\n * Call this when the user clicks \"Enable Editor\" or when the iframe reloads.\n */\n pingClient(): void {\n if (this._mode !== 'editor') return;\n\n this.messenger.send(MessageKey.INTLAYER_ARE_YOU_THERE);\n // Clients older than v8.9.4 have no handshake and wait for this instead\n this.messenger.send(`${MessageKey.INTLAYER_EDITOR_ENABLED}/post`, true);\n }\n\n // ─── Focus helpers ──────────────────────────────────────────────────────────\n\n setFocusedContentKeyPath(keyPath: KeyPath[]): void {\n const filtered = keyPath.filter(\n (key) => key.type !== NodeTypes.TRANSLATION\n );\n const prev = this.focusedContent.value;\n\n if (!prev) return;\n\n this.focusedContent.set({ ...prev, keyPath: filtered });\n }\n\n // ─── Dictionary record helpers ───────────────────────────────────────────\n\n setLocaleDictionary(dictionary: Dictionary): void {\n if (!dictionary.localId) return;\n const current = this.localeDictionaries.value ?? {};\n\n this.localeDictionaries.set({\n ...current,\n [dictionary.localId as LocalDictionaryId]: dictionary,\n });\n }\n\n // ─── Edited content helpers ───────────────────────────────────────────────\n\n setEditedDictionary(newDict: Dictionary): void {\n if (!newDict.localId) {\n console.error('setEditedDictionary: missing localId', newDict);\n return;\n }\n const current = this.editedContent.value ?? {};\n\n this.editedContent.set({\n ...current,\n [newDict.localId as LocalDictionaryId]: newDict,\n });\n }\n\n setEditedContent(\n localDictionaryId: LocalDictionaryId,\n newValue: Dictionary['content']\n ): void {\n const current = this.editedContent.value ?? {};\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: newValue,\n },\n });\n }\n\n addContent(\n localDictionaryId: LocalDictionaryId,\n newValue: ContentNode,\n keyPath: KeyPath[] = [],\n overwrite = true\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n\n let newKeyPath = keyPath;\n if (!overwrite) {\n let index = 0;\n\n const otherKeyPath = keyPath.slice(0, -1);\n const lastKeyPath = keyPath[keyPath.length - 1];\n\n let finalKey = lastKeyPath.key;\n\n while (\n typeof getContentNodeByKeyPath(currentContent, newKeyPath) !==\n 'undefined'\n ) {\n index++;\n finalKey =\n index === 0 ? lastKeyPath.key : `${lastKeyPath.key} (${index})`;\n newKeyPath = [\n ...otherKeyPath,\n { ...lastKeyPath, key: finalKey } as KeyPath,\n ];\n }\n }\n\n const updatedContent = editDictionaryByKeyPath(\n currentContent,\n newKeyPath,\n newValue\n );\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: updatedContent as Dictionary['content'],\n },\n });\n }\n\n renameContent(\n localDictionaryId: LocalDictionaryId,\n newKey: KeyPath['key'],\n keyPath: KeyPath[] = []\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n const updated = renameContentNodeByKeyPath(currentContent, newKey, keyPath);\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: updated as Dictionary['content'],\n },\n });\n }\n\n removeContent(\n localDictionaryId: LocalDictionaryId,\n keyPath: KeyPath[]\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n const initialContent = getContentNodeByKeyPath(originalContent, keyPath);\n const restored = editDictionaryByKeyPath(\n currentContent,\n keyPath,\n initialContent\n );\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: restored as Dictionary['content'],\n },\n });\n }\n\n restoreContent(localDictionaryId: LocalDictionaryId): void {\n const { [localDictionaryId]: _restored, ...remainingContent } =\n this.editedContent.value ?? {};\n\n this.editedContent.set(remainingContent);\n }\n\n getContentValue(\n localDictionaryIdOrKey: LocalDictionaryId | string,\n keyPath: KeyPath[]\n ): ContentNode | undefined {\n const edited = this.editedContent.value;\n if (!edited) return undefined;\n\n const filteredKeyPath = keyPath.filter(\n (key) => key.type !== NodeTypes.TRANSLATION\n );\n\n // Only use edited content entries whose localId is known to this client.\n // This prevents stale edits from other apps (different framework demos) from\n // being applied when the editor sends back its stored editedContent.\n const localeDicts = this.localeDictionaries.value;\n\n const isDictionaryId =\n localDictionaryIdOrKey.includes(':local:') ||\n localDictionaryIdOrKey.includes(':remote:');\n\n if (isDictionaryId) {\n // If localeDictionaries is loaded, verify this localId belongs to us\n if (localeDicts && !(localDictionaryIdOrKey in localeDicts)) {\n return undefined;\n }\n const content =\n edited[localDictionaryIdOrKey as LocalDictionaryId]?.content ?? {};\n\n return getContentNodeByKeyPath(\n content,\n filteredKeyPath,\n this.currentLocale.value\n );\n }\n\n const matchingIds = Object.keys(edited).filter(\n (key) =>\n key.startsWith(`${localDictionaryIdOrKey}:`) &&\n // If localeDictionaries is loaded, only include known localIds\n (!localeDicts || key in localeDicts)\n );\n\n for (const localId of matchingIds) {\n const content = edited[localId as LocalDictionaryId]?.content ?? {};\n const node = getContentNodeByKeyPath(\n content,\n filteredKeyPath,\n this.currentLocale.value\n );\n if (node) return node;\n }\n\n return undefined;\n }\n\n // ─── Shared window state sync ───────────────────────────────────────────\n\n /**\n * Mirrors a state with the managers of the same window, seeding it with the\n * shared value when there is one. Returns a function stopping the sync.\n */\n private _syncWithSharedState<T>(\n state: CrossFrameStateManager<T>,\n sharedState: SharedWindowState<T>,\n shouldSeed: (sharedValue: T) => boolean = () => true\n ): () => void {\n // Guards against echoing back a value received from the shared state\n let isApplyingSharedValue = false;\n\n const applySharedValue = (value: T) => {\n isApplyingSharedValue = true;\n state.set(value);\n isApplyingSharedValue = false;\n };\n\n const publishLocalChange = (event: Event) => {\n if (isApplyingSharedValue) return;\n sharedState.set(\n (event as CustomEvent<T>).detail,\n this.messenger.senderId\n );\n };\n\n state.addEventListener('change', publishLocalChange);\n\n const unsubscribeShared = sharedState.subscribe((value, sourceId) => {\n if (sourceId !== this.messenger.senderId) applySharedValue(value);\n });\n\n const sharedValue = sharedState.get();\n if (sharedValue !== undefined && shouldSeed(sharedValue)) {\n applySharedValue(sharedValue);\n }\n\n return () => {\n state.removeEventListener('change', publishLocalChange);\n unsubscribeShared();\n };\n }\n\n // ─── Displayed dictionaries tracking (client mode only) ──────────────────\n\n private _scanDisplayedDictionaryKeys(): void {\n if (typeof document === 'undefined') return;\n const elements = document.querySelectorAll(\n 'intlayer-content-selector-wrapper[dictionary-key]'\n );\n const keys = Array.from(\n new Set(\n Array.from(elements)\n .map((el) => el.getAttribute('dictionary-key') ?? '')\n .filter(Boolean)\n )\n );\n this.displayedDictionaryKeys.set(keys);\n }\n\n private _startDisplayedDictionariesTracking(): void {\n if (\n typeof document === 'undefined' ||\n typeof MutationObserver === 'undefined'\n )\n return;\n\n const schedule = () => {\n if (this._displayedKeysTimer) clearTimeout(this._displayedKeysTimer);\n this._displayedKeysTimer = setTimeout(\n () => this._scanDisplayedDictionaryKeys(),\n 100\n );\n };\n\n this._displayedKeysObserver = new MutationObserver(schedule);\n this._displayedKeysObserver.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n for (const evt of ['locationchange', 'popstate'] as const) {\n const listener = schedule as EventListener;\n window.addEventListener(evt, listener);\n this._displayedKeysListeners.push([evt, listener]);\n }\n\n this._scanDisplayedDictionaryKeys();\n }\n\n private _stopDisplayedDictionariesTracking(): void {\n this._displayedKeysObserver?.disconnect();\n this._displayedKeysObserver = null;\n if (this._displayedKeysTimer) {\n clearTimeout(this._displayedKeysTimer);\n this._displayedKeysTimer = null;\n }\n for (const [evt, listener] of this._displayedKeysListeners) {\n window.removeEventListener(evt, listener);\n }\n this._displayedKeysListeners = [];\n }\n\n // ─── Handshake helpers ───────────────────────────────────────────────────────\n\n /**\n * EDITOR mode: listen for CLIENT_READY and respond with EDITOR_ACTIVATE.\n * Also pings the client immediately in case it loaded before the editor.\n */\n private _setupEditorHandshake(): void {\n // When the client announces it is ready, activate it\n this._unsubClientReady = this.messenger.subscribe(\n MessageKey.INTLAYER_CLIENT_READY,\n () => {\n this.editorEnabled.set(true);\n this.messenger.send(MessageKey.INTLAYER_EDITOR_ACTIVATE);\n }\n );\n\n // Ping any already-running client (covers editor-opens-after-client scenario)\n this.messenger.send(MessageKey.INTLAYER_ARE_YOU_THERE);\n }\n\n private _setupActivationHandshake(): void {\n // Announce to the editor that the client is ready\n this.messenger.send(MessageKey.INTLAYER_CLIENT_READY);\n\n // Respond to \"are you there?\" pings from the editor\n this._unsubAreYouThere = this.messenger.subscribe(\n MessageKey.INTLAYER_ARE_YOU_THERE,\n () => {\n this.messenger.send(MessageKey.INTLAYER_CLIENT_READY);\n }\n );\n\n // When the editor activates us, enable the selector and broadcast state\n this._unsubActivate = this.messenger.subscribe(\n MessageKey.INTLAYER_EDITOR_ACTIVATE,\n () => {\n this.editorEnabled.set(true);\n this._broadcastData();\n }\n );\n }\n\n private _broadcastData(): void {\n const configVal = this.configuration.value;\n\n if (configVal) {\n this.messenger.send(\n `${MessageKey.INTLAYER_CONFIGURATION}/post`,\n configVal\n );\n }\n const localeVal = this.currentLocale.value;\n\n if (localeVal) {\n this.messenger.send(\n `${MessageKey.INTLAYER_CURRENT_LOCALE}/post`,\n localeVal\n );\n }\n const dicts = this.localeDictionaries.value;\n\n if (dicts) {\n this.messenger.send(\n `${MessageKey.INTLAYER_LOCALE_DICTIONARIES_CHANGED}/post`,\n dicts\n );\n }\n }\n\n private async _loadDictionaries(): Promise<void> {\n try {\n const mod = await import('@intlayer/dictionaries-entry/unmerged');\n const unmergedDictionaries = mod.getUnmergedDictionaries();\n const dictionariesList = Object.fromEntries(\n Object.values(unmergedDictionaries)\n .flat()\n .map((dictionary) => [dictionary.localId, dictionary])\n ) as DictionaryContent;\n\n this.localeDictionaries.set(dictionariesList);\n\n // If the editor already activated us before dictionaries finished loading,\n // re-broadcast now so the editor receives the dictionaries.\n if (this.editorEnabled.value) {\n this._broadcastData();\n }\n } catch (e) {\n // Dynamic entry not available (expected in editor mode or when not configured)\n console.warn('[intlayer] Failed to load unmerged dictionaries:', e);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,MAAM,sBACJA,uDAA2C,gBAAgB;AAC7D,MAAM,uBAAuBA,uDAC3B,iBACF;;;;;;;;;AAyBA,IAAa,qBAAb,MAAgC;CAC9B,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CAET,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAGjB,AAAQ,oBAAyC;CACjD,AAAQ,iBAAsC;CAE9C,AAAQ,oBAAyC;CAGjD,AAAQ,yBAAkD;CAC1D,AAAQ,sBAA4D;CACpE,AAAQ,0BAA0D,CAAC;CAGnE,AAAQ,wBAA2C,CAAC;CAEpD,YAAY,QAAkC;EAC5C,KAAK,QAAQ,OAAO;EACpB,KAAK,iBAAiB,OAAO;EAE7B,KAAK,YAAY,IAAIC,qDAAoB,OAAO,SAAS;EAEzD,KAAK,gBAAgB,IAAIC,sFAEvB,KAAK,WACL;GAAE,MAAM;GAAO,SAAS;GAAM,cAAc;EAAM,CACpD;EAEA,KAAK,iBAAiB,IAAIA,+FAExB,KAAK,WACL;GAAE,MAAM;GAAM,SAAS;GAAM,cAAc;EAAK,CAClD;EAEA,KAAK,qBAAqB,IAAIA,mGAE5B,KAAK,SACP;EAEA,KAAK,gBAAgB,IAAIA,8FAEvB,KAAK,SACP;EAEA,KAAK,gBAAgB,IAAIA,qFAEvB,KAAK,WACL;GACE,MAAM;GACN,SAAS;GACT,GAAI,OAAO,gBAAgB,EAAE,cAAc,OAAO,cAAc,IAAI,CAAC;EACvE,CACF;EAGA,KAAK,gBAAgB,IAAIA,sFAEvB,KAAK,WACL;GACE,MAAM,OAAO,SAAS;GACtB,SAAS,OAAO,SAAS;EAC3B,CACF;EAGA,KAAK,0BAA0B,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C;CAClC;;;;;CAQA,AAAQ,wBAA8B;EAEpC,KAAK,oBAAoB,KAAK,UAAU,yCAEhC;GACJ,KAAK,cAAc,IAAI,IAAI;GAC3B,KAAK,UAAU,+BAAwC;EACzD,CACF;EAGA,KAAK,UAAU,6BAAsC;CACvD;CAEA,AAAQ,4BAAkC;EAExC,KAAK,UAAU,4BAAqC;EAGpD,KAAK,oBAAoB,KAAK,UAAU,0CAEhC;GACJ,KAAK,UAAU,4BAAqC;EACtD,CACF;EAGA,KAAK,iBAAiB,KAAK,UAAU,4CAE7B;GACJ,KAAK,cAAc,IAAI,IAAI;GAC3B,KAAK,eAAe;EACtB,CACF;CACF;CAEA,AAAQ,iBAAuB;EAC7B,MAAM,YAAY,KAAK,cAAc;EAErC,IAAI,WACF,KAAK,UAAU,KACb,4BAAqC,QACrC,SACF;EAEF,MAAM,YAAY,KAAK,cAAc;EAErC,IAAI,WACF,KAAK,UAAU,KACb,6BAAsC,QACtC,SACF;EAEF,MAAM,QAAQ,KAAK,mBAAmB;EAEtC,IAAI,OACF,KAAK,UAAU,KACb,0CAAmD,QACnD,KACF;CAEJ;CAEA,MAAc,oBAAmC;EAC/C,IAAI;GAEF,MAAM,wBAAuB,MADX,OAAO,yCACO,CAAC,wBAAwB;GACzD,MAAM,mBAAmB,OAAO,YAC9B,OAAO,OAAO,oBAAoB,CAAC,CAChC,KAAK,CAAC,CACN,KAAK,eAAe,CAAC,WAAW,SAAS,UAAU,CAAC,CACzD;GAEA,KAAK,mBAAmB,IAAI,gBAAgB;GAI5C,IAAI,KAAK,cAAc,OACrB,KAAK,eAAe;EAExB,SAAS,GAAG;GAEV,QAAQ,KAAK,oDAAoD,CAAC;EACpE;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"EditorStateManager.cjs","names":["createSharedWindowState","CrossFrameMessenger","CrossFrameStateManager","UrlStateManager","IframeClickInterceptor","NodeTypes","getContentNodeByKeyPath","editDictionaryByKeyPath","renameContentNodeByKeyPath"],"sources":["../../../src/core/EditorStateManager.ts"],"sourcesContent":["import {\n editDictionaryByKeyPath,\n getContentNodeByKeyPath,\n renameContentNodeByKeyPath,\n} from '@intlayer/core/dictionaryManipulator';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type {\n ContentNode,\n Dictionary,\n LocalDictionaryId,\n} from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { MessageKey } from '../messageKey';\nimport {\n CrossFrameMessenger,\n type MessengerConfig,\n} from './CrossFrameMessenger';\nimport { CrossFrameStateManager } from './CrossFrameStateManager';\nimport { IframeClickInterceptor } from './IframeClickInterceptor';\nimport {\n createSharedWindowState,\n type SharedWindowState,\n} from './sharedWindowState';\nimport { UrlStateManager } from './UrlStateManager';\n\nexport type DictionaryContent = Record<LocalDictionaryId, Dictionary>;\n\ntype EditorConfig = Pick<IntlayerConfig, 'editor'>;\n\nconst sharedEditedContent =\n createSharedWindowState<DictionaryContent>('edited_content');\nconst sharedFocusedContent = createSharedWindowState<FileContent | null>(\n 'focused_content'\n);\n\nexport type FileContent = {\n dictionaryKey: string;\n dictionaryLocalId?: LocalDictionaryId;\n keyPath?: KeyPath[];\n};\n\nexport type EditorStateManagerConfig = {\n /** 'client' = the app running inside the iframe; 'editor' = the editor wrapping the app */\n mode: 'editor' | 'client';\n /** Cross-frame messaging configuration */\n messenger: MessengerConfig;\n /** Optional initial Intlayer configuration to broadcast */\n configuration?: EditorConfig;\n};\n\n/**\n * EditorStateManager is the single entry point for all Intlayer editor state.\n * It is framework-agnostic: instantiate one instance at the root of the application\n * and subscribe to its EventTarget-based events from any framework adapter.\n *\n * Replaces all context providers, hooks and store files across React, Preact,\n * Solid, Svelte, and Vue integrations.\n */\nexport class EditorStateManager {\n readonly messenger: CrossFrameMessenger;\n readonly editorEnabled: CrossFrameStateManager<boolean>;\n readonly focusedContent: CrossFrameStateManager<FileContent | null>;\n readonly localeDictionaries: CrossFrameStateManager<DictionaryContent>;\n readonly editedContent: CrossFrameStateManager<DictionaryContent>;\n readonly configuration: CrossFrameStateManager<EditorConfig>;\n readonly currentLocale: CrossFrameStateManager<Locale | undefined>;\n readonly displayedDictionaryKeys: CrossFrameStateManager<string[]>;\n\n private readonly _urlManager: UrlStateManager;\n private readonly _iframeInterceptor: IframeClickInterceptor;\n private readonly _mode: 'editor' | 'client';\n private readonly _configuration: EditorConfig | undefined;\n\n // Client-mode handshake subscribers\n private _unsubAreYouThere: (() => void) | null = null;\n private _unsubActivate: (() => void) | null = null;\n // Editor-mode handshake subscriber\n private _unsubClientReady: (() => void) | null = null;\n\n // Client-mode displayed-keys tracking\n private _displayedKeysObserver: MutationObserver | null = null;\n private _displayedKeysTimer: ReturnType<typeof setTimeout> | null = null;\n private _displayedKeysListeners: Array<[string, EventListener]> = [];\n\n // Sync with the other managers of this window\n private _stopSharedStateSyncs: Array<() => void> = [];\n\n constructor(config: EditorStateManagerConfig) {\n this._mode = config.mode;\n this._configuration = config.configuration;\n\n this.messenger = new CrossFrameMessenger(config.messenger);\n\n this.editorEnabled = new CrossFrameStateManager<boolean>(\n MessageKey.INTLAYER_EDITOR_ENABLED,\n this.messenger,\n { emit: false, receive: true, initialValue: false }\n );\n\n this.focusedContent = new CrossFrameStateManager<FileContent | null>(\n MessageKey.INTLAYER_FOCUSED_CONTENT_CHANGED,\n this.messenger,\n { emit: true, receive: true, initialValue: null }\n );\n\n this.localeDictionaries = new CrossFrameStateManager<DictionaryContent>(\n MessageKey.INTLAYER_LOCALE_DICTIONARIES_CHANGED,\n this.messenger\n );\n\n this.editedContent = new CrossFrameStateManager<DictionaryContent>(\n MessageKey.INTLAYER_EDITED_CONTENT_CHANGED,\n this.messenger\n );\n\n this.configuration = new CrossFrameStateManager<EditorConfig>(\n MessageKey.INTLAYER_CONFIGURATION,\n this.messenger,\n {\n emit: true,\n receive: false,\n ...(config.configuration ? { initialValue: config.configuration } : {}),\n }\n );\n\n // Client emits its locale to the editor; editor receives it.\n this.currentLocale = new CrossFrameStateManager<Locale>(\n MessageKey.INTLAYER_CURRENT_LOCALE,\n this.messenger,\n {\n emit: config.mode === 'client',\n receive: config.mode === 'editor',\n }\n );\n\n // Client emits displayed dictionary keys; editor receives them.\n this.displayedDictionaryKeys = new CrossFrameStateManager<string[]>(\n MessageKey.INTLAYER_DISPLAYED_DICTIONARY_KEYS,\n this.messenger,\n {\n emit: config.mode === 'client',\n receive: config.mode === 'editor',\n initialValue: [],\n }\n );\n\n this._urlManager = new UrlStateManager(this.messenger);\n this._iframeInterceptor = new IframeClickInterceptor(this.messenger);\n }\n\n start(): void {\n this.messenger.start();\n this.editorEnabled.start();\n this.focusedContent.start();\n this.localeDictionaries.start();\n this.editedContent.start();\n this.configuration.start();\n this.currentLocale.start();\n this.displayedDictionaryKeys.start();\n this._stopSharedStateSyncs = [\n this._syncWithSharedState(\n this.editedContent,\n sharedEditedContent,\n // An empty record carries no edit worth broadcasting to the client\n (content) => Object.keys(content).length > 0\n ),\n this._syncWithSharedState(this.focusedContent, sharedFocusedContent),\n ];\n\n if (this._mode === 'client') {\n this._urlManager.start();\n this._iframeInterceptor.startInterceptor();\n this._loadDictionaries();\n this._startDisplayedDictionariesTracking();\n // Request current edited content from the editor\n this.messenger.send(`${MessageKey.INTLAYER_EDITED_CONTENT_CHANGED}/get`);\n // Activation handshake: only participate if editor.enabled !== false\n if (this._configuration?.editor?.enabled !== false) {\n this._setupActivationHandshake();\n }\n } else {\n this._iframeInterceptor.startMerger();\n this._setupEditorHandshake();\n }\n }\n\n stop(): void {\n this._unsubAreYouThere?.();\n this._unsubActivate?.();\n this._unsubClientReady?.();\n this._unsubAreYouThere = null;\n this._unsubActivate = null;\n this._unsubClientReady = null;\n this.messenger.stop();\n this.editorEnabled.stop();\n this.focusedContent.stop();\n this.localeDictionaries.stop();\n this.editedContent.stop();\n this.configuration.stop();\n this.currentLocale.stop();\n this.displayedDictionaryKeys.stop();\n this._stopDisplayedDictionariesTracking();\n for (const stopSync of this._stopSharedStateSyncs) stopSync();\n this._stopSharedStateSyncs = [];\n this._urlManager.stop();\n this._iframeInterceptor.stopInterceptor();\n this._iframeInterceptor.stopMerger();\n }\n\n // ─── Handshake helpers ───────────────────────────────────────────────────────\n\n /**\n * EDITOR mode: re-send ARE_YOU_THERE to attempt re-connection with the client.\n * Call this when the user clicks \"Enable Editor\" or when the iframe reloads.\n */\n pingClient(): void {\n if (this._mode !== 'editor') return;\n\n this.messenger.send(MessageKey.INTLAYER_ARE_YOU_THERE);\n // Clients older than v8.9.4 have no handshake and wait for this instead\n this.messenger.send(`${MessageKey.INTLAYER_EDITOR_ENABLED}/post`, true);\n }\n\n // ─── Locale helpers ─────────────────────────────────────────────────────────\n\n /**\n * EDITOR mode: asks the client to switch locale. Covers applications whose\n * locale is held in memory or storage only (no locale segment in the URL).\n */\n requestLocaleChange(locale: Locale): void {\n if (this._mode !== 'editor') return;\n\n this.messenger.send(MessageKey.INTLAYER_LOCALE_CHANGE_REQUESTED, locale);\n }\n\n /**\n * CLIENT mode: subscribes to the locale changes requested by the editor.\n * Returns an unsubscribe function.\n */\n onLocaleChangeRequested(handler: (locale: Locale) => void): () => void {\n if (this._mode !== 'client') return () => {};\n\n return this.messenger.subscribe<Locale>(\n MessageKey.INTLAYER_LOCALE_CHANGE_REQUESTED,\n handler\n );\n }\n\n // ─── Focus helpers ──────────────────────────────────────────────────────────\n\n setFocusedContentKeyPath(keyPath: KeyPath[]): void {\n const filtered = keyPath.filter(\n (key) => key.type !== NodeTypes.TRANSLATION\n );\n const prev = this.focusedContent.value;\n\n if (!prev) return;\n\n this.focusedContent.set({ ...prev, keyPath: filtered });\n }\n\n // ─── Dictionary record helpers ───────────────────────────────────────────\n\n setLocaleDictionary(dictionary: Dictionary): void {\n if (!dictionary.localId) return;\n const current = this.localeDictionaries.value ?? {};\n\n this.localeDictionaries.set({\n ...current,\n [dictionary.localId as LocalDictionaryId]: dictionary,\n });\n }\n\n // ─── Edited content helpers ───────────────────────────────────────────────\n\n setEditedDictionary(newDict: Dictionary): void {\n if (!newDict.localId) {\n console.error('setEditedDictionary: missing localId', newDict);\n return;\n }\n const current = this.editedContent.value ?? {};\n\n this.editedContent.set({\n ...current,\n [newDict.localId as LocalDictionaryId]: newDict,\n });\n }\n\n setEditedContent(\n localDictionaryId: LocalDictionaryId,\n newValue: Dictionary['content']\n ): void {\n const current = this.editedContent.value ?? {};\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: newValue,\n },\n });\n }\n\n addContent(\n localDictionaryId: LocalDictionaryId,\n newValue: ContentNode,\n keyPath: KeyPath[] = [],\n overwrite = true\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n\n let newKeyPath = keyPath;\n if (!overwrite) {\n let index = 0;\n\n const otherKeyPath = keyPath.slice(0, -1);\n const lastKeyPath = keyPath[keyPath.length - 1];\n\n let finalKey = lastKeyPath.key;\n\n while (\n typeof getContentNodeByKeyPath(currentContent, newKeyPath) !==\n 'undefined'\n ) {\n index++;\n finalKey =\n index === 0 ? lastKeyPath.key : `${lastKeyPath.key} (${index})`;\n newKeyPath = [\n ...otherKeyPath,\n { ...lastKeyPath, key: finalKey } as KeyPath,\n ];\n }\n }\n\n const updatedContent = editDictionaryByKeyPath(\n currentContent,\n newKeyPath,\n newValue\n );\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: updatedContent as Dictionary['content'],\n },\n });\n }\n\n renameContent(\n localDictionaryId: LocalDictionaryId,\n newKey: KeyPath['key'],\n keyPath: KeyPath[] = []\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n const updated = renameContentNodeByKeyPath(currentContent, newKey, keyPath);\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: updated as Dictionary['content'],\n },\n });\n }\n\n removeContent(\n localDictionaryId: LocalDictionaryId,\n keyPath: KeyPath[]\n ): void {\n const current = this.editedContent.value ?? {};\n const localeDicts = this.localeDictionaries.value ?? {};\n const originalContent = localeDicts[localDictionaryId]?.content;\n const currentContent = structuredClone(\n current[localDictionaryId]?.content ?? originalContent\n );\n const initialContent = getContentNodeByKeyPath(originalContent, keyPath);\n const restored = editDictionaryByKeyPath(\n currentContent,\n keyPath,\n initialContent\n );\n\n this.editedContent.set({\n ...current,\n [localDictionaryId]: {\n ...current[localDictionaryId],\n content: restored as Dictionary['content'],\n },\n });\n }\n\n restoreContent(localDictionaryId: LocalDictionaryId): void {\n const { [localDictionaryId]: _restored, ...remainingContent } =\n this.editedContent.value ?? {};\n\n this.editedContent.set(remainingContent);\n }\n\n getContentValue(\n localDictionaryIdOrKey: LocalDictionaryId | string,\n keyPath: KeyPath[]\n ): ContentNode | undefined {\n const edited = this.editedContent.value;\n if (!edited) return undefined;\n\n const filteredKeyPath = keyPath.filter(\n (key) => key.type !== NodeTypes.TRANSLATION\n );\n\n // Only use edited content entries whose localId is known to this client.\n // This prevents stale edits from other apps (different framework demos) from\n // being applied when the editor sends back its stored editedContent.\n const localeDicts = this.localeDictionaries.value;\n\n const isDictionaryId =\n localDictionaryIdOrKey.includes(':local:') ||\n localDictionaryIdOrKey.includes(':remote:');\n\n if (isDictionaryId) {\n // If localeDictionaries is loaded, verify this localId belongs to us\n if (localeDicts && !(localDictionaryIdOrKey in localeDicts)) {\n return undefined;\n }\n const content =\n edited[localDictionaryIdOrKey as LocalDictionaryId]?.content ?? {};\n\n return getContentNodeByKeyPath(\n content,\n filteredKeyPath,\n this.currentLocale.value\n );\n }\n\n const matchingIds = Object.keys(edited).filter(\n (key) =>\n key.startsWith(`${localDictionaryIdOrKey}:`) &&\n // If localeDictionaries is loaded, only include known localIds\n (!localeDicts || key in localeDicts)\n );\n\n for (const localId of matchingIds) {\n const content = edited[localId as LocalDictionaryId]?.content ?? {};\n const node = getContentNodeByKeyPath(\n content,\n filteredKeyPath,\n this.currentLocale.value\n );\n if (node) return node;\n }\n\n return undefined;\n }\n\n // ─── Shared window state sync ───────────────────────────────────────────\n\n /**\n * Mirrors a state with the managers of the same window, seeding it with the\n * shared value when there is one. Returns a function stopping the sync.\n */\n private _syncWithSharedState<T>(\n state: CrossFrameStateManager<T>,\n sharedState: SharedWindowState<T>,\n shouldSeed: (sharedValue: T) => boolean = () => true\n ): () => void {\n // Guards against echoing back a value received from the shared state\n let isApplyingSharedValue = false;\n\n const applySharedValue = (value: T) => {\n isApplyingSharedValue = true;\n state.set(value);\n isApplyingSharedValue = false;\n };\n\n const publishLocalChange = (event: Event) => {\n if (isApplyingSharedValue) return;\n sharedState.set(\n (event as CustomEvent<T>).detail,\n this.messenger.senderId\n );\n };\n\n state.addEventListener('change', publishLocalChange);\n\n const unsubscribeShared = sharedState.subscribe((value, sourceId) => {\n if (sourceId !== this.messenger.senderId) applySharedValue(value);\n });\n\n const sharedValue = sharedState.get();\n if (sharedValue !== undefined && shouldSeed(sharedValue)) {\n applySharedValue(sharedValue);\n }\n\n return () => {\n state.removeEventListener('change', publishLocalChange);\n unsubscribeShared();\n };\n }\n\n // ─── Displayed dictionaries tracking (client mode only) ──────────────────\n\n private _scanDisplayedDictionaryKeys(): void {\n if (typeof document === 'undefined') return;\n const elements = document.querySelectorAll(\n 'intlayer-content-selector-wrapper[dictionary-key]'\n );\n const keys = Array.from(\n new Set(\n Array.from(elements)\n .map((el) => el.getAttribute('dictionary-key') ?? '')\n .filter(Boolean)\n )\n );\n this.displayedDictionaryKeys.set(keys);\n }\n\n private _startDisplayedDictionariesTracking(): void {\n if (\n typeof document === 'undefined' ||\n typeof MutationObserver === 'undefined'\n )\n return;\n\n const schedule = () => {\n if (this._displayedKeysTimer) clearTimeout(this._displayedKeysTimer);\n this._displayedKeysTimer = setTimeout(\n () => this._scanDisplayedDictionaryKeys(),\n 100\n );\n };\n\n this._displayedKeysObserver = new MutationObserver(schedule);\n this._displayedKeysObserver.observe(document.body, {\n childList: true,\n subtree: true,\n });\n\n for (const evt of ['locationchange', 'popstate'] as const) {\n const listener = schedule as EventListener;\n window.addEventListener(evt, listener);\n this._displayedKeysListeners.push([evt, listener]);\n }\n\n this._scanDisplayedDictionaryKeys();\n }\n\n private _stopDisplayedDictionariesTracking(): void {\n this._displayedKeysObserver?.disconnect();\n this._displayedKeysObserver = null;\n if (this._displayedKeysTimer) {\n clearTimeout(this._displayedKeysTimer);\n this._displayedKeysTimer = null;\n }\n for (const [evt, listener] of this._displayedKeysListeners) {\n window.removeEventListener(evt, listener);\n }\n this._displayedKeysListeners = [];\n }\n\n // ─── Handshake helpers ───────────────────────────────────────────────────────\n\n /**\n * EDITOR mode: listen for CLIENT_READY and respond with EDITOR_ACTIVATE.\n * Also pings the client immediately in case it loaded before the editor.\n */\n private _setupEditorHandshake(): void {\n // When the client announces it is ready, activate it\n this._unsubClientReady = this.messenger.subscribe(\n MessageKey.INTLAYER_CLIENT_READY,\n () => {\n this.editorEnabled.set(true);\n this.messenger.send(MessageKey.INTLAYER_EDITOR_ACTIVATE);\n }\n );\n\n // Ping any already-running client (covers editor-opens-after-client scenario)\n this.messenger.send(MessageKey.INTLAYER_ARE_YOU_THERE);\n }\n\n private _setupActivationHandshake(): void {\n // Announce to the editor that the client is ready\n this.messenger.send(MessageKey.INTLAYER_CLIENT_READY);\n\n // Respond to \"are you there?\" pings from the editor\n this._unsubAreYouThere = this.messenger.subscribe(\n MessageKey.INTLAYER_ARE_YOU_THERE,\n () => {\n this.messenger.send(MessageKey.INTLAYER_CLIENT_READY);\n }\n );\n\n // When the editor activates us, enable the selector and broadcast state\n this._unsubActivate = this.messenger.subscribe(\n MessageKey.INTLAYER_EDITOR_ACTIVATE,\n () => {\n this.editorEnabled.set(true);\n this._broadcastData();\n }\n );\n }\n\n private _broadcastData(): void {\n const configVal = this.configuration.value;\n\n if (configVal) {\n this.messenger.send(\n `${MessageKey.INTLAYER_CONFIGURATION}/post`,\n configVal\n );\n }\n const localeVal = this.currentLocale.value;\n\n if (localeVal) {\n this.messenger.send(\n `${MessageKey.INTLAYER_CURRENT_LOCALE}/post`,\n localeVal\n );\n }\n const dicts = this.localeDictionaries.value;\n\n if (dicts) {\n this.messenger.send(\n `${MessageKey.INTLAYER_LOCALE_DICTIONARIES_CHANGED}/post`,\n dicts\n );\n }\n }\n\n private async _loadDictionaries(): Promise<void> {\n try {\n const mod = await import('@intlayer/dictionaries-entry/unmerged');\n const unmergedDictionaries = mod.getUnmergedDictionaries();\n const dictionariesList = Object.fromEntries(\n Object.values(unmergedDictionaries)\n .flat()\n .map((dictionary) => [dictionary.localId, dictionary])\n ) as DictionaryContent;\n\n this.localeDictionaries.set(dictionariesList);\n\n // If the editor already activated us before dictionaries finished loading,\n // re-broadcast now so the editor receives the dictionaries.\n if (this.editorEnabled.value) {\n this._broadcastData();\n }\n } catch (e) {\n // Dynamic entry not available (expected in editor mode or when not configured)\n console.warn('[intlayer] Failed to load unmerged dictionaries:', e);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,MAAM,sBACJA,uDAA2C,gBAAgB;AAC7D,MAAM,uBAAuBA,uDAC3B,iBACF;;;;;;;;;AAyBA,IAAa,qBAAb,MAAgC;CAC9B,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CAET,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAGjB,AAAQ,oBAAyC;CACjD,AAAQ,iBAAsC;CAE9C,AAAQ,oBAAyC;CAGjD,AAAQ,yBAAkD;CAC1D,AAAQ,sBAA4D;CACpE,AAAQ,0BAA0D,CAAC;CAGnE,AAAQ,wBAA2C,CAAC;CAEpD,YAAY,QAA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,IAAI;GAC3B,KAAK,eAAe;EACtB,CACF;CACF;CAEA,AAAQ,iBAAuB;EAC7B,MAAM,YAAY,KAAK,cAAc;EAErC,IAAI,WACF,KAAK,UAAU,KACb,4BAAqC,QACrC,SACF;EAEF,MAAM,YAAY,KAAK,cAAc;EAErC,IAAI,WACF,KAAK,UAAU,KACb,6BAAsC,QACtC,SACF;EAEF,MAAM,QAAQ,KAAK,mBAAmB;EAEtC,IAAI,OACF,KAAK,UAAU,KACb,0CAAmD,QACnD,KACF;CAEJ;CAEA,MAAc,oBAAmC;EAC/C,IAAI;GAEF,MAAM,wBAAuB,MADX,OAAO,yCACO,CAAC,wBAAwB;GACzD,MAAM,mBAAmB,OAAO,YAC9B,OAAO,OAAO,oBAAoB,CAAC,CAChC,KAAK,CAAC,CACN,KAAK,eAAe,CAAC,WAAW,SAAS,UAAU,CAAC,CACzD;GAEA,KAAK,mBAAmB,IAAI,gBAAgB;GAI5C,IAAI,KAAK,cAAc,OACrB,KAAK,eAAe;EAExB,SAAS,GAAG;GAEV,QAAQ,KAAK,oDAAoD,CAAC;EACpE;CACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_messageKey = require('../messageKey.cjs');
|
|
3
|
+
const require_core_selectionClick = require('./selectionClick.cjs');
|
|
3
4
|
|
|
4
5
|
//#region src/core/IframeClickInterceptor.ts
|
|
5
6
|
/**
|
|
@@ -16,30 +17,37 @@ const replayIframeClick = () => {
|
|
|
16
17
|
/**
|
|
17
18
|
* Forwards clicks across the iframe boundary.
|
|
18
19
|
*
|
|
19
|
-
* - startInterceptor(): client (iframe) side — reports each
|
|
20
|
+
* - startInterceptor(): client (iframe) side — reports each click to the editor
|
|
20
21
|
* - startMerger(): editor (parent) side — replays reported clicks on its window
|
|
22
|
+
*
|
|
23
|
+
* Clicks are reported once released rather than on mousedown: a long press on
|
|
24
|
+
* content starts with a mousedown too, and reporting it closed the editor
|
|
25
|
+
* drawers right before the press focused content in them. A completed long
|
|
26
|
+
* press stops its own click (see `ContentSelector`), and a click selecting
|
|
27
|
+
* content is marked as such, so neither is reported.
|
|
21
28
|
*/
|
|
22
29
|
var IframeClickInterceptor = class {
|
|
23
30
|
_messenger;
|
|
24
|
-
|
|
31
|
+
_clickHandler = null;
|
|
25
32
|
_unsubscribeMerge = null;
|
|
26
33
|
constructor(messenger) {
|
|
27
34
|
this._messenger = messenger;
|
|
28
35
|
}
|
|
29
36
|
startInterceptor() {
|
|
30
37
|
if (typeof window === "undefined") return;
|
|
31
|
-
this.
|
|
38
|
+
this._clickHandler = (event) => {
|
|
39
|
+
if (require_core_selectionClick.isSelectionClick(event)) return;
|
|
32
40
|
this._messenger.send("INTLAYER_IFRAME_CLICKED");
|
|
33
41
|
};
|
|
34
|
-
window.addEventListener("
|
|
42
|
+
window.addEventListener("click", this._clickHandler);
|
|
35
43
|
}
|
|
36
44
|
startMerger() {
|
|
37
45
|
this._unsubscribeMerge = this._messenger.subscribe("INTLAYER_IFRAME_CLICKED", replayIframeClick);
|
|
38
46
|
}
|
|
39
47
|
stopInterceptor() {
|
|
40
|
-
if (this.
|
|
41
|
-
window.removeEventListener("
|
|
42
|
-
this.
|
|
48
|
+
if (this._clickHandler) {
|
|
49
|
+
window.removeEventListener("click", this._clickHandler);
|
|
50
|
+
this._clickHandler = null;
|
|
43
51
|
}
|
|
44
52
|
}
|
|
45
53
|
stopMerger() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IframeClickInterceptor.cjs","names":[],"sources":["../../../src/core/IframeClickInterceptor.ts"],"sourcesContent":["import { MessageKey } from '../messageKey';\nimport type { CrossFrameMessenger } from './CrossFrameMessenger';\n\n/**\n * Replays a click made inside the iframe on the editor window, so the editor's\n * \"click outside\" handlers (popovers, drawers) react to it.\n */\nconst replayIframeClick = (): void => {\n for (const eventType of ['mousedown', 'click']) {\n window.dispatchEvent(\n new MouseEvent(eventType, {\n bubbles: true,\n cancelable: true,\n view: window,\n })\n );\n }\n};\n\n/**\n * Forwards clicks across the iframe boundary.\n *\n * - startInterceptor(): client (iframe) side — reports each
|
|
1
|
+
{"version":3,"file":"IframeClickInterceptor.cjs","names":["isSelectionClick"],"sources":["../../../src/core/IframeClickInterceptor.ts"],"sourcesContent":["import { MessageKey } from '../messageKey';\nimport type { CrossFrameMessenger } from './CrossFrameMessenger';\nimport { isSelectionClick } from './selectionClick';\n\n/**\n * Replays a click made inside the iframe on the editor window, so the editor's\n * \"click outside\" handlers (popovers, drawers) react to it.\n */\nconst replayIframeClick = (): void => {\n for (const eventType of ['mousedown', 'click']) {\n window.dispatchEvent(\n new MouseEvent(eventType, {\n bubbles: true,\n cancelable: true,\n view: window,\n })\n );\n }\n};\n\n/**\n * Forwards clicks across the iframe boundary.\n *\n * - startInterceptor(): client (iframe) side — reports each click to the editor\n * - startMerger(): editor (parent) side — replays reported clicks on its window\n *\n * Clicks are reported once released rather than on mousedown: a long press on\n * content starts with a mousedown too, and reporting it closed the editor\n * drawers right before the press focused content in them. A completed long\n * press stops its own click (see `ContentSelector`), and a click selecting\n * content is marked as such, so neither is reported.\n */\nexport class IframeClickInterceptor {\n private readonly _messenger: CrossFrameMessenger;\n private _clickHandler: EventListener | null = null;\n private _unsubscribeMerge: (() => void) | null = null;\n\n constructor(messenger: CrossFrameMessenger) {\n this._messenger = messenger;\n }\n\n startInterceptor(): void {\n if (typeof window === 'undefined') return;\n this._clickHandler = (event) => {\n if (isSelectionClick(event)) return;\n\n this._messenger.send(MessageKey.INTLAYER_IFRAME_CLICKED);\n };\n window.addEventListener('click', this._clickHandler);\n }\n\n startMerger(): void {\n this._unsubscribeMerge = this._messenger.subscribe(\n MessageKey.INTLAYER_IFRAME_CLICKED,\n replayIframeClick\n );\n }\n\n stopInterceptor(): void {\n if (this._clickHandler) {\n window.removeEventListener('click', this._clickHandler);\n this._clickHandler = null;\n }\n }\n\n stopMerger(): void {\n this._unsubscribeMerge?.();\n this._unsubscribeMerge = null;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,0BAAgC;CACpC,KAAK,MAAM,aAAa,CAAC,aAAa,OAAO,GAC3C,OAAO,cACL,IAAI,WAAW,WAAW;EACxB,SAAS;EACT,YAAY;EACZ,MAAM;CACR,CAAC,CACH;AAEJ;;;;;;;;;;;;;AAcA,IAAa,yBAAb,MAAoC;CAClC,AAAiB;CACjB,AAAQ,gBAAsC;CAC9C,AAAQ,oBAAyC;CAEjD,YAAY,WAAgC;EAC1C,KAAK,aAAa;CACpB;CAEA,mBAAyB;EACvB,IAAI,OAAO,WAAW,aAAa;EACnC,KAAK,iBAAiB,UAAU;GAC9B,IAAIA,6CAAiB,KAAK,GAAG;GAE7B,KAAK,WAAW,8BAAuC;EACzD;EACA,OAAO,iBAAiB,SAAS,KAAK,aAAa;CACrD;CAEA,cAAoB;EAClB,KAAK,oBAAoB,KAAK,WAAW,qCAEvC,iBACF;CACF;CAEA,kBAAwB;EACtB,IAAI,KAAK,eAAe;GACtB,OAAO,oBAAoB,SAAS,KAAK,aAAa;GACtD,KAAK,gBAAgB;EACvB;CACF;CAEA,aAAmB;EACjB,KAAK,oBAAoB;EACzB,KAAK,oBAAoB;CAC3B;AACF"}
|