@contentstack/studio-react-editor 1.2.0 → 1.3.1

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.
Files changed (53) hide show
  1. package/dist/components/BuildingIllustration.js +8 -0
  2. package/dist/components/BuildingIllustration.js.map +1 -0
  3. package/dist/components/EditableRenderer.js +29 -6
  4. package/dist/components/EditableRenderer.js.map +1 -1
  5. package/dist/components/Element.js +61 -29
  6. package/dist/components/Element.js.map +1 -1
  7. package/dist/components/PreviewRenderer.js +4 -0
  8. package/dist/components/PreviewRenderer.js.map +1 -1
  9. package/dist/components/Slot.js +31 -4
  10. package/dist/components/Slot.js.map +1 -1
  11. package/dist/components/WelcomeState.js +33 -0
  12. package/dist/components/WelcomeState.js.map +1 -0
  13. package/dist/components/elements/ConditionBlock.js +4 -0
  14. package/dist/components/elements/ConditionBlock.js.map +1 -1
  15. package/dist/components/elements/Repeater.js +24 -7
  16. package/dist/components/elements/Repeater.js.map +1 -1
  17. package/dist/components/elements/SectionComposition.js +94 -0
  18. package/dist/components/elements/SectionComposition.js.map +1 -0
  19. package/dist/components/elements/SectionSlot.js +154 -0
  20. package/dist/components/elements/SectionSlot.js.map +1 -0
  21. package/dist/components/elements/Symbol.js +6 -2
  22. package/dist/components/elements/Symbol.js.map +1 -1
  23. package/dist/components/styles.js +85 -0
  24. package/dist/components/styles.js.map +1 -1
  25. package/dist/contexts/providers/renderer.provider.js +1 -0
  26. package/dist/contexts/providers/renderer.provider.js.map +1 -1
  27. package/dist/contexts/providers/symbol-ui.provider.js +18 -6
  28. package/dist/contexts/providers/symbol-ui.provider.js.map +1 -1
  29. package/dist/hooks/use-active-node-path.hook.js +5 -1
  30. package/dist/hooks/use-active-node-path.hook.js.map +1 -1
  31. package/dist/hooks/use-canvas-events.hook.js +7 -2
  32. package/dist/hooks/use-canvas-events.hook.js.map +1 -1
  33. package/dist/hooks/use-condition-block-context.js +5 -1
  34. package/dist/hooks/use-condition-block-context.js.map +1 -1
  35. package/dist/hooks/use-design-preview.hook.js +5 -1
  36. package/dist/hooks/use-design-preview.hook.js.map +1 -1
  37. package/dist/hooks/use-preview-mode.hook.js +5 -1
  38. package/dist/hooks/use-preview-mode.hook.js.map +1 -1
  39. package/dist/hooks/use-register-section.hook.js +110 -0
  40. package/dist/hooks/use-register-section.hook.js.map +1 -0
  41. package/dist/hooks/use-renderer.hook.js +5 -1
  42. package/dist/hooks/use-renderer.hook.js.map +1 -1
  43. package/dist/hooks/use-repeater.hook.js +5 -1
  44. package/dist/hooks/use-repeater.hook.js.map +1 -1
  45. package/dist/hooks/use-section-events.hook.js +63 -0
  46. package/dist/hooks/use-section-events.hook.js.map +1 -0
  47. package/dist/hooks/use-should-show-design.hook.js +8 -1
  48. package/dist/hooks/use-should-show-design.hook.js.map +1 -1
  49. package/dist/hooks/use-spec-data-listener.hook.js +335 -10
  50. package/dist/hooks/use-spec-data-listener.hook.js.map +1 -1
  51. package/dist/hooks/use-symbol-events.hook.js +13 -0
  52. package/dist/hooks/use-symbol-events.hook.js.map +1 -1
  53. package/package.json +11 -11
@@ -1,7 +1,8 @@
1
- import { isCompositionBeingEdited, applyOperation } from '@contentstack/studio-client';
1
+ import { clientRendererModeUtil, SECTION_COMPOSITIONS_KEY, applyOperation, NODE_TO_PARENT, NODE_TO_PATH_NODE } from '@contentstack/studio-client';
2
2
  import { composableStudioEventManager, POST_MESSAGE_EVENTS } from '@contentstack/studio-messenger';
3
3
  import { DATA_SOURCES_PREFIX } from '@contentstack/studio-registry';
4
- import { useEffect } from 'react';
4
+ import { seedSectionInstanceBindings } from '@contentstack/studio-react-components/utils';
5
+ import { useRef, useEffect } from 'react';
5
6
  import { setAutoFreeze, produce } from 'immer';
6
7
 
7
8
  // NOTE: Immer (produce) automatically freezes the state to prevent mutations.
@@ -10,39 +11,277 @@ import { setAutoFreeze, produce } from 'immer';
10
11
  // Since the state is frozen by default, this throws an error.
