Metadata-Version: 2.5
Name: wagtail-visual-editor
Version: 0.1.3
Summary: Visual editor for headless Wagtail: edit a StreamField on top of your frontend's live preview.
Author-email: Eric Kersten <eric.kersten@egodesign.io>
License-Expression: MIT
License-File: LICENSE
Keywords: headless,preview,streamfield,visual editor,wagtail
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Wagtail
Classifier: Framework :: Wagtail :: 7
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Requires-Dist: wagtail<7.5,>=7.4
Description-Content-Type: text/markdown

# wagtail-visual-editor

A visual page editor for **headless Wagtail**. Your editors work on top of the real frontend preview (Next.js, Astro, or anything else) instead of a long form:

- hover a block in the preview to get **Edit, move up, move down, Duplicate and Delete**, and a **+** on its top and bottom edges to add a block above or below;
- each block is edited in a **modal** that uses Wagtail's own block form (choosers, rich text, `TabbedStructBlock`, validation, everything);
- a collapsible **tree index** of the page, with an eye toggle to **hide a block** from the live site without deleting it, and a **full screen** button that hides it;
- **mobile / tablet / desktop** widths;
- the **block picker previews each block** rendered by your frontend;
- live **social share previews** (Google, WhatsApp, Facebook, X, LinkedIn, Slack, Pinterest) for the promote tab.

Wagtail's native StreamField stays in the form, hidden. It is still the source of truth: saving, drafts, autosave, revisions and validation work exactly as before. The editor only drives it through its JavaScript API.

The package has two parts, released together with the same version number:

