Rebuild the editor around one sidebar and play motion by default in 1.11.0
CMS quality / php (8.2) (push) Canceled after 0s
CMS quality / php (8.4) (push) Canceled after 0s
CMS quality / browser (push) Canceled after 0s
CMS quality / mysql (push) Canceled after 0s

The editor follows the Flatsome UX Builder: dark top bar with the device
switch, one sidebar with tabs for elements, structure and page, an element
view with breadcrumbs, property tabs and actions, element cards, a context
menu in the preview and keyboard shortcuts that also work inside the preview.

Entrance and hover effects play for every visitor unless the website chooses
to respect the browser's reduced-motion preference (setting "motion", class
"motion-respect" on <html>). Waiting blocks stay hidden until they scroll into
view and are shown at once when the reader jumps past them.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
kantarciandClaude Fable 5.1 committed 2026-09-14 16:41:04 +02:00
1 parent ebc16777d6
commit a1f8b905cd
18 files changed
+723 -433

No files matched your search

+207 -104
View File
@@ -33,15 +33,45 @@ let renderedProperties = null;
let revealAfterPreview = null;
let previewPlayback = false, stopPlayback = () => {};
const motionPreference = window.matchMedia('(prefers-reduced-motion: reduce)');
const showMotionStatus = () => { $('#motion-status').hidden = !motionPreference.matches; };
// Worth a note only when the website actually follows the browser (Einstellungen → Bewegung);
// the preview carries that decision as a class on its <html>.
const showMotionStatus = () => {
const respects = $('#preview').contentDocument?.documentElement.classList.contains('motion-respect') ?? false;
$('#motion-status').hidden = !(motionPreference.matches && respects);
};
motionPreference.addEventListener('change', showMotionStatus);
showMotionStatus();
// ---------------------------------------------------------------------------------------------
// The sidebar shows one thing at a time.
//
// `elements` is the library, `structure` the tree, `page` the page settings and `element` the
// options of the selected block. The last one is not a tab: it appears when something is
// selected and gives way to the library when the selection is dropped - the Flatsome rhythm of
// "pick, edit, back to the list".
// ---------------------------------------------------------------------------------------------
let view = 'elements';
function setView(name) {
view = name;
const sidebar = $('.sidebar');
sidebar.dataset.view = name;
const showsProperties = name === 'element' || name === 'page';
for (const section of sidebar.querySelectorAll('.sidebar-view')) section.hidden = section.dataset.view !== (showsProperties ? 'element' : name);
// The tabs stay in reach while an element is open, so the library and the tree are one click
// away; none of them is marked then, because the element view is not a tab.
for (const tab of sidebar.querySelectorAll('.sidebar-nav [role=tab]')) tab.setAttribute('aria-selected', String(tab.dataset.view === name));
$('.sidebar-element').hidden = name !== 'element';
$('.property-tabs').hidden = name !== 'element';
$('.sidebar-foot').hidden = name !== 'element';
$('.sidebar-body').scrollTop = 0;
}
function playPreview() {
stopPlayback(); stopPlayback = () => {};
const button = $('#preview-motion');
button.setAttribute('aria-pressed', String(previewPlayback));
button.textContent = previewPlayback ? 'Bewegung stoppen' : 'Bewegung testen';
button.title = previewPlayback ? 'Bewegung in der Vorschau stoppen' : 'Bewegung in der Vorschau abspielen';
button.setAttribute('aria-label', button.title);
const doc = $('#preview').contentDocument;
if (previewPlayback && doc?.body) {
const stopMotion = initMotion(doc), stopSliders = initSliders(doc);
@@ -86,20 +116,19 @@ function controls() {
$('#undo').disabled = !ready || busy || !history.past.length;
$('#redo').disabled = !ready || busy || !history.future.length;
const current = ready ? locate(history.document.blocks, selected) : null;
for (const id of ['duplicate', 'delete', 'move-up', 'move-down', 'nest', 'outdent']) $(`#${id}`).disabled = !current || busy;
for (const id of ['duplicate', 'delete', 'move-up', 'move-down', 'nest', 'outdent', 'go-parent', 'add-here', 'close-element']) $(`#${id}`).disabled = !current || busy;
if (current) {
$('#move-up').disabled ||= current.index === 0;
$('#move-down').disabled ||= current.index === current.siblings.length - 1;
$('#nest').disabled ||= current.index === 0 || !canContain(current.siblings[current.index - 1], current.block);
$('#outdent').disabled ||= !current.parent;
$('#go-parent').disabled ||= !current.parent;
}
updateLibrary();
$('#presets').querySelectorAll('button').forEach(button => button.disabled = !ready || busy);
$('#properties').querySelectorAll('input,textarea,select,button').forEach(input => input.disabled = busy);
document.querySelectorAll('[data-panel],[data-viewport],#tree-search,#library-search,#expand-all,#collapse-all').forEach(input => input.disabled = !ready || busy);
document.querySelectorAll('[data-panel],[data-viewport],.sidebar-nav [role=tab],#tree-search,#library-search,#expand-all,#collapse-all').forEach(input => input.disabled = !ready || busy);
$('[data-panel="design"]').disabled ||= !current;
$('#select-page').disabled = !ready || busy;
$('#add-root-section').disabled = !ready || busy;
$('#open-media-library').disabled = !ready || busy;
$('#preview-motion').disabled = !ready || busy;
}
@@ -136,6 +165,14 @@ function renderTree() {
button.title = badge.textContent; button.append(badge);
button.setAttribute('aria-label', `${blockLabel(block)}: ${displayText} – ${badge.textContent}`);
}
if (block.id === selected) {
// In the tree a click only selects, so the tree stays open while moving through the
// page. Editing is one step further - this button, or a double click.
const edit = document.createElement('button'); edit.type = 'button'; edit.className = 'tree-edit';
edit.dataset.editBlock = block.id; edit.textContent = 'Bearbeiten';
edit.setAttribute('aria-label', `${blockLabel(block)} bearbeiten`);
item.append(edit);
}
if (block.children?.length && (!collapsed.has(block.id) || query)) item.append(build(block.children));
list.append(item);
}
@@ -153,15 +190,31 @@ function choose(id, scroll = true) {
blockPath(history.document.blocks, selected).slice(0, -1).forEach(block => collapsed.delete(block.id));
if (!selected) propertyPanel = 'content';
history.mergeKey = null;
syncView();
renderTree(); renderProperties(); controls(); highlight(scroll);
}
/**
* Selecting opens the element; dropping the selection goes back to the library. The tree is
* the exception: there the selection only moves the highlight, editing is one more step.
*/
function syncView() {
if (selected && view !== 'structure') setView('element');
else if (!selected && view === 'element') setView('elements');
}
function highlight(scroll = false) {
const doc = $('#preview').contentDocument;
if (!doc) return;
doc.querySelectorAll('.editor-selected').forEach(element => element.classList.remove('editor-selected'));
const element = selected ? doc.getElementById(selected) : null;
if (element) { element.classList.add('editor-selected'); if (scroll) element.scrollIntoView({ block: 'nearest' }); }
if (element) {
element.classList.add('editor-selected');
// Scroll the preview window only. scrollIntoView would also drag the editor document along
// with it, and the whole workspace would slide out from under the header.
const win = doc.defaultView, box = element.getBoundingClientRect();
if (scroll && win && (box.top < 0 || box.bottom > win.innerHeight)) win.scrollTo({ top: win.scrollY + box.top - 40 });
}
overlay?.sync();
}
@@ -169,15 +222,15 @@ function renderProperties() {
const block = locate(history.document.blocks, selected)?.block;
if (!block) propertyPanel = 'content';
const context = `${selected ?? 'page'}:${propertyPanel}`;
if (context !== renderedProperties) $('.right-panel').scrollTop = 0;
if (context !== renderedProperties) $('.sidebar-body').scrollTop = 0;
renderedProperties = context;
$('#properties-title').textContent = block ? blockLabel(block) : 'Seiteneinstellungen';
const panel = $('#properties'); panel.replaceChildren();
document.querySelectorAll('[data-panel]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.panel === propertyPanel)));
// The way up, as a trail above the name: page, then every container the element sits in.
$('#breadcrumbs').replaceChildren();
for (const item of [{ id: null, type: null }, ...blockPath(history.document.blocks, selected)]) {
const button = document.createElement('button'); button.className = 'text-button'; button.textContent = item.type ? blockLabel(item) : 'Seite';
button.setAttribute('aria-current', item.id === selected ? 'location' : 'false');
for (const item of [{ id: null, type: null }, ...blockPath(history.document.blocks, selected)].slice(0, -1)) {
const button = document.createElement('button'); button.type = 'button'; button.className = 'crumb'; button.textContent = item.type ? blockLabel(item) : 'Seite';
button.addEventListener('click', () => choose(item.id)); $('#breadcrumbs').append(button);
}
if (block && isPluginBlock(block)) {
@@ -188,21 +241,33 @@ function renderProperties() {
panel.append(note);
return;
}
if (block) {
const label = document.createElement('label'); label.htmlFor = 'block-visibility'; label.textContent = 'Sichtbarkeit';
const select = document.createElement('select'); select.id = 'block-visibility';
for (const [value, text] of Object.entries(VISIBILITY)) select.append(new Option(text, value));
select.value = block.layout?.visibility ?? 'all';
select.addEventListener('change', () => {
history.change(doc => setVisibility(doc, block.id, select.value));
renderTree(); controls(); schedulePreview();
});
const help = document.createElement('p'); help.className = 'field-help'; help.id = 'visibility-help';
help.textContent = 'Desktop ab 1025 px · Tablet 768–1024 px · Mobil bis 767 px. Ausgeblendete Elemente bleiben links in der Struktur auswählbar. Ein ausgeblendeter Elternbereich blendet auch seinen Inhalt aus.';
select.setAttribute('aria-describedby', help.id); panel.append(label, select, help);
}
if (block && propertyPanel === 'advanced') { renderAdvanced(block, panel); return; }
if (block && propertyPanel === 'advanced') { renderAdvanced(block, panel); renderVisibility(block, panel); return; }
if (block && propertyPanel === 'design') { renderDesign(block, panel); return; }
renderContent(block, panel);
if (block) renderVisibility(block, panel);
}
/** On which devices the element is shown. Part of the content, so it sits at its end. */
function renderVisibility(block, panel) {
const group = document.createElement('details'); group.className = 'design-group';
group.open = (block.layout?.visibility ?? 'all') !== 'all';
const summary = document.createElement('summary'); summary.textContent = 'Sichtbarkeit';
const body = document.createElement('div'); body.className = 'design-group-body';
const label = document.createElement('label'); label.htmlFor = 'block-visibility'; label.textContent = 'Anzeigen';
const select = document.createElement('select'); select.id = 'block-visibility';
for (const [value, text] of Object.entries(VISIBILITY)) select.append(new Option(text, value));
select.value = block.layout?.visibility ?? 'all';
select.addEventListener('change', () => {
history.change(doc => setVisibility(doc, block.id, select.value));
renderTree(); controls(); schedulePreview();
});
const help = document.createElement('p'); help.className = 'field-help'; help.id = 'visibility-help';
help.textContent = 'Desktop ab 1025 px · Tablet 768–1024 px · Mobil bis 767 px. Ausgeblendete Elemente bleiben in der Struktur auswählbar.';
select.setAttribute('aria-describedby', help.id);
body.append(label, select, help); group.append(summary, body); panel.append(group);
}
function renderContent(block, panel) {
let imagePreview;
const field = (label, key, value, options = {}) => {
const container = options.container || panel;
@@ -802,6 +867,16 @@ async function updatePreview() {
const block = locate(history.document.blocks, element.id)?.block;
if (block && INLINE_TEXT[block.type]) { event.preventDefault(); choose(element.id, false); startInlineEdit(element.id); }
});
// Right click: the element's actions where the pointer is, as in Flatsome.
doc.addEventListener('contextmenu', event => {
const element = event.target.closest('[id]');
if (!element || !locate(history.document.blocks, element.id) || busy || inlineEdit) return;
event.preventDefault();
choose(element.id, false);
openContextMenu(element.id, event.clientX, event.clientY);
});
doc.addEventListener('mousedown', event => { if (event.button === 0) closeContextMenu(); });
doc.addEventListener('keydown', onKey);
doc.addEventListener('submit', event => event.preventDefault());
// The head may arrive before the blocks. Decorate only once the complete DOM exists.
const finish = () => {
@@ -814,6 +889,7 @@ async function updatePreview() {
highlight(revealAfterPreview === selected); revealAfterPreview = null;
markInsertTarget();
frame.style.visibility = '';
showMotionStatus();
playPreview();
$('#preview-status').textContent = loaded
? 'Entwurf · Klicken wählt aus, Doppelklick bearbeitet Text, Elemente lassen sich hierher ziehen.'
@@ -853,6 +929,7 @@ async function updatePreview() {
function changed() {
if (!locate(history.document.blocks, selected)) selected = null;
if (selected && !$('#preview').contentDocument?.getElementById(selected)) revealAfterPreview = selected;
syncView();
renderTree(); renderProperties(); controls(); schedulePreview();
}
@@ -914,9 +991,9 @@ function addElement(type) {
if (busy || !history) return;
const at = pendingInsert;
setPendingInsert(null);
selected = history.change(doc => at
selected = history.change(doc => at && type !== 'section'
? insertBlockAt(doc, type, at.parentId, at.index) ?? insertBlock(doc, type, selected)
: insertBlock(doc, type, selected));
: insertBlock(doc, type, at?.parentId ?? selected));
if (type === 'accordion') selected = locate(history.document.blocks, selected)?.block.children?.[0]?.id ?? selected;
if (['accordion', 'accordionitem'].includes(type)) propertyPanel = 'content';
changed();
@@ -954,12 +1031,11 @@ function setPendingInsert(target) {
$('#insert-hint').hidden = !target;
markInsertTarget();
if (target) {
if ($('#toolbox').hidden) $('#toggle-library').click();
setView('elements');
$('#library-search').value = ''; filterLibrary();
const name = target.parentId ? $('#preview').contentDocument?.getElementById(target.parentId)?.dataset.editorLabel || blockLabel(locate(history.document.blocks, target.parentId)?.block) : 'Seite';
$('#insert-hint').firstChild.textContent = `Einfügen in ${name}. Wähle jetzt ein Element. `;
$('#library-search').focus({ preventScroll: true });
$('#library-search').scrollIntoView({ block: 'nearest' });
}
}
@@ -998,10 +1074,10 @@ function buildLibrary() {
button.type = 'button'; button.draggable = true;
button.dataset.add = type;
if (columns) button.dataset.row = String(columns);
const name = columns ? `${labels[type]}, ${columns} Spalten` : labels[type];
const name = columns ? `${columns} Spalten` : labels[type];
// What is searched for: the name, the internal type and the group it sits in. Someone
// looking for "slider" should not have to know it is filed under "Gruppen".
button.dataset.search = `${name} ${type} ${category.name}`.toLocaleLowerCase('de');
button.dataset.search = `${name} ${columns ? labels[type] + ' ' : ''}${type} ${category.name}`.toLocaleLowerCase('de');
const picture = document.createElement('span');
picture.className = 'library-preview';
// Drawn, not written: the shapes come from this editor and carry no untrusted text.
@@ -1027,9 +1103,10 @@ function updateLibrary() {
for (const button of $('#library').querySelectorAll('button')) {
const type = button.dataset.add;
if (!ready || busy) { button.disabled = true; button.removeAttribute('title'); continue; }
const target = pendingInsert
// A section always has a place - on the page, after the area the insert point sits in.
const target = pendingInsert && type !== 'section'
? (dropList(history.document, pendingInsert.parentId, { type }) ? pendingInsert : null)
: insertionTarget(history.document, selected, type);
: insertionTarget(history.document, pendingInsert?.parentId ?? selected, type);
button.disabled = !target;
if (!target) {
button.title = locate(history.document.blocks, selected)?.block.type === 'accordion'
@@ -1074,13 +1151,22 @@ $('#library').addEventListener('click', event => {
}
addElement(button.dataset.add);
});
$('#cancel-insert').addEventListener('click', () => setPendingInsert(null));
$('#add-root-section').addEventListener('click', () => {
$('#cancel-insert').addEventListener('click', () => { setPendingInsert(null); if (selected) setView('element'); });
// The tabs at the top of the sidebar. "Seite" also drops the selection: its settings are what
// the page shows when nothing is chosen.
for (const tab of document.querySelectorAll('.sidebar-nav [role=tab]')) tab.addEventListener('click', () => {
if (busy || !history) return;
stopInlineEdit();
setPendingInsert(null);
selected = history.change(doc => insertBlock(doc, 'section', selected));
propertyPanel = 'content'; changed();
if (tab.dataset.view === 'page') { setView('page'); choose(null); return; }
setView(tab.dataset.view);
});
$('#go-parent').addEventListener('click', () => actions.parent(selected));
$('#close-element').addEventListener('click', () => choose(null));
// The plus next to the name: into a container, otherwise behind the element.
$('#add-here').addEventListener('click', () => {
const item = locate(history.document.blocks, selected);
if (!item || busy) return;
if (isContainer(item.block) && item.block.type !== 'accordion') beginContainerInsert(item.block.id);
else setPendingInsert({ parentId: item.parent?.id ?? null, index: item.index + 1 });
});
$('#presets').addEventListener('click', event => {
const name = event.target.closest('[data-preset]')?.dataset.preset;
@@ -1090,15 +1176,15 @@ $('#presets').addEventListener('click', event => {
$('#structure').addEventListener('click', event => {
const toggle = event.target.closest('[data-toggle]')?.dataset.toggle;
if (toggle) { collapsed.has(toggle) ? collapsed.delete(toggle) : collapsed.add(toggle); renderTree(); $(`[data-toggle="${toggle}"]`)?.focus({ preventScroll: true }); return; }
const edit = event.target.closest('[data-edit-block]')?.dataset.editBlock;
if (edit) { setView('element'); choose(edit); return; }
const id = event.target.closest('[data-block-id]')?.dataset.blockId; if (id) choose(id);
});
$('#tree-search').addEventListener('input', renderTree);
$('#toggle-library').addEventListener('click', () => {
const hidden = !$('#toolbox').hidden; $('#toolbox').hidden = hidden;
$('#toggle-library').setAttribute('aria-expanded', String(!hidden));
$('#toggle-library').setAttribute('aria-label', `Werkzeugkasten ${hidden ? 'öffnen' : 'einklappen'}`);
$('#toggle-library').textContent = hidden ? '+' : '−';
$('#structure').addEventListener('dblclick', event => {
const id = event.target.closest('[data-block-id]')?.dataset.blockId;
if (id && !busy) { setView('element'); choose(id); }
});
$('#tree-search').addEventListener('input', renderTree);
$('#expand-all').addEventListener('click', () => { collapsed.clear(); renderTree(); });
$('#collapse-all').addEventListener('click', () => {
const visit = blocks => blocks.forEach(block => { if (block.children?.length) { collapsed.add(block.id); visit(block.children); } });
@@ -1149,6 +1235,53 @@ const actions = {
parent: id => choose(locate(history.document.blocks, id)?.parent?.id ?? null),
};
// ---------------------------------------------------------------------------------------------
// The context menu of the preview. Lives in the editor document, so it is drawn at full size
// above a scaled preview; the frame coordinates are converted once, here.
// ---------------------------------------------------------------------------------------------
function openContextMenu(id, frameX, frameY) {
const item = locate(history.document.blocks, id);
if (!item) return;
const menu = $('#context-menu');
const label = blockLabel(item.block);
const sibling = dropList(history.document, item.parent?.id ?? null, item.block);
const entries = [
{ text: `${label} bearbeiten`, run: () => { setView('element'); choose(id, false); } },
isContainer(item.block) && item.block.type !== 'accordion' ? { text: 'Element hinein', run: () => beginContainerInsert(id) } : null,
sibling ? { text: 'Element davor', run: () => setPendingInsert({ parentId: item.parent?.id ?? null, index: item.index }) } : null,
sibling ? { text: 'Element dahinter', run: () => setPendingInsert({ parentId: item.parent?.id ?? null, index: item.index + 1 }) } : null,
{ text: 'Duplizieren', run: () => actions.duplicate(id) },
item.index > 0 ? { text: 'Nach oben', run: () => actions.move(id, -1) } : null,
item.index < item.siblings.length - 1 ? { text: 'Nach unten', run: () => actions.move(id, 1) } : null,
item.parent ? { text: `Übergeordnet: ${blockLabel(item.parent)}`, run: () => actions.parent(id) } : null,
{ text: 'Löschen', danger: true, run: () => actions.delete(id) },
].filter(Boolean);
menu.replaceChildren(...entries.map(entry => {
const button = document.createElement('button'); button.type = 'button'; button.setAttribute('role', 'menuitem');
button.textContent = entry.text; if (entry.danger) button.className = 'danger-text';
button.addEventListener('click', () => { closeContextMenu(); entry.run(); });
return button;
}));
const frame = $('#preview').getBoundingClientRect();
menu.hidden = false;
const x = frame.left + frameX * previewScale, y = frame.top + frameY * previewScale;
menu.style.left = `${Math.min(x, window.innerWidth - menu.offsetWidth - 8)}px`;
menu.style.top = `${Math.min(y, window.innerHeight - menu.offsetHeight - 8)}px`;
menu.querySelector('button')?.focus({ preventScroll: true });
}
function closeContextMenu() { $('#context-menu').hidden = true; }
document.addEventListener('mousedown', event => { if (event.button === 0 && !event.target.closest('#context-menu')) closeContextMenu(); });
window.addEventListener('blur', closeContextMenu);
window.addEventListener('resize', closeContextMenu);
$('.canvas-scroll').addEventListener('scroll', closeContextMenu, { passive: true });
$('#context-menu').addEventListener('keydown', event => {
const items = [...event.currentTarget.querySelectorAll('button')];
const index = items.indexOf(document.activeElement);
if (event.key === 'ArrowDown') { event.preventDefault(); items[(index + 1) % items.length]?.focus(); }
if (event.key === 'ArrowUp') { event.preventDefault(); items[(index - 1 + items.length) % items.length]?.focus(); }
if (event.key === 'Escape') { event.stopPropagation(); closeContextMenu(); $('.canvas-scroll').focus({ preventScroll: true }); }
});
$('#duplicate').addEventListener('click', () => actions.duplicate(selected));
$('#delete').addEventListener('click', () => actions.delete(selected));
for (const [id, direction] of [['move-up', -1], ['move-down', 1]]) $(`#${id}`).addEventListener('click', () => actions.move(selected, direction));
@@ -1208,7 +1341,6 @@ $('#library').addEventListener('dragstart', event => {
});
$('#library').addEventListener('dragend', () => overlay.endDrag());
$('#select-page').addEventListener('click', () => choose(null));
$('#undo').addEventListener('click', () => { history.undo(); changed(); });
$('#redo').addEventListener('click', () => { history.redo(); changed(); });
$('#save').addEventListener('click', () => save());
@@ -1259,66 +1391,37 @@ function setViewport(name) {
}
document.querySelectorAll('[data-viewport]').forEach(button => button.addEventListener('click', () => setViewport(button.dataset.viewport)));
new ResizeObserver(resizePreview).observe($('.canvas-scroll'));
// Panel sizes are workspace preferences, independent of document history and publication.
const panelSizes = { left: 280, right: 320 };
try {
const saved = JSON.parse(localStorage.getItem('kantsites.panel-widths'));
for (const side of ['left', 'right']) if (Number.isFinite(saved?.[side])) panelSizes[side] = saved[side];
} catch { /* Storage can be unavailable; resizing still works for this session. */ }
const panelMinimum = { left: 240, right: 280 };
function layoutPanels() {
let left = Math.max(240, Math.min(560, panelSizes.left));
let right = Math.max(280, Math.min(560, panelSizes.right));
const budget = Math.max(520, $('.editor-layout').clientWidth - 292);
const excess = Math.max(0, left + right - budget);
const spare = left + right - 520;
if (excess && spare) { left -= excess * (left - 240) / spare; right -= excess * (right - 280) / spare; }
for (const [side, size] of Object.entries({ left, right })) {
root.style.setProperty(`--panel-${side}`, `${size}px`);
const handle = $(`[data-resize="${side}"]`);
handle.setAttribute('aria-valuenow', String(Math.round(size)));
handle.setAttribute('aria-valuemax', String(Math.floor(Math.min(560, budget - (side === 'left' ? right : left)))));
handle.setAttribute('aria-valuetext', `${Math.round(size)} Pixel`);
/** Whether a key press belongs to a field rather than to the page. */
const inField = target => ['INPUT', 'TEXTAREA', 'SELECT'].includes(target?.tagName) || target?.isContentEditable;
// One handler for the editor window and for the preview document: a key pressed while the
// preview has the focus - after a click into it - must mean the same thing.
function onKey(event) {
if (!history || busy) return;
const key = event.key.toLowerCase();
if (event.ctrlKey || event.metaKey) {
if (key === 's') { event.preventDefault(); save(); }
// Keep native text-field undo intact; the toolbar always undoes the complete document.
if (inField(event.target)) return;
if (key === 'z' || key === 'y') { event.preventDefault(); (event.shiftKey || key === 'y') ? history.redo() : history.undo(); changed(); }
return;
}
if (event.key === 'Escape') {
if (!$('#context-menu').hidden) { closeContextMenu(); return; }
if (document.querySelector('dialog[open]') || inlineEdit) return;
if (pendingInsert) { setPendingInsert(null); if (selected) setView('element'); return; }
if (selected) { choose(null); $('.canvas-scroll').focus({ preventScroll: true }); }
return;
}
// Delete removes the selected element - but never while a field or the preview text is
// being typed in, and never something the sidebar buttons would refuse.
if ((event.key === 'Delete' || event.key === 'Backspace') && selected && !inField(event.target) && !inlineEdit && !$('#delete').disabled) {
event.preventDefault(); actions.delete(selected);
}
}
const persistPanels = () => { try { localStorage.setItem('kantsites.panel-widths', JSON.stringify(panelSizes)); } catch {} };
for (const handle of document.querySelectorAll('[data-resize]')) {
const side = handle.dataset.resize, direction = side === 'left' ? 1 : -1;
let drag = null;
const setSize = value => {
panelSizes[side] = Math.max(panelMinimum[side], Math.min(Number(handle.getAttribute('aria-valuemax')), value));
layoutPanels();
};
handle.addEventListener('pointerdown', event => {
if (event.button !== 0) return;
event.preventDefault(); handle.focus();
drag = { x: event.clientX, size: Number(handle.getAttribute('aria-valuenow')) };
handle.setPointerCapture(event.pointerId); root.classList.add('resizing-panels');
});
handle.addEventListener('pointermove', event => { if (drag) setSize(drag.size + direction * (event.clientX - drag.x)); });
const stop = () => { drag = null; root.classList.remove('resizing-panels'); persistPanels(); };
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
handle.addEventListener('lostpointercapture', stop);
handle.addEventListener('dblclick', () => { panelSizes[side] = side === 'left' ? 280 : 320; layoutPanels(); persistPanels(); });
handle.addEventListener('keydown', event => {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
event.preventDefault();
const current = Number(handle.getAttribute('aria-valuenow'));
setSize(event.key === 'Home' ? panelMinimum[side] : event.key === 'End' ? 560 : current + (event.key === 'ArrowRight' ? 1 : -1) * direction * (event.shiftKey ? 40 : 10));
persistPanels();
});
}
new ResizeObserver(layoutPanels).observe($('.editor-layout'));
layoutPanels();
window.addEventListener('keydown', event => {
if (!history || busy || !(event.ctrlKey || event.metaKey)) return;
const key = event.key.toLowerCase();
if (key === 's') { event.preventDefault(); save(); }
// Keep native text-field undo intact; the toolbar always undoes the complete document.
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(event.target.tagName)) return;
if (key === 'z' || key === 'y') { event.preventDefault(); (event.shiftKey || key === 'y') ? history.redo() : history.undo(); changed(); }
});
window.addEventListener('keydown', onKey);
window.addEventListener('beforeunload', event => { if (history?.dirty || busy) { event.preventDefault(); event.returnValue = ''; } });
buildLibrary();
// The workspace is a fixed frame; a scroll position restored from an earlier visit would push
// the header out of view.
window.scrollTo(0, 0);
load();