11
12
  // To work around this, we disable auto-freezing here.
12
13
  setAutoFreeze(false);
13
- const useSpecDataListener = (setState, state, composableUid) => {
14
+ /**
15
+ * Walk a fresh UI tree (post-Immer-produce) and populate the NODE_TO_PARENT
16
+ * and NODE_TO_PATH_NODE WeakMaps for every node. These maps are normally
17
+ * populated during React render (in Element.tsx). After APPLY_OPERATION
18
+ * produces a brand-new tree via Immer, the maps still hold entries for
19
+ * stale node refs — `findPath` (used to compute hover/highlight paths sent
20
+ * back to Studio) returns stale paths until the next React commit. Calling
21
+ * this immediately after applyOperation closes that window.
22
+ */
23
+ function refreshNodeWeakMaps(root) {
24
+ if (!root || typeof root !== "object")
25
+ return;
26
+ NODE_TO_PARENT.set(root, undefined);
27
+ const visit = (parent) => {
28
+ const slots = parent?.slots || {};
29
+ for (const slotUid of Object.keys(slots)) {
30
+ const children = slots[slotUid] || [];
31
+ for (let idx = 0; idx < children.length; idx++) {
32
+ const child = children[idx];
33
+ if (!child || typeof child !== "object")
34
+ continue;
35
+ NODE_TO_PARENT.set(child, parent);
36
+ NODE_TO_PATH_NODE.set(child, [slotUid, idx]);
37
+ visit(child);
38
+ }
39
+ }
40
+ };
41
+ visit(root);
42
+ }
43
+ const useSpecDataListener = (setState,
44
+ // Read into `stateRef` only — listener bodies use `stateRef.current` (not
45
+ // `state` directly) so the effect's deps don't include `state.data`, which
46
+ // would force re-register on every data change and create a window with
47
+ // zero handlers between unregister/re-register (the original
48
+ // `NO_REQUEST_LISTENER_FOUND` cause).
49
+ state, composableUid) => {
50
+ // Keep a ref to the latest state so the listener registrations don't have
51
+ // to depend on state.data — they can read latest via stateRef.current
52
+ // synchronously. Without this, every state.data change tore down + re-registered
53
+ // the listeners, creating a window where Studio's UPDATE_SECTION_CONTEXTS
54
+ // message was dropped with NO_REQUEST_LISTENER_FOUND.
55
+ const stateRef = useRef(state);
56
+ stateRef.current = state;
57
+ // Rebuild section_scoped_data entries for instances whose binding metadata
58
+ // (selectedField / uidRemapping / parentRepeaterUID) is present in the
59
+ // legacy section_compositions slice. Mirrors build-scoped-data.ts logic
60
+ // inline so the hook can rebuild without re-running the full fetchSpec
61
+ // pipeline. Needed because Studio's fresh per-instance bindings arrive via
62
+ // UPDATE_SPEC_DATA (and UPDATE_SECTION_CONTEXTS), while the provider only
63
+ // reads from section_scoped_data — without this rebuild, sections render
64
+ // the stale pre-computed scope from the initial fetchSpec (selectedField
65
+ // missing from UI metadata on cold load → scoped template = whole page
66
+ // template → placeholder text).
67
+ const rebuildScopedFromBindings = (prevData, incomingBindings) => {
68
+ const dataSources = prevData?.dataSources || {};
69
+ const sectionBindings = incomingBindings && Object.keys(incomingBindings).length
70
+ ? {
71
+ ...(dataSources[SECTION_COMPOSITIONS_KEY] || {}),
72
+ ...incomingBindings,
73
+ }
74
+ : dataSources[SECTION_COMPOSITIONS_KEY] || {};
75
+ const pageTemplate = dataSources.template;
76
+ const prevScoped = prevData?.section_scoped_data || {};
77
+ const nextScoped = { ...prevScoped };
78
+ const getScopedData = (obj, selectedField) => {
79
+ if (!selectedField)
80
+ return obj;
81
+ return (selectedField.split(".").reduce((val, seg) => {
82
+ if (val == null)
83
+ return val;
84
+ const arrayMatch = seg.match(/^(.*?)\[(\d+)\]$/);
85
+ if (arrayMatch) {
86
+ const [, name, idxStr] = arrayMatch;
87
+ const next = name ? val[name] : val;
88
+ return next == null ? next : next[Number(idxStr)];
89
+ }
90
+ return val[seg];
91
+ }, obj) ?? null);
92
+ };
93
+ const applyUidRemapping = (scoped, uidRemapping = {}) => {
94
+ if (!scoped ||
95
+ typeof scoped !== "object" ||
96
+ Object.keys(uidRemapping).length === 0) {
97
+ return scoped;
98
+ }
99
+ if (Array.isArray(scoped)) {
100
+ return scoped.map((item) => applyUidRemapping(item, uidRemapping));
101
+ }
102
+ const remapped = {};
103
+ const pageKeyValues = new Set(Object.values(uidRemapping));
104
+ for (const [sectionKey, pageKey] of Object.entries(uidRemapping)) {
105
+ remapped[sectionKey] = applyUidRemapping(scoped[pageKey], uidRemapping);
106
+ }
107
+ for (const key of Object.keys(scoped)) {
108
+ if (!pageKeyValues.has(key) && !(key in uidRemapping)) {
109
+ remapped[key] = applyUidRemapping(scoped[key], uidRemapping);
110
+ }
111
+ }
112
+ return remapped;
113
+ };
114
+ let changed = false;
115
+ for (const [instanceUid, bindingUnknown] of Object.entries(sectionBindings)) {
116
+ const binding = bindingUnknown;
117
+ // Skip context-only legacy shape — no selectedField to re-scope from.
118
+ if (binding && "context" in binding && !("selectedField" in binding)) {
119
+ continue;
120
+ }
121
+ const scopedTemplate = applyUidRemapping(getScopedData(pageTemplate, binding?.selectedField), binding?.uidRemapping);
122
+ let repeater;
123
+ if (binding?.parentRepeaterUID) {
124
+ const ctx = dataSources.repeater?.[binding.parentRepeaterUID];
125
+ if (ctx !== undefined) {
126
+ repeater = { [binding.parentRepeaterUID]: ctx };
127
+ }
128
+ }
129
+ const prev = prevScoped[instanceUid] || {};
130
+ // Refresh contentstack / contentstack_queries from the live page
131
+ // dataSources every time we rebuild. The initial scoped data built
132
+ // during fetchSpec may have stale (or empty) entries because the
133
+ // iframe loaded with getSpecFromParent and never fetched the section's
134
+ // data sources itself — the studio pushes them later via
135
+ // UPDATE_SPEC_DATA. Pool-keyed maps would be ideal but the listener
136
+ // doesn't have access to them; copying the full page slice is a safe
137
+ // superset (same composite-key format the resolver expects).
138
+ const refreshedContentstack = dataSources.contentstack && typeof dataSources.contentstack === "object"
139
+ ? { ...dataSources.contentstack }
140
+ : prev.contentstack || {};
141
+ const refreshedQueries = dataSources.contentstack_queries &&
142
+ typeof dataSources.contentstack_queries === "object"
143
+ ? { ...dataSources.contentstack_queries }
144
+ : prev.contentstack_queries || {};
145
+ const next = {
146
+ ...prev,
147
+ template: scopedTemplate,
148
+ contentstack: refreshedContentstack,
149
+ contentstack_queries: refreshedQueries,
150
+ page: dataSources,
151
+ repeater: repeater ?? prev.repeater,
152
+ // Carry binding metadata so SectionCompositionProvider can re-scope the
153
+ // template from the LIVE per-iteration repeater item. The scopedTemplate
154
+ // above is page-root-scoped and shared across every iteration of this
155
+ // instance, so it can't represent per-iteration values on its own.
156
+ parentRepeaterUID: binding?.parentRepeaterUID ?? null,
157
+ selectedField: binding?.selectedField,
158
+ uidRemapping: binding?.uidRemapping,
159
+ componentPropsFallback: binding?.componentPropsFallback,
160
+ };
161
+ if (prev.template !== next.template ||
162
+ prev.page !== next.page ||
163
+ prev.repeater !== next.repeater ||
164
+ prev.contentstack !== next.contentstack ||
165
+ prev.contentstack_queries !== next.contentstack_queries ||
166
+ prev.componentPropsFallback !== next.componentPropsFallback) {
167
+ nextScoped[instanceUid] = next;
168
+ changed = true;
169
+ }
170
+ }
171
+ if (!changed)
172
+ return prevData;
173
+ return { ...prevData, section_scoped_data: nextScoped };
174
+ };
14
175
  // HOOK TO UPDATE THE STATE WITH THE LATEST SPEC DATA
176
+ // Listeners are registered as soon as we're inside the Studio frame, before
177
+ // spec has been fetched. Studio decides when to push UPDATE_SECTION_CONTEXTS
178
+ // and UPDATE_SPEC_DATA based on its own readiness signal; the SDK can't
179
+ // gate on `isCompositionBeingEdited(composableUid)` because that requires the
180
+ // spec — and the parent reaches "ready" before the SDK's setState effect
181
+ // has propagated, producing NO_REQUEST_LISTENER_FOUND.
182
+ // The handlers themselves still defensively check `stateRef.current?.data`
183
+ // before acting, so registering early is safe.
15
184
  useEffect(() => {
16
- if (!isCompositionBeingEdited(composableUid || ""))
185
+ if (!clientRendererModeUtil.isInsideStudioFrame())
17
186
  return;
18
187
  const specDataChangeListener = composableStudioEventManager?.on(POST_MESSAGE_EVENTS.UPDATE_SPEC_DATA, async (event) => {
19
188
  const { data } = event;
20
- if (!data || !state?.data)
189
+ if (!data || !stateRef.current?.data)
21
190
  return;
22
191
  setState((state) => {
23
192
  if (!state)
24
193
  return state;
194
+ // Merge incoming over existing — never replace dataSources
195
+ // wholesale. Studio's UPDATE_SPEC_DATA pushes can carry only
196
+ // a subset of slices (e.g., only `template` + `section_compositions`),
197
+ // and a naive overwrite would wipe slices the SDK relied on
198
+ // (e.g., the `repeater` item context populated earlier from
199
+ // preview data resolution). Result was a visible flicker as
200
+ // sections inside a Repeater suddenly lost their item context.
201
+ // Also merge section_compositions key-by-key so SDK-seeded
202
+ // per-instance bindings survive when Studio's push is partial.
203
+ const incomingSections = data?.dataSources?.[SECTION_COMPOSITIONS_KEY] || {};
204
+ const existingSections = state.data?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||
205
+ {};
206
+ const mergedDataSources = {
207
+ ...(state.data?.dataSources || {}),
208
+ ...(data?.dataSources || {}),
209
+ [SECTION_COMPOSITIONS_KEY]: {
210
+ ...existingSections,
211
+ ...incomingSections,
212
+ },
213
+ };
214
+ const mergedData = {
215
+ ...state.data,
216
+ ...data,
217
+ dataSources: mergedDataSources,
218
+ };
219
+ const rebuilt = rebuildScopedFromBindings(mergedData);
25
220
  return {
26
221
  ...state,
27
- data: data,
222
+ data: rebuilt,
28
223
  };
29
224
  });
30
225
  });
31
226
  const previewEntryChangeListener = composableStudioEventManager?.on(POST_MESSAGE_EVENTS.REPLACE_PREVIEW_ENTRY, async (event) => {
32
227
  const { data } = event;
33
- if (!data?.dataSources || !state?.data)
228
+ if (!data?.dataSources || !stateRef.current?.data)
34
229
  return;
35
230
  setState((prevState) => {
36
231
  if (!prevState)
37
232
  return prevState;
233
+ // REPLACE_PREVIEW_ENTRY pushes dataSources for the preview-entry change
234
+ // (typically just `template`/`contentstack` slices). Merge into existing
235
+ // dataSources — don't wipe sibling slices like `repeater` or
236
+ // `section_compositions`, which would cause a flicker for sections
237
+ // inside a Repeater (their item context would disappear).
38
238
  return {
39
239
  ...prevState,
40
- data: { ...state?.data, [DATA_SOURCES_PREFIX]: data?.dataSources },
240
+ data: {
241
+ ...prevState?.data,
242
+ [DATA_SOURCES_PREFIX]: {
243
+ ...(prevState?.data?.[DATA_SOURCES_PREFIX] || {}),
244
+ ...data?.dataSources,
245
+ },
246
+ },
41
247
  };
42
248
  });
43
249
  });
44
250
  const applyOperationListener = composableStudioEventManager?.on(POST_MESSAGE_EVENTS.APPLY_OPERATION, (event) => {
45
251
  const { data } = event;
252
+ // Self-heal section catalog: if any op inserts a section-composition
253
+ // node whose compositionUID isn't in the locally-known catalog
254
+ // (race between Studio's section store hydration and the iframe's
255
+ // initial GET_SECTIONS reply), re-fetch the catalog and merge.
256
+ // Without this the section renders with "Component … is not
257
+ // registered" until the page is saved + reloaded.
258
+ const newSectionUids = new Set();
259
+ for (const op of data?.operations || []) {
260
+ const node = op?.node;
261
+ if (op &&
262
+ op.type === "insert_node" &&
263
+ node &&
264
+ typeof node === "object" &&
265
+ node.type === "section-composition" &&
266
+ typeof node.metadata?.compositionUID === "string") {
267
+ newSectionUids.add(node.metadata.compositionUID);
268
+ }
269
+ }
270
+ const known = new Set((stateRef.current?.sectionCompositions || []).map((s) => s.uid));
271
+ const unknown = [...newSectionUids].filter((u) => !known.has(u));
272
+ if (unknown.length > 0) {
273
+ composableStudioEventManager
274
+ ?.send(POST_MESSAGE_EVENTS.GET_SECTIONS, {})
275
+ .then((resp) => {
276
+ if (!resp?.sectionCompositions)
277
+ return;
278
+ setState((prevState) => ({
279
+ ...prevState,
280
+ sectionCompositions: resp.sectionCompositions,
281
+ }));
282
+ })
283
+ .catch(() => { });
284
+ }
46
285
  setState((prevState) => {
47
286
  if (!prevState?.ui || !data?.operations)
48
287
  return prevState;
@@ -50,15 +289,101 @@ const useSpecDataListener = (setState, state, composableUid) => {
50
289
  const operations = data.operations;
51
290
  return applyOperation(ui, operations);
52
291
  });
53
- return { ...prevState, ui: newUI };
292
+ // Eagerly refresh the NODE_TO_PARENT / NODE_TO_PATH_NODE WeakMaps for
293
+ // the new tree. These WeakMaps are otherwise only populated during
294
+ // React render (Element.tsx) and `findPath` (used by hover/highlight
295
+ // postMessages back to Studio) reads from them. Without this refresh
296
+ // there is a window between APPLY_OPERATION and the next React commit
297
+ // where mouse-move events emit paths derived from old node refs —
298
+ // those paths don't exist in Studio's now-updated slate editor and
299
+ // surface as "Cannot find a descendant at path" errors.
300
+ refreshNodeWeakMaps(newUI);
301
+ // Re-seed per-instance section bindings ONLY when the slate op might
302
+ // have moved/inserted/removed a section-composition node. Property /
303
+ // style / text-content ops can't change the section-instance graph,
304
+ // so the seeder's full UI walk on those is wasted work. The seeder
305
+ // itself is idempotent (it short-circuits when nothing mutated), but
306
+ // skipping the walk altogether keeps interactive ops (typing, style
307
+ // edits) cheap on large pages.
308
+ const ops = data.operations;
309
+ const opAffectsSectionInstances = ops.some((op) => op?.type === "insert_node" ||
310
+ op?.type === "remove_node" ||
311
+ op?.type === "move_node" ||
312
+ op?.type === "merge_node" ||
313
+ op?.type === "split_node");
314
+ if (!opAffectsSectionInstances) {
315
+ return { ...prevState, ui: newUI };
316
+ }
317
+ return seedSectionInstanceBindings({ ...prevState, ui: newUI });
54
318
  });
55
319
  });
320
+ // Studio pushes only the section_compositions slice when section contexts
321
+ // are recomputed (e.g. after a section node is added/moved/removed). We
322
+ // patch just that slice on top of existing dataSources so other data
323
+ // (template, contentstack, query results) isn't clobbered.
324
+ //
325
+ // We ALSO rebuild the matching `section_scoped_data[instanceUid].template`
326
+ // (and repeater slot) using the fresh selectedField / uidRemapping /
327
+ // parentRepeaterUID Studio just sent. Without this, SectionCompositionProvider
328
+ // would keep rendering the stale pre-computed scoped data from fetchSpec
329
+ // (which can be wrong on cold load if the UI node lacked
330
+ // metadata.selectedField), because the provider prefers section_scoped_data
331
+ // and never falls back to the legacy section_compositions slot when it
332
+ // exists.
333
+ const sectionContextsListener = composableStudioEventManager?.on(POST_MESSAGE_EVENTS.UPDATE_SECTION_CONTEXTS, (event) => {
334
+ const { data } = event;
335
+ if (!data?.sectionCompositions)
336
+ return;
337
+ // Merge key-by-key on top of SDK-seeded defaults. Studio only pushes
338
+ // user-driven overrides for specific instance nodes; replacing the whole
339
+ // slice would wipe the SDK's seeded baseline for all other instances.
340
+ setState((prevState) => {
341
+ if (!prevState?.data)
342
+ return prevState;
343
+ const existing = prevState.data?.dataSources?.[SECTION_COMPOSITIONS_KEY] ||
344
+ {};
345
+ const mergedData = {
346
+ ...prevState.data,
347
+ dataSources: {
348
+ ...prevState.data?.dataSources,
349
+ [SECTION_COMPOSITIONS_KEY]: {
350
+ ...existing,
351
+ ...data.sectionCompositions,
352
+ },
353
+ },
354
+ };
355
+ const finalData = rebuildScopedFromBindings(mergedData, data.sectionCompositions);
356
+ return {
357
+ ...prevState,
358
+ data: finalData,
359
+ };
360
+ });
361
+ });
362
+ // Signal to Studio that our editor→iframe post-message listeners are now
363
+ // in the handler map. Studio gates UPDATE_SPEC_DATA (and similar) on this
364
+ // event because earlier readiness signals (SDK_SPEC_RESOLVED, INIT_STUDIO)
365
+ // fire before EditableRenderer commits its first render and race against
366
+ // the .on(...) calls above.
367
+ composableStudioEventManager
368
+ ?.send(POST_MESSAGE_EVENTS.LISTENERS_READY, { composableUid })
369
+ .then(() => { })
370
+ .catch(() => {
371
+ // Studio may not have its LISTENERS_READY handler registered yet on
372
+ // very first paint — the bridge resolves this via its message queue,
373
+ // so a dropped first emit is harmless. Not an error worth surfacing.
374
+ });
56
375
  return () => {
57
376
  applyOperationListener?.unregister();
58
377
  specDataChangeListener?.unregister();
59
378
  previewEntryChangeListener?.unregister();
379
+ sectionContextsListener?.unregister();
60
380
  };
61
- }, [state?.compositionEntry?.uid, state?.data, composableUid]);
381
+ // Deps deliberately exclude state.data — see stateRef above. Re-registering
382
+ // on every data change creates a window where Studio's pushes are dropped
383
+ // with NO_REQUEST_LISTENER_FOUND. We do re-register on composableUid change
384
+ // (e.g. switching to a different composition without unmount); the
385
+ // LISTENERS_READY emit above re-signals Studio after each rebind.
386
+ }, [composableUid]);
62
387
  };