| Part | Package | Where it runs |
| --- | --- | --- |
| Django app | [`wagtail-visual-editor`](https://pypi.org/project/wagtail-visual-editor/) (PyPI) | Wagtail admin |
| Preview bridge | [`wagtail-visual-editor-bridge`](https://www.npmjs.com/package/wagtail-visual-editor-bridge) (npm) | Your frontend's preview route |

## Compatibility

| wagtail-visual-editor | Wagtail | Python | Django |
| --- | --- | --- | --- |
| 0.1.x | 7.4 | 3.10+ | as required by Wagtail |

The Wagtail range is capped on purpose: the editor uses Wagtail's internal StreamField JavaScript API, which can change in any minor release. A new Wagtail minor is supported only after it has been tested. If you force an untested version, `manage.py check` reports the warning `wagtail_visual_editor.W001`.

## Requirements

- A **headless preview** that already works: Wagtail's preview must redirect to your frontend, for example with [wagtail-headless-preview](https://github.com/torchbox/wagtail-headless-preview).
- The page's **Site points to the frontend**. The editor trusts messages only from the Site's `root_url` (scheme, hostname and port), so it must be the origin that serves the preview.
- The frontend's preview routes can be **embedded in an iframe by the Wagtail admin**: allow the admin origin in `Content-Security-Policy: frame-ancestors` (and don't send `X-Frame-Options: DENY`) on `/preview` and `/preview/block`.

## Installation

### Backend

```bash
pip install wagtail-visual-editor
```

```python
# settings.py
INSTALLED_APPS = [
    # ...
    "wagtail_visual_editor",
]
```

There is nothing to add to `urls.py`: the app registers its admin URLs through Wagtail's `register_admin_urls` hook.

### Frontend

```bash
npm install wagtail-visual-editor-bridge
```

See [Frontend integration](#frontend-integration) below.

## Usage

### 1. Add the visual editor panel

Use `VisualStreamPanel` instead of `FieldPanel` for the StreamField. Give it its own tab: it uses the full width and height of the screen.

```python
from wagtail.admin.panels import FieldPanel, ObjectList, TabbedInterface
from wagtail.fields import StreamField
from wagtail.models import Page
from wagtail_headless_preview.models import HeadlessMixin
from wagtail_visual_editor.panels import VisualStreamPanel


class BasePage(HeadlessMixin, Page):
    body = StreamField([...])

    content_panels = Page.content_panels  # title and other fields

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading="Content"),
        ObjectList([VisualStreamPanel("body")], heading="Visual editor"),
        ObjectList(Page.promote_panels, heading="Promote"),
        ObjectList(Page.settings_panels, heading="Settings"),
    ])
```

Put the panel on the generic page your other page types inherit from, and they all get the visual editor. Subclasses can still change the blocks of the StreamField.

It works on new pages too. Note that Wagtail 7.4's autosave creates the page as soon as the editor changes something; the editor follows that switch from "add" to "edit" by itself.

### 2. Social share previews (optional)

```python
from wagtail.admin.panels import FieldPanel, MultiFieldPanel
from wagtail_visual_editor.panels import SocialCardPreviewPanel


class BasePage(HeadlessMixin, Page):
    og_image = models.ForeignKey("wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+")

    promote_panels = Page.promote_panels + [
        MultiFieldPanel([FieldPanel("og_image"), SocialCardPreviewPanel()], heading="Sharing"),
    ]

    def get_social_preview_defaults(self, site):
        # Optional: the image used when og_image is empty (for example from a site setting)
        return {"image_url": "https://example.com/default-share.jpg"}
```

The previews update live from the form: `seo_title` (falls back to `title`), `search_description`, `slug` and `og_image`. The chosen image is shown with the crop that gets shared, `fill-1200x630` by default.

### 3. Block previews in the block picker (optional)

When the editor adds a block, the picker shows each block type rendered by your frontend. To make that possible, the app replaces Wagtail's block preview view: it stores the block's preview value in Django's cache under a random token and redirects to `<frontend>/preview/block?token=...`.

Preview values come from `Meta.preview_value`, or are generated from the block's structure with `SamplePreviewMixin`:

```python
from wagtail import blocks
from wagtail_visual_editor.sample_values import SamplePreviewMixin


class HeroBlock(SamplePreviewMixin, blocks.StructBlock):
    title = blocks.CharBlock()
    image = ImageChooserBlock()
    # no preview_value needed: a title and the first image in the library are used
```

Your backend serves the stored value to the frontend, serialized exactly like a block of a page:

```python
from wagtail_visual_editor.views import get_block_preview

def block_preview_api(request, token):
    data = get_block_preview(token)  # {"type": "hero", "value": {...}} (raw StreamField format) or None
    ...
```

Tokens live in Django's cache for 10 minutes. **In production with more than one process, configure a shared cache** (Redis, Memcached or the database cache); the default local-memory cache is per process.

### 4. Hide blocks without deleting them (optional)

Root blocks that have a field named `hidden` get an eye toggle in the tree index:

```python
class BaseBlock(blocks.StructBlock):
    hidden = blocks.BooleanBlock(required=False, help_text="Keep the block but don't show it on the site")
```

The editor only toggles the value. Skipping hidden blocks when you serialize the page for the API is up to your project.

### 5. When the frontend is not there

- **No frontend yet** (a new project): set `WAGTAIL_VISUAL_EDITOR_ENABLED = False`, for example from an environment variable. Pages are edited with Wagtail's standard StreamField, with no errors in the admin. Turn it on once the preview routes exist.
- **Frontend down or unreachable**: if the preview doesn't answer (the bridge never says `ready`), the editor falls back to Wagtail's standard StreamField after a few seconds, with a notice and a **Retry** button. Nothing is lost: it is the same field that gets saved.

## Frontend integration

The frontend needs two routes. Both must accept being framed by the Wagtail admin.

### Page preview: `/preview`

The route your headless preview already has. When it renders the StreamField for a preview, wrap **each root block** with its id, and start the bridge with the origin of the Wagtail admin:

```html
<div data-block-id="{block.id}" style="display: contents">
  <!-- your block component -->
</div>
```

`display: contents` means the wrapper has no box of its own, so it doesn't change the layout. Only add the wrappers in the preview, not on the public site.

Next.js (App Router):

```tsx
"use client";
import { useEffect } from "react";
import { startVisualEditBridge } from "wagtail-visual-editor-bridge";

export function VisualEditBridge({ adminOrigin }: { adminOrigin: string }) {
	useEffect(() => startVisualEditBridge(adminOrigin), [adminOrigin]);
	return null;
}
```

Astro:

```astro
---
const { adminOrigin } = Astro.props;
---
<div hidden data-admin-origin={adminOrigin}></div>
<script>
	import { startVisualEditBridge } from "wagtail-visual-editor-bridge";

	const origin = document.querySelector<HTMLElement>("[data-admin-origin]")?.dataset.adminOrigin;
	if (origin) startVisualEditBridge(origin);
</script>
```

### Block preview: `/preview/block?token=...`

Fetch the block from your backend (see `get_block_preview` above) and render it alone, without the site header and footer.

### Incomplete blocks

Wagtail doesn't enforce required fields in drafts and previews. A block that was just added is usually empty, so **the preview must tolerate missing values**. A good pattern is to validate each block on its own and replace the ones that fail with a placeholder ("Incomplete block, click Edit"), instead of failing the whole page.

### Message protocol

The admin and the preview talk through `postMessage`. Every message carries `source: "wagtail-visual-editor"`, and each side checks the other's origin: the admin accepts only the Site's `root_url`, the bridge accepts only the admin origin you pass to it.

| Direction | `action` | Payload |
| --- | --- | --- |
| preview → admin | `ready` | — |
| preview → admin | `edit`, `moveUp`, `moveDown`, `duplicate`, `delete`, `insertBefore`, `insertAfter` | `id` of the block |
| admin → preview | `scrollTo` | `id` of the block |
| admin → preview | `labels` | `labels`: `{action: [text, title]}` for the action bar, in the admin user's language (icon-only buttons use just the title) |

## Translations

The UI follows each admin user's language, like the rest of Wagtail. The preview action bar too: the admin sends its translated labels to the bridge when the preview loads (the bridge falls back to English).

Available languages: English and Spanish. Strings that Wagtail already has, such as "Cancel", "Edit", "Delete" or the preview sizes, use Wagtail's own translations, so they are translated in every language Wagtail supports.

To add a language, from the `wagtail_visual_editor` directory:

```bash
django-admin makemessages -l fr --no-location
# translate locale/fr/LC_MESSAGES/django.po
django-admin compilemessages
```

## Settings

| Setting | Default | Description |
| --- | --- | --- |
| `WAGTAIL_VISUAL_EDITOR_ENABLED` | `True` | `False` turns `VisualStreamPanel` into a plain `FieldPanel` and restores Wagtail's own block previews. Useful while the frontend doesn't exist yet |
| `WAGTAIL_VISUAL_EDITOR_SOCIAL_RENDITION` | `"fill-1200x630"` | Image crop shown in the social share previews |

## Limitations

- One `VisualStreamPanel` per page.
- The block picker previews replace Wagtail's block previews for every StreamField of the admin, not only the visual editor.
- Hidden blocks don't appear in the preview, so they can only be edited from the tree index.

## Development

```bash
python -m unittest discover -s tests   # Django app
cd bridge && npm install && npm run build   # bridge
```

Releasing: bump the version in `pyproject.toml`, `wagtail_visual_editor/__init__.py` and `bridge/package.json`, then push a tag `X.Y.Z` (no `v` prefix). The release workflow checks that the three versions match the tag and publishes both packages.

## License

MIT
