# Headless frontend preview in Page Builder

> For the complete documentation index, see [llms.txt](https://doc.ibexa.co/en/saas/llms.txt).

Preview and edit in Page Builder using your frontend.

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

1. In the left panel, go to **Administration** -> **SiteAccess Configuration**
2. 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.
3. In **Available configurations** list, click **Headless**.
4. In **Edit configuration** section, expand the **Headless mode** drop-down list and select **Enabled**.
5. Populate the **Page Builder preview URL** field and click **Save**.

![Headless mode enabled with Page Builder preview URL](https://doc.ibexa.co/en/saas/content_management/img/headless-saas-siteaccess-config.png)

## 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](https://developer.mozilla.org/en-US/docs/Web/API/Window/message_event).

The frontend resource sends messages back to the Page Builder. You can send them by using the [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) method. The target origin of those messages must be the Page Builder's origin.

```js
const pbOrigin = 'https://my-company.cohesivo.app';
window.parent.postMessage(message, pbOrigin);
```

These messages are JavaScript objects with the following structure:

```js
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.

| Capability         | Message type                                                                                | Description                                       |
| ------------------ | ------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| (handshake)        | [`APP:INITIALIZED`](#communication-initialization)                                          | Establishes protocol and capabilities.            |
| (handshake)        | [`PB:INIT_MODE`](#communication-initialization)                                             | Confirms protocol and draft info.                 |
| (core)             | [`PB:UPDATE_FIELD_DATA`](#on-field-update)                                                  | Sends updated field data.                         |
| (core)             | [`PB:DISPATCH_EVENT`](#re-dispatching-events)                                               | Re-dispatches a frontend event.                   |
| `blocks.dnd`       | [`PB:DRAG_START_PREVIEW`](#dragging-and-dropping-blocksdnd)                                 | Informs that existing block dragging has started. |
| `blocks.dnd`       | [`PB:DRAG_OVER`](#dragging-and-dropping-blocksdnd)                                          | Passes mouse position during dragging.            |
| `blocks.dnd`       | [`PB:DRAG_END_PREVIEW`](#dragging-and-dropping-blocksdnd)                                   | Informs that existing block dragging has ended.   |
| `blocks.dnd`       | [`PB:DROP`](#dragging-and-dropping-blocksdnd)                                               | Drop notification.                                |
| `blocks.dnd`       | [`APP:DROP_RESPONSE`](#dragging-and-dropping-blocksdnd)                                     | Reports where the block was dropped.              |
| `blocks.dnd`       | [`PB:SCROLL_BY`](#dragging-and-dropping-blocksdnd)                                          | Scrolls the preview.                              |
| `blocks.geometry`  | [`APP:POSITIONS_UPDATE`](#geometry-and-pointer-tracking-blocksgeometry-and-pointertracking) | Reports block positions.                          |
| `blocks.geometry`  | [`APP:SCROLL_END`](#geometry-and-pointer-tracking-blocksgeometry-and-pointertracking)       | Informs that scrolling has ended.                 |
| `blocks.remove`    | [`PB:BLOCK_REMOVE`](#block-removal-blocksremove)                                            | Removes a block.                                  |
| `blocks.remove`    | [`APP:BLOCK_REMOVE_RESPONSE`](#block-removal-blocksremove)                                  | Confirms removal.                                 |
| `blocks.remove`    | [`APP:BLOCK_REMOVE_REQUEST`](#block-removal-blocksremove)                                   | Requests block removal.                           |
| `blocks.reveal`    | [`PB:SCROLL_INTO_BLOCK`](#block-reveal-blocksreveal)                                        | Scrolls a block into view.                        |
| `blocks.select`    | `APP:BLOCK_CLICKED`                                                                         | Informs that block is clicked.                    |
| `pointer.tracking` | [`APP:MOUSE_POSITION`](#geometry-and-pointer-tracking-blocksgeometry-and-pointertracking)   | Reports mouse position.                           |

### Communication initialization

First, the frontend sends an initialization message to the Page Builder, indicating which protocol versions and capabilities it supports:

```js
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`)

```json
{
    "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`)

```json
{
    "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`).

```js
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`](#on-field-update)
  - `blockIds` - A list of all the block IDs
  - `blocksMaps` - A map of block config per block ID

```js
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.

```js
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()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) method.

```js
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`](#on-field-update), 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.

```js
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.

> **Tip: 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`).

```js
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`.

```js
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`).

```js
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`)](#geometry-and-pointer-tracking-blocksgeometry-and-pointertracking).

### 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()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method.

```js
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.

```js
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;
    }
});
```

```css
.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`)](#block-removal-blocksremove))    |
| `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`

```html
<!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: '&nbsp;';
        }

        .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 = '&nbsp;';
                    } 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 &ldquo;' + block.name + '&rdquo; (' + 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