63
388
 
64
389
  export { useSpecDataListener };
@@ -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} 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 { useEffect } 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\nexport const useSpecDataListener = (\n setState: React.Dispatch<React.SetStateAction<StudioSpec>>,\n state?: StudioSpec,\n composableUid?: string,\n) => {\n // HOOK TO UPDATE THE STATE WITH THE LATEST SPEC DATA\n useEffect(() => {\n if (!isCompositionBeingEdited(composableUid || \"\")) 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 || !state?.data) return;\n\n setState((state: StudioSpec) => {\n if (!state) return state;\n return {\n ...state,\n data: data,\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 || !state?.data) return;\n\n setState((prevState: StudioSpec) => {\n if (!prevState) return prevState;\n return {\n ...prevState,\n data: { ...state?.data, [DATA_SOURCES_PREFIX]: data?.dataSources },\n };\n });\n });\n\n const applyOperationListener = composableStudioEventManager?.on<{\n operations: Operation[];\n }>(POST_MESSAGE_EVENTS.APPLY_OPERATION, (event) => {\n const { data } = event;\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 return { ...prevState, ui: newUI };\n });\n });\n return () => {\n applyOperationListener?.unregister();\n specDataChangeListener?.unregister();\n previ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;AACH,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;AAEF,QAAA,MAAM,sBAAsB,GAAG,4BAA4B,EAAE,EAAE,CAE5D,mBAAmB,CAAC,eAAe,EAAE,CAAC,KAAK,KAAI;AAChD,YAAA,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK;AACtB,YAAA,QAAQ,CAAC,CAAC,SAAqB,KAAI;gBACjC,IAAI,CAAC,SAAS,EAAE,EAAE,IAAI,CAAC,IAAI,EAAE,UAAU;AAAE,oBAAA,OAAO,SAAS;gBACzD,MAAM,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,CAAC,EAAE,KAAI;AACzC,oBAAA,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU;AAClC,oBAAA,OAAO,cAAc,CAAC,EAAE,EAAE,UAAU,CAAC;AACvC,gBAAA,CAAC,CAAC;gBACF,OAAO,EAAE,GAAG,SAAS,EAAE,EAAE,EAAE,KAAK,EAAE;AACpC,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,MAAK;YACV,sBAAsB,EAAE,UAAU,EAAE;YACpC,sBAAsB,EAAE,UAAU,EAAE;YACpC,0BAA0B,EAAE,UAAU,EAAE;AAC1C,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,aAAa,CAAC,CAAC;AAChE;;;;"}
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 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 };\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 const scopedTemplate = applyUidRemapping(\n getScopedData(pageTemplate, binding?.selectedField),\n binding?.uidRemapping,\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 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 // 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 const mergedDataSources = {\n ...((state.data as any)?.dataSources || {}),\n ...((data as any)?.dataSources || {}),\n [SECTION_COMPOSITIONS_KEY]: {\n ...existingSections,\n ...incomingSections,\n },\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 return {\n ...prevState,\n data: {\n ...prevState?.data,\n [DATA_SOURCES_PREFIX]: {\n ...((prevState?.data as any)?.[DATA_SOURCES_PREFIX] || {}),\n ...(data?.dataSources as any),\n },\n },\n };\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 const mergedData = {\n ...prevState.data,\n dataSources: {\n ...prevState.data?.dataSources,\n [SECTION_COMPOSITIONS_KEY]: {\n ...existing,\n ...data.sectionCompositions,\n },\n },\n } as any;\n const finalData = rebuildScopedFromBindings(\n mergedData,\n data.sectionCompositions,\n );\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,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,GA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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;;;;"}
@@ -22,6 +22,19 @@ const useSymbolsEvents = (setState, state, composableUid) => {
22
22
  };
23
23
  });
