@uniformdev/canvas-vue 17.7.1-alpha.34 → 18.0.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/LICENSE.txt CHANGED
@@ -1,2 +1,2 @@
1
- © 2022 Uniform Systems, Inc. All Rights Reserved.
1
+ © 2023 Uniform Systems, Inc. All Rights Reserved.
2
2
  See details of Uniform Systems, Inc. Master Subscription Agreement here: https://uniform.dev/eula
package/dist/index.d.ts CHANGED
@@ -24,12 +24,12 @@ interface PersonalizeComponent {
24
24
  * TProps is the Canvas component's parameters object after
25
25
  * all enhancers have been applied.
26
26
  */
27
- declare type ComponentProps<TProps = unknown> = TProps & {
27
+ type ComponentProps<TProps = unknown> = TProps & {
28
28
  component: ComponentInstance;
29
29
  };
30
- declare type ResolveRenderer = (componentInstance: ComponentInstance) => ConcreteComponent<any>;
30
+ type ResolveRenderer = (componentInstance: ComponentInstance) => ConcreteComponent<any>;
31
31
 
32
- declare type CompositionProps = {
32
+ type CompositionProps = {
33
33
  /** A dynamic vue component that provides data to the Uniform Canvas SlotContent component via provide/inject */
34
34
  data: ComponentInstance;
35
35
  /** Resolves a Vue component to render a Canvas component, generally by inspecting type/variant */
@@ -81,7 +81,7 @@ declare const Composition: vue_demi.DefineComponent<{
81
81
  behaviorTracking: "onLoad" | "onView" | undefined;
82
82
  }>;
83
83
 
84
- declare type DefaultNotImplementedComponentProps = {
84
+ type DefaultNotImplementedComponentProps = {
85
85
  component: ComponentInstance;
86
86
  };
87
87
  declare const DefaultNotImplementedComponent: vue_demi.DefineComponent<{
@@ -98,7 +98,7 @@ declare const DefaultNotImplementedComponent: vue_demi.DefineComponent<{
98
98
  };
99
99
  }>>, {}>;
100
100
 
101
- declare type SlotComponentProps = {
101
+ type SlotComponentProps = {
102
102
  /** Name of the slot to render */
103
103
  name?: string;
104
104
  /**
@@ -128,7 +128,7 @@ declare const SlotContent: vue_demi.DefineComponent<{
128
128
  };
129
129
  }>>, {}>;
130
130
 
131
- declare type UseCompositionEventEffectOptions = Omit<Partial<SubscribeToCompositionOptions>, 'callback' | 'compositionId'> & {
131
+ type UseCompositionEventEffectOptions = Omit<Partial<SubscribeToCompositionOptions>, 'callback' | 'compositionId'> & {
132
132
  compositionIdRef: Ref<SubscribeToCompositionOptions['compositionId']>;
133
133
  enabled: boolean;
134
134
  effect: () => void;
package/dist/index.esm.js CHANGED
@@ -1 +1,440 @@
1
- import{CANVAS_ENRICHMENT_TAG_PARAM as N}from"@uniformdev/canvas";import{isUsingUniformContext as _,Track as O,TrackSlot as A}from"@uniformdev/context-vue";import{computed as T,defineComponent as k,h as U,inject as I,provide as S,resolveComponent as V}from"vue-demi";var h="Composition",P="SlotContent",y="uniformComposition",v="uniformResolveRenderer";var E=k({name:h,inheritAttrs:!1,props:{data:{type:Object,required:!0},resolveRenderer:{type:Function,default:()=>({type:e})=>V(e)},behaviorTracking:{type:String,default:"onView"}},setup(e,t){var c,i,C;let o=T(()=>{var l,d;return(d=e.data)!=null?d:(l=I(y))==null?void 0:l.value}),s=(c=e.resolveRenderer)!=null?c:I(v);S(y,o),S(v,s);let r=T(()=>{var l,d;return(d=(l=o.value)==null?void 0:l.slots)!=null?d:{}}),n=T(()=>{var l,d;return(d=(l=o.value)==null?void 0:l.parameters)!=null?d:{}}),p=T(()=>JSON.stringify(o.value)),m=(C=(i=o.value.parameters)==null?void 0:i[N])==null?void 0:C.value,a=()=>{var l,d;return(d=(l=t.slots).default)==null?void 0:d.call(l,{slots:r.value,parameters:n.value})};if(_()){let l=e.behaviorTracking==="onLoad"?A:O;return()=>U(l,{behavior:m,key:p.value},a)}return a}});import{defineComponent as j,h as u}from"vue-demi";var M={borderLeft:"10px solid #e42535",background:"rgba(122, 215, 218, 0.3)",color:"#1d3557",padding:"1rem",textAlign:"left",margin:"1rem 5vw"},L={margin:"0 0 1rem"},Te=j({name:"DefaultNotImplementedComponent",props:{component:{type:Object,required:!0}},setup(e,{attrs:t}){var s;let o=(s=e.component)==null?void 0:s.type;return()=>u("div",{key:"content",style:{...M}},[u("h2",{style:{...L}},`Component: ${o}`),u("p",[u("strong",`${o} has no Vue implementation. It may need to be added to your `),u("code",{},"resolveRenderer()"),u("strong",{}," function.")]),u("details",{},[u("summary",{},"props/attributes"),u("pre",{style:{overflowX:"auto"}},`${JSON.stringify(t)}`)])])}});import{CANVAS_PERSONALIZE_TYPE as D,CANVAS_TEST_TYPE as K,IN_CONTEXT_EDITOR_COMPONENT_START_ROLE as Y,mapSlotToPersonalizedVariations as B,mapSlotToTestVariations as $,PLACEHOLDER_ID as F}from"@uniformdev/canvas";import{Personalize as J,Test as X}from"@uniformdev/context-vue";import{computed as q,defineComponent as G,h as f,inject as w}from"vue-demi";function b(e){var r;let t=(r=e.parameters)!=null?r:{};return{...Object.entries(t).reduce((n,[p,{value:m}])=>({...n,[z(p)]:m}),{}),...e.data,component:e}}function z(e){return e.replace("$","")}var ge=G({name:P,inheritAttrs:!1,props:{name:{type:String},resolveRenderer:{type:Function}},setup(e,t){var m;let o=w(y),s=(m=e.resolveRenderer)!=null?m:w(v),r=t.slots.emptyPlaceholder;if(!o||!s)throw new Error("<SlotContent /> can only be used inside a <Composition />");let n=q(()=>{var a,c,i;return e.name?(c=(a=o==null?void 0:o.value.slots)==null?void 0:a[e.name])!=null?c:[]:Object.values((i=o==null?void 0:o.value.slots)!=null?i:{}).flat()}),p=n.value.map((a,c)=>{let i=R({component:a,resolveRenderer:s,indexInSlot:c,slotName:e.name,parentComponent:o.value,slotChildrenCount:n.value.length,emptyPlaceholder:r});return t.slots.default?t.slots.default({child:i,component:a}):i});return()=>p}});function H(e,t){var n,p,m,a,c,i;let o=e==null?void 0:e.parameters,s=B((n=e.slots)==null?void 0:n.pz),r=(a=(m=(p=e.parameters)==null?void 0:p.trackingEventName)==null?void 0:m.value)!=null?a:"Untitled Personalization";return f(J,{name:r,component:C=>t(C),variations:s,count:Number((i=(c=o==null?void 0:o.count)==null?void 0:c.value)!=null?i:1)})}function Q(e,t){var n,p,m,a,c;let o=(p=(n=e==null?void 0:e.slots)==null?void 0:n.test)!=null?p:[],s=(c=(a=(m=e==null?void 0:e.parameters)==null?void 0:m.test)==null?void 0:a.value)!=null?c:"Untitled Test",r=$(o);return f(X,{variations:r,name:s,component:i=>t(i)})}function R({component:e,resolveRenderer:t,indexInSlot:o,slotName:s,parentComponent:r,slotChildrenCount:n,emptyPlaceholder:p}){var a,c;if(e.type===K)return Q(e,i=>R({component:i,resolveRenderer:t}));if(e.type===D)return H(e,i=>R({component:i,resolveRenderer:t}));let m=t==null?void 0:t(e);if(m){let i=b(e),C=Boolean(e._id),l=e._id===F,d=C?[f("script",{"data-role":Y,"data-parent-id":r==null?void 0:r._id,"data-parent-type":r==null?void 0:r.type,"data-component-id":e._id,"data-slot-name":s,"data-component-index":o,"data-total-components":n,"data-component-name":e.type,"data-is-placeholder":l?"true":void 0,"data-component-title":(c=(a=e.parameters)==null?void 0:a.title)==null?void 0:c.value}),l&&p!==void 0?p():f(m,i),f("script",{"data-role":"component-end"})]:[f(m,i)];return f(E,{data:e,resolveRenderer:t},()=>d)}return console.warn(`[canvas] found component of type '${e.type}' which the 'resolveRenderer' prop returned no component for. Nothing will be rendered. The resolveRenderer function may need to be extended to handle the new type.`,e),f("")}import{CANVAS_DRAFT_STATE as Z,createEventBus as W,subscribeToComposition as ee}from"@uniformdev/canvas";import{watch as oe}from"vue-demi";async function Oe({enabled:e,projectId:t,compositionIdRef:o,effect:s}){let r;oe([()=>e,()=>o.value,()=>t],async()=>{if(r==null||r(),!e||!o.value||!t)return;let n=await W();n&&(r=ee({eventBus:n,compositionId:o.value,compositionState:Z,projectId:t,callback:s,event:"updated"}))},{immediate:!0})}import{createCanvasChannel as te,IN_CONTEXT_EDITOR_QUERY_STRING_PARAM as ne,isUpdateCompositionMessage as re}from"@uniformdev/canvas";import{computed as se,onMounted as ie,ref as ae,watch as pe}from"vue-demi";var g="uniform-canvas-preview-script",Me=({apiUrl:e})=>async t=>{let o=await fetch(e,{method:"post",body:JSON.stringify({composition:t.composition,hash:t.hash}),headers:{"Content-Type":"application/json"}}),s=await o.json();if(!o.ok)throw new Error("Error reading enhanced composition");return s.composition},Le=({initialCompositionValue:e,enhance:t=o=>o.composition})=>{let o=ae(),s=se(()=>{var n;return x()?te({broadcastTo:[(n=window.opener)!=null?n:window.top],listenTo:[window]}):void 0});return pe([s,()=>t],()=>{if(!s.value)return;let r=s.value.on("update-composition",async n=>{if(re(n)){let p=await t(n);o.value=p}});return()=>{r()}},{immediate:!0}),ie(()=>{if(!x()||document.getElementById(g))return;let n=document.createElement("script");n.id=g,n.src=me(),n.async=!0,document.head.appendChild(n)}),{composition:o!=null?o:e}};function me(){return`${window.document.referrer}files/canvas-in-context-embed/index.js`}function x(){if(typeof window=="undefined")return!1;let e=new URLSearchParams(window.location.search).has(ne),t=Boolean(window.document.referrer.match(/(^https:\/\/|\.)(uniform.app|uniform.wtf|localhost:\d{4})\//));return e&&t}export{h as CANVAS_COMPOSITION_TYPE,P as CANVAS_SLOT_CONTENT_TYPE,E as Composition,Te as DefaultNotImplementedComponent,ge as SlotContent,y as compositionInjectionKey,b as convertComponentToProps,Me as createApiEnhancer,v as resolveRendererInjectionKey,Oe as useCompositionEventEffect,Le as useContextualEditing};
1
+ // src/components/Composition.ts
2
+ import { CANVAS_ENRICHMENT_TAG_PARAM } from "@uniformdev/canvas";
3
+ import { isUsingUniformContext, Track, TrackSlot } from "@uniformdev/context-vue";
4
+ import {
5
+ computed,
6
+ defineComponent,
7
+ h,
8
+ inject,
9
+ provide,
10
+ resolveComponent as nativeResolveComponent
11
+ } from "vue-demi";
12
+
13
+ // src/utils/constants.ts
14
+ var CANVAS_COMPOSITION_TYPE = "Composition";
15
+ var CANVAS_SLOT_CONTENT_TYPE = "SlotContent";
16
+ var compositionInjectionKey = "uniformComposition";
17
+ var resolveRendererInjectionKey = "uniformResolveRenderer";
18
+
19
+ // src/components/Composition.ts
20
+ var Composition = defineComponent({
21
+ name: CANVAS_COMPOSITION_TYPE,
22
+ inheritAttrs: false,
23
+ props: {
24
+ data: {
25
+ type: Object,
26
+ required: true
27
+ },
28
+ resolveRenderer: {
29
+ type: Function,
30
+ default: () => ({ type }) => nativeResolveComponent(type)
31
+ },
32
+ behaviorTracking: {
33
+ type: String,
34
+ default: "onView"
35
+ }
36
+ },
37
+ setup(props, context) {
38
+ var _a, _b, _c;
39
+ const data = computed(() => {
40
+ var _a2, _b2;
41
+ return (_b2 = props.data) != null ? _b2 : (_a2 = inject(compositionInjectionKey)) == null ? void 0 : _a2.value;
42
+ });
43
+ const resolveRenderer = (_a = props.resolveRenderer) != null ? _a : inject(resolveRendererInjectionKey);
44
+ provide(compositionInjectionKey, data);
45
+ provide(resolveRendererInjectionKey, resolveRenderer);
46
+ const slots = computed(() => {
47
+ var _a2, _b2;
48
+ return (_b2 = (_a2 = data.value) == null ? void 0 : _a2.slots) != null ? _b2 : {};
49
+ });
50
+ const parameters = computed(() => {
51
+ var _a2, _b2;
52
+ return (_b2 = (_a2 = data.value) == null ? void 0 : _a2.parameters) != null ? _b2 : {};
53
+ });
54
+ const componentKey = computed(() => {
55
+ return JSON.stringify(data.value);
56
+ });
57
+ const enrichmentTags = (_c = (_b = data.value.parameters) == null ? void 0 : _b[CANVAS_ENRICHMENT_TAG_PARAM]) == null ? void 0 : _c.value;
58
+ const renderChildren = () => {
59
+ var _a2, _b2;
60
+ return (_b2 = (_a2 = context.slots).default) == null ? void 0 : _b2.call(_a2, {
61
+ slots: slots.value,
62
+ parameters: parameters.value
63
+ });
64
+ };
65
+ if (isUsingUniformContext()) {
66
+ const TrackComponent = props.behaviorTracking === "onLoad" ? TrackSlot : Track;
67
+ return () => h(
68
+ TrackComponent,
69
+ { behavior: enrichmentTags, key: componentKey.value },
70
+ renderChildren
71
+ );
72
+ }
73
+ return renderChildren;
74
+ }
75
+ });
76
+
77
+ // src/components/DefaultNotImplementedComponent.ts
78
+ import { CANVAS_LOCALIZATION_TYPE } from "@uniformdev/canvas";
79
+ import { defineComponent as defineComponent2, h as h2 } from "vue-demi";
80
+ var wrapperStyles = {
81
+ borderLeft: "4px solid #e42535",
82
+ padding: "16px",
83
+ fontSize: "16px",
84
+ borderRadius: "0 8px 8px 0",
85
+ margin: "8px",
86
+ backgroundColor: "rgba(255, 255, 255, 0.45)",
87
+ color: "#1d3557"
88
+ };
89
+ var DefaultNotImplementedComponent = defineComponent2({
90
+ name: "DefaultNotImplementedComponent",
91
+ props: {
92
+ component: {
93
+ type: Object,
94
+ required: true
95
+ }
96
+ },
97
+ setup(props, { attrs }) {
98
+ var _a;
99
+ const componentType = (_a = props.component) == null ? void 0 : _a.type;
100
+ if (componentType === CANVAS_LOCALIZATION_TYPE) {
101
+ h2("div", { key: "content", style: wrapperStyles }, [
102
+ h2("p", [
103
+ `Seems like localization is not enabled in your application. Please read our documentation on how to `,
104
+ h2(
105
+ "a",
106
+ {
107
+ href: "https://docs.uniform.app/guides/composition/localization#activate-front-end",
108
+ target: "_blank",
109
+ style: { fontWeight: "bolder", textDecoration: "underline" }
110
+ },
111
+ "enable localization in your front-end application."
112
+ )
113
+ ])
114
+ ]);
115
+ }
116
+ return () => h2("div", { key: "content", style: wrapperStyles }, [
117
+ h2("h2", {}, `Component: ${componentType}`),
118
+ h2("p", [
119
+ h2("strong", `${componentType} has no Vue implementation. It may need to be added to your `),
120
+ h2("code", {}, "resolveRenderer()"),
121
+ h2("strong", {}, " function.")
122
+ ]),
123
+ h2("details", {}, [
124
+ h2("summary", {}, "props/attributes"),
125
+ h2(
126
+ "pre",
127
+ {
128
+ style: {
129
+ overflowX: "auto"
130
+ }
131
+ },
132
+ `${JSON.stringify(attrs)}`
133
+ )
134
+ ])
135
+ ]);
136
+ }
137
+ });
138
+
139
+ // src/components/SlotContent.ts
140
+ import {
141
+ CANVAS_PERSONALIZE_TYPE,
142
+ CANVAS_TEST_TYPE,
143
+ IN_CONTEXT_EDITOR_COMPONENT_START_ROLE,
144
+ mapSlotToPersonalizedVariations,
145
+ mapSlotToTestVariations,
146
+ PLACEHOLDER_ID
147
+ } from "@uniformdev/canvas";
148
+ import { Personalize, Test } from "@uniformdev/context-vue";
149
+ import {
150
+ computed as computed2,
151
+ defineComponent as defineComponent3,
152
+ h as h3,
153
+ inject as inject2
154
+ } from "vue-demi";
155
+
156
+ // src/utils/convertComponentToProps.ts
157
+ function convertComponentToProps(component) {
158
+ var _a;
159
+ const parameters = (_a = component.parameters) != null ? _a : {};
160
+ const flatParams = Object.entries(parameters).reduce(
161
+ (props, [key, { value }]) => ({
162
+ ...props,
163
+ [normalizePropName(key)]: value
164
+ }),
165
+ {}
166
+ );
167
+ const renderComponentProps = {
168
+ ...flatParams,
169
+ ...component.data,
170
+ component
171
+ };
172
+ return renderComponentProps;
173
+ }
174
+ function normalizePropName(name) {
175
+ return name.replace("$", "");
176
+ }
177
+
178
+ // src/components/SlotContent.ts
179
+ var SlotContent = defineComponent3({
180
+ name: CANVAS_SLOT_CONTENT_TYPE,
181
+ inheritAttrs: false,
182
+ props: {
183
+ name: {
184
+ type: String
185
+ },
186
+ resolveRenderer: {
187
+ type: Function
188
+ }
189
+ },
190
+ setup(props, context) {
191
+ var _a;
192
+ const componentData = inject2(compositionInjectionKey);
193
+ const resolveRenderer = (_a = props.resolveRenderer) != null ? _a : inject2(resolveRendererInjectionKey);
194
+ const emptyPlaceholder = context.slots.emptyPlaceholder;
195
+ if (!componentData || !resolveRenderer) {
196
+ throw new Error("<SlotContent /> can only be used inside a <Composition />");
197
+ }
198
+ const slotItems = computed2(() => {
199
+ var _a2, _b, _c;
200
+ if (props.name) {
201
+ return (_b = (_a2 = componentData == null ? void 0 : componentData.value.slots) == null ? void 0 : _a2[props.name]) != null ? _b : [];
202
+ }
203
+ return Object.values((_c = componentData == null ? void 0 : componentData.value.slots) != null ? _c : {}).flat();
204
+ });
205
+ const childrenToRender = slotItems.value.map((component, index) => {
206
+ const child = renderComponent({
207
+ component,
208
+ resolveRenderer,
209
+ indexInSlot: index,
210
+ slotName: props.name,
211
+ parentComponent: componentData.value,
212
+ slotChildrenCount: slotItems.value.length,
213
+ emptyPlaceholder
214
+ });
215
+ return context.slots.default ? context.slots.default({ child, component }) : child;
216
+ });
217
+ return () => childrenToRender;
218
+ }
219
+ });
220
+ function renderPersonalizeComponent(component, resolveRenderer) {
221
+ var _a, _b, _c, _d, _e, _f;
222
+ const parameters = component == null ? void 0 : component.parameters;
223
+ const processedVariants = mapSlotToPersonalizedVariations((_a = component.slots) == null ? void 0 : _a.pz);
224
+ const name = (_d = (_c = (_b = component.parameters) == null ? void 0 : _b.trackingEventName) == null ? void 0 : _c.value) != null ? _d : "Untitled Personalization";
225
+ return h3(Personalize, {
226
+ name,
227
+ component: (variant) => resolveRenderer(variant),
228
+ variations: processedVariants,
229
+ count: Number((_f = (_e = parameters == null ? void 0 : parameters.count) == null ? void 0 : _e.value) != null ? _f : 1)
230
+ });
231
+ }
232
+ function renderTestComponent(component, resolveRenderer) {
233
+ var _a, _b, _c, _d, _e;
234
+ const variants = (_b = (_a = component == null ? void 0 : component.slots) == null ? void 0 : _a.test) != null ? _b : [];
235
+ const testName = (_e = (_d = (_c = component == null ? void 0 : component.parameters) == null ? void 0 : _c.test) == null ? void 0 : _d.value) != null ? _e : "Untitled Test";
236
+ const finalVariants = mapSlotToTestVariations(variants);
237
+ return h3(Test, {
238
+ variations: finalVariants,
239
+ name: testName,
240
+ component: (variant) => resolveRenderer(variant)
241
+ });
242
+ }
243
+ function renderComponent({
244
+ component,
245
+ resolveRenderer,
246
+ indexInSlot,
247
+ slotName,
248
+ parentComponent,
249
+ slotChildrenCount,
250
+ emptyPlaceholder
251
+ }) {
252
+ var _a, _b;
253
+ if (component.type === CANVAS_TEST_TYPE) {
254
+ return renderTestComponent(
255
+ component,
256
+ (component2) => renderComponent({ component: component2, resolveRenderer })
257
+ );
258
+ }
259
+ if (component.type === CANVAS_PERSONALIZE_TYPE) {
260
+ return renderPersonalizeComponent(
261
+ component,
262
+ (component2) => renderComponent({ component: component2, resolveRenderer })
263
+ );
264
+ }
265
+ const resolvedComponent = resolveRenderer == null ? void 0 : resolveRenderer(component);
266
+ if (resolvedComponent) {
267
+ const props = convertComponentToProps(component);
268
+ const shouldRenderContextualEditingTags = Boolean(component._id);
269
+ const isPlaceholder = component._id === PLACEHOLDER_ID;
270
+ const elementsToRender = shouldRenderContextualEditingTags ? [
271
+ h3("script", {
272
+ "data-role": IN_CONTEXT_EDITOR_COMPONENT_START_ROLE,
273
+ "data-parent-id": parentComponent == null ? void 0 : parentComponent._id,
274
+ "data-parent-type": parentComponent == null ? void 0 : parentComponent.type,
275
+ "data-component-id": component._id,
276
+ "data-slot-name": slotName,
277
+ "data-component-index": indexInSlot,
278
+ "data-total-components": slotChildrenCount,
279
+ "data-component-name": component.type,
280
+ "data-is-placeholder": isPlaceholder ? "true" : void 0,
281
+ "data-component-title": (_b = (_a = component.parameters) == null ? void 0 : _a.title) == null ? void 0 : _b.value
282
+ }),
283
+ isPlaceholder && emptyPlaceholder !== void 0 ? emptyPlaceholder() : h3(resolvedComponent, props),
284
+ h3("script", { "data-role": "component-end" })
285
+ ] : [h3(resolvedComponent, props)];
286
+ return h3(Composition, { data: component, resolveRenderer }, () => elementsToRender);
287
+ }
288
+ console.warn(
289
+ `[canvas] found component of type '${component.type}' which the 'resolveRenderer' prop returned no component for. Nothing will be rendered. The resolveRenderer function may need to be extended to handle the new type.`,
290
+ component
291
+ );
292
+ return h3("");
293
+ }
294
+
295
+ // src/composables/useCompositionEventEffect.ts
296
+ import {
297
+ CANVAS_DRAFT_STATE,
298
+ createEventBus,
299
+ subscribeToComposition
300
+ } from "@uniformdev/canvas";
301
+ import { watch } from "vue-demi";
302
+ async function useCompositionEventEffect({
303
+ enabled,
304
+ projectId,
305
+ compositionIdRef,
306
+ effect
307
+ }) {
308
+ let unsubscribe;
309
+ watch(
310
+ [() => enabled, () => compositionIdRef.value, () => projectId],
311
+ async () => {
312
+ unsubscribe == null ? void 0 : unsubscribe();
313
+ if (!enabled || !compositionIdRef.value || !projectId) {
314
+ return;
315
+ }
316
+ const eventBus = await createEventBus();
317
+ if (eventBus) {
318
+ unsubscribe = subscribeToComposition({
319
+ eventBus,
320
+ compositionId: compositionIdRef.value,
321
+ compositionState: CANVAS_DRAFT_STATE,
322
+ projectId,
323
+ callback: effect,
324
+ event: "updated"
325
+ });
326
+ }
327
+ },
328
+ { immediate: true }
329
+ );
330
+ }
331
+
332
+ // src/composables/useContextualEditing.ts
333
+ import {
334
+ createCanvasChannel,
335
+ IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
336
+ isUpdateCompositionMessage
337
+ } from "@uniformdev/canvas";
338
+ import { computed as computed3, onMounted, ref, watch as watch2 } from "vue-demi";
339
+ var previewScriptId = "uniform-canvas-preview-script";
340
+ var createApiEnhancer = ({ apiUrl }) => {
341
+ return async (message) => {
342
+ const response = await fetch(apiUrl, {
343
+ method: "post",
344
+ body: JSON.stringify({
345
+ composition: message.composition,
346
+ hash: message.hash
347
+ }),
348
+ headers: {
349
+ "Content-Type": "application/json"
350
+ }
351
+ });
352
+ const json = await response.json();
353
+ if (!response.ok) {
354
+ throw new Error("Error reading enhanced composition");
355
+ }
356
+ const body = json;
357
+ return body.composition;
358
+ };
359
+ };
360
+ var useContextualEditing = ({
361
+ initialCompositionValue,
362
+ enhance = (message) => message.composition
363
+ }) => {
364
+ const contextualComposition = ref();
365
+ const channel = computed3(() => {
366
+ var _a;
367
+ if (!isInContextEditingMode()) {
368
+ return;
369
+ }
370
+ const channel2 = createCanvasChannel({
371
+ broadcastTo: [(_a = window.opener) != null ? _a : window.top],
372
+ listenTo: [window]
373
+ });
374
+ return channel2;
375
+ });
376
+ watch2(
377
+ [channel, () => enhance],
378
+ () => {
379
+ if (!channel.value) {
380
+ return;
381
+ }
382
+ const unsubscribe = channel.value.on("update-composition", async (message) => {
383
+ if (isUpdateCompositionMessage(message)) {
384
+ const composition = await enhance(message);
385
+ contextualComposition.value = composition;
386
+ }
387
+ });
388
+ return () => {
389
+ unsubscribe();
390
+ };
391
+ },
392
+ { immediate: true }
393
+ );
394
+ onMounted(() => {
395
+ if (!isInContextEditingMode()) {
396
+ return;
397
+ }
398
+ const existingScript = document.getElementById(previewScriptId);
399
+ if (existingScript) {
400
+ return;
401
+ }
402
+ const script = document.createElement("script");
403
+ script.id = previewScriptId;
404
+ script.src = getCanvasInContextEmbedScriptUrl();
405
+ script.async = true;
406
+ document.head.appendChild(script);
407
+ });
408
+ return {
409
+ composition: contextualComposition != null ? contextualComposition : initialCompositionValue
410
+ };
411
+ };
412
+ function getCanvasInContextEmbedScriptUrl() {
413
+ const scriptUrl = `${window.document.referrer}files/canvas-in-context-embed/index.js`;
414
+ return scriptUrl;
415
+ }
416
+ function isInContextEditingMode() {
417
+ if (typeof window === "undefined") {
418
+ return false;
419
+ }
420
+ const isOpenedByInContextEditor = new URLSearchParams(window.location.search).has(
421
+ IN_CONTEXT_EDITOR_QUERY_STRING_PARAM
422
+ );
423
+ const isAllowlistedReferrer = Boolean(
424
+ window.document.referrer.match(/(^https:\/\/|\.)(uniform.app|uniform.wtf|localhost:\d{4})\//)
425
+ );
426
+ return isOpenedByInContextEditor && isAllowlistedReferrer;
427
+ }
428
+ export {
429
+ CANVAS_COMPOSITION_TYPE,
430
+ CANVAS_SLOT_CONTENT_TYPE,
431
+ Composition,
432
+ DefaultNotImplementedComponent,
433
+ SlotContent,
434
+ compositionInjectionKey,
435
+ convertComponentToProps,
436
+ createApiEnhancer,
437
+ resolveRendererInjectionKey,
438
+ useCompositionEventEffect,
439
+ useContextualEditing
440
+ };