@contentstack/studio-react-editor 1.8.0 → 1.9.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/components/AddIcon.js +18 -0
- package/dist/components/AddIcon.js.map +1 -0
- package/dist/components/BuildingIllustration.js +1 -1
- package/dist/components/BuildingIllustration.js.map +1 -1
- package/dist/components/EditableRenderer.js +4 -3
- package/dist/components/EditableRenderer.js.map +1 -1
- package/dist/components/Element.js +48 -20
- package/dist/components/Element.js.map +1 -1
- package/dist/components/Slot.js +5 -4
- package/dist/components/Slot.js.map +1 -1
- package/dist/components/WelcomeState.js +43 -10
- package/dist/components/WelcomeState.js.map +1 -1
- package/dist/components/elements/ConditionBlock.js +7 -20
- package/dist/components/elements/ConditionBlock.js.map +1 -1
- package/dist/components/elements/SectionSlot.js +12 -6
- package/dist/components/elements/SectionSlot.js.map +1 -1
- package/dist/components/styles.js +73 -17
- package/dist/components/styles.js.map +1 -1
- package/dist/contexts/providers/selected-node.provider.js +7 -1
- package/dist/contexts/providers/selected-node.provider.js.map +1 -1
- package/dist/hooks/use-slot-copy-color.hook.js +54 -0
- package/dist/hooks/use-slot-copy-color.hook.js.map +1 -0
- package/dist/hooks/use-spec-data-listener.hook.js +114 -15
- package/dist/hooks/use-spec-data-listener.hook.js.map +1 -1
- package/dist/utils/backdrop-watcher.util.js +79 -0
- package/dist/utils/backdrop-watcher.util.js.map +1 -0
- package/dist/utils/copy-color.util.js +300 -0
- package/dist/utils/copy-color.util.js.map +1 -0
- package/dist/utils/renderer.util.js +92 -1
- package/dist/utils/renderer.util.js.map +1 -1
- package/package.json +9 -10
- package/LICENSE +0 -21
|
@@ -3,14 +3,15 @@ import { composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack
|
|
|
3
3
|
import { DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
|
|
4
4
|
import { seedSectionInstanceBindings } from '@contentstack/studio-react-components/utils';
|
|
5
5
|
import { useRef, useEffect } from 'react';
|
|
6
|
-
import {
|
|
6
|
+
import { Immer } from 'immer';
|
|
7
7
|
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
|
|
8
|
+
// Immer freezes what it produces, but metadata-binding resolution (currently
|
|
9
|
+
// just styles) writes onto the produced node afterwards, which throws on frozen
|
|
10
|
+
// state — so this module needs a non-freezing `produce`. Scoped to an isolated
|
|
11
|
+
// instance rather than the global `setAutoFreeze(false)`: this is a published
|
|
12
|
+
// package, and the global switch would silently remove the mutation guard for
|
|
13
|
+
// the consuming app's own Immer usage.
|
|
14
|
+
const { produce } = new Immer({ autoFreeze: false });
|
|
14
15
|
/**
|
|
15
16
|
* Walk a fresh UI tree (post-Immer-produce) and populate the NODE_TO_PARENT
|
|
16
17
|
* and NODE_TO_PATH_NODE WeakMaps for every node. These maps are normally
|
|
@@ -73,19 +74,95 @@ state, composableUid) => {
|
|
|
73
74
|
}
|
|
74
75
|
: dataSources[SECTION_COMPOSITIONS_KEY] || {};
|
|
75
76
|
const pageTemplate = dataSources.template;
|
|
77
|
+
/**
|
|
78
|
+
* The document an instance's section data lives in (ADR 0017).
|
|
79
|
+
*
|
|
80
|
+
* The editor re-scopes every section from `dataSources.template` — the page
|
|
81
|
+
* template entry. A FREEFORM page has none, so a section whose Section data
|
|
82
|
+
* points at a pinned entry or a query resolved to `undefined` here and
|
|
83
|
+
* rendered component defaults, even though the binding was stored
|
|
84
|
+
* correctly and the fetch/cold-load path (build-scoped-data) resolved it
|
|
85
|
+
* fine. This is the same hardcoded-anchor bug, in the live editor path.
|
|
86
|
+
*/
|
|
87
|
+
const resolveFetchRootDocument = (fetchRootKey) => {
|
|
88
|
+
if (!fetchRootKey || fetchRootKey === "template")
|
|
89
|
+
return pageTemplate;
|
|
90
|
+
if (fetchRootKey.startsWith("query:")) {
|
|
91
|
+
const qUid = fetchRootKey.slice("query:".length);
|
|
92
|
+
return (dataSources.contentstack_queries || {})[qUid];
|
|
93
|
+
}
|
|
94
|
+
// `<ct>:<uid>` — the same composite key the contentstack resolver uses.
|
|
95
|
+
return (dataSources.contentstack || {})[fetchRootKey];
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Reference stubs, followed to their pooled entry — the step this scoper was
|
|
99
|
+
* missing entirely (the fetch path's `build-scoped-data` has it at every
|
|
100
|
+
* traversal step).
|
|
101
|
+
*
|
|
102
|
+
* CDA returns `{uid, _content_type_uid}` at a reference field unless the
|
|
103
|
+
* request included it, and Studio's read funnel pools the resolved entry
|
|
104
|
+
* separately under its `<ct>:<uid>` key. Without following the stub, a
|
|
105
|
+
* Section data whose path CROSSES a reference resolved to the stub object:
|
|
106
|
+
* the section's own fields were absent from it, so the canvas rendered
|
|
107
|
+
* component defaults while the deployed site — which does follow — was
|
|
108
|
+
* correct (COMS-2031: DR5.5, and the wrapper half of DR7.4).
|
|
109
|
+
*/
|
|
110
|
+
const META_KEYS = new Set([
|
|
111
|
+
"uid",
|
|
112
|
+
"_content_type_uid",
|
|
113
|
+
"_version",
|
|
114
|
+
"locale",
|
|
115
|
+
"ACL",
|
|
116
|
+
"_metadata",
|
|
117
|
+
// Live-preview edit tags. The Preview service stamps `$` onto every entry
|
|
118
|
+
// and reference stub in the editor, so a bare stub arrives as
|
|
119
|
+
// `{uid, _content_type_uid, $}` — three keys, one of which used to read as
|
|
120
|
+
// "this stub already carries a payload". The stub was then handed back
|
|
121
|
+
// unfollowed and a Section data whose path crosses a reference resolved to
|
|
122
|
+
// the stub instead of the entry (E2E DR7.4). Metadata, never content.
|
|
123
|
+
"$",
|
|
124
|
+
]);
|
|
125
|
+
const followReference = (v) => {
|
|
126
|
+
if (!v ||
|
|
127
|
+
typeof v !== "object" ||
|
|
128
|
+
Array.isArray(v) ||
|
|
129
|
+
typeof v.uid !== "string" ||
|
|
130
|
+
typeof v._content_type_uid !== "string") {
|
|
131
|
+
return v;
|
|
132
|
+
}
|
|
133
|
+
// CDA may already have inlined the entry into the stub object; anything
|
|
134
|
+
// beyond the meta keys means it is resolved already.
|
|
135
|
+
if (Object.keys(v).some((k) => !META_KEYS.has(k)))
|
|
136
|
+
return v;
|
|
137
|
+
const resolved = (dataSources.contentstack || {})[`${v._content_type_uid}:${v.uid}`];
|
|
138
|
+
return resolved !== undefined ? resolved : v;
|
|
139
|
+
};
|
|
140
|
+
const followAll = (v) => Array.isArray(v) ? v.map(followReference) : followReference(v);
|
|
76
141
|
const prevScoped = prevData?.section_scoped_data || {};
|
|
77
142
|
const nextScoped = { ...prevScoped };
|
|
78
143
|
const getScopedData = (obj, selectedField) => {
|
|
79
144
|
if (!selectedField)
|
|
80
|
-
return obj;
|
|
81
|
-
|
|
145
|
+
return followAll(obj);
|
|
146
|
+
const traversed = selectedField
|
|
147
|
+
.split(".")
|
|
148
|
+
.reduce((val, seg) => {
|
|
82
149
|
if (val == null)
|
|
83
150
|
return val;
|
|
151
|
+
// Swap a stub for its resolved entry BEFORE drilling into it.
|
|
152
|
+
val = followReference(val);
|
|
84
153
|
const arrayMatch = seg.match(/^(.*?)\[(\d+)\]$/);
|
|
85
154
|
if (arrayMatch) {
|
|
86
155
|
const [, name, idxStr] = arrayMatch;
|
|
87
156
|
const next = name ? val[name] : val;
|
|
88
|
-
return next == null ? next : next[Number(idxStr)];
|
|
157
|
+
return next == null ? next : followReference(next[Number(idxStr)]);
|
|
158
|
+
}
|
|
159
|
+
// A bare NUMERIC segment is an array index. Contentstack bindings
|
|
160
|
+
// encode one as a plain segment (`page_sections.17.keynote_speakers`)
|
|
161
|
+
// rather than bracket notation, so this must precede the
|
|
162
|
+
// array→first-element fallback below, which would otherwise look `17`
|
|
163
|
+
// up as a key on element [0].
|
|
164
|
+
if (Array.isArray(val) && /^\d+$/.test(seg)) {
|
|
165
|
+
return followReference(val[Number(seg)]);
|
|
89
166
|
}
|
|
90
167
|
// Non-indexed field access landing on an ARRAY → default to the first
|
|
91
168
|
// element so an un-indexed array-ancestor path (e.g.
|
|
@@ -94,11 +171,12 @@ state, composableUid) => {
|
|
|
94
171
|
// undefined → null. Indexed pushes (`navigation_menu_3[1]…`) override
|
|
95
172
|
// this with the picked instance.
|
|
96
173
|
if (Array.isArray(val)) {
|
|
97
|
-
const first = val[0];
|
|
98
|
-
return first == null ? null : first[seg];
|
|
174
|
+
const first = followReference(val[0]);
|
|
175
|
+
return first == null ? null : followReference(first[seg]);
|
|
99
176
|
}
|
|
100
|
-
return val[seg];
|
|
101
|
-
}, obj)
|
|
177
|
+
return followReference(val[seg]);
|
|
178
|
+
}, obj);
|
|
179
|
+
return ((Array.isArray(traversed) ? followAll(traversed) : traversed) ?? null);
|
|
102
180
|
};
|
|
103
181
|
const applyUidRemapping = (scoped, uidRemapping = {}) => {
|
|
104
182
|
if (!scoped ||
|
|
@@ -128,7 +206,17 @@ state, composableUid) => {
|
|
|
128
206
|
if (binding && "context" in binding && !("selectedField" in binding)) {
|
|
129
207
|
continue;
|
|
130
208
|
}
|
|
131
|
-
|
|
209
|
+
// A non-template fetch root carries its own in-document path; the
|
|
210
|
+
// legacy `selectedField` is a page-template path and does not apply.
|
|
211
|
+
const fetchRootKey = binding?.fetchRootKey;
|
|
212
|
+
const fetchRootPrefix = binding
|
|
213
|
+
?.fetchRootPrefix;
|
|
214
|
+
const usesPageTemplate = !fetchRootKey || fetchRootKey === "template";
|
|
215
|
+
const rootDocument = resolveFetchRootDocument(fetchRootKey);
|
|
216
|
+
const rootScopePath = usesPageTemplate
|
|
217
|
+
? binding?.selectedField
|
|
218
|
+
: fetchRootPrefix?.join(".");
|
|
219
|
+
let scopedTemplate = applyUidRemapping(getScopedData(rootDocument, rootScopePath), binding?.uidRemapping);
|
|
132
220
|
// Single-element section: `selectedField` stays index-free, so an
|
|
133
221
|
// un-indexed terminal array resolves to the WHOLE array. Collapse to the
|
|
134
222
|
// first element (the deploy default — the preview instance is session-only)
|
|
@@ -139,6 +227,15 @@ state, composableUid) => {
|
|
|
139
227
|
if (binding?.cardinality === "single" && Array.isArray(scopedTemplate)) {
|
|
140
228
|
scopedTemplate = scopedTemplate[0] ?? null;
|
|
141
229
|
}
|
|
230
|
+
// A CT-anchored section is ONE document. When its scope reached it through
|
|
231
|
+
// a REFERENCE — a wrapper pinned at `settings_ref` rebasing its slot
|
|
232
|
+
// children (ADR 0017) — CDA's array arrives instead of the entry, and the
|
|
233
|
+
// section's own fields are not on an array. Collapse to the document.
|
|
234
|
+
if (binding
|
|
235
|
+
?.expectsSingleDocument &&
|
|
236
|
+
Array.isArray(scopedTemplate)) {
|
|
237
|
+
scopedTemplate = scopedTemplate[0] ?? null;
|
|
238
|
+
}
|
|
142
239
|
let repeater;
|
|
143
240
|
if (binding?.parentRepeaterUID) {
|
|
144
241
|
const ctx = dataSources.repeater?.[binding.parentRepeaterUID];
|
|
@@ -175,6 +272,8 @@ state, composableUid) => {
|
|
|
175
272
|
// instance, so it can't represent per-iteration values on its own.
|
|
176
273
|
parentRepeaterUID: binding?.parentRepeaterUID ?? null,
|
|
177
274
|
selectedField: binding?.selectedField,
|
|
275
|
+
fetchRootKey,
|
|
276
|
+
fetchRootPrefix,
|
|
178
277
|
uidRemapping: binding?.uidRemapping,
|
|
179
278
|
cardinality: binding?.cardinality,
|
|
180
279
|
componentPropsFallback: binding?.componentPropsFallback,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-spec-data-listener.hook.js","sources":["../../src/hooks/use-spec-data-listener.hook.ts"],"sourcesContent":["import {\n isCompositionBeingEdited,\n StudioSpec,\n applyOperation,\n SECTION_COMPOSITIONS_KEY,\n clientRendererModeUtil,\n NODE_TO_PARENT,\n NODE_TO_PATH_NODE,\n SectionCompositionEntry,\n} from \"@contentstack/studio-client\";\nimport { Operation } from \"@contentstack/studio-internal\";\nimport {\n composableStudioEventManager,\n POST_MESSAGE_EVENTS,\n} from \"@contentstack/studio-messenger\";\nimport {\n StudioSpecData,\n DataSourceItem,\n DATA_SOURCES_PREFIX,\n} from \"@contentstack/studio-registry\";\nimport { seedSectionInstanceBindings } from \"@contentstack/studio-react-components/utils\";\nimport { useEffect, useRef } from \"react\";\nimport { produce, setAutoFreeze } from \"immer\";\n\n// NOTE: Immer (produce) automatically freezes the state to prevent mutations.\n// However, while resolving metadata bindings (which currently only include styles),\n// we need to add binding values directly to the node object.\n// Since the state is frozen by default, this throws an error.\n// To work around this, we disable auto-freezing here.\nsetAutoFreeze(false);\n\n/**\n * Walk a fresh UI tree (post-Immer-produce) and populate the NODE_TO_PARENT\n * and NODE_TO_PATH_NODE WeakMaps for every node. These maps are normally\n * populated during React render (in Element.tsx). After APPLY_OPERATION\n * produces a brand-new tree via Immer, the maps still hold entries for\n * stale node refs — `findPath` (used to compute hover/highlight paths sent\n * back to Studio) returns stale paths until the next React commit. Calling\n * this immediately after applyOperation closes that window.\n */\nfunction refreshNodeWeakMaps(root: any): void {\n if (!root || typeof root !== \"object\") return;\n NODE_TO_PARENT.set(root, undefined);\n const visit = (parent: any) => {\n const slots = parent?.slots || {};\n for (const slotUid of Object.keys(slots)) {\n const children = slots[slotUid] || [];\n for (let idx = 0; idx < children.length; idx++) {\n const child = children[idx];\n if (!child || typeof child !== \"object\") continue;\n NODE_TO_PARENT.set(child, parent);\n NODE_TO_PATH_NODE.set(child, [slotUid, idx] as any);\n visit(child);\n }\n }\n };\n visit(root);\n}\n\nexport const useSpecDataListener = (\n setState: React.Dispatch<React.SetStateAction<StudioSpec>>,\n // Read into `stateRef` only — listener bodies use `stateRef.current` (not\n // `state` directly) so the effect's deps don't include `state.data`, which\n // would force re-register on every data change and create a window with\n // zero handlers between unregister/re-register (the original\n // `NO_REQUEST_LISTENER_FOUND` cause).\n state?: StudioSpec,\n composableUid?: string,\n) => {\n // Keep a ref to the latest state so the listener registrations don't have\n // to depend on state.data — they can read latest via stateRef.current\n // synchronously. Without this, every state.data change tore down + re-registered\n // the listeners, creating a window where Studio's UPDATE_SECTION_CONTEXTS\n // message was dropped with NO_REQUEST_LISTENER_FOUND.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Rebuild section_scoped_data entries for instances whose binding metadata\n // (selectedField / uidRemapping / parentRepeaterUID) is present in the\n // legacy section_compositions slice. Mirrors build-scoped-data.ts logic\n // inline so the hook can rebuild without re-running the full fetchSpec\n // pipeline. Needed because Studio's fresh per-instance bindings arrive via\n // UPDATE_SPEC_DATA (and UPDATE_SECTION_CONTEXTS), while the provider only\n // reads from section_scoped_data — without this rebuild, sections render\n // the stale pre-computed scope from the initial fetchSpec (selectedField\n // missing from UI metadata on cold load → scoped template = whole page\n // template → placeholder text).\n const rebuildScopedFromBindings = (\n prevData: any,\n incomingBindings?: Record<string, unknown>,\n ): any => {\n const dataSources = prevData?.dataSources || {};\n const sectionBindings: Record<string, any> =\n incomingBindings && Object.keys(incomingBindings).length\n ? {\n ...(dataSources[SECTION_COMPOSITIONS_KEY] || {}),\n ...incomingBindings,\n }\n : dataSources[SECTION_COMPOSITIONS_KEY] || {};\n\n const pageTemplate = dataSources.template;\n const prevScoped = prevData?.section_scoped_data || {};\n const nextScoped: Record<string, any> = { ...prevScoped };\n\n const getScopedData = (obj: any, selectedField?: string): any => {\n if (!selectedField) return obj;\n return (\n selectedField.split(\".\").reduce((val: any, seg: string) => {\n if (val == null) return val;\n const arrayMatch = seg.match(/^(.*?)\\[(\\d+)\\]$/);\n if (arrayMatch) {\n const [, name, idxStr] = arrayMatch;\n const next = name ? val[name] : val;\n return next == null ? next : next[Number(idxStr)];\n }\n // Non-indexed field access landing on an ARRAY → default to the first\n // element so an un-indexed array-ancestor path (e.g.\n // \"navigation_menu_3.menu_subitems\", where navigation_menu_3 is a\n // multiple group) still resolves instead of `array[field]` →\n // undefined → null. Indexed pushes (`navigation_menu_3[1]…`) override\n // this with the picked instance.\n if (Array.isArray(val)) {\n const first = val[0];\n return first == null ? null : first[seg];\n }\n return val[seg];\n }, obj) ?? null\n );\n };\n\n const applyUidRemapping = (\n scoped: any,\n uidRemapping: Record<string, string> = {},\n ): any => {\n if (\n !scoped ||\n typeof scoped !== \"object\" ||\n Object.keys(uidRemapping).length === 0\n ) {\n return scoped;\n }\n if (Array.isArray(scoped)) {\n return scoped.map((item: any) => applyUidRemapping(item, uidRemapping));\n }\n const remapped: Record<string, unknown> = {};\n const pageKeyValues = new Set(Object.values(uidRemapping));\n for (const [sectionKey, pageKey] of Object.entries(uidRemapping)) {\n remapped[sectionKey] = applyUidRemapping(scoped[pageKey], uidRemapping);\n }\n for (const key of Object.keys(scoped)) {\n if (!pageKeyValues.has(key) && !(key in uidRemapping)) {\n remapped[key] = applyUidRemapping(scoped[key], uidRemapping);\n }\n }\n return remapped;\n };\n\n let changed = false;\n for (const [instanceUid, bindingUnknown] of Object.entries(\n sectionBindings,\n )) {\n const binding = bindingUnknown as {\n selectedField?: string;\n uidRemapping?: Record<string, string>;\n parentRepeaterUID?: string | null;\n context?: unknown;\n componentPropsFallback?: Record<string, unknown>;\n cardinality?: \"collection\" | \"single\";\n };\n // Skip context-only legacy shape — no selectedField to re-scope from.\n if (binding && \"context\" in binding && !(\"selectedField\" in binding)) {\n continue;\n }\n let scopedTemplate = applyUidRemapping(\n getScopedData(pageTemplate, binding?.selectedField),\n binding?.uidRemapping,\n );\n // Single-element section: `selectedField` stays index-free, so an\n // un-indexed terminal array resolves to the WHOLE array. Collapse to the\n // first element (the deploy default — the preview instance is session-only)\n // so the bound field resolves live, without depending on a save+reload\n // running the cold-load scoper. Mirrors build-scoped-data.ts. When the\n // path is already indexed (`menu_items[0]`, from Studio's push),\n // getScopedData returns the element and this is a no-op.\n if (binding?.cardinality === \"single\" && Array.isArray(scopedTemplate)) {\n scopedTemplate = scopedTemplate[0] ?? null;\n }\n let repeater: Record<string, { context: unknown }> | undefined;\n if (binding?.parentRepeaterUID) {\n const ctx = dataSources.repeater?.[binding.parentRepeaterUID];\n if (ctx !== undefined) {\n repeater = { [binding.parentRepeaterUID]: ctx };\n }\n }\n const prev = prevScoped[instanceUid] || {};\n // Refresh contentstack / contentstack_queries from the live page\n // dataSources every time we rebuild. The initial scoped data built\n // during fetchSpec may have stale (or empty) entries because the\n // iframe loaded with getSpecFromParent and never fetched the section's\n // data sources itself — the studio pushes them later via\n // UPDATE_SPEC_DATA. Pool-keyed maps would be ideal but the listener\n // doesn't have access to them; copying the full page slice is a safe\n // superset (same composite-key format the resolver expects).\n const refreshedContentstack =\n dataSources.contentstack && typeof dataSources.contentstack === \"object\"\n ? { ...dataSources.contentstack }\n : prev.contentstack || {};\n const refreshedQueries =\n dataSources.contentstack_queries &&\n typeof dataSources.contentstack_queries === \"object\"\n ? { ...dataSources.contentstack_queries }\n : prev.contentstack_queries || {};\n\n const next = {\n ...prev,\n template: scopedTemplate,\n contentstack: refreshedContentstack,\n contentstack_queries: refreshedQueries,\n page: dataSources,\n repeater: repeater ?? prev.repeater,\n // Carry binding metadata so SectionCompositionProvider can re-scope the\n // template from the LIVE per-iteration repeater item. The scopedTemplate\n // above is page-root-scoped and shared across every iteration of this\n // instance, so it can't represent per-iteration values on its own.\n parentRepeaterUID: binding?.parentRepeaterUID ?? null,\n selectedField: binding?.selectedField,\n uidRemapping: binding?.uidRemapping,\n cardinality: binding?.cardinality,\n componentPropsFallback: binding?.componentPropsFallback,\n };\n if (\n prev.template !== next.template ||\n prev.page !== next.page ||\n prev.repeater !== next.repeater ||\n prev.contentstack !== next.contentstack ||\n prev.contentstack_queries !== next.contentstack_queries ||\n prev.componentPropsFallback !== next.componentPropsFallback\n ) {\n nextScoped[instanceUid] = next;\n changed = true;\n }\n }\n if (!changed) return prevData;\n return { ...prevData, section_scoped_data: nextScoped };\n };\n\n // Self-heal when the section catalog arrives after the initial seed.\n // `sectionCompositions` (each section's `linked_schemas` + authored UI) is\n // fetched asynchronously (GET_SECTIONS / UPDATE_SECTIONS_CATALOG) and can land\n // AFTER the first `seedSectionInstanceBindings` run (on GET_COMPOSITION_SPEC).\n // A root section seeded without the catalog gets `selectedField=\"\"` → its\n // scoped template resolves to the whole page (renders the page root, e.g. the\n // page title, instead of its bound field) and stays wedged unless Studio's\n // UPDATE_SECTION_CONTEXTS push wins the race. This is especially visible after\n // a preview-entry switch, which re-navigates the canvas iframe (a fresh cold\n // load). Re-run the seeder — which now heals empty root scopes from the\n // freshly-available `linked_schemas` — and rebuild `section_scoped_data` so the\n // render picks up the corrected scope without depending on the timing of\n // Studio's push. No-op when the seeder heals nothing (`seeded === prev`), so\n // working specs are unaffected and this can't loop.\n useEffect(() => {\n // Editor-only heal — mirror every other effect in this hook, which\n // early-returns outside the Studio frame. No reason to re-seed/commit in a\n // standalone or published render.\n if (!clientRendererModeUtil.isInsideStudioFrame()) return;\n if (!state?.sectionCompositions?.length) return;\n setState((prev: StudioSpec) => {\n if (!prev?.ui || !prev?.data) return prev;\n const seeded = seedSectionInstanceBindings(prev);\n // Gate the rebuild + commit on the seeder's own no-op signal.\n // `rebuildScopedFromBindings` re-spreads the live `contentstack` /\n // `contentstack_queries` slices on every call, so for a page that has\n // sections it never returns its input unchanged — testing its result\n // would commit a fresh state (extra render + full scoped rebuild) on\n // every `sectionCompositions` ref change (Studio re-pushes the catalog on\n // refetch/refocus), not just when a cold-load scope actually heals.\n if (seeded === prev) return prev;\n return { ...seeded, data: rebuildScopedFromBindings(seeded.data) };\n });\n // Re-run whenever EITHER input the root-scope heal depends on lands:\n // • `sectionCompositions` — the section catalog (`linked_schemas`), and\n // • `connected_content_type` — the page CT that selects which linked\n // schema supplies the anchor field.\n // Both arrive asynchronously after a (re)load and in either order; keying on\n // only one leaves a race where the heal runs before the other is present,\n // computes an empty scope, and never retries — re-wedging the section.\n // The setState above changes neither dep, so this can't self-trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n state?.sectionCompositions,\n (state?.compositionEntry as any)?.connected_content_type,\n ]);\n\n // HOOK TO UPDATE THE STATE WITH THE LATEST SPEC DATA\n // Listeners are registered as soon as we're inside the Studio frame, before\n // spec has been fetched. Studio decides when to push UPDATE_SECTION_CONTEXTS\n // and UPDATE_SPEC_DATA based on its own readiness signal; the SDK can't\n // gate on `isCompositionBeingEdited(composableUid)` because that requires the\n // spec — and the parent reaches \"ready\" before the SDK's setState effect\n // has propagated, producing NO_REQUEST_LISTENER_FOUND.\n // The handlers themselves still defensively check `stateRef.current?.data`\n // before acting, so registering early is safe.\n useEffect(() => {\n if (!clientRendererModeUtil.isInsideStudioFrame()) return;\n const specDataChangeListener =\n composableStudioEventManager?.on<StudioSpecData>(\n POST_MESSAGE_EVENTS.UPDATE_SPEC_DATA,\n async (event) => {\n const { data } = event;\n if (!data || !stateRef.current?.data) return;\n\n setState((state: StudioSpec) => {\n if (!state) return state;\n // Merge incoming over existing — never replace dataSources\n // wholesale. Studio's UPDATE_SPEC_DATA pushes can carry only\n // a subset of slices (e.g., only `template` + `section_compositions`),\n // and a naive overwrite would wipe slices the SDK relied on\n // (e.g., the `repeater` item context populated earlier from\n // preview data resolution). Result was a visible flicker as\n // sections inside a Repeater suddenly lost their item context.\n // Also merge section_compositions key-by-key so SDK-seeded\n // per-instance bindings survive when Studio's push is partial.\n const incomingSections =\n (data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] || {};\n const existingSections =\n (state.data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||\n {};\n // Per-uid merge preserves `cardinality` when the incoming entry\n // lacks it — cardinality is a stable schema property, and a stale\n // push dropping it would disable the single-element array→element\n // collapse in rebuildScopedFromBindings (section blanks out).\n const mergedSections: Record<string, any> = {\n ...existingSections,\n };\n for (const [uid, incoming] of Object.entries(incomingSections)) {\n const prev = existingSections[uid];\n mergedSections[uid] =\n incoming &&\n typeof incoming === \"object\" &&\n (incoming as any).cardinality === undefined &&\n prev?.cardinality !== undefined\n ? { ...(incoming as any), cardinality: prev.cardinality }\n : incoming;\n }\n const mergedDataSources = {\n ...((state.data as any)?.dataSources || {}),\n ...((data as any)?.dataSources || {}),\n [SECTION_COMPOSITIONS_KEY]: mergedSections,\n };\n const mergedData = {\n ...state.data,\n ...data,\n dataSources: mergedDataSources,\n };\n const rebuilt = rebuildScopedFromBindings(mergedData);\n return {\n ...state,\n data: rebuilt,\n };\n });\n },\n );\n\n const previewEntryChangeListener = composableStudioEventManager?.on<{\n dataSources: DataSourceItem[];\n }>(POST_MESSAGE_EVENTS.REPLACE_PREVIEW_ENTRY, async (event) => {\n const { data } = event;\n if (!data?.dataSources || !stateRef.current?.data) return;\n\n setState((prevState: StudioSpec) => {\n if (!prevState) return prevState;\n // REPLACE_PREVIEW_ENTRY pushes dataSources for the preview-entry change\n // (typically just `template`/`contentstack` slices). Merge into existing\n // dataSources — don't wipe sibling slices like `repeater` or\n // `section_compositions`, which would cause a flicker for sections\n // inside a Repeater (their item context would disappear).\n const mergedData = {\n ...prevState?.data,\n [DATA_SOURCES_PREFIX]: {\n ...((prevState?.data as any)?.[DATA_SOURCES_PREFIX] || {}),\n ...(data?.dataSources as any),\n },\n };\n // The merge updates dataSources.template, but each section's SCOPED\n // template in section_scoped_data is derived from it — re-scope here,\n // else a section keeps its stale (often null) scope and renders the\n // empty placeholder after the preview entry is set/switched. (The\n // UPDATE_SPEC_DATA handler already rebuilds; this is the equivalent for\n // the preview-entry change path that EntryPickerBtn sends.)\n const rebuilt = rebuildScopedFromBindings(mergedData);\n return { ...prevState, data: rebuilt };\n });\n });\n\n const applyOperationListener = composableStudioEventManager?.on<{\n operations: Operation[];\n }>(POST_MESSAGE_EVENTS.APPLY_OPERATION, (event) => {\n const { data } = event;\n\n // Self-heal section catalog: if any op inserts a section-composition\n // node whose compositionUID isn't in the locally-known catalog\n // (race between Studio's section store hydration and the iframe's\n // initial GET_SECTIONS reply), re-fetch the catalog and merge.\n // Without this the section renders with \"Component … is not\n // registered\" until the page is saved + reloaded.\n const newSectionUids = new Set<string>();\n for (const op of data?.operations || []) {\n const node = (op as any)?.node;\n if (\n op &&\n (op as any).type === \"insert_node\" &&\n node &&\n typeof node === \"object\" &&\n node.type === \"section-composition\" &&\n typeof node.metadata?.compositionUID === \"string\"\n ) {\n newSectionUids.add(node.metadata.compositionUID as string);\n }\n }\n const known = new Set(\n (stateRef.current?.sectionCompositions || []).map(\n (s: SectionCompositionEntry) => s.uid,\n ),\n );\n const unknown = [...newSectionUids].filter((u) => !known.has(u));\n if (unknown.length > 0) {\n composableStudioEventManager\n ?.send<{ sectionCompositions: SectionCompositionEntry[] }>(\n POST_MESSAGE_EVENTS.GET_SECTIONS,\n {},\n )\n .then((resp) => {\n if (!resp?.sectionCompositions) return;\n setState((prevState: StudioSpec) => ({\n ...prevState,\n sectionCompositions: resp.sectionCompositions,\n }));\n })\n .catch(() => {});\n }\n\n setState((prevState: StudioSpec) => {\n if (!prevState?.ui || !data?.operations) return prevState;\n const newUI = produce(prevState.ui, (ui) => {\n const operations = data.operations;\n return applyOperation(ui, operations);\n });\n // Eagerly refresh the NODE_TO_PARENT / NODE_TO_PATH_NODE WeakMaps for\n // the new tree. These WeakMaps are otherwise only populated during\n // React render (Element.tsx) and `findPath` (used by hover/highlight\n // postMessages back to Studio) reads from them. Without this refresh\n // there is a window between APPLY_OPERATION and the next React commit\n // where mouse-move events emit paths derived from old node refs —\n // those paths don't exist in Studio's now-updated slate editor and\n // surface as \"Cannot find a descendant at path\" errors.\n refreshNodeWeakMaps(newUI as any);\n // Re-seed per-instance section bindings ONLY when the slate op might\n // have moved/inserted/removed a section-composition node. Property /\n // style / text-content ops can't change the section-instance graph,\n // so the seeder's full UI walk on those is wasted work. The seeder\n // itself is idempotent (it short-circuits when nothing mutated), but\n // skipping the walk altogether keeps interactive ops (typing, style\n // edits) cheap on large pages.\n const ops = data.operations as any[];\n const opAffectsSectionInstances = ops.some(\n (op) =>\n op?.type === \"insert_node\" ||\n op?.type === \"remove_node\" ||\n op?.type === \"move_node\" ||\n op?.type === \"merge_node\" ||\n op?.type === \"split_node\",\n );\n if (!opAffectsSectionInstances) {\n return { ...prevState, ui: newUI };\n }\n return seedSectionInstanceBindings({ ...prevState, ui: newUI });\n });\n });\n\n // Studio pushes only the section_compositions slice when section contexts\n // are recomputed (e.g. after a section node is added/moved/removed). We\n // patch just that slice on top of existing dataSources so other data\n // (template, contentstack, query results) isn't clobbered.\n //\n // We ALSO rebuild the matching `section_scoped_data[instanceUid].template`\n // (and repeater slot) using the fresh selectedField / uidRemapping /\n // parentRepeaterUID Studio just sent. Without this, SectionCompositionProvider\n // would keep rendering the stale pre-computed scoped data from fetchSpec\n // (which can be wrong on cold load if the UI node lacked\n // metadata.selectedField), because the provider prefers section_scoped_data\n // and never falls back to the legacy section_compositions slot when it\n // exists.\n const sectionContextsListener = composableStudioEventManager?.on<{\n sectionCompositions: Record<string, unknown>;\n }>(POST_MESSAGE_EVENTS.UPDATE_SECTION_CONTEXTS, (event) => {\n const { data } = event;\n if (!data?.sectionCompositions) return;\n // Merge key-by-key on top of SDK-seeded defaults. Studio only pushes\n // user-driven overrides for specific instance nodes; replacing the whole\n // slice would wipe the SDK's seeded baseline for all other instances.\n setState((prevState: StudioSpec) => {\n if (!prevState?.data) return prevState;\n const existing =\n (prevState.data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||\n {};\n // Per-uid merge preserves `cardinality` when an incoming entry lacks\n // it (mirrors the UPDATE_SPEC_DATA merge below). Cardinality is a\n // stable schema property; a push dropping it disables the\n // single-element item-identity scoping for repeater-nested sections\n // and the array→element collapse — the section blanks out.\n const merged: Record<string, any> = { ...existing };\n for (const [uid, incoming] of Object.entries(\n data.sectionCompositions,\n )) {\n const prev = existing[uid];\n merged[uid] =\n incoming &&\n typeof incoming === \"object\" &&\n (incoming as any).cardinality === undefined &&\n prev?.cardinality !== undefined\n ? { ...(incoming as any), cardinality: prev.cardinality }\n : incoming;\n }\n const mergedData = {\n ...prevState.data,\n dataSources: {\n ...prevState.data?.dataSources,\n [SECTION_COMPOSITIONS_KEY]: merged,\n },\n } as any;\n // Pass the MERGED entries for the incoming uids (not the raw incoming)\n // — rebuildScopedFromBindings spreads incomingBindings over the slice,\n // so raw entries would reintroduce the dropped cardinality.\n const incomingMerged = Object.fromEntries(\n Object.keys(data.sectionCompositions).map((uid) => [\n uid,\n merged[uid],\n ]),\n );\n const finalData = rebuildScopedFromBindings(mergedData, incomingMerged);\n return {\n ...prevState,\n data: finalData,\n };\n });\n });\n\n // Signal to Studio that our editor→iframe post-message listeners are now\n // in the handler map. Studio gates UPDATE_SPEC_DATA (and similar) on this\n // event because earlier readiness signals (SDK_SPEC_RESOLVED, INIT_STUDIO)\n // fire before EditableRenderer commits its first render and race against\n // the .on(...) calls above.\n composableStudioEventManager\n ?.send(POST_MESSAGE_EVENTS.LISTENERS_READY, { composableUid })\n .then(() => {})\n .catch(() => {\n // Studio may not have its LISTENERS_READY handler registered yet on\n // very first paint — the bridge resolves this via its message queue,\n // so a dropped first emit is harmless. Not an error worth surfacing.\n });\n\n return () => {\n applyOperationListener?.unregister();\n specDataChangeListener?.unregister();\n previewEntryChangeListener?.unregister();\n sectionContextsListener?.unregister();\n };\n // Deps deliberately exclude state.data — see stateRef above. Re-registering\n // on every data change creates a window where Studio's pushes are dropped\n // with NO_REQUEST_LISTENER_FOUND. We do re-register on composableUid change\n // (e.g. switching to a different composition without unmount); the\n // LISTENERS_READY emit above re-signals Studio after each rebind.\n }, [composableUid]);\n};\n"],"names":[],"mappings":";;;;;;;AAwBA;AACA;AACA;AACA;AACA;AACA,aAAa,CAAC,KAAK,CAAC;AAEpB;;;;;;;;AAQG;AACH,SAAS,mBAAmB,CAAC,IAAS,EAAA;AACpC,IAAA,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE;AACvC,IAAA,cAAc,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC;AACnC,IAAA,MAAM,KAAK,GAAG,CAAC,MAAW,KAAI;AAC5B,QAAA,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,IAAI,EAAE;QACjC,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;YACxC,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAA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,mBAAmB,CAAC,eAAe,EAAE,EAAE,aAAa,EAAE;AAC5D,aAAA,IAAI,CAAC,MAAK,EAAE,CAAC;aACb,KAAK,CAAC,MAAK;;;;AAIZ,QAAA,CAAC,CAAC;AAEJ,QAAA,OAAO,MAAK;YACV,sBAAsB,EAAE,UAAU,EAAE;YACpC,sBAAsB,EAAE,UAAU,EAAE;YACpC,0BAA0B,EAAE,UAAU,EAAE;YACxC,uBAAuB,EAAE,UAAU,EAAE;AACvC,QAAA,CAAC;;;;;;AAMH,IAAA,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;AACrB;;;;"}
|
|
1
|
+
{"version":3,"file":"use-spec-data-listener.hook.js","sources":["../../src/hooks/use-spec-data-listener.hook.ts"],"sourcesContent":["import {\n isCompositionBeingEdited,\n StudioSpec,\n applyOperation,\n SECTION_COMPOSITIONS_KEY,\n clientRendererModeUtil,\n NODE_TO_PARENT,\n NODE_TO_PATH_NODE,\n SectionCompositionEntry,\n} from \"@contentstack/studio-client\";\nimport { Operation } from \"@contentstack/studio-internal\";\nimport {\n composableStudioEventManager,\n POST_MESSAGE_EVENTS,\n} from \"@contentstack/studio-messenger\";\nimport {\n StudioSpecData,\n DataSourceItem,\n DATA_SOURCES_PREFIX,\n} from \"@contentstack/studio-registry\";\nimport { seedSectionInstanceBindings } from \"@contentstack/studio-react-components/utils\";\nimport { useEffect, useRef } from \"react\";\nimport { Immer } from \"immer\";\n\n// Immer freezes what it produces, but metadata-binding resolution (currently\n// just styles) writes onto the produced node afterwards, which throws on frozen\n// state — so this module needs a non-freezing `produce`. Scoped to an isolated\n// instance rather than the global `setAutoFreeze(false)`: this is a published\n// package, and the global switch would silently remove the mutation guard for\n// the consuming app's own Immer usage.\nconst { produce } = new Immer({ autoFreeze: false });\n\n/**\n * Walk a fresh UI tree (post-Immer-produce) and populate the NODE_TO_PARENT\n * and NODE_TO_PATH_NODE WeakMaps for every node. These maps are normally\n * populated during React render (in Element.tsx). After APPLY_OPERATION\n * produces a brand-new tree via Immer, the maps still hold entries for\n * stale node refs — `findPath` (used to compute hover/highlight paths sent\n * back to Studio) returns stale paths until the next React commit. Calling\n * this immediately after applyOperation closes that window.\n */\nfunction refreshNodeWeakMaps(root: any): void {\n if (!root || typeof root !== \"object\") return;\n NODE_TO_PARENT.set(root, undefined);\n const visit = (parent: any) => {\n const slots = parent?.slots || {};\n for (const slotUid of Object.keys(slots)) {\n const children = slots[slotUid] || [];\n for (let idx = 0; idx < children.length; idx++) {\n const child = children[idx];\n if (!child || typeof child !== \"object\") continue;\n NODE_TO_PARENT.set(child, parent);\n NODE_TO_PATH_NODE.set(child, [slotUid, idx] as any);\n visit(child);\n }\n }\n };\n visit(root);\n}\n\nexport const useSpecDataListener = (\n setState: React.Dispatch<React.SetStateAction<StudioSpec>>,\n // Read into `stateRef` only — listener bodies use `stateRef.current` (not\n // `state` directly) so the effect's deps don't include `state.data`, which\n // would force re-register on every data change and create a window with\n // zero handlers between unregister/re-register (the original\n // `NO_REQUEST_LISTENER_FOUND` cause).\n state?: StudioSpec,\n composableUid?: string,\n) => {\n // Keep a ref to the latest state so the listener registrations don't have\n // to depend on state.data — they can read latest via stateRef.current\n // synchronously. Without this, every state.data change tore down + re-registered\n // the listeners, creating a window where Studio's UPDATE_SECTION_CONTEXTS\n // message was dropped with NO_REQUEST_LISTENER_FOUND.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Rebuild section_scoped_data entries for instances whose binding metadata\n // (selectedField / uidRemapping / parentRepeaterUID) is present in the\n // legacy section_compositions slice. Mirrors build-scoped-data.ts logic\n // inline so the hook can rebuild without re-running the full fetchSpec\n // pipeline. Needed because Studio's fresh per-instance bindings arrive via\n // UPDATE_SPEC_DATA (and UPDATE_SECTION_CONTEXTS), while the provider only\n // reads from section_scoped_data — without this rebuild, sections render\n // the stale pre-computed scope from the initial fetchSpec (selectedField\n // missing from UI metadata on cold load → scoped template = whole page\n // template → placeholder text).\n const rebuildScopedFromBindings = (\n prevData: any,\n incomingBindings?: Record<string, unknown>,\n ): any => {\n const dataSources = prevData?.dataSources || {};\n const sectionBindings: Record<string, any> =\n incomingBindings && Object.keys(incomingBindings).length\n ? {\n ...(dataSources[SECTION_COMPOSITIONS_KEY] || {}),\n ...incomingBindings,\n }\n : dataSources[SECTION_COMPOSITIONS_KEY] || {};\n\n const pageTemplate = dataSources.template;\n\n /**\n * The document an instance's section data lives in (ADR 0017).\n *\n * The editor re-scopes every section from `dataSources.template` — the page\n * template entry. A FREEFORM page has none, so a section whose Section data\n * points at a pinned entry or a query resolved to `undefined` here and\n * rendered component defaults, even though the binding was stored\n * correctly and the fetch/cold-load path (build-scoped-data) resolved it\n * fine. This is the same hardcoded-anchor bug, in the live editor path.\n */\n const resolveFetchRootDocument = (fetchRootKey?: string): unknown => {\n if (!fetchRootKey || fetchRootKey === \"template\") return pageTemplate;\n if (fetchRootKey.startsWith(\"query:\")) {\n const qUid = fetchRootKey.slice(\"query:\".length);\n return (dataSources.contentstack_queries || {})[qUid];\n }\n // `<ct>:<uid>` — the same composite key the contentstack resolver uses.\n return (dataSources.contentstack || {})[fetchRootKey];\n };\n /**\n * Reference stubs, followed to their pooled entry — the step this scoper was\n * missing entirely (the fetch path's `build-scoped-data` has it at every\n * traversal step).\n *\n * CDA returns `{uid, _content_type_uid}` at a reference field unless the\n * request included it, and Studio's read funnel pools the resolved entry\n * separately under its `<ct>:<uid>` key. Without following the stub, a\n * Section data whose path CROSSES a reference resolved to the stub object:\n * the section's own fields were absent from it, so the canvas rendered\n * component defaults while the deployed site — which does follow — was\n * correct (COMS-2031: DR5.5, and the wrapper half of DR7.4).\n */\n const META_KEYS = new Set([\n \"uid\",\n \"_content_type_uid\",\n \"_version\",\n \"locale\",\n \"ACL\",\n \"_metadata\",\n // Live-preview edit tags. The Preview service stamps `$` onto every entry\n // and reference stub in the editor, so a bare stub arrives as\n // `{uid, _content_type_uid, $}` — three keys, one of which used to read as\n // \"this stub already carries a payload\". The stub was then handed back\n // unfollowed and a Section data whose path crosses a reference resolved to\n // the stub instead of the entry (E2E DR7.4). Metadata, never content.\n \"$\",\n ]);\n const followReference = (v: any): any => {\n if (\n !v ||\n typeof v !== \"object\" ||\n Array.isArray(v) ||\n typeof v.uid !== \"string\" ||\n typeof v._content_type_uid !== \"string\"\n ) {\n return v;\n }\n // CDA may already have inlined the entry into the stub object; anything\n // beyond the meta keys means it is resolved already.\n if (Object.keys(v).some((k) => !META_KEYS.has(k))) return v;\n const resolved = (dataSources.contentstack || {})[\n `${v._content_type_uid}:${v.uid}`\n ];\n return resolved !== undefined ? resolved : v;\n };\n const followAll = (v: any): any =>\n Array.isArray(v) ? v.map(followReference) : followReference(v);\n\n const prevScoped = prevData?.section_scoped_data || {};\n const nextScoped: Record<string, any> = { ...prevScoped };\n\n const getScopedData = (obj: any, selectedField?: string): any => {\n if (!selectedField) return followAll(obj);\n const traversed = selectedField\n .split(\".\")\n .reduce((val: any, seg: string) => {\n if (val == null) return val;\n // Swap a stub for its resolved entry BEFORE drilling into it.\n val = followReference(val);\n const arrayMatch = seg.match(/^(.*?)\\[(\\d+)\\]$/);\n if (arrayMatch) {\n const [, name, idxStr] = arrayMatch;\n const next = name ? val[name] : val;\n return next == null ? next : followReference(next[Number(idxStr)]);\n }\n // A bare NUMERIC segment is an array index. Contentstack bindings\n // encode one as a plain segment (`page_sections.17.keynote_speakers`)\n // rather than bracket notation, so this must precede the\n // array→first-element fallback below, which would otherwise look `17`\n // up as a key on element [0].\n if (Array.isArray(val) && /^\\d+$/.test(seg)) {\n return followReference(val[Number(seg)]);\n }\n // Non-indexed field access landing on an ARRAY → default to the first\n // element so an un-indexed array-ancestor path (e.g.\n // \"navigation_menu_3.menu_subitems\", where navigation_menu_3 is a\n // multiple group) still resolves instead of `array[field]` →\n // undefined → null. Indexed pushes (`navigation_menu_3[1]…`) override\n // this with the picked instance.\n if (Array.isArray(val)) {\n const first = followReference(val[0]);\n return first == null ? null : followReference(first[seg]);\n }\n return followReference(val[seg]);\n }, obj);\n return (\n (Array.isArray(traversed) ? followAll(traversed) : traversed) ?? null\n );\n };\n\n const applyUidRemapping = (\n scoped: any,\n uidRemapping: Record<string, string> = {},\n ): any => {\n if (\n !scoped ||\n typeof scoped !== \"object\" ||\n Object.keys(uidRemapping).length === 0\n ) {\n return scoped;\n }\n if (Array.isArray(scoped)) {\n return scoped.map((item: any) => applyUidRemapping(item, uidRemapping));\n }\n const remapped: Record<string, unknown> = {};\n const pageKeyValues = new Set(Object.values(uidRemapping));\n for (const [sectionKey, pageKey] of Object.entries(uidRemapping)) {\n remapped[sectionKey] = applyUidRemapping(scoped[pageKey], uidRemapping);\n }\n for (const key of Object.keys(scoped)) {\n if (!pageKeyValues.has(key) && !(key in uidRemapping)) {\n remapped[key] = applyUidRemapping(scoped[key], uidRemapping);\n }\n }\n return remapped;\n };\n\n let changed = false;\n for (const [instanceUid, bindingUnknown] of Object.entries(\n sectionBindings,\n )) {\n const binding = bindingUnknown as {\n selectedField?: string;\n uidRemapping?: Record<string, string>;\n parentRepeaterUID?: string | null;\n context?: unknown;\n componentPropsFallback?: Record<string, unknown>;\n cardinality?: \"collection\" | \"single\";\n expectsSingleDocument?: boolean;\n };\n // Skip context-only legacy shape — no selectedField to re-scope from.\n if (binding && \"context\" in binding && !(\"selectedField\" in binding)) {\n continue;\n }\n // A non-template fetch root carries its own in-document path; the\n // legacy `selectedField` is a page-template path and does not apply.\n const fetchRootKey = (binding as { fetchRootKey?: string })?.fetchRootKey;\n const fetchRootPrefix = (binding as { fetchRootPrefix?: string[] })\n ?.fetchRootPrefix;\n const usesPageTemplate = !fetchRootKey || fetchRootKey === \"template\";\n const rootDocument = resolveFetchRootDocument(fetchRootKey);\n const rootScopePath = usesPageTemplate\n ? binding?.selectedField\n : fetchRootPrefix?.join(\".\");\n\n let scopedTemplate = applyUidRemapping(\n getScopedData(rootDocument, rootScopePath),\n binding?.uidRemapping,\n );\n // Single-element section: `selectedField` stays index-free, so an\n // un-indexed terminal array resolves to the WHOLE array. Collapse to the\n // first element (the deploy default — the preview instance is session-only)\n // so the bound field resolves live, without depending on a save+reload\n // running the cold-load scoper. Mirrors build-scoped-data.ts. When the\n // path is already indexed (`menu_items[0]`, from Studio's push),\n // getScopedData returns the element and this is a no-op.\n if (binding?.cardinality === \"single\" && Array.isArray(scopedTemplate)) {\n scopedTemplate = scopedTemplate[0] ?? null;\n }\n // A CT-anchored section is ONE document. When its scope reached it through\n // a REFERENCE — a wrapper pinned at `settings_ref` rebasing its slot\n // children (ADR 0017) — CDA's array arrives instead of the entry, and the\n // section's own fields are not on an array. Collapse to the document.\n if (\n (binding as { expectsSingleDocument?: boolean })\n ?.expectsSingleDocument &&\n Array.isArray(scopedTemplate)\n ) {\n scopedTemplate = scopedTemplate[0] ?? null;\n }\n let repeater: Record<string, { context: unknown }> | undefined;\n if (binding?.parentRepeaterUID) {\n const ctx = dataSources.repeater?.[binding.parentRepeaterUID];\n if (ctx !== undefined) {\n repeater = { [binding.parentRepeaterUID]: ctx };\n }\n }\n const prev = prevScoped[instanceUid] || {};\n // Refresh contentstack / contentstack_queries from the live page\n // dataSources every time we rebuild. The initial scoped data built\n // during fetchSpec may have stale (or empty) entries because the\n // iframe loaded with getSpecFromParent and never fetched the section's\n // data sources itself — the studio pushes them later via\n // UPDATE_SPEC_DATA. Pool-keyed maps would be ideal but the listener\n // doesn't have access to them; copying the full page slice is a safe\n // superset (same composite-key format the resolver expects).\n const refreshedContentstack =\n dataSources.contentstack && typeof dataSources.contentstack === \"object\"\n ? { ...dataSources.contentstack }\n : prev.contentstack || {};\n const refreshedQueries =\n dataSources.contentstack_queries &&\n typeof dataSources.contentstack_queries === \"object\"\n ? { ...dataSources.contentstack_queries }\n : prev.contentstack_queries || {};\n\n const next = {\n ...prev,\n template: scopedTemplate,\n contentstack: refreshedContentstack,\n contentstack_queries: refreshedQueries,\n page: dataSources,\n repeater: repeater ?? prev.repeater,\n // Carry binding metadata so SectionCompositionProvider can re-scope the\n // template from the LIVE per-iteration repeater item. The scopedTemplate\n // above is page-root-scoped and shared across every iteration of this\n // instance, so it can't represent per-iteration values on its own.\n parentRepeaterUID: binding?.parentRepeaterUID ?? null,\n selectedField: binding?.selectedField,\n fetchRootKey,\n fetchRootPrefix,\n uidRemapping: binding?.uidRemapping,\n cardinality: binding?.cardinality,\n componentPropsFallback: binding?.componentPropsFallback,\n };\n if (\n prev.template !== next.template ||\n prev.page !== next.page ||\n prev.repeater !== next.repeater ||\n prev.contentstack !== next.contentstack ||\n prev.contentstack_queries !== next.contentstack_queries ||\n prev.componentPropsFallback !== next.componentPropsFallback\n ) {\n nextScoped[instanceUid] = next;\n changed = true;\n }\n }\n if (!changed) return prevData;\n return { ...prevData, section_scoped_data: nextScoped };\n };\n\n // Self-heal when the section catalog arrives after the initial seed.\n // `sectionCompositions` (each section's `linked_schemas` + authored UI) is\n // fetched asynchronously (GET_SECTIONS / UPDATE_SECTIONS_CATALOG) and can land\n // AFTER the first `seedSectionInstanceBindings` run (on GET_COMPOSITION_SPEC).\n // A root section seeded without the catalog gets `selectedField=\"\"` → its\n // scoped template resolves to the whole page (renders the page root, e.g. the\n // page title, instead of its bound field) and stays wedged unless Studio's\n // UPDATE_SECTION_CONTEXTS push wins the race. This is especially visible after\n // a preview-entry switch, which re-navigates the canvas iframe (a fresh cold\n // load). Re-run the seeder — which now heals empty root scopes from the\n // freshly-available `linked_schemas` — and rebuild `section_scoped_data` so the\n // render picks up the corrected scope without depending on the timing of\n // Studio's push. No-op when the seeder heals nothing (`seeded === prev`), so\n // working specs are unaffected and this can't loop.\n useEffect(() => {\n // Editor-only heal — mirror every other effect in this hook, which\n // early-returns outside the Studio frame. No reason to re-seed/commit in a\n // standalone or published render.\n if (!clientRendererModeUtil.isInsideStudioFrame()) return;\n if (!state?.sectionCompositions?.length) return;\n setState((prev: StudioSpec) => {\n if (!prev?.ui || !prev?.data) return prev;\n const seeded = seedSectionInstanceBindings(prev);\n // Gate the rebuild + commit on the seeder's own no-op signal.\n // `rebuildScopedFromBindings` re-spreads the live `contentstack` /\n // `contentstack_queries` slices on every call, so for a page that has\n // sections it never returns its input unchanged — testing its result\n // would commit a fresh state (extra render + full scoped rebuild) on\n // every `sectionCompositions` ref change (Studio re-pushes the catalog on\n // refetch/refocus), not just when a cold-load scope actually heals.\n if (seeded === prev) return prev;\n return { ...seeded, data: rebuildScopedFromBindings(seeded.data) };\n });\n // Re-run whenever EITHER input the root-scope heal depends on lands:\n // • `sectionCompositions` — the section catalog (`linked_schemas`), and\n // • `connected_content_type` — the page CT that selects which linked\n // schema supplies the anchor field.\n // Both arrive asynchronously after a (re)load and in either order; keying on\n // only one leaves a race where the heal runs before the other is present,\n // computes an empty scope, and never retries — re-wedging the section.\n // The setState above changes neither dep, so this can't self-trigger.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n state?.sectionCompositions,\n (state?.compositionEntry as any)?.connected_content_type,\n ]);\n\n // HOOK TO UPDATE THE STATE WITH THE LATEST SPEC DATA\n // Listeners are registered as soon as we're inside the Studio frame, before\n // spec has been fetched. Studio decides when to push UPDATE_SECTION_CONTEXTS\n // and UPDATE_SPEC_DATA based on its own readiness signal; the SDK can't\n // gate on `isCompositionBeingEdited(composableUid)` because that requires the\n // spec — and the parent reaches \"ready\" before the SDK's setState effect\n // has propagated, producing NO_REQUEST_LISTENER_FOUND.\n // The handlers themselves still defensively check `stateRef.current?.data`\n // before acting, so registering early is safe.\n useEffect(() => {\n if (!clientRendererModeUtil.isInsideStudioFrame()) return;\n const specDataChangeListener =\n composableStudioEventManager?.on<StudioSpecData>(\n POST_MESSAGE_EVENTS.UPDATE_SPEC_DATA,\n async (event) => {\n const { data } = event;\n if (!data || !stateRef.current?.data) return;\n\n setState((state: StudioSpec) => {\n if (!state) return state;\n // Merge incoming over existing — never replace dataSources\n // wholesale. Studio's UPDATE_SPEC_DATA pushes can carry only\n // a subset of slices (e.g., only `template` + `section_compositions`),\n // and a naive overwrite would wipe slices the SDK relied on\n // (e.g., the `repeater` item context populated earlier from\n // preview data resolution). Result was a visible flicker as\n // sections inside a Repeater suddenly lost their item context.\n // Also merge section_compositions key-by-key so SDK-seeded\n // per-instance bindings survive when Studio's push is partial.\n const incomingSections =\n (data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] || {};\n const existingSections =\n (state.data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||\n {};\n // Per-uid merge preserves `cardinality` when the incoming entry\n // lacks it — cardinality is a stable schema property, and a stale\n // push dropping it would disable the single-element array→element\n // collapse in rebuildScopedFromBindings (section blanks out).\n const mergedSections: Record<string, any> = {\n ...existingSections,\n };\n for (const [uid, incoming] of Object.entries(incomingSections)) {\n const prev = existingSections[uid];\n mergedSections[uid] =\n incoming &&\n typeof incoming === \"object\" &&\n (incoming as any).cardinality === undefined &&\n prev?.cardinality !== undefined\n ? { ...(incoming as any), cardinality: prev.cardinality }\n : incoming;\n }\n const mergedDataSources = {\n ...((state.data as any)?.dataSources || {}),\n ...((data as any)?.dataSources || {}),\n [SECTION_COMPOSITIONS_KEY]: mergedSections,\n };\n const mergedData = {\n ...state.data,\n ...data,\n dataSources: mergedDataSources,\n };\n const rebuilt = rebuildScopedFromBindings(mergedData);\n return {\n ...state,\n data: rebuilt,\n };\n });\n },\n );\n\n const previewEntryChangeListener = composableStudioEventManager?.on<{\n dataSources: DataSourceItem[];\n }>(POST_MESSAGE_EVENTS.REPLACE_PREVIEW_ENTRY, async (event) => {\n const { data } = event;\n if (!data?.dataSources || !stateRef.current?.data) return;\n\n setState((prevState: StudioSpec) => {\n if (!prevState) return prevState;\n // REPLACE_PREVIEW_ENTRY pushes dataSources for the preview-entry change\n // (typically just `template`/`contentstack` slices). Merge into existing\n // dataSources — don't wipe sibling slices like `repeater` or\n // `section_compositions`, which would cause a flicker for sections\n // inside a Repeater (their item context would disappear).\n const mergedData = {\n ...prevState?.data,\n [DATA_SOURCES_PREFIX]: {\n ...((prevState?.data as any)?.[DATA_SOURCES_PREFIX] || {}),\n ...(data?.dataSources as any),\n },\n };\n // The merge updates dataSources.template, but each section's SCOPED\n // template in section_scoped_data is derived from it — re-scope here,\n // else a section keeps its stale (often null) scope and renders the\n // empty placeholder after the preview entry is set/switched. (The\n // UPDATE_SPEC_DATA handler already rebuilds; this is the equivalent for\n // the preview-entry change path that EntryPickerBtn sends.)\n const rebuilt = rebuildScopedFromBindings(mergedData);\n return { ...prevState, data: rebuilt };\n });\n });\n\n const applyOperationListener = composableStudioEventManager?.on<{\n operations: Operation[];\n }>(POST_MESSAGE_EVENTS.APPLY_OPERATION, (event) => {\n const { data } = event;\n\n // Self-heal section catalog: if any op inserts a section-composition\n // node whose compositionUID isn't in the locally-known catalog\n // (race between Studio's section store hydration and the iframe's\n // initial GET_SECTIONS reply), re-fetch the catalog and merge.\n // Without this the section renders with \"Component … is not\n // registered\" until the page is saved + reloaded.\n const newSectionUids = new Set<string>();\n for (const op of data?.operations || []) {\n const node = (op as any)?.node;\n if (\n op &&\n (op as any).type === \"insert_node\" &&\n node &&\n typeof node === \"object\" &&\n node.type === \"section-composition\" &&\n typeof node.metadata?.compositionUID === \"string\"\n ) {\n newSectionUids.add(node.metadata.compositionUID as string);\n }\n }\n const known = new Set(\n (stateRef.current?.sectionCompositions || []).map(\n (s: SectionCompositionEntry) => s.uid,\n ),\n );\n const unknown = [...newSectionUids].filter((u) => !known.has(u));\n if (unknown.length > 0) {\n composableStudioEventManager\n ?.send<{ sectionCompositions: SectionCompositionEntry[] }>(\n POST_MESSAGE_EVENTS.GET_SECTIONS,\n {},\n )\n .then((resp) => {\n if (!resp?.sectionCompositions) return;\n setState((prevState: StudioSpec) => ({\n ...prevState,\n sectionCompositions: resp.sectionCompositions,\n }));\n })\n .catch(() => {});\n }\n\n setState((prevState: StudioSpec) => {\n if (!prevState?.ui || !data?.operations) return prevState;\n const newUI = produce(prevState.ui, (ui) => {\n const operations = data.operations;\n return applyOperation(ui, operations);\n });\n // Eagerly refresh the NODE_TO_PARENT / NODE_TO_PATH_NODE WeakMaps for\n // the new tree. These WeakMaps are otherwise only populated during\n // React render (Element.tsx) and `findPath` (used by hover/highlight\n // postMessages back to Studio) reads from them. Without this refresh\n // there is a window between APPLY_OPERATION and the next React commit\n // where mouse-move events emit paths derived from old node refs —\n // those paths don't exist in Studio's now-updated slate editor and\n // surface as \"Cannot find a descendant at path\" errors.\n refreshNodeWeakMaps(newUI as any);\n // Re-seed per-instance section bindings ONLY when the slate op might\n // have moved/inserted/removed a section-composition node. Property /\n // style / text-content ops can't change the section-instance graph,\n // so the seeder's full UI walk on those is wasted work. The seeder\n // itself is idempotent (it short-circuits when nothing mutated), but\n // skipping the walk altogether keeps interactive ops (typing, style\n // edits) cheap on large pages.\n const ops = data.operations as any[];\n const opAffectsSectionInstances = ops.some(\n (op) =>\n op?.type === \"insert_node\" ||\n op?.type === \"remove_node\" ||\n op?.type === \"move_node\" ||\n op?.type === \"merge_node\" ||\n op?.type === \"split_node\",\n );\n if (!opAffectsSectionInstances) {\n return { ...prevState, ui: newUI };\n }\n return seedSectionInstanceBindings({ ...prevState, ui: newUI });\n });\n });\n\n // Studio pushes only the section_compositions slice when section contexts\n // are recomputed (e.g. after a section node is added/moved/removed). We\n // patch just that slice on top of existing dataSources so other data\n // (template, contentstack, query results) isn't clobbered.\n //\n // We ALSO rebuild the matching `section_scoped_data[instanceUid].template`\n // (and repeater slot) using the fresh selectedField / uidRemapping /\n // parentRepeaterUID Studio just sent. Without this, SectionCompositionProvider\n // would keep rendering the stale pre-computed scoped data from fetchSpec\n // (which can be wrong on cold load if the UI node lacked\n // metadata.selectedField), because the provider prefers section_scoped_data\n // and never falls back to the legacy section_compositions slot when it\n // exists.\n const sectionContextsListener = composableStudioEventManager?.on<{\n sectionCompositions: Record<string, unknown>;\n }>(POST_MESSAGE_EVENTS.UPDATE_SECTION_CONTEXTS, (event) => {\n const { data } = event;\n if (!data?.sectionCompositions) return;\n // Merge key-by-key on top of SDK-seeded defaults. Studio only pushes\n // user-driven overrides for specific instance nodes; replacing the whole\n // slice would wipe the SDK's seeded baseline for all other instances.\n setState((prevState: StudioSpec) => {\n if (!prevState?.data) return prevState;\n const existing =\n (prevState.data as any)?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||\n {};\n // Per-uid merge preserves `cardinality` when an incoming entry lacks\n // it (mirrors the UPDATE_SPEC_DATA merge below). Cardinality is a\n // stable schema property; a push dropping it disables the\n // single-element item-identity scoping for repeater-nested sections\n // and the array→element collapse — the section blanks out.\n const merged: Record<string, any> = { ...existing };\n for (const [uid, incoming] of Object.entries(\n data.sectionCompositions,\n )) {\n const prev = existing[uid];\n merged[uid] =\n incoming &&\n typeof incoming === \"object\" &&\n (incoming as any).cardinality === undefined &&\n prev?.cardinality !== undefined\n ? { ...(incoming as any), cardinality: prev.cardinality }\n : incoming;\n }\n const mergedData = {\n ...prevState.data,\n dataSources: {\n ...prevState.data?.dataSources,\n [SECTION_COMPOSITIONS_KEY]: merged,\n },\n } as any;\n // Pass the MERGED entries for the incoming uids (not the raw incoming)\n // — rebuildScopedFromBindings spreads incomingBindings over the slice,\n // so raw entries would reintroduce the dropped cardinality.\n const incomingMerged = Object.fromEntries(\n Object.keys(data.sectionCompositions).map((uid) => [\n uid,\n merged[uid],\n ]),\n );\n const finalData = rebuildScopedFromBindings(mergedData, incomingMerged);\n return {\n ...prevState,\n data: finalData,\n };\n });\n });\n\n // Signal to Studio that our editor→iframe post-message listeners are now\n // in the handler map. Studio gates UPDATE_SPEC_DATA (and similar) on this\n // event because earlier readiness signals (SDK_SPEC_RESOLVED, INIT_STUDIO)\n // fire before EditableRenderer commits its first render and race against\n // the .on(...) calls above.\n composableStudioEventManager\n ?.send(POST_MESSAGE_EVENTS.LISTENERS_READY, { composableUid })\n .then(() => {})\n .catch(() => {\n // Studio may not have its LISTENERS_READY handler registered yet on\n // very first paint — the bridge resolves this via its message queue,\n // so a dropped first emit is harmless. Not an error worth surfacing.\n });\n\n return () => {\n applyOperationListener?.unregister();\n specDataChangeListener?.unregister();\n previewEntryChangeListener?.unregister();\n sectionContextsListener?.unregister();\n };\n // Deps deliberately exclude state.data — see stateRef above. Re-registering\n // on every data change creates a window where Studio's pushes are dropped\n // with NO_REQUEST_LISTENER_FOUND. We do re-register on composableUid change\n // (e.g. switching to a different composition without unmount); the\n // LISTENERS_READY emit above re-signals Studio after each rebind.\n }, [composableUid]);\n};\n"],"names":[],"mappings":";;;;;;;AAwBA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,KAAK,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AAEpD;;;;;;;;AAQG;AACH,SAAS,mBAAmB,CAAC,IAAS,EAAA;AACpC,IAAA,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE;AACvC,IAAA,cAAc,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC;AACnC,IAAA,MAAM,KAAK,GAAG,CAAC,MAAW,KAAI;AAC5B,QAAA,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,IAAI,EAAE;QACjC,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;YACxC,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE;AACrC,YAAA,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,QAAQ,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;AAC9C,gBAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC;AAC3B,gBAAA,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;oBAAE;AACzC,gBAAA,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC;gBACjC,iBAAiB,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,GAAG,CAAQ,CAAC;gBACnD,KAAK,CAAC,KAAK,CAAC;YACd;QACF;AACF,IAAA,CAAC;IACD,KAAK,CAAC,IAAI,CAAC;A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AAE,WAAW,EAAE,IAAI,CAAC,WAAW;8BACrD,QAAQ;gBAChB;AACA,gBAAA,MAAM,UAAU,GAAG;oBACjB,GAAG,SAAS,CAAC,IAAI;AACjB,oBAAA,WAAW,EAAE;AACX,wBAAA,GAAG,SAAS,CAAC,IAAI,EAAE,WAAW;wBAC9B,CAAC,wBAAwB,GAAG,MAAM;AACnC,qBAAA;iBACK;;;;gBAIR,MAAM,cAAc,GAAG,MAAM,CAAC,WAAW,CACvC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK;oBACjD,GAAG;oBACH,MAAM,CAAC,GAAG,CAAC;AACZ,iBAAA,CAAC,CACH;gBACD,MAAM,SAAS,GAAG,yBAAyB,CAAC,UAAU,EAAE,cAAc,CAAC;gBACvE,OAAO;AACL,oBAAA,GAAG,SAAS;AACZ,oBAAA,IAAI,EAAE,SAAS;iBAChB;AACH,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;;;;;;QAOF;cACI,IAAI,CAAC,mBAAmB,CAAC,eAAe,EAAE,EAAE,aAAa,EAAE;AAC5D,aAAA,IAAI,CAAC,MAAK,EAAE,CAAC;aACb,KAAK,CAAC,MAAK;;;;AAIZ,QAAA,CAAC,CAAC;AAEJ,QAAA,OAAO,MAAK;YACV,sBAAsB,EAAE,UAAU,EAAE;YACpC,sBAAsB,EAAE,UAAU,EAAE;YACpC,0BAA0B,EAAE,UAAU,EAAE;YACxC,uBAAuB,EAAE,UAAU,EAAE;AACvC,QAAA,CAAC;;;;;;AAMH,IAAA,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC;AACrB;;;;"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One shared watcher for "the page behind the chrome may have changed".
|
|
3
|
+
*
|
|
4
|
+
* Studio chrome picks its colours by measuring the customer's page once, when
|
|
5
|
+
* it mounts. That is wrong the moment the page changes underneath it: a host
|
|
6
|
+
* with its own dark-mode toggle flips the background and leaves the chrome
|
|
7
|
+
* holding a colour chosen for the old one, which measures as low as 1.05:1
|
|
8
|
+
* against the new — invisible rather than merely dimmed.
|
|
9
|
+
*
|
|
10
|
+
* The cost of being right is small. A full re-measure of every line of chrome
|
|
11
|
+
* on a page takes well under a frame, so there is no need to be clever about
|
|
12
|
+
* which elements are affected: on any signal, everything measures again.
|
|
13
|
+
*
|
|
14
|
+
* One observer serves every subscriber. A page can hold a great many empty
|
|
15
|
+
* slots, and an observer each would be a real cost for no benefit.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Attributes worth watching. A theme swap lands on one of these — a class on
|
|
19
|
+
* `<html>` or `<body>`, an inline style, or a data attribute that CSS keys off.
|
|
20
|
+
*/
|
|
21
|
+
const THEME_ATTRIBUTES = ["class", "style", "data-theme", "data-mode"];
|
|
22
|
+
const listeners = new Set();
|
|
23
|
+
let observer = null;
|
|
24
|
+
let colorScheme = null;
|
|
25
|
+
let pending = false;
|
|
26
|
+
/** Collapse a burst of mutations into one pass — a theme swap touches many nodes. */
|
|
27
|
+
function scheduleNotify() {
|
|
28
|
+
if (pending)
|
|
29
|
+
return;
|
|
30
|
+
pending = true;
|
|
31
|
+
const run = () => {
|
|
32
|
+
pending = false;
|
|
33
|
+
for (const listener of [...listeners])
|
|
34
|
+
listener();
|
|
35
|
+
};
|
|
36
|
+
if (typeof requestAnimationFrame === "function")
|
|
37
|
+
requestAnimationFrame(run);
|
|
38
|
+
else
|
|
39
|
+
setTimeout(run, 0);
|
|
40
|
+
}
|
|
41
|
+
function start() {
|
|
42
|
+
if (observer || typeof window === "undefined")
|
|
43
|
+
return;
|
|
44
|
+
observer = new MutationObserver(scheduleNotify);
|
|
45
|
+
observer.observe(document.documentElement, {
|
|
46
|
+
attributes: true,
|
|
47
|
+
attributeFilter: THEME_ATTRIBUTES,
|
|
48
|
+
subtree: true,
|
|
49
|
+
});
|
|
50
|
+
// A host that follows the OS rather than a toggle changes on this instead,
|
|
51
|
+
// without any attribute moving.
|
|
52
|
+
colorScheme = window.matchMedia?.("(prefers-color-scheme: dark)") ?? null;
|
|
53
|
+
colorScheme?.addEventListener?.("change", scheduleNotify);
|
|
54
|
+
}
|
|
55
|
+
function stop() {
|
|
56
|
+
observer?.disconnect();
|
|
57
|
+
observer = null;
|
|
58
|
+
colorScheme?.removeEventListener?.("change", scheduleNotify);
|
|
59
|
+
colorScheme = null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Calls `onChange` whenever the page behind the chrome may have changed colour.
|
|
63
|
+
*
|
|
64
|
+
* @returns an unsubscribe function. The shared observer starts with the first
|
|
65
|
+
* subscriber and is torn down when the last one leaves, so an idle page runs
|
|
66
|
+
* nothing.
|
|
67
|
+
*/
|
|
68
|
+
function watchBackdropChanges(onChange) {
|
|
69
|
+
listeners.add(onChange);
|
|
70
|
+
start();
|
|
71
|
+
return () => {
|
|
72
|
+
listeners.delete(onChange);
|
|
73
|
+
if (listeners.size === 0)
|
|
74
|
+
stop();
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export { watchBackdropChanges };
|
|
79
|
+
//# sourceMappingURL=backdrop-watcher.util.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backdrop-watcher.util.js","sources":["../../src/utils/backdrop-watcher.util.ts"],"sourcesContent":["/**\n * One shared watcher for \"the page behind the chrome may have changed\".\n *\n * Studio chrome picks its colours by measuring the customer's page once, when\n * it mounts. That is wrong the moment the page changes underneath it: a host\n * with its own dark-mode toggle flips the background and leaves the chrome\n * holding a colour chosen for the old one, which measures as low as 1.05:1\n * against the new — invisible rather than merely dimmed.\n *\n * The cost of being right is small. A full re-measure of every line of chrome\n * on a page takes well under a frame, so there is no need to be clever about\n * which elements are affected: on any signal, everything measures again.\n *\n * One observer serves every subscriber. A page can hold a great many empty\n * slots, and an observer each would be a real cost for no benefit.\n */\n\ntype BackdropListener = () => void;\n\n/**\n * Attributes worth watching. A theme swap lands on one of these — a class on\n * `<html>` or `<body>`, an inline style, or a data attribute that CSS keys off.\n */\nconst THEME_ATTRIBUTES = [\"class\", \"style\", \"data-theme\", \"data-mode\"];\n\nconst listeners = new Set<BackdropListener>();\nlet observer: MutationObserver | null = null;\nlet colorScheme: MediaQueryList | null = null;\nlet pending = false;\n\n/** Collapse a burst of mutations into one pass — a theme swap touches many nodes. */\nfunction scheduleNotify(): void {\n if (pending) return;\n pending = true;\n const run = (): void => {\n pending = false;\n for (const listener of [...listeners]) listener();\n };\n if (typeof requestAnimationFrame === \"function\") requestAnimationFrame(run);\n else setTimeout(run, 0);\n}\n\nfunction start(): void {\n if (observer || typeof window === \"undefined\") return;\n\n observer = new MutationObserver(scheduleNotify);\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: THEME_ATTRIBUTES,\n subtree: true,\n });\n\n // A host that follows the OS rather than a toggle changes on this instead,\n // without any attribute moving.\n colorScheme = window.matchMedia?.(\"(prefers-color-scheme: dark)\") ?? null;\n colorScheme?.addEventListener?.(\"change\", scheduleNotify);\n}\n\nfunction stop(): void {\n observer?.disconnect();\n observer = null;\n colorScheme?.removeEventListener?.(\"change\", scheduleNotify);\n colorScheme = null;\n}\n\n/**\n * Calls `onChange` whenever the page behind the chrome may have changed colour.\n *\n * @returns an unsubscribe function. The shared observer starts with the first\n * subscriber and is torn down when the last one leaves, so an idle page runs\n * nothing.\n */\nexport function watchBackdropChanges(onChange: BackdropListener): () => void {\n listeners.add(onChange);\n start();\n\n return () => {\n listeners.delete(onChange);\n if (listeners.size === 0) stop();\n };\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;AAeG;AAIH;;;AAGG;AACH,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,CAAC;AAEtE,MAAM,SAAS,GAAG,IAAI,GAAG,EAAoB;AAC7C,IAAI,QAAQ,GAA4B,IAAI;AAC5C,IAAI,WAA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