24
24
  });
25
+ // Pull current symbols from Studio now that listener is ready.
26
+ // Avoids race where UPDATE_SYMBOLS fires before this listener mounts.
27
+ composableStudioEventManager
28
+ ?.send(POST_MESSAGE_EVENTS.GET_SYMBOLS, {})
29
+ .then((data) => {
30
+ if (data?.symbols?.length) {
31
+ setState((prevState) => ({
32
+ ...prevState,
33
+ symbols: data.symbols,
34
+ }));
35
+ }
36
+ })
37
+ .catch(() => { });
25
38
  return () => {
26
39
  symbolEventListener?.unregister();
27
40
  };
@@ -1 +1 @@
1
- {"version":3,"file":"use-symbol-events.hook.js","sources":["../../src/hooks/use-symbol-events.hook.ts"],"sourcesContent":["import {\n StudioSpec,\n isCompositionBeingEdited,\n SymbolEntry,\n} from \"@contentstack/studio-client\";\nimport {\n composableStudioEventManager,\n POST_MESSAGE_EVENTS,\n} from \"@contentstack/studio-messenger\";\nimport { useEffect } from \"react\";\nimport { useRegisterSymbolComponents } from \"./use-register-symbol.hook\";\n\n/**\n * This hook is used to listen to the symbols events and update the state with the latest symbols.\n */\nexport const useSymbolsEvents = (\n setState: React.Dispatch<React.SetStateAction<StudioSpec>>,\n state?: StudioSpec,\n composableUid?: string,\n) => {\n useRegisterSymbolComponents(state?.symbols || []);\n useEffect(() => {\n if (!isCompositionBeingEdited(composableUid || \"\")) return;\n const symbolEventListener = composableStudioEventManager?.on<{\n symbols: SymbolEntry[];\n }>(POST_MESSAGE_EVENTS.UPDATE_SYMBOLS, (event) => {\n const { data } = event;\n if (!data?.symbols) return;\n setState((prevState: StudioSpec) => {\n return {\n ...prevState,\n symbols: data.symbols,\n };\n });\n });\n return () => {\n symbolEventListener?.unregister();\n };\n }, [state?.compositionEntry?.uid, composableUid]);\n};\n"],"names":[],"mappings":";;;;;AAYA;;AAEG;AACI,MAAM,gBAAgB,GAAG,CAC9B,QAA0D,EAC1D,KAAkB,EAClB,aAAsB,KACpB;AACF,IAAA,2BAA2B,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,CAAC;IACjD,SAAS,CAAC,MAAK;AACb,QAAA,IAAI,CAAC,wBAAwB,CAAC,aAAa,IAAI,EAAE,CAAC;YAAE;AACpD,QAAA,MAAM,mBAAmB,GAAG,4BAA4B,EAAE,EAAE,CAEzD,mBAAmB,CAAC,cAAc,EAAE,CAAC,KAAK,KAAI;AAC/C,YAAA,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK;YACtB,IAAI,CAAC,IAAI,EAAE,OAAO;gBAAE;AACpB,YAAA,QAAQ,CAAC,CAAC,SAAqB,KAAI;gBACjC,OAAO;AACL,oBAAA,GAAG,SAAS;oBACZ,OAAO,EAAE,IAAI,CAAC,OAAO;iBACtB;AACH,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;AACF,QAAA,OAAO,MAAK;YACV,mBAAmB,EAAE,UAAU,EAAE;AACnC,QAAA,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAC;AACnD;;;;"}
1
+ {"version":3,"file":"use-symbol-events.hook.js","sources":["../../src/hooks/use-symbol-events.hook.ts"],"sourcesContent":["import {\n StudioSpec,\n isCompositionBeingEdited,\n SymbolEntry,\n} from \"@contentstack/studio-client\";\nimport {\n composableStudioEventManager,\n POST_MESSAGE_EVENTS,\n} from \"@contentstack/studio-messenger\";\nimport { useEffect } from \"react\";\nimport { useRegisterSymbolComponents } from \"./use-register-symbol.hook\";\n\n/**\n * This hook is used to listen to the symbols events and update the state with the latest symbols.\n */\nexport const useSymbolsEvents = (\n setState: React.Dispatch<React.SetStateAction<StudioSpec>>,\n state?: StudioSpec,\n composableUid?: string,\n) => {\n useRegisterSymbolComponents(state?.symbols || []);\n useEffect(() => {\n if (!isCompositionBeingEdited(composableUid || \"\")) return;\n const symbolEventListener = composableStudioEventManager?.on<{\n symbols: SymbolEntry[];\n }>(POST_MESSAGE_EVENTS.UPDATE_SYMBOLS, (event) => {\n const { data } = event;\n if (!data?.symbols) return;\n setState((prevState: StudioSpec) => {\n return {\n ...prevState,\n symbols: data.symbols,\n };\n });\n });\n\n // Pull current symbols from Studio now that listener is ready.\n // Avoids race where UPDATE_SYMBOLS fires before this listener mounts.\n composableStudioEventManager\n ?.send<{ symbols: SymbolEntry[] }>(POST_MESSAGE_EVENTS.GET_SYMBOLS, {})\n .then((data) => {\n if (data?.symbols?.length) {\n setState((prevState: StudioSpec) => ({\n ...prevState,\n symbols: data.symbols,\n }));\n }\n })\n .catch(() => {});\n\n return () => {\n symbolEventListener?.unregister();\n };\n }, [state?.compositionEntry?.uid, composableUid]);\n};\n"],"names":[],"mappings":";;;;;AAYA;;AAEG;AACI,MAAM,gBAAgB,GAAG,CAC9B,QAA0D,EAC1D,KAAkB,EAClB,aAAsB,KACpB;AACF,IAAA,2BAA2B,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,CAAC;IACjD,SAAS,CAAC,MAAK;AACb,QAAA,IAAI,CAAC,wBAAwB,CAAC,aAAa,IAAI,EAAE,CAAC;YAAE;AACpD,QAAA,MAAM,mBAAmB,GAAG,4BAA4B,EAAE,EAAE,CAEzD,mBAAmB,CAAC,cAAc,EAAE,CAAC,KAAK,KAAI;AAC/C,YAAA,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK;YACtB,IAAI,CAAC,IAAI,EAAE,OAAO;gBAAE;AACpB,YAAA,QAAQ,CAAC,CAAC,SAAqB,KAAI;gBACjC,OAAO;AACL,oBAAA,GAAG,SAAS;oBACZ,OAAO,EAAE,IAAI,CAAC,OAAO;iBACtB;AACH,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,CAAC;;;QAIF;AACE,cAAE,IAAI,CAA6B,mBAAmB,CAAC,WAAW,EAAE,EAAE;AACrE,aAAA,IAAI,CAAC,CAAC,IAAI,KAAI;AACb,YAAA,IAAI,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE;AACzB,gBAAA,QAAQ,CAAC,CAAC,SAAqB,MAAM;AACnC,oBAAA,GAAG,SAAS;oBACZ,OAAO,EAAE,IAAI,CAAC,OAAO;AACtB,iBAAA,CAAC,CAAC;YACL;AACF,QAAA,CAAC;AACA,aAAA,KAAK,CAAC,MAAK,EAAE,CAAC,CAAC;AAElB,QAAA,OAAO,MAAK;YACV,mBAAmB,EAAE,UAAU,EAAE;AACnC,QAAA,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,GAAG,EAAE,aAAa,CAAC,CAAC;AACnD;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentstack/studio-react-editor",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Contains all logic of editing for react based environment",
5
5
  "author": "RavenColEvol <ravilamkoti@gmail.com>",
6
6
  "homepage": "https://github.com/contentstack/composable-studio-sdk#readme",
@@ -39,10 +39,10 @@
39
39
  "react-dom": ">=16.0.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@contentstack/common-config": "1.0.2",
42
+ "@contentstack/common-config": "^1.1.7",
43
43
  "@rollup/plugin-commonjs": "^28.0.6",
44
44
  "@rollup/plugin-node-resolve": "^16.0.1",
45
- "@rollup/plugin-terser": "^0.4.4",
45
+ "@rollup/plugin-terser": "^1.0.0",
46
46
  "@rollup/plugin-typescript": "^12.1.4",
47
47
  "@types/lodash": "^4.17.5",
48
48
  "@types/react": "^18.3.5",
@@ -60,17 +60,17 @@
60
60
  "typescript": "^5.2.2"
61
61
  },
