8000 perf(core): a sidebar save ships the preview markup by Klehm · Pull Request #100 · Klehm/content-blocks-project · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ Les composants `ContentAreaBuilder`, `Column` et `Section` n'existent plus : tou
### Stimulus Controllers (contrôle DOM)
Les 13 controllers livrés (source unique : `assets/package.json`) :
- `cb-builder-launcher` : ouvre le `<dialog>` du builder depuis le widget hôte
- `cb-builder` : orchestration de la fenêtre builder (sidebar, postMessage iframe, sauvegarde). The controller keeps its lifecycle and the `_onMessage` table; each feature is a file in `assets/builder/` (a class never instantiated, copied onto the controller by `mix()`, which throws on a name defined twice), so `this` is still the controller and the Vitest spies on `controller._x` still hold. A new feature is a new file plus one line in the `mix()` call. Rationale: [docs/internals/frontend.md#the-builder-controller-is-split-by-feature](docs/internals/frontend.md#the-builder-controller-is-split-by-feature). Porte aussi le **contrat d'événements `cb:*`** : nine are public (detail shapes in docs/guide/host-services.md#builder-events) — five outbound (`cb:ready`, re-emitted as a DOM event from the iframe's postMessage, `cb:block:saved`, `cb:section:saved`, `cb:builder:action`, and `cb:block:rendered` inside the iframe) et trois **entrants** qu'un fragment de shell ou l'hôte dispatche vers le builder : `cb:area:changed` après avoir modifié la zone côté serveur (le builder recharge la preview et resynchronise Publier/Annuler), et `cb:notify` (`detail.message` + `link: {label, href}` optionnel, ouvert dans un nouvel onglet) pour parler dans le snackbar du builder — la page hôte est sous la modale, hors de vue — et `cb:focus` (`{kind: block|section, id}`) pour sélectionner un élément comme un clic dessus — plus `cb:media:browse`, émis par le widget d'upload (voir `cb-file-upload`) — les 33 autres sont de la chorégraphie interne
- `cb-builder` : orchestration de la fenêtre builder (sidebar, postMessage iframe, sauvegarde). The controller keeps its lifecycle and the `_onMessage` table; each feature is a file in `assets/builder/` (a class never instantiated, copied onto the controller by `mix()`, which throws on a name defined twice), so `this` is still the controller and the Vitest spies on `controller._x` still hold. A new feature is a new file plus one line in the `mix()` call. Rationale: [docs/internals/frontend.md#the-builder-controller-is-split-by-feature](docs/internals/frontend.md#the-builder-controller-is-split-by-feature). Porte aussi le **contrat d'événements `cb:*`** : nine are public (detail shapes in docs/guide/host-services.md#builder-events) — five outbound (`cb:ready`, re-emitted as a DOM event from the iframe's postMessage, `cb:block:saved`, `cb:section:saved`, `cb:builder:action`, and `cb:block:rendered` inside the iframe) et trois **entrants** qu'un fragment de shell ou l'hôte dispatche vers le builder : `cb:area:changed` après avoir modifié la zone côté serveur (le builder recharge la preview et resynchronise Publier/Annuler), et `cb:notify` (`detail.message` + `link: {label, href}` optionnel, ouvert dans un nouvel onglet) pour parler dans le snackbar du builder — la page hôte est sous la modale, hors de vue — et `cb:focus` (`{kind: block|section, id}`) pour sélectionner un élément comme un clic dessus — plus `cb:media:browse`, émis par le widget d'upload (voir `cb-file-upload`) — les 35 autres sont de la chorégraphie interne (including `cb:block:preview` / `cb:section:preview`, the preview markup shipped by the save itself: docs/internals/frontend.md#the-save-carries-the-preview-markup)
- **Fragments de shell** (`BuilderShellExtensionInterface`, autoconfiguré, fonction Twig `cb_shell_fragments(area)`; the Actions menu likewise calls `cb_builder_actions(area, topbarActions)` so `BuilderActionProviderInterface` entries show on a direct launcher include) : la moitié UI de `BuilderActionProviderInterface`. Un bundle rend ses propres templates **dans** `.cb-shell` (après le chrome, contexte isolé + `area`), donc son `<dialog>` et un `<script type="module">` servi par sa propre route — sans controller Stimulus, sans `controllers.json`, sans recompilation. Le shell appelle la fonction lui-même, donc un fragment apparaît aussi quand l'hôte inclut `launcher.html.twig` directement. Précédent : `DemoShellExtension` dans la sandbox, `assets/test/e2e/shell-fragments.spec.js`
- `cb-autosave` : sauvegarde debouncée des forms de sidebar
- `cb-section-settings-form` : sync live de la sidebar de settings de section
Expand Down
30 changes: 30 additions & 0 deletions docs/internals/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,36 @@ leaving the inner blocks untouched. That is always safe, because a section's
settings never change its structure. Overlay-owned classes are re-applied after
the copy.

### The save carries the preview markup

A sidebar edit used to cost two requests: the save, then, after a 500 ms quiet
period, `GET /block/{id}/render` (or `/section/{id}/render`) for the markup to
swap in. The save already holds the freshly written entity, so it renders it
too: `BlockComponent` dispatches the internal `cb:block:preview`
(`{blockId, html}`) right before `cb:block:saved`, and a section settings save
answers `200 {hotReload, html}` instead of `204`, relayed by the form as
`cb:section:preview`. The builder keeps that markup for the saved-event that
follows and swaps it in at once: one request per edit, and no quiet period.

The markup does not ride on `cb:block:saved` / `cb:section:saved`: those are
public, and a host listener has no use for a block's HTML that would justify
freezing it into the contract.

Everything else is unchanged, which is what keeps it safe:

- The render goes through the same `renderBlock()` / `renderSection()` with
`RenderContext::forPreview()` as the endpoints, so the markup is identical.
- A type that opts out of hot reload ships nothing, and a render that throws
ships nothing either: the save succeeds and the builder falls back to the
render endpoint, which reloads the preview as before. A render error never
costs a save.
- The render endpoints stay. They are the fallback, they serve a column label
save (which has no markup of its own) and the i18n workbench, whose preview
asks for another locale.
- A saved-event with no markup kept for *that* block or section, by id, takes
the old path: the markup is taken at most once, so a stale one is never
swapped onto the wrong node.

## Focus and the sidebar

Clicking a block or a section is what opens its sidebar, so **the sidebar *is*
Expand Down
7 changes: 7 additions & 0 deletions packages/content-blocks/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **An edit in the sidebar costs one request, and the preview follows at
once.** A block or section save now returns the saved element's preview
markup, which the builder swaps in straight away. Before, it waited 500 ms
and asked `/block/{id}/render` (or `/section/{id}/render`) for it. A section
settings save answers `200` with `{hotReload, html}` where it answered
`204`; a block type that opts out of hot reload, or a render that fails,
falls back to the render endpoint as before, and never fails the save.
- **The upload endpoint's errors are translated.** `error` is now a sentence
in the request's language naming the file and the limit, where it was an
English string, and PHP's own wording (`upload_max_filesize`) no longer
Expand Down
72 changes: 62 additions & 10 deletions packages/content-blocks/assets/builder/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,8 @@ export default class Preview {
}

/**
* Hot-swaps the focused block where possible, the server having the final
* say. Both paths share one debounce, so a burst of saves is one refresh.
* Swaps in the markup the save shipped; without it, hot-swaps or reloads
* after one shared debounce, so a burst of saves is one refresh.
*
* @see docs/internals/frontend.md#hot-reload-and-when-it-is-refused
*/
Expand All @@ -232,11 +232,18 @@ export default class Preview {
const blockId = this.hasSidebarT 8000 arget
? this.sidebarTarget.getAttribute('data-cb-sidebar-block-id')
: null;
if (blockId) {
this._scheduleBlockRefresh(parseInt(blockId, 10));
} else {
if (!blockId) {
this._scheduleReload();
return;
}
const id = parseInt(blockId, 10);
const html = this._takePreviewMarkup('block', id);
if (html === null) {
this._scheduleBlockRefresh(id);
return;
}
clearTimeout(this._reloadTimer);
this._swapBlock(id, html);
}

_onSectionSaved(event) {
Expand All @@ -247,11 +254,40 @@ export default class Preview {
const sectionId = this.hasSidebarTarget
? this.sidebarTarget.getAttribute('data-cb-sidebar-section-id')
: null;
if (sectionId) {
this._scheduleSectionRefresh(parseInt(sectionId, 10));
} else {
if (!sectionId) {
this._scheduleReload();
return;
}
const id = parseInt(sectionId, 10);
const html = this._takePreviewMarkup('section', id);
if (html === null) {
this._scheduleSectionRefresh(id);
return;
}
clearTimeout(this._reloadTimer);
this._patchSection(id, html);
}

/**
* Kept until the saved-event right behind it, which is dispatched from the
* same response.
*
* @see docs/internals/frontend.md#the-save-carries-the-preview-markup
*/
_onPreviewMarkup(event) {
const detail = event.detail ?? {};
const kind = event.type === 'cb:section:preview' ? 'section' : 'block';
const id = Number(kind === 'section' ? detail.sectionId : detail.blockId);
if (!id || typeof detail.html !== 'string') return;
this._previewMarkup = { kind, id, html: detail.html };
}

/** The markup the last save shipped for this node, at most once. */
_takePreviewMarkup(kind, id) {
const markup = this._previewMarkup;
this._previewMarkup = null;

return markup && markup.kind === kind && markup.id === id ? markup.html : null;
}

_scheduleReload() {
Expand Down Expand Up @@ -305,9 +341,17 @@ export default class Preview {
return;
}

this._swapBlock(blockId, payload.html);
}

_swapBlock(blockId, html) {
if (!this.hasIframeTarget) {
this.reload();
return;
}
try {
this.iframeTarget.contentWindow?.postMessage(
{ type: 'cb:block:replace', blockId, html: payload.html },
{ type: 'cb:block:replace', blockId, html },
window.location.origin,
);
} catch (_) {
Expand Down Expand Up @@ -359,9 +403,17 @@ export default class Preview {
return;
}

this._patchSection(sectionId, payload.html);
}

_patchSection(sectionId, html) {
if (!this.hasIframeTarget) {
this.reload();
return;
}
try {
this.iframeTarget.contentWindow?.postMessage(
{ type: 'cb:section:patch', sectionId, html: payload.html },
{ type: 'cb:section:patch', sectionId, html },
window.location.origin,
);
} catch (_) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class BuilderController extends Controller {
this._onMessage = this._onMessage.bind(this);
this._onBlockSaved = this._onBlockSaved.bind(this);
this._onSectionSaved = this._onSectionSaved.bind(this);
this._onPreviewMarkup = this._onPreviewMarkup.bind(this);
this._onColumnAddRequested = this._onColumnAddRequested.bind(this);
this._onColumnDeleteRequested = this._onColumnDeleteRequested.bind(this);
this._onResizeMove = this._onResizeMove.bind(this);
Expand Down Expand Up @@ -118,6 +119,10 @@ class BuilderController extends Controller {
// dispatchBrowserEvent on save; the events bubble up to here.
this.element.addEventListener('cb:block:saved', this._onBlockSaved);
this.element.addEventListener('cb:section:saved', this._onSectionSaved);
// Dispatched right before the saved-events when the save shipped the
// preview markup, which spares the render request.
this.element.addEventListener('cb:block:preview', this._onPreviewMarkup);
this.element.addEventListener('cb:section:preview', this._onPreviewMarkup);
// The section sidebar asks; the columns change through the queue.
this.element.addEventListener('cb:column:add-requested', this._onColumnAddRequested);
this.element.addEventListener('cb:column:delete-requested', this._onColumnDeleteRequested);
Expand Down Expand Up @@ -162,6 +167,8 @@ class BuilderController extends Controller {
document.removeEventListener('visibilitychange', this._onVisibilityChange);
this.element.removeEventListener('cb:block:saved', this._onBlockSaved);
this.element.removeEventListener('cb:section:saved', this._onSectionSaved);
this.element.removeEventListener('cb:block:preview', this._onPreviewMarkup);
this.element.removeEventListener('cb:section:preview', this._onPreviewMarkup);
this.element.removeEventListener('cb:column:add-requested', this._onColumnAddRequested);
this.element.removeEventListener('cb:column:delete-requested', this._onColumnDeleteRequested);
this.element.removeEventListener('live:connect', this._onLiveConnect);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,17 @@ export default class extends Controller {
}

if (response.ok) {
// The save may carry the section's preview markup: the builder
// then patches it without fetching it again.
const result = response.status === 200
? await response.json().catch(() => null)
: null;
if (typeof result?.html === 'string') {
this.element.dispatchEvent(new CustomEvent('cb:section:preview', {
bubbles: true,
detail: { sectionId: this.sectionIdValue, html: result.html },
}));
}
this.element.dispatchEvent(new CustomEvent('cb:section:saved', {
bubbles: true,
detail: { sectionId: this.sectionIdValue },
Expand Down
72 changes: 72 additions & 0 deletions packages/content-blocks/assets/test/cb-builder.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,51 @@ describe('cb-builder: block hot reload', () => {
vi.useRealTimers();
});

it('a save that shipped the markup swaps the block at once, with no request', () => {
vi.useFakeTimers();
sidebar.setAttribute('data-cb-sidebar-block-id', '7');
const html = '<div class="cb-block" data-cb-block-id="7">Fresh</div>';
global.fetch = vi.fn();
const postSpy = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
const reloadSpy = vi.spyOn(controller, 'reload').mockImplementation(() => {});
controller.connect();

// As Live dispatches them: the markup first, then the saved-event.
sidebar.dispatchEvent(new CustomEvent('cb:block:preview', {
bubbles: true, detail: { blockId: 7, html },
}));
sidebar.dispatchEvent(new CustomEvent('cb:block:saved', {
bubbles: true, detail: { blockId: 7 },
}));

expect(postSpy).toHaveBeenCalledWith(
{ type: 'cb:block:replace', blockId: 7, html },
window.location.origin,
);
vi.advanceTimersByTime(Controller.SAVE_RELOAD_DEBOUNCE_MS + 10);
expect(global.fetch).not.toHaveBeenCalled();
expect(reloadSpy).not.toHaveBeenCalled();
controller.disconnect();
vi.useRealTimers();
});

it('markup shipped for another block is dropped, and the render is fetched', () => {
vi.useFakeTimers();
sidebar.setAttribute('data-cb-sidebar-block-id', '7');
const refreshSpy = vi.spyOn(controller, '_refreshBlock').mockImplementation(() => {});
const postSpy = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});

controller._onPreviewMarkup({ type: 'cb:block:preview', detail: { blockId: 8, html: '<p></p>' } });
controller._onBlockSaved({ detail: { blockId: 7 } });
vi.advanceTimersByTime(Controller.SAVE_RELOAD_DEBOUNCE_MS + 10);

expect(postSpy).not.toHaveBeenCalled();
expect(refreshSpy).toHaveBeenCalledWith(7);
// Taken once: a later save of block 8 shipping nothing fetches too.
expect(controller._takePreviewMarkup('block', 8)).toBeNull();
vi.useRealTimers();
});

it('_refreshBlock posts cb:block:replace when the server allows hot reload', async () => {
const html = '<div class="cb-block" data-cb-block-id="7">Fresh</div>';
global.fetch = vi.fn(() => Promise.resolve({
Expand Down Expand Up @@ -474,6 +519,33 @@ describe('cb-builder: section hot reload', () => {
vi.useRealTimers();
});

it('a save that shipped the markup patches the section at once, with no request', () => {
vi.useFakeTimers();
sidebar.setAttribute('data-cb-sidebar-section-id', '5');
const html = '<section class="cb-section" data-cb-section-id="5"></section>';
global.fetch = vi.fn();
const postSpy = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});
const reloadSpy = vi.spyOn(controller, 'reload').mockImplementation(() => {});
controller.connect();

sidebar.dispatchEvent(new CustomEvent('cb:section:preview', {
bubbles: true, detail: { sectionId: 5, html },
}));
sidebar.dispatchEvent(new CustomEvent('cb:section:saved', {
bubbles: true, detail: { sectionId: 5 },
}));

expect(postSpy).toHaveBeenCalledWith(
{ type: 'cb:section:patch', sectionId: 5, html },
window.location.origin,
);
vi.advanceTimersByTime(Controller.SAVE_RELOAD_DEBOUNCE_MS + 10);
expect(global.fetch).not.toHaveBeenCalled();
expect(reloadSpy).not.toHaveBeenCalled();
controller.disconnect();
vi.useRealTimers();
});

it('_refreshSection posts cb:section:patch when the server allows hot reload', async () => {
const html = '<section class="cb-section cb-section--styled" data-cb-section-id="5"></section>';
global.fetch = vi.fn(() => Promise.resolve({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,28 @@ describe('cb-section-settings-form — submit error feedback', () => {

expect(events).toEqual(['saved']);
});

it('a save answering with markup relays it before cb:section:saved', async () => {
const { c, events } = setupSubmit();
const html = '<section data-cb-section-id="5"></section>';
const previews = [];
const => {
events.push('preview');
previews.push(e.detail);
};
document.body.addEventListener('cb:section:preview', onPreview);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: () => Promise.resolve({ hotReload: true, html }),
}));

await c._onSubmit(new Event('submit', { cancelable: true }));

expect(events).toEqual(['preview', 'saved']);
expect(previews).toEqual([{ sectionId: 5, html }]);
document.body.removeEventListener('cb:section:preview', onPreview);
});
});

// ---------- One save in flight ----------
Expand Down
Loading
0