Headless frontend preview in Page Builder
The Page Builder can preview landing pages rendered by your frontend application.
You provide a single URL for the frontend page and let it communicate with the Page Builder using the JavaScript message API.
Configuration
- In the left panel, go to Administration -> SiteAccess Configuration
- Choose the SiteAccess that you want to set up a preview for. Do not choose a SiteAccess if you want to set up a default preview for the SiteAccesses that don't have a specific preview.
- In Available configurations list, click Headless.
- In Edit configuration section, expand the Headless mode drop-down list and select Enabled.
- Populate the Page Builder preview URL field and click Save.

Communication protocol
The Page Builder loads the specified frontend resource when you edit a content item with the Landing page field.
The resource must use the JavaScript message API-based protocol to communicate with the Page Builder from within the iframe in which the Page Builder loads it.
The Page Builder sends messages to the frontend resource in the iframe.
You can receive them by listening for the message event.
The frontend resource sends messages back to the Page Builder.
You can send them by using the postMessage() method.
The target origin of those messages must be the Page Builder's origin.
| const pbOrigin = 'https://my-company.cohesivo.app';
window.parent.postMessage(message, pbOrigin);
|
These messages are JavaScript objects with the following structure:
| let message = {
type: '<PREFIX>:<MESSAGE_TYPE>',
data: {}
};
|
The PREFIX identifies the sender of each message type:
PB: - for messages sent by the Page Builder
APP: - for messages sent by the frontend resource
The data depends on the message type.
Message types are grouped by capability.
The frontend can declare which capabilities it supports, so that the Page Builder can avoid sending or expecting unsupported messages.
Message types and capabilities
Handshake and core messages are mandatory and don't depend on optional capabilities.
Communication initialization
First, the frontend sends an initialization message to the Page Builder, indicating which protocol versions and capabilities it supports:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | const initializedMessage = {
type: 'APP:INITIALIZED',
data: {
protocol: {
supported: [1]
},
capabilities: [
'blocks.dnd',
'blocks.geometry',
'pointer.tracking',
// …
],
}
};
|
The frontend may send the initialization message several times until the Page Builder replies.
The Page Builder replies with a confirmation message.
The confirmation data property object contains:
- the protocol version in use (
protocol.version) and other supported versions (protocol.supported)
- a list of all available capabilities (
capabilities)
- all block types, their attributes, and their configuration (
blocksConfig) - types unavailable for this field are marked as not visible
- information about the content draft currently being edited (
intentParameters)
- the current value of the Landing page field being edited (
fieldValue), including the layout, zones, and blocks
- a block-ID-to-name mapping (
blocksIdMap)
- a list of translations for the frontend to use (
translations)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 | {
"type": "PB:INIT_MODE",
"data": {
"protocol": {
"version": 1,
"supported": [
1
]
},
"capabilities": [
"blocks.dnd",
"blocks.geometry",
"blocks.remove",
"blocks.reveal",
"blocks.select",
"pointer.tracking",
"preview.params"
],
"blocksConfig": [
{
"type": "block_type",
"name": "Block type name",
"category": "Block category",
"thumbnail": "path/to/block/thumbnail.file",
"visible": true,
"views": {
"default": {
"name": "Default"
}
},
"attributes": [
{
"id": "attribute_id",
"name": "Attribute name",
"type": "attribute_type",
"value": null,
"constraints": {
"not_blank": {
"message": "Please select…"
}
}
}
]
}
],
"intentParameters": {
"locationId": "2",
"contentId": 52,
"versionNo": 6,
"languageCode": "eng-GB"
},
"fieldValue": {
"layout": "ibexa_fieldtype_page.layouts.<layout_definition>.identifier",
"zones": [
{
"id": "123",
"name": "ibexa_fieldtype_page.layouts.<layout_definition>.zones.<zone_definition>.name",
"blocks": [
{
"visible": true,
"id": "456",
"type": "block_type",
"name": "Block name",
"view": "default",
"class": null,
"style": null,
"compiled": "",
"since": null,
"till": null,
"attributes": [
{
"id": "789",
"name": "attribute_name",
"value": "…"
}
]
}
]
}
]
},
"blocksIdMap": {
"456": "Block name"
},
"translations": {
"block.attribute.invalid": "%name% is invalid",
"block.no_availability.content": "You have to delete it to publish",
"block.no_availability.delete": "Delete",
"block.no_availability.title": "This element is not available in this page",
"block.unknown.type": "Unknown block type: %type% (block name: %name%)",
"drag.drop.blocks.here": "Drag and drop blocks here",
"structure.drop.zone": "Drop zone %number%"
}
}
}
|
On field update
When the **Landing page* field value is updated, the Page Builder sends the PB:UPDATE_FIELD_DATA message to the frontend resource.
The message's data contains the field's new value, with the following structure:
- the current value of the Landing page field being edited (
fieldValue), including the layout, zones, and blocks
- a list of the existing block types, their attributes, and their configuration (
blocksConfig)
- the block-ID-to-name mapping (
blocksIdMap)
- a list of IDs from the new blocks that have been added (
highlightedBlockIds)
1
2
3
4
5
6
7
8
9
10
11
12 | {
"type": "PB:UPDATE_FIELD_DATA",
"data": {
"fieldValue": {
"layout": "…",
"zones": []
},
"blocksConfig": [],
"blocksIdMap": {},
"highlightedBlockIds": []
}
}
|
Re-dispatching events
The Page Builder sends the PB:DISPATCH_EVENT message to the frontend resource to be re-dispatched there as a custom event.
The message's data contains the name of the event to dispatch (eventName) and the data to pass in the event's detail property (eventDetail).
| window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:DISPATCH_EVENT':
window.dispatchEvent(new CustomEvent(messageEvent.data.data.eventName, { detail: messageEvent.data.data.eventDetail }));
break;
}
});
|
Available events
ibexa-active-block-clicked - Confirms that APP:BLOCK_CLICKED was received. It has no data
ibexa-post-update-blocks-preview - Sent when the timeline is used
fieldValue - The same as in PB:UPDATE_FIELD_DATA
blockIds - A list of all the block IDs
blocksMaps - A map of block config per block ID
| window.addEventListener('ibexa-post-update-blocks-preview', (customEvent) => {
setLayout(customEvent.detail.fieldValue.layout);
renderZones(customEvent.detail.fieldValue.zones);
});
|
Geometry and pointer tracking (blocks.geometry and pointer.tracking)
Pointer tracking and geometry help the Page Builder position block-editing menus over the frontend preview.
The menus are the .c-pb-headless-preview-menu elements that the Page Builder positions in its DOM above the preview iframe.
The frontend preview sends the APP:MOUSE_POSITION message to report the mouse's current position to the Page Builder.
| window.addEventListener('mousemove', (mouseEvent) => {
window.parent.postMessage({
type: 'APP:MOUSE_POSITION',
data: {
x: mouseEvent.clientX,
y: mouseEvent.clientY,
},
}, pbOrigin);
});
|
The frontend preview sends the APP:POSITIONS_UPDATE message to report the blocks' current positions to the Page Builder.
Its data contains a list of objects with block IDs, positions, and dimensions in the frontend preview.
This format is similar to the object returned by the getBoundingClientRect() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | const positionsUpdate = () => {
let blocks = [];
for (const blockElement of document.getElementsByClassName('landing-page__block')) {
const blockId = blockElement.dataset.ibexaBlockId;
const blockRect = blockElement.getBoundingClientRect();
blocks.push({
id: blockId,
top: blockRect.top,
left: blockRect.left,
right: blockRect.right,
bottom: blockRect.bottom,
width: blockRect.width,
height: blockRect.height,
});
}
window.parent.postMessage({
type: 'APP:POSITIONS_UPDATE',
data: {
blocks: blocks,
},
}, pbOrigin);
};
|
Send this message whenever the positions of the blocks change, for example, after updating the blocks in response to PB:UPDATE_FIELD_DATA, scrolling, or resizing.
The frontend preview sends the APP:SCROLL_END message to notify the Page Builder that a scroll operation has ended.
It has no data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | window.addEventListener('scrollend', (event) => {
window.parent.postMessage({
type: 'APP:SCROLL_END',
}, pbOrigin);
positionsUpdate();
});
window.addEventListener('resize', (event) => {
positionsUpdate();
});
window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:UPDATE_FIELD_DATA':
setLayout(messageEvent.data.data.fieldValue.layout);
renderZones(messageEvent.data.data.fieldValue.zones);
positionsUpdate();
break;
}
});
|
Dragging and dropping (blocks.dnd)
The Page Builder sends the PB:DRAG_OVER message to the frontend preview to report the mouse position while a new or existing block is being dragged.
Mouse tracking
APP:MOUSE_POSITION helps the Page Builder track the mouse as it moves over the preview. Together with APP:POSITIONS_UPDATE, it lets the Page Builder determine whether the pointer is over a preview block.
PB:DRAG_OVER helps the frontend track the mouse as a block is dragged over the preview.
The Page Builder sends PB:DRAG_START_PREVIEW and PB:DRAG_END_PREVIEW messages at the beginning and end of a drag operation on an existing block in the frontend preview.
Message data contains the ID of the block being dragged (blockId).
| window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:DRAG_START_PREVIEW':
document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`).classList.add('c-pb-block-preview--is-dragging-out');
break;
case 'PB:DRAG_END_PREVIEW':
document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`).classList.remove('c-pb-block-preview--is-dragging-out');
break;
}
});
|
The Page Builder sends the PB:DROP message to the frontend preview to notify it that a block has been dropped.
The message has no data.
Combined with the most recent PB:DRAG_OVER message, it lets the frontend determine where the block was dropped.
The frontend preview sends the APP:DROP_RESPONSE message to the Page Builder to report where the block was dropped.
Its data contains:
- the ID of the zone where the block has been dropped (
zoneId)
- the ID of the block that will follow the dropped block (
nextBlockId), if the dropped block is not the last block in the zone
In the following example, targetBlockId is the ID of the block that the dragged block was dropped on or just before.
The dragged block is inserted in that block's place, moving the existing block down by one position.
If the dragged block is dropped at the bottom of the zone, targetBlockId is null.
| const dropResponseMessage = {
type: 'APP:DROP_RESPONSE',
data: {
zoneId: zoneId,
nextBlockId: targetBlockId,
}
};
|
After the frontend sends APP:DROP_RESPONSE, the next PB:UPDATE_FIELD_DATA message from the Page Builder contains the dropped block's ID in its highlightedBlockIds array (messageEvent.data.data.highlightedBlockIds).
The Page Builder sends the PB:SCROLL_BY message when a block is dragged near an edge of the preview, indicating that the preview needs to be scrolled.
Its data contains the amount to scroll vertically (top).
| window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:SCROLL_BY':
window.scrollBy(messageEvent.data.data);
break;
}
});
|
For information about reporting the end of a scroll operation and updating block positions, see APP:SCROLL_END and APP:POSITIONS_UPDATE in Geometry (blocks.geometry).
Block reveal (blocks.reveal)
The Page Builder sends the PB:SCROLL_INTO_BLOCK message to the frontend preview to request that a block be scrolled into view.
Its data contains the ID of the block to scroll into view (blockId).
It can be used with the scrollIntoView() method.
| window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:SCROLL_INTO_BLOCK':
const blockElementToScrollInto = document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`);
blockElementToScrollInto.scrollIntoView({ behavior: 'smooth', block: 'center' });
break;
}
});
|
Block removal (blocks.remove)
The Page Builder sends the PB:BLOCK_REMOVE message to the frontend preview to notify it that a block should be removed, for example, from the Structure view.
Message data contains the ID of the block to remove (blockId).
The frontend preview sends the APP:BLOCK_REMOVE_RESPONSE message to the Page Builder to confirm that the block has been removed as requested by PB:BLOCK_REMOVE.
Message data contains the ID of the removed block (blockId).
You can send it immediately or after the removal animation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | window.addEventListener('message', (messageEvent) => {
switch (messageEvent.data.type) {
case 'PB:BLOCK_REMOVE':
const blockId = messageEvent.data.data.blockId;
const blockElementToRemove = document.querySelector(`[data-ibexa-block-id="${blockId}"]`);
if (blockElementToRemove) {
blockElementToRemove.addEventListener('animationend', () => {
blockElementToRemove.remove();
window.parent.postMessage({
type: 'APP:BLOCK_REMOVE_RESPONSE',
data: {
blockId: blockId,
},
}, pbOrigin);
});
blockElementToRemove.classList.add('c-pb-block-preview--is-removing');
} else {
console.error('No block element found for block ID ' + messageEvent.data.data.blockId, 'notification.headless_unresponsive_preview');
}
break;
}
});
|
| .c-pb-block-preview--is-removing {
animation-duration: 1s;
animation-name: c-pb-block-preview--is-removing;
}
@keyframes c-pb-block-preview--is-removing {
to {
opacity: 0;
height: 0;
}
}
|
The frontend preview sends the APP:BLOCK_REMOVE_REQUEST message to the Page Builder to request that a block be removed.
Message data contains the ID of the block to remove (blockId).
The Page Builder responds with a PB:UPDATE_FIELD_DATA message.
Guidelines for frontend implementation
The protocol documentation uses vanilla JavaScript examples, but you should use a JavaScript framework to implement the frontend.
The frontend and Page Builder preview should share as much code as possible.
For example, you could use the same controller, called in different ways, to determine whether to render the regular frontend or the Page Builder preview.
Each block type view should be implemented as a component so you can easily add new block types and new views.
You can name CSS classes as you wish, but following these conventions can make existing stylesheets easier to reuse.
CSS classes and data attribute conventions
By convention, some class names are used only in the Page Builder preview, while others are used in both final frontend and Page Builder frontend preview.
For example, when the frontend is used in the Page Builder preview, the c-pb-iframe__preview-body class is added to the document body.
Zones
The always present data-ibexa-zone-id attribute (zoneElement.dataset.ibexaZoneId) contains the zone ID.
| Class name |
PB only |
Description |
landing-page__zone |
No |
Every zone container |
landing-page__zone--${zone.id} |
No |
Each zone container with its own ID |
m-page-builder__zone |
Yes |
Every zone container in the Page Builder preview |
m-page-builder__zone--dragover |
Yes |
When a block is dragged over the zone |
m-page-builder__zone--empty |
Yes |
When the zone has no block |
Blocks
The always present data-ibexa-block-id attribute (blockElement.dataset.ibexaBlockId) contains the block ID.
| Class name |
PB only |
Description |
landing-page__block |
No |
Every block container |
c-pb-block-preview |
Yes |
Every block container in the Page Builder preview |
c-pb-block-preview--is-dragging-out |
Yes |
When a block is being dragged |
c-pb-block-preview--is-removing |
Yes |
When a block is being removed (see Block removal (blocks.remove)) |
ibexa-mark-invisible |
Yes |
When a scheduled block is marked as invisible |
c-pb-block-preview--unavailable |
Yes |
When a block is unavailable for this field |
c-pb-block-preview__inner |
Yes |
The inner container of a block |
c-pb-block-preview__inner--invalid |
Yes |
The inner container of a block with invalid attribute value |
droppable-placeholder |
Yes |
The placeholder element shown when a block is being dragged over a zone to indicate the drop position |
c-pb-block-preview--highlighted |
Yes |
When a block is highlighted, for example, when newly dropped |
Static example
The following vanilla JavaScript demo is provided as-is to illustrate how to use the Page Builder protocol.
You can use it to observe the messages exchanged between the Page Builder and a frontend preview in the browser's JavaScript console.
It doesn't support all block types or views.
page.html is a static HTML page with JavaScript that handles Page Builder protocol messages and demonstrates the intended uses of the conventional CSS classes.
It works both as a standalone page and as a Page Builder preview.
page.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774 | <!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Headless Page Builder test</title>
<style>
/* Front-end style */
body {
background: oklch(47.52% 0.0999 241.4deg);
}
header, footer {
color: white;
background: oklch(62.57% 0.0038 247.89deg);
border-radius: 5px;
padding: 10px;
text-align: center;
font-family: sans-serif;
}
.layout {
margin: 10px 0;
}
.landing-page__zone {
background: oklch(86.53% 0.0233 241.92deg);
border: 1px solid oklch(47.52% 0.0999 241.4deg);
border-radius: 5px;
padding: 5px;
}
.landing-page__block {
border: 1px solid black;
border-radius: 10px;
background: oklch(95.81% 0 0deg);
margin: 5px;
padding: 10px;
}
.landing-page__block .loader {
margin: 0;
padding: 0;
}
.block-contentlist ul {
margin: 0;
padding: 0;
list-style-position: inside;
}
</style>
<style>
/* Page Builder embedded style */
.m-page-builder__zone::after {
display: block;
content: attr(data-drag-drop-blocks-here);
text-align: center;
opacity: 67%;
}
.m-page-builder__zone--empty {
border: 1px dashed oklch(47.52% 0.0999 241.4deg);
}
.m-page-builder__zone--dragover {
border: 1px dashed white;
}
.droppable-placeholder {
opacity: 90%;
border: 1px dashed black;
border-radius: 10px;
background: oklch(95.81% 0 0deg);
margin: 5px;
padding: 10px;
content: ' ';
}
.c-pb-block-preview--is-dragging-out {
opacity: 75%;
border-style: dashed;
}
.c-pb-block-preview.ibexa-mark-invisible {
opacity: 50%;
border-style: dotted;
}
.c-pb-block-preview--highlighted {
animation-duration: 3s;
animation-name: c-pb-block-preview--highlighted;
}
@keyframes c-pb-block-preview--highlighted {
from {
opacity: 0;
}
to {
opacity: 100%;
}
}
.c-pb-block-preview .c-pb-block-preview__inner {
margin: 0;
padding: 0;
}
.landing-page__block:has(.c-pb-block-preview__inner--invalid) {
cursor: help;
background: orange;
}
.landing-page__block .c-pb-block-preview__inner--invalid::before {
content: '⚠';
display: block;
height: 10px;
line-height: 10px;
}
.c-pb-block-preview--unavailable {
cursor: not-allowed;
background: oklch(51.12% 0.1876 26.3deg);
}
.c-pb-block-preview--unavailable:hover:after {
position: absolute;
z-index: 1;
content: attr(data-block-no-availability);
white-space: pre-wrap;
font-family: sans-serif;
font-size: smaller;
color: oklch(51.12% 0.1876 26.3deg);
background: white;
border: 3px solid oklch(51.12% 0.1876 26.3deg);
border-radius: 3px;
padding: 1px 3px;
}
.c-pb-block-preview--is-removing {
animation-duration: 1s;
animation-name: c-pb-block-preview--is-removing;
}
@keyframes c-pb-block-preview--is-removing {
to {
opacity: 0;
height: 0;
}
}
</style>
</head>
<body>
<header>Header</header>
<main>
<div class="layout" id="layout-default" style="display: none;">
<div class="zone-0 zone-default landing-page__zone" data-ibexa-zone-id=""></div>
</div>
</main>
<footer>Footer</footer>
</body>
<script>
const apiBaseUrl = 'https://my-company.cohesivo.app';
/**
* @param {string} layout - Layout identifier
*/
const setLayout = (layout) => {
for (const layoutElement of document.getElementsByClassName('layout')) {
layoutElement.setAttribute('style', 'display: none;');
}
const layoutElement = document.getElementById('layout-' + layout);
if (layoutElement) {
layoutElement.removeAttribute('style');
} else {
console.error('No layout found for layout "' + layout + '".');
}
};
/**
* @typedef PageBuilderConfig
* @type {object}
* @property {string} pbOrigin - Page Builder origin, the full URL to the back office root with scheme, domain, and port.
* @property {Array.<object>} blocksConfig - the array of block configurations.
* @property {blockClickedEventHandler} blockClickedEventHandler - the function handling the ID of a clicked block.
* @property {unavailableBlockClickedEventHandler} unavailableBlockClickedEventHandler - the function handling the ID of a clicked unavailable block.
* @property {Array.<string>} highlightedBlockIds - the array of highlighted block IDs.
* @property {boolean} init - if the Page Builder is initializing and its config passed for the first time.
*/
/**
* @callback blockClickedEventHandler
* @param {number} blockId - the ID of the clicked block
*/
/**
* @callback unavailableBlockClickedEventHandler
* @param {number} blockId - the ID of the clicked unavailable block
*/
/**
* @function renderZones
* @param {Array.<object>} zones
* @param {PageBuilderConfig} pageBuilderConfig
*/
const renderZones = (zones, pageBuilderConfig = null) => {
for (const zone of zones) {
//console.log('zone', zone);
const zoneElement = document.getElementsByClassName('zone-' + zone.name.replace(/\s+/g, '-').toLowerCase())[0]; // Not conventional
if (!zoneElement) {
console.error('No zone element found for zone "' + zone.name + '".', zone);
continue;
}
if (!pageBuilderConfig || pageBuilderConfig.init) {
zoneElement.dataset.ibexaZoneId = zone.id;
zoneElement.classList.add(`landing-page__zone--${zone.id}`);
if (pageBuilderConfig) {
zoneElement.classList.add('m-page-builder__zone');
zoneElement.dataset.dragDropBlocksHere = window.translations['drag.drop.blocks.here'];
}
} else {
zoneElement.innerHTML = '';
}
if (zone.blocks.length) {
zoneElement.classList.remove('m-page-builder__zone--empty');
for (const block of zone.blocks) {
//console.log('block', block);
if (block.visible || pageBuilderConfig) {
const blockElement = document.createElement('div');
blockElement.dataset.ibexaBlockId = block.id;
blockElement.setAttribute('title', block.name + (pageBuilderConfig ? ' (' + block.id + ') [' + block.type + ']' : ''));
const innerHTML = getBlockInnerHTML(block, null !== pageBuilderConfig);
if (!innerHTML) {
console.error('Unable to render', block);
continue;
}
blockElement.innerHTML = innerHTML;
blockElement.classList.add('landing-page__block');
blockElement.classList.add('block-' + block.type);
blockElement.dataset.type = block.type;
blockElement.dataset.name = block.name;
if (block.class) {
blockElement.classList.add(...block.class.split(' '));
}
if (block.style) {
blockElement.setAttribute('style', block.style);
}
if (pageBuilderConfig) {
blockElement.classList.add('c-pb-block-preview');
if (null !== block.visible && false === block.visible) {
blockElement.classList.add('ibexa-mark-invisible');
}
if (pageBuilderConfig.blockClickedEventHandler) {
blockElement.addEventListener('click', (clickEvent) => {
pageBuilderConfig.blockClickedEventHandler(block.id);
});
}
if (pageBuilderConfig.highlightedBlockIds && pageBuilderConfig.highlightedBlockIds.includes(block.id)) {
console.log('Start highlighting block', block.id);
blockElement.addEventListener('animationend', () => {
console.log('End highlighting block', block.id);
blockElement.classList.remove('c-pb-block-preview--highlighted');
//positionsUpdate();
});
blockElement.classList.add('c-pb-block-preview--highlighted');
}
}
zoneElement.appendChild(blockElement);
}
}
} else {
zoneElement.classList.add('m-page-builder__zone--empty');
}
if (pageBuilderConfig && pageBuilderConfig.blocksConfig && pageBuilderConfig.blocksConfig.length) {
const setBlockAsUnavailable = (blockElement) => {
blockElement.classList.add('c-pb-block-preview--unavailable');
if (pageBuilderConfig.unavailableBlockClickedEventHandler) {
blockElement.dataset.blockNoAvailability = '🚫 ' + window.translations['block.no_availability.title'] + '. ' + window.translations['block.no_availability.content'] + '.\n\r 🗑 ' + window.translations['block.no_availability.delete'];
blockElement.addEventListener('click', (clickEvent) => {
pageBuilderConfig.unavailableBlockClickedEventHandler(blockElement.dataset.ibexaBlockId);
});
}
};
let existingBlockTypes = [];
for (const blockConfig of pageBuilderConfig.blocksConfig) {
existingBlockTypes.push(blockConfig.type);
if (!blockConfig.visible) {
for (const unavailableBlockElement of document.getElementsByClassName('block-' + blockConfig.type)) {
setBlockAsUnavailable(unavailableBlockElement);
}
}
}
for (const blockElement of document.querySelectorAll('.landing-page__block:not(.c-pb-block-preview--unavailable)')) {
if (!existingBlockTypes.includes(blockElement.dataset.type)) {
console.error(window.translations['block.unknown.type'].replace('%type%', blockElement.dataset.type).replace('%name%', blockElement.dataset.name));
setBlockAsUnavailable(blockElement);
}
}
}
}
};
/**
* @param {object} block
* @param {string} attributeName
* @returns {*|null}
*/
const getBlockAttributeValue = (block, attributeName) => {
for (const attribute of block.attributes) {
if (attribute.name === attributeName) {
return attribute.value;
}
}
console.error('No attribute "' + attributeName + '" found for block "' + block.name + '" (' + block.id + ') [' + block.type + '].');
return null;
};
/**
* @param {object} block
* @param {boolean} pb - if the block is rendered inside the Page Builder
* @returns {string|null}
*/
const getBlockInnerHTML = (block, pb = false) => {
switch (block.type) {
case 'tag': // </> Code
let tagBlockContent = getBlockAttributeValue(block, 'content');
if (!tagBlockContent) {
if (pb) {
tagBlockContent = ' ';
} else {
return null;
}
}
return '<div' + (pb ? ' class="c-pb-block-preview__inner"' : '') + '>' + tagBlockContent + '</div>';
case 'contentlist': // • Content List
let listBlockContent = '';
let isInvalid = false;
const contentId = getBlockAttributeValue(block, 'contentId');
if (!contentId) {
isInvalid = true;
console.error('contentId is not set for block "' + block.name + '" (' + block.id + ').');
if (pb) {
if (window.translations && window.translations['block.attribute.invalid']) {
listBlockContent += (listBlockContent.length ? '<br/>' : '') + window.translations['block.attribute.invalid'].replace('%name%', '<code>contentId</code>');
}
} else {
return null;
}
}
const contentTypes = getBlockAttributeValue(block, 'contentType')?.split(',') ?? [];
if (!contentTypes || !contentTypes.length) {
isInvalid = true;
console.error('No contentType selected for block "' + block.name + '" (' + block.id + ').');
if (pb) {
if (window.translations && window.translations['block.attribute.invalid']) {
listBlockContent += (listBlockContent.length ? '<br/>' : '') + window.translations['block.attribute.invalid'].replace('%name%', '<code>contentType</code>');
}
} else {
return null;
}
}
const limit = getBlockAttributeValue(block, 'limit');
if (!limit || isNaN(limit) || limit < 0) {
isInvalid = true;
console.error('Invalid limit "' + limit + '" for block "' + block.name + '" (' + block.id + ').');
if (pb) {
if (window.translations && window.translations['block.attribute.invalid']) {
listBlockContent += (listBlockContent.length ? '<br/>' : '') + window.translations['block.attribute.invalid'].replace('%name%', '<code>limit</code>');
}
} else {
return null;
}
}
if (isInvalid) {
return '<p class="c-pb-block-preview__inner c-pb-block-preview__inner--invalid">' + listBlockContent + '</p>';
}
getContentInfoList(contentId, contentTypes, limit)
.then((contentInfoList) => {
let innerHTML = '<div' + (pb ? ' class="c-pb-block-preview__inner"' : '') + '>';
if (contentInfoList.length > 0) {
innerHTML += '<ul>';
for (const contentInfo of contentInfoList) {
innerHTML += '<li>' + contentInfo.Content.Name + '</li>';
}
innerHTML += '</ul>';
}
innerHTML += '</div>';
const blockElement = document.querySelector(`[data-ibexa-block-id="${block.id}"]`);
if (blockElement) {
blockElement.innerHTML = innerHTML;
}
})
.catch((error) => {
console.error('Error fetching content list:', error);
});
return '<p class="' + (pb ? 'c-pb-block-preview__inner ' : '') + 'loader">Loading content list…</p>';
default:
console.error('No rendering for block type "' + block.type + '".');
if (pb) {
return '<p' + (pb ? ' class="c-pb-block-preview__inner"' : '') + '>Block “' + block.name + '” (' + block.id + ') [' + block.type + ']</p>';
}
return null;
}
};
/**
* @param {number} contentId - the parent content ID to fetch children from
* @param {Array.<string>} contentTypes - list of content type identifiers to filter by
* @param {number} limit - maximum number of content items to return
* @returns {Promise<Array.<object>>} - a promise that resolves to an array of content info objects
*/
const getContentInfoList = async (contentId, contentTypes, limit) => {
let contentInfoList = [];
if (0 === limit) {
return contentInfoList;
}
let response;
let contentTypeHrefIdentifierMap = {};
// contentId -> mainLocationId
response = await fetch(`${apiBaseUrl}/api/ibexa/v2/content/objects/${contentId}`, {
method: 'GET',
headers: {
'Accept': 'application/vnd.ibexa.api.ContentInfo+json',
},
});
const parent = await response.json();
// mainLocationId -> children
response = await fetch(`${apiBaseUrl}${parent.Content.MainLocation._href}/children`, {
method: 'GET',
headers: {
'Accept': 'application/vnd.ibexa.api.LocationList+json',
},
});
const children = await response.json();
// child -> contentId + ContentType
for (const child of children.LocationList.Location) {
response = await fetch(`${apiBaseUrl}${child._href}`, {
method: 'GET',
headers: {
'Accept': child['_media-type'],
},
});
const location = await response.json();
// ContentType._href -> ContentType.identifier
const contentTypeHref = location.Location.ContentInfo.Content.ContentType._href;
let contentTypeIdentifier;
if (undefined === contentTypeHrefIdentifierMap[contentTypeHref]) {
response = await fetch(`${apiBaseUrl}${contentTypeHref}`, {
method: 'GET',
headers: {
'Accept': child['_media-type'],
},
});
const contentType = await response.json();
contentTypeIdentifier = contentType.ContentType.identifier;
contentTypeHrefIdentifierMap[contentTypeHref] = contentTypeIdentifier;
} else {
contentTypeIdentifier = contentTypeHrefIdentifierMap[contentTypeHref];
}
// Filter by content type identifier
if (contentTypes.includes(contentTypeIdentifier)) {
response = await fetch(`${apiBaseUrl}${contentTypeHref}`, {
method: 'GET',
headers: {
'Accept': child['_media-type'],
},
});
contentInfoList.push(location.Location.ContentInfo);
}
// Loop until limit or no more children
if (contentInfoList.length >= limit) {
break;
}
}
return contentInfoList;
};
if (window.parent !== window) { // Inside the Page Builder iframe
const pbOrigin = 'https://my-company.cohesivo.app';
const capabilities = [
'blocks.dnd',
'blocks.geometry',
'blocks.remove',
'blocks.reveal',
'blocks.select',
'pointer.tracking',
];
const initInterval = 1500; // ms
const initRetries = -1; // -1 = infinite, 0 = no retry, 1 = 1 retry, etc.
const idleLogDelay = 500; // ms
const postMessageToPB = (type, data = {}) => {
window.parent.postMessage({
type: type,
data: data,
}, pbOrigin);
logMessage(type, data);
};
const logMessage = (type, data) => {
if (['APP:MOUSE_POSITION', 'PB:DRAG_OVER'].includes(type)) {
window.clearTimeout(window.logIdleTimer);
window.logIdleTimer = window.setTimeout(() => {
console.log(type + ' (idle ' + idleLogDelay + 'ms)', data);
}, idleLogDelay);
} else {
console.log(type, data);
}
}
window.addEventListener('message', (messageEvent) => {
logMessage(messageEvent.data.type, messageEvent.data.data);
switch (messageEvent.data.type) {
case 'PB:INIT_MODE':
window.clearInterval(window.initIntervalId);
window.blocksConfig = messageEvent.data.data.blocksConfig;
window.translations = messageEvent.data.data.translations;
document.body.classList.add('c-pb-iframe__preview-body');
setLayout(messageEvent.data.data.fieldValue.layout);
renderZones(messageEvent.data.data.fieldValue.zones, {
pbOrigin: pbOrigin,
blocksConfig: window.blocksConfig,
blockClickedEventHandler: blockClicked,
unavailableBlockClickedEventHandler: blockRemoveRequest,
highlightedBlockIds: [],
init: true,
});
window.addEventListener('mousemove', (mouseEvent) => {
window.mouseX = mouseEvent.clientX;
window.mouseY = mouseEvent.clientY;
postMessageToPB('APP:MOUSE_POSITION', {
x: window.mouseX,
y: window.mouseY,
});
});
window.addEventListener('scrollend', (event) => {
postMessageToPB('APP:SCROLL_END');
positionsUpdate();
});
window.addEventListener('resize', (event) => {
positionsUpdate();
});
positionsUpdate();
break;
case 'PB:DRAG_START_PREVIEW':
document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`).classList.add('c-pb-block-preview--is-dragging-out');
break;
case 'PB:DRAG_END_PREVIEW':
document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`).classList.remove('c-pb-block-preview--is-dragging-out');
break;
case 'PB:DRAG_OVER':
window.mouseX = messageEvent.data.data.x;
window.mouseY = messageEvent.data.data.y;
const hoveredElement = document.elementFromPoint(window.mouseX, window.mouseY);
const hoveredZoneElement = hoveredElement.closest('.landing-page__zone');
if (hoveredZoneElement) {
hoveredZoneElement.classList.add('m-page-builder__zone--dragover');
}
for (const zoneElement of document.getElementsByClassName('m-page-builder__zone--dragover')) {
if (zoneElement !== hoveredZoneElement) {
zoneElement.classList.remove('m-page-builder__zone--dragover');
}
}
let hoveredPlaceHolderElement = hoveredElement.closest('.droppable-placeholder');
for (const placeHolderElement of document.getElementsByClassName('droppable-placeholder')) {
if (placeHolderElement !== hoveredPlaceHolderElement) {
placeHolderElement.remove();
}
}
if (hoveredZoneElement && !hoveredPlaceHolderElement) {
let hoveredBlockElement = hoveredElement.closest('.landing-page__block');
if (!hoveredBlockElement) {
hoveredBlockElement = document.elementFromPoint(window.mouseX, window.mouseY - 5).closest('.landing-page__block');
}
let newPlaceHolderElement = document.createElement('div');
newPlaceHolderElement.classList.add('droppable-placeholder');
if (hoveredBlockElement) {
hoveredBlockElement.before(newPlaceHolderElement);
} else {
hoveredZoneElement.appendChild(newPlaceHolderElement);
}
}
break;
case 'PB:DROP':
for (const zoneElement of document.getElementsByClassName('m-page-builder__zone--dragover')) {
zoneElement.classList.remove('m-page-builder__zone--dragover');
}
for (const placeHolderElement of document.getElementsByClassName('droppable-placeholder')) {
placeHolderElement.remove();
}
const dropTargetElement = document.elementFromPoint(window.mouseX, window.mouseY);
if (!dropTargetElement) {
console.error('No drop target element found.', 'notification.headless_unresponsive_preview');
return;
}
const dropTargetOffsetBlockElement = dropTargetElement.closest('.landing-page__block');
let nextBlockId;
if (dropTargetOffsetBlockElement) {
nextBlockId = dropTargetOffsetBlockElement.dataset.ibexaBlockId;
}
const zoneElement = dropTargetElement.closest('.landing-page__zone');
if (!zoneElement) {
console.error('No zone element found. Drop target element: ', dropTargetElement, 'notification.headless_unresponsive_preview');
return;
}
postMessageToPB('APP:DROP_RESPONSE', {
zoneId: zoneElement.dataset.ibexaZoneId,
nextBlockId: nextBlockId,
});
break;
case 'PB:SCROLL_BY':
window.scrollBy(messageEvent.data.data);
break;
case 'PB:SCROLL_INTO_BLOCK':
const blockElementToScrollInto = document.querySelector(`[data-ibexa-block-id="${messageEvent.data.data.blockId}"]`);
if (blockElementToScrollInto) {
blockElementToScrollInto.scrollIntoView({behavior: 'smooth', block: 'center'});
} else {
console.error('No block element found for block ID "' + messageEvent.data.data.blockId + '".');
}
break;
case 'PB:UPDATE_FIELD_DATA':
renderZones(messageEvent.data.data.fieldValue.zones, {
pbOrigin: pbOrigin,
blocksConfig: window.blocksConfig,
blockClickedEventHandler: blockClicked,
unavailableBlockClickedEventHandler: blockRemoveRequest,
highlightedBlockIds: messageEvent.data.data.highlightedBlockIds,
init: false,
});
positionsUpdate();
break;
case 'PB:DISPATCH_EVENT':
window.dispatchEvent(new CustomEvent(messageEvent.data.data.eventName, {detail: messageEvent.data.data.eventDetail}));
break;
case 'PB:BLOCK_REMOVE':
const blockId = messageEvent.data.data.blockId;
const blockElementToRemove = document.querySelector(`[data-ibexa-block-id="${blockId}"]`);
if (blockElementToRemove) {
blockElementToRemove.addEventListener('animationend', () => {
blockElementToRemove.remove();
postMessageToPB('APP:BLOCK_REMOVE_RESPONSE', {
blockId: blockId,
});
});
blockElementToRemove.classList.add('c-pb-block-preview--is-removing');
} else {
console.error('No block element found for block ID "' + messageEvent.data.data.blockId + '".', 'notification.headless_unresponsive_preview');
}
break;
default:
// As you can't receive an optional message from undeclared capabilities, to receive an unsupported one has to be an error.
// The unsupported received message reaching this is a mandatory message or one from a capability declared as supported.
console.error('Unsupported message type "' + messageEvent.data.type + '".');
console.log(messageEvent);
}
});
window.addEventListener('ibexa-active-block-clicked', (customEvent) => {
console.log(customEvent);
});
window.addEventListener('ibexa-post-update-blocks-preview', (customEvent) => {
console.log(customEvent);
setLayout(customEvent.detail.fieldValue.layout);
renderZones(customEvent.detail.fieldValue.zones, {
pbOrigin: pbOrigin,
blocksConfig: window.blocksConfig,
blockClickedEventHandler: blockClicked,
unavailableBlockClickedEventHandler: blockRemoveRequest,
highlightedBlockIds: [],
init: false,
});
});
let initRetry = 0;
window.initIntervalId = window.setInterval(() => {
postMessageToPB('APP:INITIALIZED', {
protocol: {supported: [1]},
capabilities: capabilities,
});
if (initRetries >= 0 && initRetry >= initRetries) {
window.clearInterval(window.initIntervalId);
}
initRetry++;
}, initInterval);
const positionsUpdate = () => {
let blocks = [];
for (const blockElement of document.getElementsByClassName('landing-page__block')) {
const blockId = blockElement.dataset.ibexaBlockId;
const blockRect = blockElement.getBoundingClientRect();
blocks.push({
id: blockId,
top: blockRect.top,
left: blockRect.left,
right: blockRect.right,
bottom: blockRect.bottom,
width: blockRect.width,
height: blockRect.height,
});
}
postMessageToPB('APP:POSITIONS_UPDATE', {
blocks: blocks,
});
};
window.positionsUpdate = positionsUpdate; // TMP
const blockClicked = (blockId) => {
postMessageToPB('APP:BLOCK_CLICKED', {
blockId: blockId,
});
};
const blockRemoveRequest = (blockId) => {
postMessageToPB('APP:BLOCK_REMOVE_REQUEST', {
blockId: blockId,
});
};
} else { // Stand-alone front page
// ⚠ This is done purely on client side for demo purposes only.
// In real project, content rendering, API requests, as much as possible should be done on front-end server's side.
// For example: /page.html?contentId=52
const pageContentTypeIds = [42/*landing_page*/];
const searchParams = new URLSearchParams(window.location.search);
const renderContent = async (contentId) => {
try {
const response = await fetch(`${apiBaseUrl}/api/ibexa/v2/content/objects/${contentId}`, {
method: 'GET',
headers: {
'Accept': 'application/vnd.ibexa.api.Content+json',
},
});
if (!response.ok) {
throw new Error('Response status "' + response.status + '" is not OK.');
}
const result = await response.json();
const contentTypeId = parseInt(result.Content.ContentType._href.replace('/api/ibexa/v2/content/types/', ''));
if (pageContentTypeIds && !pageContentTypeIds.includes(contentTypeId)) {
throw new Error('Wrong content type ' + contentTypeId + '.');
}
let fieldIsFound = false;
for (field of result.Content.CurrentVersion.Version.Fields.field) {
if (field.fieldDefinitionIdentifier === 'page') {
fieldIsFound = true;
setLayout(field.fieldValue.layout);
renderZones(field.fieldValue.zones);
break;
}
}
if (!fieldIsFound) {
throw new Error('No field "page" found in content with ID ' + contentId + '.');
}
} catch (error) {
console.error(error.message);
}
}
renderContent(searchParams.get('contentId'));
}
</script>
</html>
|
Edit page.html:
- Change the
apiBaseUrl constant to set the origin to which requests are sent for the REST API and conversion controller.
- Change the
pbOrigin constant to set the Page Builder's origin.
- Change
pageContentTypeIds to list the content type IDs that have a Landing Page field. You can set it to false to skip the content type check.
The demo supports the following block types and views:
- Code (
tag) block type with default and source_code views
- Content List (
contentlist) block type with default view