62
62
  "dependencies": {
63
- "@contentstack/studio-client": "^1.4.0",
64
- "@contentstack/studio-core": "^1.1.5",
65
- "@contentstack/studio-internal": "^1.1.5",
66
- "@contentstack/studio-messenger": "^1.2.0",
67
- "@contentstack/studio-react-components": "^1.4.1",
68
- "@contentstack/studio-registry": "^1.3.0",
63
+ "@contentstack/studio-client": "^1.5.1",
64
+ "@contentstack/studio-core": "^1.1.7",
65
+ "@contentstack/studio-internal": "^1.2.1",
66
+ "@contentstack/studio-messenger": "^1.3.1",
67
+ "@contentstack/studio-react-components": "^1.5.1",
68
+ "@contentstack/studio-registry": "^1.4.1",
69
69
  "classnames": "^2.5.1",
70
70
  "goober": "^2.1.16",
71
71
  "immer": "^10.1.1",
72
- "lodash-es": "^4.17.23",
72
+ "lodash-es": "^4.18.1",
73
73
  "react-error-boundary": "^6.0.0"
74
74
  },
75
- "gitHead": "6739518a282ff9788218b0acd2e46e0be2a6fb68"
75
+ "gitHead": "d4e0a1d80b39a2bfa9ac12baa5d4d4a852f4b326"
76
76
  }