@dotcms/uve 0.0.1-beta.2 → 0.0.1-beta.21

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