@uniformdev/next-app-router-client 20.7.1-alpha.118

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/index.js ADDED
@@ -0,0 +1,550 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ ClientContextTestTransfer: () => ClientContextTestTransfer,
35
+ ClientUniformText: () => ClientUniformText,
36
+ ContextUpdateTransfer: () => ContextUpdateTransfer,
37
+ DefaultUniformClientContext: () => DefaultUniformClientContext,
38
+ Personalize: () => Personalize,
39
+ UniformScript: () => UniformScript,
40
+ VisibilityRulesWrapperClient: () => VisibilityRulesWrapperClient,
41
+ createClientUniformContext: () => createClientUniformContext,
42
+ useInitUniformContext: () => useInitUniformContext,
43
+ useQuirks: () => useQuirks,
44
+ useScores: () => useScores,
45
+ useUniformContext: () => useUniformContext
46
+ });
47
+ module.exports = __toCommonJS(src_exports);
48
+
49
+ // src/components/ClientContextTestTransfer.tsx
50
+ var import_react3 = require("react");
51
+
52
+ // src/hooks/useStableValue.ts
53
+ var import_react = require("react");
54
+ var useStableValue = (value, isValid) => {
55
+ const previousRef = (0, import_react.useRef)(null);
56
+ const [stableValue, setStableValue] = (0, import_react.useState)(void 0);
57
+ (0, import_react.useEffect)(() => {
58
+ const serialized = JSON.stringify(value);
59
+ const valid = isValid ? isValid(value) : true;
60
+ if (serialized !== previousRef.current && valid) {
61
+ previousRef.current = serialized;
62
+ setStableValue(value);
63
+ }
64
+ }, [value]);
65
+ return stableValue;
66
+ };
67
+
68
+ // src/hooks/useUniformContext.ts
69
+ var import_react2 = require("react");
70
+ var useUniformContext = () => {
71
+ const [context, setContext] = (0, import_react2.useState)(
72
+ typeof window !== "undefined" ? window.__UNIFORM_CONTEXT__ : void 0
73
+ );
74
+ useInterval(
75
+ () => {
76
+ if (context) {
77
+ return;
78
+ }
79
+ if (window.__UNIFORM_CONTEXT__) {
80
+ setContext(window.__UNIFORM_CONTEXT__);
81
+ }
82
+ },
83
+ 100,
84
+ !context
85
+ );
86
+ return {
87
+ context
88
+ };
89
+ };
90
+ var useInterval = (callback, delay, enabled) => {
91
+ const intervalRef = (0, import_react2.useRef)(null);
92
+ (0, import_react2.useEffect)(() => {
93
+ if (!enabled) {
94
+ if (intervalRef.current) {
95
+ clearInterval(intervalRef.current);
96
+ }
97
+ return;
98
+ }
99
+ const interval = setInterval(callback, delay);
100
+ return () => clearInterval(interval);
101
+ }, [callback, delay, enabled]);
102
+ };
103
+
104
+ // src/components/ClientContextTestTransfer.tsx
105
+ var hasVariantId = (event) => Boolean(event.variantId);
106
+ var ClientContextTestTransfer = ({ event }) => {
107
+ const { context } = useUniformContext();
108
+ const stableEvent = useStableValue(event, hasVariantId);
109
+ (0, import_react3.useEffect)(() => {
110
+ if (context && stableEvent) {
111
+ context.internal_processTestEvent(stableEvent);
112
+ }
113
+ }, [context, stableEvent]);
114
+ return null;
115
+ };
116
+
117
+ // src/components/ClientUniformText.tsx
118
+ var import_canvas = require("@uniformdev/canvas");
119
+ var import_react5 = require("react");
120
+
121
+ // src/hooks/useQuirks.ts
122
+ var import_react4 = require("react");
123
+ function useQuirks() {
124
+ var _a;
125
+ const { context } = useUniformContext();
126
+ const [quirks, setQuirks] = (0, import_react4.useState)((_a = context == null ? void 0 : context.quirks) != null ? _a : {});
127
+ (0, import_react4.useEffect)(() => {
128
+ if (!context) {
129
+ return;
130
+ }
131
+ const quirkChangeListener = (updatedQuirks) => {
132
+ setQuirks(updatedQuirks);
133
+ };
134
+ setQuirks(context.quirks);
135
+ context == null ? void 0 : context.events.on("quirksUpdated", quirkChangeListener);
136
+ return () => {
137
+ context == null ? void 0 : context.events.off("quirksUpdated", quirkChangeListener);
138
+ };
139
+ }, [context]);
140
+ return quirks;
141
+ }
142
+
143
+ // src/components/ClientUniformText.tsx
144
+ var import_jsx_runtime = require("react/jsx-runtime");
145
+ var ClientUniformText = ({
146
+ as,
147
+ component,
148
+ parameter: providedParameter,
149
+ isMultiline = false,
150
+ placeholder,
151
+ render = (value) => value != null ? value : "",
152
+ ...props
153
+ }) => {
154
+ const parameter = providedParameter;
155
+ const quirks = useQuirks();
156
+ const rules = (0, import_react5.useMemo)(() => {
157
+ return {
158
+ ...(0, import_canvas.createQuirksVisibilityRule)(quirks)
159
+ };
160
+ }, [quirks]);
161
+ const currentValue = (0, import_react5.useMemo)(() => {
162
+ var _a;
163
+ if (!parameter) {
164
+ return void 0;
165
+ }
166
+ if (!rules.length || !((_a = parameter.conditions) == null ? void 0 : _a.length)) {
167
+ return parameter.value;
168
+ }
169
+ const match = (0, import_canvas.evaluatePropertyCriteria)({
170
+ baseValue: parameter.value,
171
+ conditionalValues: parameter.conditions,
172
+ rules
173
+ });
174
+ if (typeof match.currentValue === "string") {
175
+ return match.currentValue;
176
+ }
177
+ return parameter.value;
178
+ }, [rules, parameter]);
179
+ if (!parameter || parameter.type !== "text") {
180
+ return null;
181
+ }
182
+ const Tag = as || "span";
183
+ const parameterId = parameter.parameterId;
184
+ const isContextualEditing = Boolean(parameter._contextualEditing);
185
+ if (!isContextualEditing) {
186
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Tag, { style: isMultiline ? { whiteSpace: "pre-wrap" } : {}, ...props, children: render(currentValue) });
187
+ }
188
+ const computedPlaceholder = typeof placeholder === "function" ? placeholder({ id: parameterId }) : placeholder;
189
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
190
+ Tag,
191
+ {
192
+ ...props,
193
+ ...getParameterAttributes({
194
+ component,
195
+ parameter,
196
+ placeholder: computedPlaceholder,
197
+ isMultiline
198
+ }),
199
+ "data-uniform-parameter-type": "text",
200
+ "data-uniform-placeholder": computedPlaceholder,
201
+ style: isMultiline ? { whiteSpace: "pre-wrap" } : {},
202
+ children: isContextualEditing ? currentValue : render(currentValue)
203
+ }
204
+ );
205
+ };
206
+ var getParameterAttributes = ({
207
+ component,
208
+ parameter,
209
+ placeholder,
210
+ isMultiline = false
211
+ }) => {
212
+ var _a, _b;
213
+ const value = parameter == null ? void 0 : parameter.value;
214
+ const type = parameter == null ? void 0 : parameter.type;
215
+ const isEditable = (_b = (_a = parameter == null ? void 0 : parameter._contextualEditing) == null ? void 0 : _a.isEditable) != null ? _b : false;
216
+ return {
217
+ [import_canvas.ATTRIBUTE_COMPONENT_ID]: component._id,
218
+ [import_canvas.ATTRIBUTE_PARAMETER_ID]: parameter.parameterId,
219
+ [import_canvas.ATTRIBUTE_PARAMETER_VALUE]: String(value != null ? value : ""),
220
+ [import_canvas.ATTRIBUTE_PARAMETER_TYPE]: type,
221
+ [import_canvas.ATTRIBUTE_PLACEHOLDER]: placeholder,
222
+ [import_canvas.ATTRIBUTE_MULTILINE]: isMultiline,
223
+ contentEditable: isEditable,
224
+ suppressContentEditableWarning: true
225
+ };
226
+ };
227
+
228
+ // src/components/ContextUpdateTransfer.tsx
229
+ var import_react6 = require("react");
230
+ var hasKeys = (obj) => Object.keys(obj).length > 0;
231
+ var ContextUpdateTransfer = ({ update }) => {
232
+ const { context } = useUniformContext();
233
+ const stableUpdate = useStableValue(update, hasKeys);
234
+ (0, import_react6.useEffect)(() => {
235
+ if (context && stableUpdate) {
236
+ context.update(stableUpdate);
237
+ }
238
+ }, [context, stableUpdate]);
239
+ return null;
240
+ };
241
+
242
+ // src/components/DefaultUniformClientContext.tsx
243
+ var import_context3 = require("@uniformdev/context");
244
+ var import_navigation2 = require("next/navigation");
245
+
246
+ // src/context/createUniformContext.ts
247
+ var import_context = require("@uniformdev/context");
248
+ var createUniformContext = ({
249
+ serverCookieValue,
250
+ quirkCookieValue,
251
+ experimental_quirksEnabled,
252
+ cookieAttributes,
253
+ ...rest
254
+ }) => {
255
+ const context = new import_context.Context({
256
+ ...rest,
257
+ transitionStore: new import_context.CookieTransitionDataStore({
258
+ serverCookieValue,
259
+ quirkCookieValue,
260
+ cookieAttributes,
261
+ experimental_quirksEnabled
262
+ })
263
+ });
264
+ return context;
265
+ };
266
+
267
+ // src/context/createClientUniformContext.ts
268
+ var createClientUniformContext = (options) => {
269
+ return createUniformContext({
270
+ ...options,
271
+ serverCookieValue: void 0
272
+ });
273
+ };
274
+
275
+ // src/hooks/useInitUniformContext.ts
276
+ var import_context2 = require("@uniformdev/context");
277
+ var import_next_app_router_shared = require("@uniformdev/next-app-router-shared");
278
+ var import_js_cookie = __toESM(require("js-cookie"));
279
+ var import_navigation = require("next/navigation");
280
+ var import_react7 = require("react");
281
+ var useInitUniformContext = (callback, compositionMetadata) => {
282
+ const path = (0, import_navigation.usePathname)();
283
+ const searchParams = (0, import_navigation.useSearchParams)();
284
+ const context = (0, import_react7.useRef)(void 0);
285
+ if (typeof window !== "undefined" && context.current === void 0) {
286
+ context.current = callback();
287
+ }
288
+ (0, import_react7.useEffect)(() => {
289
+ var _a;
290
+ if (typeof window === "undefined" || typeof window.__UNIFORM_CONTEXT__ !== "undefined") {
291
+ return;
292
+ }
293
+ const url = new URL(path, "https://example.com");
294
+ searchParams.forEach((value, key) => {
295
+ url.searchParams.set(key, value);
296
+ });
297
+ const scoreCookie = import_js_cookie.default.get(import_next_app_router_shared.UNIFORM_MIDDLEWARE_SCORE_COOKIE_NAME);
298
+ const quirkCookie = import_js_cookie.default.get(import_next_app_router_shared.UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME);
299
+ const scoreCookieData = (0, import_context2.parseScoreCookie)(scoreCookie, quirkCookie);
300
+ import_js_cookie.default.remove(import_next_app_router_shared.UNIFORM_MIDDLEWARE_SCORE_COOKIE_NAME);
301
+ import_js_cookie.default.remove(import_next_app_router_shared.UNIFORM_MIDDLEWARE_QUIRK_COOKIE_NAME);
302
+ context.current.update({
303
+ url,
304
+ compositionMetadata,
305
+ quirks: (_a = scoreCookieData == null ? void 0 : scoreCookieData.quirks) != null ? _a : {}
306
+ });
307
+ if (!window.__UNIFORM_CONTEXT__) {
308
+ window.__UNIFORM_CONTEXT__ = context.current;
309
+ }
310
+ }, [path, searchParams, compositionMetadata]);
311
+ };
312
+
313
+ // src/components/DefaultUniformClientContext.tsx
314
+ var DefaultUniformClientContext = ({
315
+ manifest,
316
+ disableDevTools,
317
+ defaultConsent,
318
+ experimentalQuirkSerialization,
319
+ compositionMetadata
320
+ }) => {
321
+ const router = (0, import_navigation2.useRouter)();
322
+ useInitUniformContext(() => {
323
+ const plugins = [];
324
+ if (!disableDevTools) {
325
+ plugins.push(
326
+ (0, import_context3.enableContextDevTools)({
327
+ onAfterMessageReceived: () => {
328
+ router.refresh();
329
+ }
330
+ })
331
+ );
332
+ }
333
+ return createClientUniformContext({
334
+ manifest,
335
+ plugins,
336
+ defaultConsent,
337
+ experimental_quirksEnabled: experimentalQuirkSerialization
338
+ });
339
+ }, compositionMetadata);
340
+ return null;
341
+ };
342
+
343
+ // src/components/Personalize.tsx
344
+ var import_canvas2 = require("@uniformdev/canvas");
345
+ var import_next_app_router_shared2 = require("@uniformdev/next-app-router-shared");
346
+ var import_react9 = require("react");
347
+
348
+ // src/hooks/useScores.ts
349
+ var import_react8 = require("react");
350
+ function useScores() {
351
+ const { context } = useUniformContext();
352
+ const [scores, setScores] = (0, import_react8.useState)(context == null ? void 0 : context.scores);
353
+ (0, import_react8.useEffect)(() => {
354
+ if (!context) {
355
+ return;
356
+ }
357
+ const scoringChangeListener = (updatedScores) => {
358
+ setScores(updatedScores);
359
+ };
360
+ setScores(context.scores);
361
+ context.events.on("scoresUpdated", scoringChangeListener);
362
+ return () => {
363
+ context.events.off("scoresUpdated", scoringChangeListener);
364
+ };
365
+ }, [context]);
366
+ return scores;
367
+ }
368
+
369
+ // src/components/Personalize.tsx
370
+ var Personalize = ({
371
+ parameters,
372
+ indexes,
373
+ slots,
374
+ context: compositionContext
375
+ }) => {
376
+ var _a, _b;
377
+ const trackingEventName = (_a = parameters.trackingEventName) == null ? void 0 : _a.value;
378
+ const algorithm = (_b = parameters.algorithm) == null ? void 0 : _b.value;
379
+ const personalizationSlot = slots[import_canvas2.CANVAS_PERSONALIZE_SLOT];
380
+ const { context } = useUniformContext();
381
+ const scores = useScores();
382
+ const quirks = useQuirks();
383
+ const [indexesToShow, setIndexesToShow] = (0, import_react9.useState)(indexes);
384
+ (0, import_react9.useEffect)(() => {
385
+ if (typeof context === "undefined" || !personalizationSlot) {
386
+ return;
387
+ }
388
+ const result = (0, import_next_app_router_shared2.evaluatePersonalization)({
389
+ context,
390
+ compositionContext,
391
+ personalization: {
392
+ name: trackingEventName != null ? trackingEventName : "unknown",
393
+ algorithm,
394
+ variations: personalizationSlot.items.filter(Boolean).map((item, index) => {
395
+ var _a2;
396
+ return {
397
+ index,
398
+ id: (_a2 = item.variantId) != null ? _a2 : item._id,
399
+ pz: item.$pzCrit,
400
+ componentId: item._id
401
+ };
402
+ }),
403
+ compositionMetadata: {
404
+ compositionId: compositionContext._id,
405
+ matchedRoute: compositionContext.matchedRoute,
406
+ dynamicInputs: compositionContext.dynamicInputs
407
+ }
408
+ }
409
+ });
410
+ if (JSON.stringify(result.indexes) !== JSON.stringify(indexesToShow)) {
411
+ setIndexesToShow(result.indexes);
412
+ }
413
+ }, [
414
+ trackingEventName,
415
+ context,
416
+ personalizationSlot,
417
+ algorithm,
418
+ compositionContext,
419
+ scores,
420
+ quirks,
421
+ indexesToShow
422
+ ]);
423
+ const slotsToShow = (0, import_react9.useMemo)(() => {
424
+ return indexesToShow.map((key) => {
425
+ var _a2;
426
+ return (_a2 = personalizationSlot == null ? void 0 : personalizationSlot.items[key]) == null ? void 0 : _a2.component;
427
+ });
428
+ }, [indexesToShow, personalizationSlot]);
429
+ return (0, import_react9.createElement)(import_react9.Fragment, void 0, slotsToShow);
430
+ };
431
+
432
+ // src/components/UniformScript.tsx
433
+ var import_canvas3 = require("@uniformdev/canvas");
434
+ var import_navigation3 = require("next/navigation");
435
+ var import_react10 = require("react");
436
+ var import_jsx_runtime2 = require("react/jsx-runtime");
437
+ var UniformScript = () => {
438
+ const router = (0, import_navigation3.useRouter)();
439
+ const needsToRefreshRef = (0, import_react10.useRef)(false);
440
+ const channel = (0, import_react10.useMemo)(() => {
441
+ var _a;
442
+ if (typeof window === "undefined") {
443
+ return;
444
+ }
445
+ const instance = (0, import_canvas3.createCanvasChannel)({
446
+ broadcastTo: [(_a = window.opener) != null ? _a : window.top],
447
+ listenTo: [window]
448
+ });
449
+ return instance;
450
+ }, []);
451
+ (0, import_react10.useEffect)(() => {
452
+ if (!channel) {
453
+ return;
454
+ }
455
+ const unsubscribeFromEditorUpdates = channel.on("editor-state-updated", () => {
456
+ const el = document.activeElement;
457
+ const isActiveElementEditable = el == null ? void 0 : el.isContentEditable;
458
+ if (!isActiveElementEditable) {
459
+ router.refresh();
460
+ } else {
461
+ needsToRefreshRef.current = true;
462
+ }
463
+ });
464
+ return () => {
465
+ unsubscribeFromEditorUpdates();
466
+ };
467
+ }, [channel, router]);
468
+ (0, import_react10.useEffect)(() => {
469
+ if (typeof window === "undefined") {
470
+ return;
471
+ }
472
+ const existing = document.getElementById("uniform-script");
473
+ if (!existing) {
474
+ const textHost = (0, import_canvas3.isAllowedReferrer)(window.document.referrer) ? window.document.referrer : "https://uniform.app/";
475
+ window.__UNIFORM_CONTEXTUAL_EDITING__ = {
476
+ framework: "React",
477
+ version: 2
478
+ };
479
+ const bundleHost = new URL(textHost);
480
+ bundleHost.pathname = "/files/canvas-in-context-embed/index.js";
481
+ const script = document.createElement("script");
482
+ script.id = "uniform-script";
483
+ script.setAttribute("data-rsc", "true");
484
+ script.src = bundleHost.toString();
485
+ script.async = true;
486
+ document.head.appendChild(script);
487
+ }
488
+ }, []);
489
+ (0, import_react10.useEffect)(() => {
490
+ const handleBlurChange = () => {
491
+ if (needsToRefreshRef.current) {
492
+ router.refresh();
493
+ needsToRefreshRef.current = false;
494
+ }
495
+ };
496
+ document.addEventListener("blur", handleBlurChange, true);
497
+ return () => {
498
+ document.removeEventListener("focus", handleBlurChange, true);
499
+ };
500
+ }, [router]);
501
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, {});
502
+ };
503
+
504
+ // src/components/VisibilityRulesWrapperClient.tsx
505
+ var import_canvas4 = require("@uniformdev/canvas");
506
+ var import_react11 = require("react");
507
+ var import_jsx_runtime3 = require("react/jsx-runtime");
508
+ var VisibilityRulesWrapperClient = ({
509
+ parameter,
510
+ initialIsVisible,
511
+ children
512
+ }) => {
513
+ const [isVisible, setIsVisible] = (0, import_react11.useState)(initialIsVisible);
514
+ const [visibleSource, setVisibleSource] = (0, import_react11.useState)(
515
+ initialIsVisible === null ? "unknown" : "server"
516
+ );
517
+ const quirks = useQuirks();
518
+ const rules = (0, import_react11.useMemo)(() => {
519
+ return {
520
+ ...(0, import_canvas4.createQuirksVisibilityRule)(quirks)
521
+ };
522
+ }, [quirks]);
523
+ (0, import_react11.useEffect)(() => {
524
+ const result = (0, import_canvas4.evaluateNodeVisibilityParameter)({
525
+ rules,
526
+ parameter
527
+ });
528
+ if (visibleSource === "server" && initialIsVisible && !result) {
529
+ return;
530
+ }
531
+ setIsVisible(result);
532
+ setVisibleSource("client");
533
+ }, [initialIsVisible, visibleSource, parameter, rules]);
534
+ return isVisible ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children }) : null;
535
+ };
536
+ // Annotate the CommonJS export names for ESM import in node:
537
+ 0 && (module.exports = {
538
+ ClientContextTestTransfer,
539
+ ClientUniformText,
540
+ ContextUpdateTransfer,
541
+ DefaultUniformClientContext,
542
+ Personalize,
543
+ UniformScript,
544
+ VisibilityRulesWrapperClient,
545
+ createClientUniformContext,
546
+ useInitUniformContext,
547
+ useQuirks,
548
+ useScores,
549
+ useUniformContext
550
+ });