@dotcms/uve 0.0.1-beta.3 → 0.0.1-beta.31

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/public.cjs.js ADDED
@@ -0,0 +1,1127 @@
1
+ 'use strict';
2
+
3
+ var types = require('@dotcms/types');
4
+ var internal = require('@dotcms/types/internal');
5
+
6
+ /**
7
+ * Calculates the bounding information for each page element within the given containers.
8
+ *
9
+ * @export
10
+ * @param {HTMLDivElement[]} containers - An array of HTMLDivElement representing the containers.
11
+ * @return {DotCMSContainerBound[]} An array of objects containing the bounding information for each page element.
12
+ * @example
13
+ * ```ts
14
+ * const containers = document.querySelectorAll('.container');
15
+ * const bounds = getDotCMSPageBounds(containers);
16
+ * console.log(bounds);
17
+ * ```
18
+ */
19
+ function getDotCMSPageBounds(containers) {
20
+ return containers.map(container => {
21
+ const containerRect = container.getBoundingClientRect();
22
+ const contentlets = Array.from(container.querySelectorAll('[data-dot-object="contentlet"]'));
23
+ return {
24
+ x: containerRect.x,
25
+ y: containerRect.y,
26
+ width: containerRect.width,
27
+ height: containerRect.height,
28
+ payload: JSON.stringify({
29
+ container: getDotCMSContainerData(container)
30
+ }),
31
+ contentlets: getDotCMSContentletsBound(containerRect, contentlets)
32
+ };
33
+ });
34
+ }
35
+ /**
36
+ * Calculates the bounding information for each contentlet inside a container.
37
+ *
38
+ * @export
39
+ * @param {DOMRect} containerRect - The bounding rectangle of the container.
40
+ * @param {HTMLDivElement[]} contentlets - An array of HTMLDivElement representing the contentlets.
41
+ * @return {DotCMSContentletBound[]} An array of objects containing the bounding information for each contentlet.
42
+ * @example
43
+ * ```ts
44
+ * const containerRect = container.getBoundingClientRect();
45
+ * const contentlets = container.querySelectorAll('.contentlet');
46
+ * const bounds = getDotCMSContentletsBound(containerRect, contentlets);
47
+ * console.log(bounds); // Element bounds within the container
48
+ * ```
49
+ */
50
+ function getDotCMSContentletsBound(containerRect, contentlets) {
51
+ return contentlets.map(contentlet => {
52
+ const contentletRect = contentlet.getBoundingClientRect();
53
+ return {
54
+ x: 0,
55
+ y: contentletRect.y - containerRect.y,
56
+ width: contentletRect.width,
57
+ height: contentletRect.height,
58
+ payload: JSON.stringify({
59
+ container: contentlet.dataset?.['dotContainer'] ? JSON.parse(contentlet.dataset?.['dotContainer']) : getClosestDotCMSContainerData(contentlet),
60
+ contentlet: {
61
+ identifier: contentlet.dataset?.['dotIdentifier'],
62
+ title: contentlet.dataset?.['dotTitle'],
63
+ inode: contentlet.dataset?.['dotInode'],
64
+ contentType: contentlet.dataset?.['dotType']
65
+ }
66
+ })
67
+ };
68
+ });
69
+ }
70
+ /**
71
+ * Get container data from VTLS.
72
+ *
73
+ * @export
74
+ * @param {HTMLElement} container - The container element.
75
+ * @return {object} An object containing the container data.
76
+ * @example
77
+ * ```ts
78
+ * const container = document.querySelector('.container');
79
+ * const data = getContainerData(container);
80
+ * console.log(data);
81
+ * ```
82
+ */
83
+ function getDotCMSContainerData(container) {
84
+ return {
85
+ acceptTypes: container.dataset?.['dotAcceptTypes'] || '',
86
+ identifier: container.dataset?.['dotIdentifier'] || '',
87
+ maxContentlets: container.dataset?.['maxContentlets'] || '',
88
+ uuid: container.dataset?.['dotUuid'] || ''
89
+ };
90
+ }
91
+ /**
92
+ * Get the closest container data from the contentlet.
93
+ *
94
+ * @export
95
+ * @param {Element} element - The contentlet element.
96
+ * @return {object | null} An object containing the closest container data or null if no container is found.
97
+ * @example
98
+ * ```ts
99
+ * const contentlet = document.querySelector('.contentlet');
100
+ * const data = getClosestDotCMSContainerData(contentlet);
101
+ * console.log(data);
102
+ * ```
103
+ */
104
+ function getClosestDotCMSContainerData(element) {
105
+ // Find the closest ancestor element with data-dot-object="container" attribute
106
+ const container = element.closest('[data-dot-object="container"]');
107
+ // If a container element is found
108
+ if (container) {
109
+ // Return the dataset of the container element
110
+ return getDotCMSContainerData(container);
111
+ } else {
112
+ // If no container element is found, return null
113
+ console.warn('No container found for the contentlet');
114
+ return null;
115
+ }
116
+ }
117
+ /**
118
+ * Find the closest contentlet element based on HTMLElement.
119
+ *
120
+ * @export
121
+ * @param {HTMLElement | null} element - The starting element.
122
+ * @return {HTMLElement | null} The closest contentlet element or null if not found.
123
+ * @example
124
+ * const element = document.querySelector('.some-element');
125
+ * const contentlet = findDotCMSElement(element);
126
+ * console.log(contentlet);
127
+ */
128
+ function findDotCMSElement(element) {
129
+ if (!element) return null;
130
+ if (element?.dataset?.['dotObject'] === 'contentlet' || element?.dataset?.['dotObject'] === 'container' && element.children.length === 0) {
131
+ return element;
132
+ }
133
+ return findDotCMSElement(element?.['parentElement']);
134
+ }
135
+ /**
136
+ * Find VTL data within a target element.
137
+ *
138
+ * @export
139
+ * @param {HTMLElement} target - The target element to search within.
140
+ * @return {Array<{ inode: string, name: string }> | null} An array of objects containing VTL data or null if none found.
141
+ * @example
142
+ * ```ts
143
+ * const target = document.querySelector('.target-element');
144
+ * const vtlData = findDotCMSVTLData(target);
145
+ * console.log(vtlData);
146
+ * ```
147
+ */
148
+ function findDotCMSVTLData(target) {
149
+ const vltElements = target.querySelectorAll('[data-dot-object="vtl-file"]');
150
+ if (!vltElements.length) {
151
+ return null;
152
+ }
153
+ return Array.from(vltElements).map(vltElement => {
154
+ return {
155
+ inode: vltElement.dataset?.['dotInode'],
156
+ name: vltElement.dataset?.['dotUrl']
157
+ };
158
+ });
159
+ }
160
+ /**
161
+ * Check if the scroll position is at the bottom of the page.
162
+ *
163
+ * @export
164
+ * @return {boolean} True if the scroll position is at the bottom, otherwise false.
165
+ * @example
166
+ * ```ts
167
+ * if (dotCMSScrollIsInBottom()) {
168
+ * console.log('Scrolled to the bottom');
169
+ * }
170
+ * ```
171
+ */
172
+ function computeScrollIsInBottom() {
173
+ const documentHeight = document.documentElement.scrollHeight;
174
+ const viewportHeight = window.innerHeight;
175
+ const scrollY = window.scrollY;
176
+ return scrollY + viewportHeight >= documentHeight;
177
+ }
178
+ /**
179
+ *
180
+ *
181
+ * Combine classes into a single string.
182
+ *
183
+ * @param {string[]} classes
184
+ * @returns {string} Combined classes
185
+ */
186
+ const combineClasses = classes => classes.filter(Boolean).join(' ');
187
+ /**
188
+ *
189
+ *
190
+ * Calculates and returns the CSS Grid positioning classes for a column based on its configuration.
191
+ * Uses a 12-column grid system where columns are positioned using grid-column-start and grid-column-end.
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const classes = getColumnPositionClasses({
196
+ * leftOffset: 1, // Starts at the first column
197
+ * width: 6 // Spans 6 columns
198
+ * });
199
+ * // Returns: { startClass: 'col-start-1', endClass: 'col-end-7' }
200
+ * ```
201
+ *
202
+ * @param {DotPageAssetLayoutColumn} column - Column configuration object
203
+ * @param {number} column.leftOffset - Starting position (0-based) in the grid
204
+ * @param {number} column.width - Number of columns to span
205
+ * @returns {{ startClass: string, endClass: string }} Object containing CSS class names for grid positioning
206
+ */
207
+ const getColumnPositionClasses = column => {
208
+ const {
209
+ leftOffset,
210
+ width
211
+ } = column;
212
+ const startClass = `${START_CLASS}${leftOffset}`;
213
+ const endClass = `${END_CLASS}${leftOffset + width}`;
214
+ return {
215
+ startClass,
216
+ endClass
217
+ };
218
+ };
219
+ /**
220
+ *
221
+ *
222
+ * Helper function that returns an object containing the dotCMS data attributes.
223
+ * @param {DotCMSBasicContentlet} contentlet - The contentlet to get the attributes for
224
+ * @param {string} container - The container to get the attributes for
225
+ * @returns {DotContentletAttributes} The dotCMS data attributes
226
+ */
227
+ function getDotContentletAttributes(contentlet, container) {
228
+ return {
229
+ 'data-dot-identifier': contentlet?.identifier,
230
+ 'data-dot-basetype': contentlet?.baseType,
231
+ 'data-dot-title': contentlet?.['widgetTitle'] || contentlet?.title,
232
+ 'data-dot-inode': contentlet?.inode,
233
+ 'data-dot-type': contentlet?.contentType,
234
+ 'data-dot-container': container,
235
+ 'data-dot-on-number-of-pages': contentlet?.['onNumberOfPages'] || '1'
236
+ };
237
+ }
238
+ /**
239
+ *
240
+ *
241
+ * Retrieves container data from a DotCMS page asset using the container reference.
242
+ * This function processes the container information and returns a standardized format
243
+ * for container editing.
244
+ *
245
+ * @param {DotCMSPageAsset} dotCMSPageAsset - The page asset containing all containers data
246
+ * @param {DotCMSColumnContainer} columContainer - The container reference from the layout
247
+ * @throws {Error} When page asset is invalid or container is not found
248
+ * @returns {EditableContainerData} Formatted container data for editing
249
+ *
250
+ * @example
251
+ * const containerData = getContainersData(pageAsset, containerRef);
252
+ * // Returns: { uuid: '123', identifier: 'cont1', acceptTypes: 'type1,type2', maxContentlets: 5 }
253
+ */
254
+ const getContainersData = (dotCMSPageAsset, columContainer) => {
255
+ const {
256
+ identifier,
257
+ uuid
258
+ } = columContainer;
259
+ const dotContainer = dotCMSPageAsset.containers[identifier];
260
+ if (!dotContainer) {
261
+ return null;
262
+ }
263
+ const {
264
+ containerStructures,
265
+ container
266
+ } = dotContainer;
267
+ const acceptTypes = containerStructures?.map(structure => structure.contentTypeVar).join(',') ?? '';
268
+ const variantId = container?.parentPermissionable?.variantId;
269
+ const maxContentlets = container?.maxContentlets ?? 0;
270
+ const path = container?.path;
271
+ return {
272
+ uuid,
273
+ variantId,
274
+ acceptTypes,
275
+ maxContentlets,
276
+ identifier: path ?? identifier
277
+ };
278
+ };
279
+ /**
280
+ *
281
+ *
282
+ * Retrieves the contentlets (content items) associated with a specific container.
283
+ * Handles different UUID formats and provides warning for missing contentlets.
284
+ *
285
+ * @param {DotCMSPageAsset} dotCMSPageAsset - The page asset containing all containers data
286
+ * @param {DotCMSColumnContainer} columContainer - The container reference from the layout
287
+ * @returns {DotCMSBasicContentlet[]} Array of contentlets in the container
288
+ *
289
+ * @example
290
+ * const contentlets = getContentletsInContainer(pageAsset, containerRef);
291
+ * // Returns: [{ identifier: 'cont1', ... }, { identifier: 'cont2', ... }]
292
+ */
293
+ const getContentletsInContainer = (dotCMSPageAsset, columContainer) => {
294
+ const {
295
+ identifier,
296
+ uuid
297
+ } = columContainer;
298
+ const {
299
+ contentlets
300
+ } = dotCMSPageAsset.containers[identifier];
301
+ const contentletsInContainer = contentlets[`uuid-${uuid}`] || contentlets[`uuid-dotParser_${uuid}`] || [];
302
+ if (!contentletsInContainer) {
303
+ console.warn(`We couldn't find the contentlets for the container with the identifier ${identifier} and the uuid ${uuid} becareful by adding content to this container.\nWe recommend to change the container in the layout and add the content again.`);
304
+ }
305
+ return contentletsInContainer;
306
+ };
307
+ /**
308
+ *
309
+ *
310
+ * Generates the required DotCMS data attributes for a container element.
311
+ * These attributes are used by DotCMS for container identification and functionality.
312
+ *
313
+ * @param {EditableContainerData} params - Container data including uuid, identifier, acceptTypes, and maxContentlets
314
+ * @returns {DotContainerAttributes} Object containing all necessary data attributes
315
+ *
316
+ * @example
317
+ * const attributes = getDotContainerAttributes({
318
+ * uuid: '123',
319
+ * identifier: 'cont1',
320
+ * acceptTypes: 'type1,type2',
321
+ * maxContentlets: 5
322
+ * });
323
+ * // Returns: { 'data-dot-object': 'container', 'data-dot-identifier': 'cont1', ... }
324
+ */
325
+ function getDotContainerAttributes({
326
+ uuid,
327
+ identifier,
328
+ acceptTypes,
329
+ maxContentlets
330
+ }) {
331
+ return {
332
+ 'data-dot-object': 'container',
333
+ 'data-dot-accept-types': acceptTypes,
334
+ 'data-dot-identifier': identifier,
335
+ 'data-max-contentlets': maxContentlets.toString(),
336
+ 'data-dot-uuid': uuid
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Subscribes to content changes in the UVE editor
342
+ *
343
+ * @param {UVEEventHandler} callback - Function to be called when content changes are detected
344
+ * @returns {Object} Object containing unsubscribe function and event type
345
+ * @returns {Function} .unsubscribe - Function to remove the event listener
346
+ * @returns {UVEEventType} .event - The event type being subscribed to
347
+ * @internal
348
+ */
349
+ function onContentChanges(callback) {
350
+ const messageCallback = event => {
351
+ if (event.data.name === internal.__DOTCMS_UVE_EVENT__.UVE_SET_PAGE_DATA) {
352
+ callback(event.data.payload);
353
+ }
354
+ };
355
+ window.addEventListener('message', messageCallback);
356
+ return {
357
+ unsubscribe: () => {
358
+ window.removeEventListener('message', messageCallback);
359
+ },
360
+ event: types.UVEEventType.CONTENT_CHANGES
361
+ };
362
+ }
363
+ /**
364
+ * Subscribes to page reload events in the UVE editor
365
+ *
366
+ * @param {UVEEventHandler} callback - Function to be called when page reload is triggered
367
+ * @returns {Object} Object containing unsubscribe function and event type
368
+ * @returns {Function} .unsubscribe - Function to remove the event listener
369
+ * @returns {UVEEventType} .event - The event type being subscribed to
370
+ * @internal
371
+ */
372
+ function onPageReload(callback) {
373
+ const messageCallback = event => {
374
+ if (event.data.name === internal.__DOTCMS_UVE_EVENT__.UVE_RELOAD_PAGE) {
375
+ callback();
376
+ }
377
+ };
378
+ window.addEventListener('message', messageCallback);
379
+ return {
380
+ unsubscribe: () => {
381
+ window.removeEventListener('message', messageCallback);
382
+ },
383
+ event: types.UVEEventType.PAGE_RELOAD
384
+ };
385
+ }
386
+ /**
387
+ * Subscribes to request bounds events in the UVE editor
388
+ *
389
+ * @param {UVEEventHandler} callback - Function to be called when bounds are requested
390
+ * @returns {Object} Object containing unsubscribe function and event type
391
+ * @returns {Function} .unsubscribe - Function to remove the event listener
392
+ * @returns {UVEEventType} .event - The event type being subscribed to
393
+ * @internal
394
+ */
395
+ function onRequestBounds(callback) {
396
+ const messageCallback = event => {
397
+ if (event.data.name === internal.__DOTCMS_UVE_EVENT__.UVE_REQUEST_BOUNDS) {
398
+ const containers = Array.from(document.querySelectorAll('[data-dot-object="container"]'));
399
+ const positionData = getDotCMSPageBounds(containers);
400
+ callback(positionData);
401
+ }
402
+ };
403
+ window.addEventListener('message', messageCallback);
404
+ return {
405
+ unsubscribe: () => {
406
+ window.removeEventListener('message', messageCallback);
407
+ },
408
+ event: types.UVEEventType.REQUEST_BOUNDS
409
+ };
410
+ }
411
+ /**
412
+ * Subscribes to iframe scroll events in the UVE editor
413
+ *
414
+ * @param {UVEEventHandler} callback - Function to be called when iframe scroll occurs
415
+ * @returns {Object} Object containing unsubscribe function and event type
416
+ * @returns {Function} .unsubscribe - Function to remove the event listener
417
+ * @returns {UVEEventType} .event - The event type being subscribed to
418
+ * @internal
419
+ */
420
+ function onIframeScroll(callback) {
421
+ const messageCallback = event => {
422
+ if (event.data.name === internal.__DOTCMS_UVE_EVENT__.UVE_SCROLL_INSIDE_IFRAME) {
423
+ const direction = event.data.direction;
424
+ callback(direction);
425
+ }
426
+ };
427
+ window.addEventListener('message', messageCallback);
428
+ return {
429
+ unsubscribe: () => {
430
+ window.removeEventListener('message', messageCallback);
431
+ },
432
+ event: types.UVEEventType.IFRAME_SCROLL
433
+ };
434
+ }
435
+ /**
436
+ * Subscribes to contentlet hover events in the UVE editor
437
+ *
438
+ * @param {UVEEventHandler} callback - Function to be called when a contentlet is hovered
439
+ * @returns {Object} Object containing unsubscribe function and event type
440
+ * @returns {Function} .unsubscribe - Function to remove the event listener
441
+ * @returns {UVEEventType} .event - The event type being subscribed to
442
+ * @internal
443
+ */
444
+ function onContentletHovered(callback) {
445
+ const pointerMoveCallback = event => {
446
+ const foundElement = findDotCMSElement(event.target);
447
+ if (!foundElement) return;
448
+ const {
449
+ x,
450
+ y,
451
+ width,
452
+ height
453
+ } = foundElement.getBoundingClientRect();
454
+ const isContainer = foundElement.dataset?.['dotObject'] === 'container';
455
+ const contentletForEmptyContainer = {
456
+ identifier: 'TEMP_EMPTY_CONTENTLET',
457
+ title: 'TEMP_EMPTY_CONTENTLET',
458
+ contentType: 'TEMP_EMPTY_CONTENTLET_TYPE',
459
+ inode: 'TEMPY_EMPTY_CONTENTLET_INODE',
460
+ widgetTitle: 'TEMP_EMPTY_CONTENTLET',
461
+ baseType: 'TEMP_EMPTY_CONTENTLET',
462
+ onNumberOfPages: 1
463
+ };
464
+ const contentlet = {
465
+ identifier: foundElement.dataset?.['dotIdentifier'],
466
+ title: foundElement.dataset?.['dotTitle'],
467
+ inode: foundElement.dataset?.['dotInode'],
468
+ contentType: foundElement.dataset?.['dotType'],
469
+ baseType: foundElement.dataset?.['dotBasetype'],
470
+ widgetTitle: foundElement.dataset?.['dotWidgetTitle'],
471
+ onNumberOfPages: foundElement.dataset?.['dotOnNumberOfPages']
472
+ };
473
+ const vtlFiles = findDotCMSVTLData(foundElement);
474
+ const contentletPayload = {
475
+ container:
476
+ // Here extract dot-container from contentlet if it is Headless
477
+ // or search in parent container if it is VTL
478
+ foundElement.dataset?.['dotContainer'] ? JSON.parse(foundElement.dataset?.['dotContainer']) : getClosestDotCMSContainerData(foundElement),
479
+ contentlet: isContainer ? contentletForEmptyContainer : contentlet,
480
+ vtlFiles
481
+ };
482
+ const contentletHoveredPayload = {
483
+ x,
484
+ y,
485
+ width,
486
+ height,
487
+ payload: contentletPayload
488
+ };
489
+ callback(contentletHoveredPayload);
490
+ };
491
+ document.addEventListener('pointermove', pointerMoveCallback);
492
+ return {
493
+ unsubscribe: () => {
494
+ document.removeEventListener('pointermove', pointerMoveCallback);
495
+ },
496
+ event: types.UVEEventType.CONTENTLET_HOVERED
497
+ };
498
+ }
499
+
500
+ /**
501
+ * Events that can be subscribed to in the UVE
502
+ *
503
+ * @internal
504
+ * @type {Record<UVEEventType, UVEEventSubscriber>}
505
+ */
506
+ const __UVE_EVENTS__ = {
507
+ [types.UVEEventType.CONTENT_CHANGES]: callback => {
508
+ return onContentChanges(callback);
509
+ },
510
+ [types.UVEEventType.PAGE_RELOAD]: callback => {
511
+ return onPageReload(callback);
512
+ },
513
+ [types.UVEEventType.REQUEST_BOUNDS]: callback => {
514
+ return onRequestBounds(callback);
515
+ },
516
+ [types.UVEEventType.IFRAME_SCROLL]: callback => {
517
+ return onIframeScroll(callback);
518
+ },
519
+ [types.UVEEventType.CONTENTLET_HOVERED]: callback => {
520
+ return onContentletHovered(callback);
521
+ }
522
+ };
523
+ /**
524
+ * Default UVE event
525
+ *
526
+ * @param {string} event - The event to subscribe to.
527
+ * @internal
528
+ */
529
+ const __UVE_EVENT_ERROR_FALLBACK__ = event => {
530
+ return {
531
+ unsubscribe: () => {
532
+ /* do nothing */
533
+ },
534
+ event
535
+ };
536
+ };
537
+ /**
538
+ * Development mode
539
+ *
540
+ * @internal
541
+ */
542
+ const DEVELOPMENT_MODE = 'development';
543
+ /**
544
+ * Production mode
545
+ *
546
+ * @internal
547
+ */
548
+ const PRODUCTION_MODE = 'production';
549
+ /**
550
+ * End class
551
+ *
552
+ * @internal
553
+ */
554
+ const END_CLASS = 'col-end-';
555
+ /**
556
+ * Start class
557
+ *
558
+ * @internal
559
+ */
560
+ const START_CLASS = 'col-start-';
561
+ /**
562
+ * Empty container style for React
563
+ *
564
+ * @internal
565
+ */
566
+ const EMPTY_CONTAINER_STYLE_REACT = {
567
+ width: '100%',
568
+ backgroundColor: '#ECF0FD',
569
+ display: 'flex',
570
+ justifyContent: 'center',
571
+ alignItems: 'center',
572
+ color: '#030E32',
573
+ height: '10rem'
574
+ };
575
+ /**
576
+ * Empty container style for Angular
577
+ *
578
+ * @internal
579
+ */
580
+ const EMPTY_CONTAINER_STYLE_ANGULAR = {
581
+ width: '100%',
582
+ 'background-color': '#ECF0FD',
583
+ display: 'flex',
584
+ 'justify-content': 'center',
585
+ 'align-items': 'center',
586
+ color: '#030E32',
587
+ height: '10rem'
588
+ };
589
+ /**
590
+ * Custom no component
591
+ *
592
+ * @internal
593
+ */
594
+ const CUSTOM_NO_COMPONENT = 'CustomNoComponent';
595
+
596
+ /**
597
+ * Gets the current state of the Universal Visual Editor (UVE).
598
+ *
599
+ * This function checks if the code is running inside the DotCMS Universal Visual Editor
600
+ * and returns information about its current state, including the editor mode.
601
+ *
602
+ * @export
603
+ * @return {UVEState | undefined} Returns the UVE state object if running inside the editor,
604
+ * undefined otherwise.
605
+ *
606
+ * The state includes:
607
+ * - mode: The current editor mode (preview, edit, live)
608
+ * - languageId: The language ID of the current page setted on the UVE
609
+ * - persona: The persona of the current page setted on the UVE
610
+ * - variantName: The name of the current variant
611
+ * - experimentId: The ID of the current experiment
612
+ * - publishDate: The publish date of the current page setted on the UVE
613
+ *
614
+ * @note The absence of any of these properties means that the value is the default one.
615
+ *
616
+ * @example
617
+ * ```ts
618
+ * const editorState = getUVEState();
619
+ * if (editorState?.mode === 'edit') {
620
+ * // Enable editing features
621
+ * }
622
+ * ```
623
+ */
624
+ function getUVEState() {
625
+ if (typeof window === 'undefined' || window.parent === window || !window.location) {
626
+ return undefined;
627
+ }
628
+ const url = new URL(window.location.href);
629
+ const possibleModes = Object.values(types.UVE_MODE);
630
+ let mode = url.searchParams.get('mode') ?? types.UVE_MODE.EDIT;
631
+ const languageId = url.searchParams.get('language_id');
632
+ const persona = url.searchParams.get('personaId');
633
+ const variantName = url.searchParams.get('variantName');
634
+ const experimentId = url.searchParams.get('experimentId');
635
+ const publishDate = url.searchParams.get('publishDate');
636
+ const dotCMSHost = url.searchParams.get('dotCMSHost');
637
+ if (!possibleModes.includes(mode)) {
638
+ mode = types.UVE_MODE.EDIT;
639
+ }
640
+ return {
641
+ mode,
642
+ languageId,
643
+ persona,
644
+ variantName,
645
+ experimentId,
646
+ publishDate,
647
+ dotCMSHost
648
+ };
649
+ }
650
+ /**
651
+ * Creates a subscription to a UVE event.
652
+ *
653
+ * @param eventType - The type of event to subscribe to
654
+ * @param callback - The callback function that will be called when the event occurs
655
+ * @returns An event subscription that can be used to unsubscribe
656
+ *
657
+ * @example
658
+ * ```ts
659
+ * // Subscribe to page changes
660
+ * const subscription = createUVESubscription(UVEEventType.CONTENT_CHANGES, (changes) => {
661
+ * console.log('Content changes:', changes);
662
+ * });
663
+ *
664
+ * // Later, unsubscribe when no longer needed
665
+ * subscription.unsubscribe();
666
+ * ```
667
+ */
668
+ function createUVESubscription(eventType, callback) {
669
+ if (!getUVEState()) {
670
+ console.warn('UVE Subscription: Not running inside UVE');
671
+ return __UVE_EVENT_ERROR_FALLBACK__(eventType);
672
+ }
673
+ const eventCallback = __UVE_EVENTS__[eventType];
674
+ if (!eventCallback) {
675
+ console.error(`UVE Subscription: Event ${eventType} not found`);
676
+ return __UVE_EVENT_ERROR_FALLBACK__(eventType);
677
+ }
678
+ return eventCallback(callback);
679
+ }
680
+
681
+ /**
682
+ * Sets the bounds of the containers in the editor.
683
+ * Retrieves the containers from the DOM and sends their position data to the editor.
684
+ * @private
685
+ * @memberof DotCMSPageEditor
686
+ */
687
+ function setBounds(bounds) {
688
+ sendMessageToUVE({
689
+ action: types.DotCMSUVEAction.SET_BOUNDS,
690
+ payload: bounds
691
+ });
692
+ }
693
+ /**
694
+ * Validates the structure of a Block Editor block.
695
+ *
696
+ * This function checks that:
697
+ * 1. The blocks parameter is a valid object
698
+ * 2. The block has a 'doc' type
699
+ * 3. The block has a valid content array that is not empty
700
+ *
701
+ * @param {Block} blocks - The blocks structure to validate
702
+ * @returns {BlockEditorState} Object containing validation state and any error message
703
+ * @property {boolean} BlockEditorState.isValid - Whether the blocks structure is valid
704
+ * @property {string | null} BlockEditorState.error - Error message if invalid, null if valid
705
+ */
706
+ const isValidBlocks = blocks => {
707
+ if (!blocks) {
708
+ return {
709
+ error: `Error: Blocks object is not defined`
710
+ };
711
+ }
712
+ if (typeof blocks !== 'object') {
713
+ return {
714
+ error: `Error: Blocks must be an object, but received: ${typeof blocks}`
715
+ };
716
+ }
717
+ if (blocks.type !== 'doc') {
718
+ return {
719
+ error: `Error: Invalid block type. Expected 'doc' but received: '${blocks.type}'`
720
+ };
721
+ }
722
+ if (!blocks.content) {
723
+ return {
724
+ error: 'Error: Blocks content is missing'
725
+ };
726
+ }
727
+ if (!Array.isArray(blocks.content)) {
728
+ return {
729
+ error: `Error: Blocks content must be an array, but received: ${typeof blocks.content}`
730
+ };
731
+ }
732
+ if (blocks.content.length === 0) {
733
+ return {
734
+ error: 'Error: Blocks content is empty. At least one block is required.'
735
+ };
736
+ }
737
+ // Validate each block in the content array
738
+ for (let i = 0; i < blocks.content.length; i++) {
739
+ const block = blocks.content[i];
740
+ if (!block.type) {
741
+ return {
742
+ error: `Error: Block at index ${i} is missing required 'type' property`
743
+ };
744
+ }
745
+ if (typeof block.type !== 'string') {
746
+ return {
747
+ error: `Error: Block type at index ${i} must be a string, but received: ${typeof block.type}`
748
+ };
749
+ }
750
+ // Validate block attributes if present
751
+ if (block.attrs && typeof block.attrs !== 'object') {
752
+ return {
753
+ error: `Error: Block attributes at index ${i} must be an object, but received: ${typeof block.attrs}`
754
+ };
755
+ }
756
+ // Validate nested content if present
757
+ if (block.content) {
758
+ if (!Array.isArray(block.content)) {
759
+ return {
760
+ error: `Error: Block content at index ${i} must be an array, but received: ${typeof block.content}`
761
+ };
762
+ }
763
+ // Recursively validate nested blocks
764
+ const nestedValidation = isValidBlocks({
765
+ type: 'doc',
766
+ content: block.content
767
+ });
768
+ if (nestedValidation.error) {
769
+ return {
770
+ error: `Error in nested block at index ${i}: ${nestedValidation.error}`
771
+ };
772
+ }
773
+ }
774
+ }
775
+ return {
776
+ error: null
777
+ };
778
+ };
779
+
780
+ /* eslint-disable @typescript-eslint/no-explicit-any */
781
+ /**
782
+ * Sets up scroll event handlers for the window to notify the editor about scroll events.
783
+ * Adds listeners for both 'scroll' and 'scrollend' events, sending appropriate messages
784
+ * to the editor when these events occur.
785
+ */
786
+ function scrollHandler() {
787
+ const scrollCallback = () => {
788
+ sendMessageToUVE({
789
+ action: types.DotCMSUVEAction.IFRAME_SCROLL
790
+ });
791
+ };
792
+ const scrollEndCallback = () => {
793
+ sendMessageToUVE({
794
+ action: types.DotCMSUVEAction.IFRAME_SCROLL_END
795
+ });
796
+ };
797
+ window.addEventListener('scroll', scrollCallback);
798
+ window.addEventListener('scrollend', scrollEndCallback);
799
+ return {
800
+ destroyScrollHandler: () => {
801
+ window.removeEventListener('scroll', scrollCallback);
802
+ window.removeEventListener('scrollend', scrollEndCallback);
803
+ }
804
+ };
805
+ }
806
+ /**
807
+ * Adds 'empty-contentlet' class to contentlet elements that have no height.
808
+ * This helps identify and style empty contentlets in the editor view.
809
+ *
810
+ * @remarks
811
+ * The function queries all elements with data-dot-object="contentlet" attribute
812
+ * and checks their clientHeight. If an element has no height (clientHeight = 0),
813
+ * it adds the 'empty-contentlet' class to that element.
814
+ */
815
+ function addClassToEmptyContentlets() {
816
+ const contentlets = document.querySelectorAll('[data-dot-object="contentlet"]');
817
+ contentlets.forEach(contentlet => {
818
+ if (contentlet.clientHeight) {
819
+ return;
820
+ }
821
+ contentlet.classList.add('empty-contentlet');
822
+ });
823
+ }
824
+ /**
825
+ * Registers event handlers for various UVE (Universal Visual Editor) events.
826
+ *
827
+ * This function sets up subscriptions for:
828
+ * - Page reload events that refresh the window
829
+ * - Bounds request events to update editor boundaries
830
+ * - Iframe scroll events to handle smooth scrolling within bounds
831
+ * - Contentlet hover events to notify the editor
832
+ *
833
+ * @remarks
834
+ * For scroll events, the function includes logic to prevent scrolling beyond
835
+ * the top or bottom boundaries of the iframe, which helps maintain proper
836
+ * scroll event handling.
837
+ */
838
+ function registerUVEEvents() {
839
+ const pageReloadSubscription = createUVESubscription(types.UVEEventType.PAGE_RELOAD, () => {
840
+ window.location.reload();
841
+ });
842
+ const requestBoundsSubscription = createUVESubscription(types.UVEEventType.REQUEST_BOUNDS, bounds => {
843
+ setBounds(bounds);
844
+ });
845
+ const iframeScrollSubscription = createUVESubscription(types.UVEEventType.IFRAME_SCROLL, direction => {
846
+ if (window.scrollY === 0 && direction === 'up' || computeScrollIsInBottom() && direction === 'down') {
847
+ // If the iframe scroll is at the top or bottom, do not send anything.
848
+ // This avoids losing the scrollend event.
849
+ return;
850
+ }
851
+ const scrollY = direction === 'up' ? -120 : 120;
852
+ window.scrollBy({
853
+ left: 0,
854
+ top: scrollY,
855
+ behavior: 'smooth'
856
+ });
857
+ });
858
+ const contentletHoveredSubscription = createUVESubscription(types.UVEEventType.CONTENTLET_HOVERED, contentletHovered => {
859
+ sendMessageToUVE({
860
+ action: types.DotCMSUVEAction.SET_CONTENTLET,
861
+ payload: contentletHovered
862
+ });
863
+ });
864
+ return {
865
+ subscriptions: [pageReloadSubscription, requestBoundsSubscription, iframeScrollSubscription, contentletHoveredSubscription]
866
+ };
867
+ }
868
+ /**
869
+ * Notifies the editor that the UVE client is ready to receive messages.
870
+ *
871
+ * This function sends a message to the editor indicating that the client-side
872
+ * initialization is complete and it's ready to handle editor interactions.
873
+ *
874
+ * @remarks
875
+ * This is typically called after all UVE event handlers and DOM listeners
876
+ * have been set up successfully.
877
+ */
878
+ function setClientIsReady(config) {
879
+ sendMessageToUVE({
880
+ action: types.DotCMSUVEAction.CLIENT_READY,
881
+ payload: config
882
+ });
883
+ }
884
+ /**
885
+ * Listen for block editor inline event.
886
+ */
887
+ function listenBlockEditorInlineEvent() {
888
+ if (document.readyState === 'complete') {
889
+ // The page is fully loaded or interactive
890
+ listenBlockEditorClick();
891
+ return {
892
+ destroyListenBlockEditorInlineEvent: () => {
893
+ window.removeEventListener('load', () => listenBlockEditorClick());
894
+ }
895
+ };
896
+ }
897
+ window.addEventListener('load', () => listenBlockEditorClick());
898
+ return {
899
+ destroyListenBlockEditorInlineEvent: () => {
900
+ window.removeEventListener('load', () => listenBlockEditorClick());
901
+ }
902
+ };
903
+ }
904
+ const listenBlockEditorClick = () => {
905
+ const editBlockEditorNodes = document.querySelectorAll('[data-block-editor-content]');
906
+ if (!editBlockEditorNodes.length) {
907
+ return;
908
+ }
909
+ editBlockEditorNodes.forEach(node => {
910
+ const {
911
+ inode,
912
+ language = '1',
913
+ contentType,
914
+ fieldName,
915
+ blockEditorContent
916
+ } = node.dataset;
917
+ const content = JSON.parse(blockEditorContent || '');
918
+ if (!inode || !language || !contentType || !fieldName) {
919
+ console.error('Missing data attributes for block editor inline editing.');
920
+ console.warn('inode, language, contentType and fieldName are required.');
921
+ return;
922
+ }
923
+ node.classList.add('dotcms__inline-edit-field');
924
+ node.addEventListener('click', () => {
925
+ initInlineEditing('BLOCK_EDITOR', {
926
+ inode,
927
+ content,
928
+ language: parseInt(language),
929
+ fieldName,
930
+ contentType
931
+ });
932
+ });
933
+ });
934
+ };
935
+
936
+ /**
937
+ * Updates the navigation in the editor.
938
+ *
939
+ * @param {string} pathname - The pathname to update the navigation with.
940
+ * @memberof DotCMSPageEditor
941
+ * @example
942
+ * updateNavigation('/home'); // Sends a message to the editor to update the navigation to '/home'
943
+ */
944
+ function updateNavigation(pathname) {
945
+ sendMessageToUVE({
946
+ action: types.DotCMSUVEAction.NAVIGATION_UPDATE,
947
+ payload: {
948
+ url: pathname || '/'
949
+ }
950
+ });
951
+ }
952
+ /**
953
+ * Post message to dotcms page editor
954
+ *
955
+ * @export
956
+ * @template T
957
+ * @param {DotCMSUVEMessage<T>} message
958
+ */
959
+ function sendMessageToUVE(message) {
960
+ window.parent.postMessage(message, '*');
961
+ }
962
+ /**
963
+ * You can use this function to edit a contentlet in the editor.
964
+ *
965
+ * Calling this function inside the editor, will prompt the UVE to open a dialog to edit the contentlet.
966
+ *
967
+ * @export
968
+ * @template T
969
+ * @param {Contentlet<T>} contentlet - The contentlet to edit.
970
+ */
971
+ function editContentlet(contentlet) {
972
+ sendMessageToUVE({
973
+ action: types.DotCMSUVEAction.EDIT_CONTENTLET,
974
+ payload: contentlet
975
+ });
976
+ }
977
+ /*
978
+ * Reorders the menu based on the provided configuration.
979
+ *
980
+ * @param {ReorderMenuConfig} [config] - Optional configuration for reordering the menu.
981
+ * @param {number} [config.startLevel=1] - The starting level of the menu to reorder.
982
+ * @param {number} [config.depth=2] - The depth of the menu to reorder.
983
+ *
984
+ * This function constructs a URL for the reorder menu page with the specified
985
+ * start level and depth, and sends a message to the editor to perform the reorder action.
986
+ */
987
+ function reorderMenu(config) {
988
+ const {
989
+ startLevel = 1,
990
+ depth = 2
991
+ } = config || {};
992
+ sendMessageToUVE({
993
+ action: types.DotCMSUVEAction.REORDER_MENU,
994
+ payload: {
995
+ startLevel,
996
+ depth
997
+ }
998
+ });
999
+ }
1000
+ /**
1001
+ * Initializes the inline editing in the editor.
1002
+ *
1003
+ * @export
1004
+ * @param {INLINE_EDITING_EVENT_KEY} type
1005
+ * @param {InlineEditEventData} eventData
1006
+ * @return {*}
1007
+ *
1008
+ * * @example
1009
+ * ```html
1010
+ * <div onclick="initInlineEditing('BLOCK_EDITOR', { inode, languageId, contentType, fieldName, content })">
1011
+ * ${My Content}
1012
+ * </div>
1013
+ * ```
1014
+ */
1015
+ function initInlineEditing(type, data) {
1016
+ sendMessageToUVE({
1017
+ action: types.DotCMSUVEAction.INIT_INLINE_EDITING,
1018
+ payload: {
1019
+ type,
1020
+ data
1021
+ }
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Initializes the block editor inline editing for a contentlet field.
1026
+ *
1027
+ * @example
1028
+ * ```html
1029
+ * <div onclick="enableBlockEditorInline(contentlet, 'MY_BLOCK_EDITOR_FIELD_VARIABLE')">
1030
+ * ${My Content}
1031
+ * </div>
1032
+ * ```
1033
+ *
1034
+ * @export
1035
+ * @param {DotCMSBasicContentlet} contentlet
1036
+ * @param {string} fieldName
1037
+ * @return {*} {void}
1038
+ */
1039
+ function enableBlockEditorInline(contentlet, fieldName) {
1040
+ if (!contentlet?.[fieldName]) {
1041
+ console.error(`Contentlet ${contentlet?.identifier} does not have field ${fieldName}`);
1042
+ return;
1043
+ }
1044
+ const data = {
1045
+ fieldName,
1046
+ inode: contentlet.inode,
1047
+ language: contentlet.languageId,
1048
+ contentType: contentlet.contentType,
1049
+ content: contentlet[fieldName]
1050
+ };
1051
+ initInlineEditing('BLOCK_EDITOR', data);
1052
+ }
1053
+ /**
1054
+ * Initializes the Universal Visual Editor (UVE) with required handlers and event listeners.
1055
+ *
1056
+ * This function sets up:
1057
+ * - Scroll handling
1058
+ * - Empty contentlet styling
1059
+ * - Block editor inline event listening
1060
+ * - Client ready state
1061
+ * - UVE event subscriptions
1062
+ *
1063
+ * @returns {Object} An object containing the cleanup function
1064
+ * @returns {Function} destroyUVESubscriptions - Function to clean up all UVE event subscriptions
1065
+ *
1066
+ * @example
1067
+ * ```typescript
1068
+ * const { destroyUVESubscriptions } = initUVE();
1069
+ *
1070
+ * // When done with UVE
1071
+ * destroyUVESubscriptions();
1072
+ * ```
1073
+ */
1074
+ function initUVE(config = {}) {
1075
+ addClassToEmptyContentlets();
1076
+ setClientIsReady(config);
1077
+ const {
1078
+ subscriptions
1079
+ } = registerUVEEvents();
1080
+ const {
1081
+ destroyScrollHandler
1082
+ } = scrollHandler();
1083
+ const {
1084
+ destroyListenBlockEditorInlineEvent
1085
+ } = listenBlockEditorInlineEvent();
1086
+ return {
1087
+ destroyUVESubscriptions: () => {
1088
+ subscriptions.forEach(subscription => subscription.unsubscribe());
1089
+ destroyScrollHandler();
1090
+ destroyListenBlockEditorInlineEvent();
1091
+ }
1092
+ };
1093
+ }
1094
+
1095
+ exports.CUSTOM_NO_COMPONENT = CUSTOM_NO_COMPONENT;
1096
+ exports.DEVELOPMENT_MODE = DEVELOPMENT_MODE;
1097
+ exports.EMPTY_CONTAINER_STYLE_ANGULAR = EMPTY_CONTAINER_STYLE_ANGULAR;
1098
+ exports.EMPTY_CONTAINER_STYLE_REACT = EMPTY_CONTAINER_STYLE_REACT;
1099
+ exports.END_CLASS = END_CLASS;
1100
+ exports.PRODUCTION_MODE = PRODUCTION_MODE;
1101
+ exports.START_CLASS = START_CLASS;
1102
+ exports.__UVE_EVENTS__ = __UVE_EVENTS__;
1103
+ exports.__UVE_EVENT_ERROR_FALLBACK__ = __UVE_EVENT_ERROR_FALLBACK__;
1104
+ exports.combineClasses = combineClasses;
1105
+ exports.computeScrollIsInBottom = computeScrollIsInBottom;
1106
+ exports.createUVESubscription = createUVESubscription;
1107
+ exports.editContentlet = editContentlet;
1108
+ exports.enableBlockEditorInline = enableBlockEditorInline;
1109
+ exports.findDotCMSElement = findDotCMSElement;
1110
+ exports.findDotCMSVTLData = findDotCMSVTLData;
1111
+ exports.getClosestDotCMSContainerData = getClosestDotCMSContainerData;
1112
+ exports.getColumnPositionClasses = getColumnPositionClasses;
1113
+ exports.getContainersData = getContainersData;
1114
+ exports.getContentletsInContainer = getContentletsInContainer;
1115
+ exports.getDotCMSContainerData = getDotCMSContainerData;
1116
+ exports.getDotCMSContentletsBound = getDotCMSContentletsBound;
1117
+ exports.getDotCMSPageBounds = getDotCMSPageBounds;
1118
+ exports.getDotContainerAttributes = getDotContainerAttributes;
1119
+ exports.getDotContentletAttributes = getDotContentletAttributes;
1120
+ exports.getUVEState = getUVEState;
1121
+ exports.initInlineEditing = initInlineEditing;
1122
+ exports.initUVE = initUVE;
1123
+ exports.isValidBlocks = isValidBlocks;
1124
+ exports.reorderMenu = reorderMenu;
1125
+ exports.sendMessageToUVE = sendMessageToUVE;
1126
+ exports.setBounds = setBounds;
1127
+ exports.updateNavigation = updateNavigation;