Drag the border between two columns to set their widths in 1.16.0

Umut, with a card of an icon next to a text as the example: "bei Rows die
Breite ändern, am besten per Drag and Drop im Editor". Rows only ever had
equal columns - both the classic `columns` token and the free `gridColumns`
produce `repeat(n, 1fr)`.

A row now carries the free style `columnWidths`, a list of shares such as
`2 1` or `66.7 33.3`, per device and without a new document schema.
`StyleCompiler::columnTracks()` turns it into `grid-template-columns`,
pads or cuts the shares to the number of columns, and gives a device whose
layout stacks the columns a single track, because the desktop rule carries
an id and would otherwise outrank the class that stacks a phone.

In the editor the border between two side-by-side columns of the selected
row is a handle: dragging restyles the row inline while the pointer moves
and writes one undo step on release; the arrow keys nudge by five points.
The design panel shows the same value as the text field "Spaltenbreiten".
The Playwright editor check drags the handle with the real mouse.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
kantarciandClaude Fable 5.1 committed 2026-09-15 10:39:06 +02:00
1 parent f6350de636
commit 067eb184e5
14 files changed
+346 -3

No files matched your search

+4
View File
@@ -4,6 +4,10 @@ Lokaler CMS-Prototyp für PHP-Webhosting mit erstem visuellen Editor. Symfony 7.
Die übernommenen Originaldokumente sind `AGENTS.md` und `ENTWICKLUNGSPLAN.md`. Den tatsächlichen Stand enthält `docs/STATUS.md`, Entscheidungen und Datenmodell stehen in `docs/ARCHITECTURE.md`.
## Spaltenbreiten einer Zeile durch Ziehen (ab 1.16.0)
Wähle eine Zeile oder eine ihrer Spalten: auf jeder Grenze zwischen zwei Spalten liegt ein Griff. Ziehen macht die eine Spalte breiter und die andere schmaler, Loslassen ist ein Schritt für „Rückgängig“; die Pfeiltasten verschieben um fünf Prozentpunkte. Der Wert steht auch im Design-Bedienfeld der Zeile unter **Layout → Spaltenbreiten**, etwa `2 1` oder `25 50 25`, und gilt je Gerät. Wo die Spalten gestapelt sind, etwa auf dem Handy, gibt es keinen Griff und die Spalten bleiben untereinander.
## Eigene Absenderadresse je Formular (ab 1.15.1)
Unter **Formulare → Zustellung** gibt es neben dem Empfänger ein Feld **Absender**. Bisher ging jede Nachricht von der Empfängeradresse an sich selbst; das scheitert, sobald der Empfänger ein Postfach bei einem anderen Anbieter ist, weil viele Hoster nur zustellen, was von einer Adresse der eigenen Domain kommt. Leer heißt weiterhin: Absender ist der Empfänger. Die Antwortadresse aus dem Formularfeld bleibt davon unberührt.
+1 -1
View File
@@ -1 +1 @@
1.15.1
1.16.0
+12
View File
@@ -2,6 +2,18 @@
Stand: 15.09.2026. Arbeitstitel KantSites; Produktname offen.
## ADR 098 – Spaltenbreiten einer Zeile durch Ziehen (15.09.2026)
**Anlass:** Umut: „bei Rows die Breite ändern – am besten per Drag and Drop im Editor.“ Bis dahin gab es nur gleich breite Spalten: die klassische Vorgabe `columns` (one/two/three/four) und die freie Eigenschaft `gridColumns` erzeugten beide `repeat(n, minmax(0, 1fr))`. Ein Symbol neben einem Text – die Karte aus seinem Beispiel – brauchte eine schmale und eine breite Spalte.
**Entscheidung:** Eine neue freie Stileigenschaft `columnWidths` am **Zeilenblock**, Typ `fractions`: bis zu zwölf Zahlen mit Leerzeichen, `2 1` oder `66.7 33.3`, je Gerät wie jede andere freie Eigenschaft (`StyleSchema::FRACTIONS`, Prüfung in `StyleCompiler::scalar()`, null ist ausgeschlossen). Die Anteile liegen an der Zeile und nicht an den Spalten, weil eine Grenze immer zwei Spalten zugleich verändert und die Reihenfolge der Kinder die Zuordnung ist. Kein neues Dokumentschema: die Eigenschaft fällt unter die freien Stile ab v10.
**CSS.** `StyleCompiler::columnTracks()` schreibt je Gerät `#id{grid-template-columns:minmax(0,2fr) minmax(0,1fr)}`. Zwei Feinheiten: Fehlende Anteile (eine später eingefügte Spalte) bekommen den Durchschnitt, überzählige fallen weg, also passt die Regel immer zur Kinderzahl. Und die Desktop-Regel trägt eine ID und würde die Klasse `.d-mobile-columns-one` schlagen, mit der ein Handy die Spalten stapelt – deshalb bekommt ein Gerät, dessen wirksame Aufteilung `one` (klassisch) oder `gridColumns` 1 ist, unter seiner Medienabfrage `minmax(0,1fr)`. Die Abfragen sind die des Stilcompilers (1024/767 px), nicht die 650 px der klassischen Klassen; zwischen 651 und 767 px stapelt eine Zeile mit Anteilen also, wo sie ohne Anteile noch zwei Spalten hätte. Das ist gewollt: Querformat-Handys sind Handys.
**Editor.** `canvas-overlay.js` zeichnet für die gewählte Zeile – oder die Zeile um die gewählte Spalte – einen Griff auf jede Grenze zwischen zwei nebeneinander liegenden Spalten (`.ov-resize`, ein Knopf mit Beschriftung „Breite zwischen Spalte 1 und 2 ändern“). Ausgangswert ist die **gemessene** Breite der Spalten, nicht der gespeicherte Wert, damit der Griff auch bei geerbten oder klassischen Aufteilungen dort anfängt, wo die Spalten wirklich stehen. Während des Ziehens wird die Zeile im Vorschaudokument inline umgestellt (`grid-template-columns`), erst beim Loslassen entsteht **ein** Verlaufsschritt (`onResize` → `setStyle(row, device, 'columnWidths')`); die Vorschau lädt danach vom Server neu. Pfeiltasten verschieben um fünf Punkte und behalten den Fokus auf dem Griff über die Neuzeichnung hinweg. Kein Griff, wo die Spalten gestapelt sind, und keiner während ein Element gezogen wird. Im Design-Bedienfeld steht derselbe Wert als Textfeld „Spaltenbreiten“ (Layout, nur bei Zeilen), für alle, die lieber Zahlen tippen.
**Verworfen:** Anteile je Spalte (`span` aus zwölf) wie in Flatsome – zwei Werte je Grenze zu pflegen und eine Summe, die 12 ergeben muss, sind für ein Drag-Ergebnis unnötig streng; Anteile summieren sich beliebig. Eine eigene Klasse je Verhältnis (`1-3`, `2-3`) – deckt genau die Fälle ab, die jemand vorhergesehen hat, und das Ziehen erzeugt jeden anderen.
## ADR 097 – Der Einwilligungshinweis bekommt ein Gesicht, und der Nach-oben-Knopf weicht ihm aus (15.09.2026)
**Anlass.** Umut gefiel das Banner nicht: nicht gestaltbar, ein kantiger Kasten in Papierfarbe. Und der Nach-oben-Knopf „funktionierte auf dem Handy nicht“ – er war ausgeblendet, solange die Frage offen stand, und auf dem Telefon bleibt sie das oft.
+10
View File
@@ -1,5 +1,15 @@
# Projektstatus
## 1.16.0 – Spaltenbreiten einer Zeile durch Ziehen (15.09.2026)
**Anlass:** Umut, mit der Karte „HausKlar“ (Symbol links, Text rechts) als Beispiel: „bei Rows die Breite ändern, am besten per Drag and Drop im Editor.“ Zeilen kannten bisher nur gleich breite Spalten. Entscheidung und Begründung: ADR 098.
**Umsetzung:** Neue freie Stileigenschaft `columnWidths` an der Zeile (Typ `fractions`, `StyleSchema::FRACTIONS`, z. B. `66.7 33.3`), je Gerät, ohne neues Dokumentschema. `StyleCompiler::columnTracks()` macht daraus `grid-template-columns:minmax(0,66.7fr) minmax(0,33.3fr)`, füllt fehlende Anteile mit dem Durchschnitt auf, kappt überzählige und setzt ein Gerät, dessen Aufteilung stapelt (`one` oder `gridColumns` 1), auf eine Spur – sonst schlüge die ID-Regel des Desktops die Stapel-Klasse des Handys. Im Editor (`canvas-overlay.js`) liegt auf jeder Grenze zwischen zwei nebeneinander stehenden Spalten der gewählten Zeile (oder der Zeile um die gewählte Spalte) ein Griff `.ov-resize`: Ziehen stellt die Zeile in der Vorschau live um, Loslassen schreibt einen Verlaufsschritt (`onResize` in `editor.js` → `setStyle`), Pfeiltasten verschieben um fünf Punkte und behalten den Fokus. Ausgangswert sind die gemessenen Spaltenbreiten. Im Design-Bedienfeld gibt es dazu das Textfeld „Spaltenbreiten“ (Layout, nur bei Zeilen). Kein Griff bei gestapelten Spalten und während ein Element gezogen wird.
**Geprüft:** `phpunit` vollständig mit PHP 8.4 512 von 512 grün, mit PHP 8.2 512 grün mit der vorbestehenden Warnung in `UpdaterTest`; neu `tests/ColumnWidthsTest.php` (Spuren, Stapeln je Gerät, Auffüllen und Kappen, Ablehnung ungültiger Werte). `npm test` 33 grün (Relevanz nur für Zeilen). `npm run test:editor` mit `PHP_BINARY=C:/php84/php.exe` vollständig bestanden – neu darin: echter Mauszug am Griff verbreitert die erste Spalte, der Wert steht im Bedienfeld der Zeile, auf „Mobil“ gibt es keinen Griff, ein Rückgängig stellt gleiche Spalten her (`reports/editor/column-widths.png`). php-cs-fixer ohne Befund. Ein erster Lauf des Checks scheiterte an `openGroup`, das im Skript erst später definiert ist – die Gruppe wird jetzt an Ort und Stelle geöffnet.
**Nebenbei:** `.claude/launch.json` trägt in der Arbeitskopie den noch nicht committeten Eintrag `maler-drews` einer anderen Sitzung auf Port 8091; die Pilotkonfiguration ist deshalb lokal auf 8092 verschoben, die Datei bleibt aus diesem Commit heraus.
## 1.15.1 veröffentlicht (15.09.2026)
Tag `v1.15.1` (Commit `d05dba3`), Release: https://git.kant-it.de/kantarci/KantSites/releases/tag/v1.15.1 – eigene Absenderadresse je Formular.
+120 -1
View File
@@ -35,7 +35,7 @@ const TOOLS = [
{ action: 'delete', glyph: '✕', title: label => `${label} löschen`, danger: true },
];
export function createCanvasOverlay({ stage, frame, getScale, getDocument, getSelected, onSelect, onAction, onInsert, onDrop }) {
export function createCanvasOverlay({ stage, frame, getScale, getDocument, getSelected, onSelect, onAction, onInsert, onDrop, onResize = () => {} }) {
const layer = document.createElement('div');
layer.className = 'canvas-overlay';
const hover = element('div', 'ov-box ov-hover');
@@ -205,6 +205,7 @@ export function createCanvasOverlay({ stage, frame, getScale, getDocument, getSe
// The toolbar is placed last because it has to keep clear of the upper plus sign, and only
// now is it settled whether there is one.
positionToolbar(selectedBox, Boolean(sibling));
placeResizers();
const hoverBox = hovered && hovered !== selectedId ? rectOf(hovered) : null;
if (place(hover, hoverBox)) paintLabel(hoverLabel, hovered);
if (dragging) {
@@ -213,6 +214,124 @@ export function createCanvasOverlay({ stage, frame, getScale, getDocument, getSe
}
}
// -------------------------------------------------------------------------------------------
// Column widths. Umut: "am besten per Drag and Drop im Editor".
//
// The border between two columns of the selected row is a handle. Dragging it moves share from
// one neighbour to the other; the row is restyled inline while the pointer moves, and the
// result is written to the document once, when the pointer is released. The arrow keys do the
// same in steps of five, so the widths are reachable without a mouse.
// -------------------------------------------------------------------------------------------
const resizers = [];
let focusResizer = null;
/** The row whose borders can be dragged: the selected row, or the row around the selected column. */
function resizableRow() {
const item = getSelected() ? locate(getDocument().blocks, getSelected()) : null;
if (!item) return null;
if (item.block.type === 'row') return item.block;
return item.parent?.type === 'row' ? item.parent : null;
}
/** The measured widths of the columns as shares of their sum - the truth a drag starts from. */
function sharesOf(rowId) {
const kids = childElements(rowId);
const total = kids.reduce((sum, kid) => sum + kid.box.width, 0);
return total > 0 ? kids.map(kid => kid.box.width / total * 100) : null;
}
/** Moves `delta` points of share from the right neighbour to the left one; neither may vanish. */
function shift(shares, index, delta) {
const pair = shares[index] + shares[index + 1];
const least = Math.min(10, pair / 2);
const left = Math.max(least, Math.min(pair - least, shares[index] + delta));
const next = shares.slice();
next[index] = left;
next[index + 1] = pair - left;
return next;
}
const tenth = share => Math.round(share * 10) / 10;
const formatShares = shares => shares.map(share => String(tenth(share))).join(' ');
const tracksOf = shares => shares.map(share => `minmax(0,${tenth(share)}fr)`).join(' ');
function placeResizers() {
const row = dragging ? null : resizableRow();
const kids = row ? childElements(row.id) : [];
// Stacked columns - a phone, or a single-column layout - have no border to drag.
const sideBySide = kids.length > 1 && kids.every((kid, index) => index === 0 || kid.box.left >= kids[index - 1].box.right - 1);
const wanted = sideBySide ? kids.length - 1 : 0;
while (resizers.length > wanted) resizers.pop().remove();
while (resizers.length < wanted) resizers.push(resizeButton());
const width = 14 / getScale();
resizers.forEach((button, index) => {
const left = kids[index].box, right = kids[index + 1].box;
button.dataset.row = row.id;
button.dataset.index = String(index);
const label = `Breite zwischen Spalte ${index + 1} und ${index + 2} ändern`;
button.setAttribute('aria-label', label);
button.title = `${label}: ziehen oder Pfeiltasten`;
button.style.left = `${(left.right + right.left) / 2 - width / 2}px`;
button.style.top = `${Math.min(left.top, right.top)}px`;
button.style.width = `${width}px`;
button.style.height = `${Math.max(left.bottom, right.bottom) - Math.min(left.top, right.top)}px`;
if (focusResizer && focusResizer.row === row.id && focusResizer.index === index) { button.focus(); focusResizer = null; }
});
}
function resizeButton() {
const button = document.createElement('button');
button.type = 'button';
button.className = 'ov-resize';
button.addEventListener('pointerdown', startResize);
button.addEventListener('keydown', event => {
const step = event.key === 'ArrowLeft' ? -5 : event.key === 'ArrowRight' ? 5 : 0;
if (!step) return;
event.preventDefault();
const rowId = button.dataset.row, index = Number(button.dataset.index);
const shares = sharesOf(rowId);
if (!shares) return;
focusResizer = { row: rowId, index };
onResize(rowId, formatShares(shift(shares, index, step)));
});
layer.append(button);
return button;
}
function startResize(event) {
if (event.button !== 0) return;
const button = event.currentTarget;
const rowId = button.dataset.row, index = Number(button.dataset.index);
const start = sharesOf(rowId);
const node = doc()?.getElementById(rowId);
if (!start || !node) return;
event.preventDefault();
button.setPointerCapture(event.pointerId);
layer.classList.add('is-resizing');
// Pointer pixels are editor pixels; the shares live in the frame's scale, on the summed
// width of the columns without the gaps between them.
const content = childElements(rowId).reduce((sum, kid) => sum + kid.box.width, 0);
const startX = event.clientX;
let current = start;
const move = moved => {
current = shift(start, index, (moved.clientX - startX) / getScale() / content * 100);
node.style.gridTemplateColumns = tracksOf(current);
sync();
};
const finish = () => {
button.removeEventListener('pointermove', move);
button.removeEventListener('pointerup', finish);
button.removeEventListener('pointercancel', finish);
layer.classList.remove('is-resizing');
if (formatShares(current) !== formatShares(start)) onResize(rowId, formatShares(current));
else sync();
};
button.addEventListener('pointermove', move);
button.addEventListener('pointerup', finish);
button.addEventListener('pointercancel', finish);
}
// -------------------------------------------------------------------------------------------
// Dropping.
// -------------------------------------------------------------------------------------------
+18
View File
@@ -248,6 +248,23 @@ export function createDesignPanel({ schema, onChange, onSavePreset, getBlock, ge
return wrap;
};
/**
* The column shares of a row, "2 1" for two thirds and a third. Dragging the border between two
* columns in the preview writes the same value; the field is for anyone who prefers numbers.
*/
const fractionsControl = (id, value, apply) => {
const input = document.createElement('input');
input.type = 'text';
input.id = id;
input.value = value ?? '';
input.placeholder = 'gleich breit';
input.pattern = String.raw`\d{1,3}(\.\d)?( \d{1,3}(\.\d)?){0,11}`;
input.setAttribute('inputmode', 'decimal');
input.title = 'Anteile je Spalte, durch Leerzeichen getrennt: 2 1 oder 25 50 25';
input.addEventListener('change', () => { if (input.checkValidity()) apply(input.value.trim()); });
return input;
};
const numberControl = (id, value, property, apply) => {
const wrap = element('div', 'number-control');
const slider = document.createElement('input');
@@ -531,6 +548,7 @@ export function createDesignPanel({ schema, onChange, onSavePreset, getBlock, ge
else if (property.type === 'choice') control = choiceControl(id, own ? current.value : '', property, apply, inheritedText);
else if (property.type === 'font') control = fontControl(id, own ? current.value : '', apply, inheritedText);
else if (property.type === 'media') control = mediaControl(key, current.value || '', apply);
else if (property.type === 'fractions') control = fractionsControl(id, own ? current.value : '', apply);
else continue;
body.append(row(id, property.label, control, { own, inherited: inheritedText, onReset, chips: deviceChips(block, key, property.label, false) }));
+1
View File
@@ -574,6 +574,7 @@ export function relevantProperty(block, key, property) {
if (property.group === 'menu') return block.type === 'menu';
if (property.group === 'image') return ['image', 'gallery', 'logos', 'postlist'].includes(block.type);
if (property.group === 'text' || key === 'textShadow') return !['image', 'gallery', 'logos', 'spacer', 'divider', 'embed'].includes(block.type);
if (key === 'columnWidths') return block.type === 'row';
if (['flexDirection', 'flexWrap', 'justifyContent', 'alignItems', 'gridColumns', 'gap', 'rowGap', 'columnGap'].includes(key)) return container || ['button', 'menu', 'form', 'postlist', 'contact', 'social'].includes(block.type);
return true;
}
+7 -1
View File
@@ -291,8 +291,14 @@ html:has(>.editor-body){overflow:hidden;height:100%}
.ov-drop{position:absolute;background:var(--ring,#b55b12);border-radius:2px;box-shadow:0 0 0 1px #fff8;pointer-events:none}
.ov-drop-inside{background:color-mix(in srgb, var(--ring,#b55b12) 15%, transparent);border:2px dashed var(--ring,#b55b12);box-shadow:none}
.ov-drop-label{position:absolute;pointer-events:none;background:#2c634a;color:#fff;border-radius:5px;padding:6px 9px;font:600 12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 7px #0002}
/* The border between two columns of the selected row: a grab area with a short bar in it. */
.ov-resize{position:absolute;display:grid;place-items:center;padding:0;min-height:0;border:0;background:transparent;cursor:col-resize;pointer-events:auto;touch-action:none}
.ov-resize::before{content:"";width:4px;height:40px;max-height:60%;border-radius:2px;background:var(--ring,#b55b12);box-shadow:0 0 0 1px #fff8;opacity:.55;transition:opacity .12s}
.ov-resize:hover::before,.ov-resize:focus-visible::before,.canvas-overlay.is-resizing .ov-resize::before{opacity:1}
.ov-resize:focus-visible{outline:2px solid var(--ring,#b55b12);outline-offset:-2px}
.canvas-overlay.is-resizing .ov-hover,.canvas-overlay.is-resizing .ov-toolbar,.canvas-overlay.is-resizing .ov-insert{display:none}
/* While something is being dragged the outlines would only add noise. */
.canvas-overlay.is-dragging .ov-hover,.canvas-overlay.is-dragging .ov-toolbar,.canvas-overlay.is-dragging .ov-insert{display:none}
.canvas-overlay.is-dragging .ov-hover,.canvas-overlay.is-dragging .ov-toolbar,.canvas-overlay.is-dragging .ov-insert,.canvas-overlay.is-dragging .ov-resize{display:none}
@media(prefers-reduced-motion:reduce){.ov-insert{transition:none;opacity:1}}
/* ---- narrow screens ---------------------------------------------------------------------- */
+7
View File
@@ -1347,6 +1347,13 @@ overlay = createCanvasOverlay({
if (!item) return;
setPendingInsert({ parentId: item.parent?.id ?? null, index: item.index + (where === 'after' ? 1 : 0) });
},
// The border between two columns was dragged (or nudged with the arrow keys): the shares of
// the whole row for the current device, one undo step per drag.
onResize: (rowId, value) => {
if (busy || !history) return;
history.change(doc => setStyle(doc, rowId, device, 'columnWidths', value));
changed();
},
onDrop: (payload, plan) => {
if (busy || !history) return;
if (payload.kind === 'add') {
+33
View File
@@ -253,6 +253,39 @@ try {
assert.equal(await frame.locator(`#${newSectionId} .block-column`).first().getAttribute('id'), firstColumnId);
}
await page.getByRole('button', { name: 'Desktop', exact: true }).click();
// Umut: "bei Rows die Breite ändern, am besten per Drag and Drop im Editor". The border
// between the two columns is a handle; dragging it to the right widens the first column.
await treeSelect(firstColumnId);
await frame.locator(`#${firstColumnId}`).scrollIntoViewIfNeeded();
const resizeHandle = page.locator('.ov-resize');
await resizeHandle.waitFor();
assert.equal(await resizeHandle.count(), 1, 'two columns have one border to drag');
const columnTracks = () => frame.locator(`#${newSectionId} .block-row`).first().evaluate(el => getComputedStyle(el).gridTemplateColumns.split(' ').map(Number.parseFloat));
const evenTracks = await columnTracks();
assert.ok(Math.abs(evenTracks[0] - evenTracks[1]) < 2, `columns start out equal: ${evenTracks}`);
const handleBox = await resizeHandle.boundingBox();
await page.mouse.move(handleBox.x + handleBox.width / 2, handleBox.y + handleBox.height / 2);
await page.mouse.down();
await page.mouse.move(handleBox.x + handleBox.width / 2 + 120, handleBox.y + handleBox.height / 2, { steps: 8 });
await page.mouse.up();
await previewReady();
const widenedTracks = await columnTracks();
assert.ok(widenedTracks[0] > widenedTracks[1] * 1.3, `dragging the border widened the first column: ${widenedTracks}`);
await page.screenshot({ path: 'reports/editor/column-widths.png', fullPage: true });
// The same value is visible as numbers in the design panel of the row.
await treeSelect(await frame.locator(`#${newSectionId} .block-row`).first().getAttribute('id'));
await page.getByRole('button', { name: 'Design', exact: true }).click();
const layoutGroup = page.locator('.design-group').filter({ has: page.locator('summary', { hasText: 'Layout' }) }).first();
if (!(await layoutGroup.evaluate(element => element.open))) await layoutGroup.locator('summary').click();
assert.match(await page.locator('#style-columnWidths').inputValue(), /^\d+(\.\d)? \d+(\.\d)?$/, 'shares are stored per column');
// On a phone the columns stack, so there is no border to drag - and one undo restores equal columns.
await page.getByRole('button', { name: 'Mobil', exact: true }).click();
await treeSelect(firstColumnId);
await page.waitForFunction(() => document.querySelectorAll('.ov-resize').length === 0);
await page.getByRole('button', { name: 'Desktop', exact: true }).click();
await page.locator('#undo').click(); await previewReady();
const restoredTracks = await columnTracks();
assert.ok(Math.abs(restoredTracks[0] - restoredTracks[1]) < 2, `undo restores equal columns: ${restoredTracks}`);
const savedEmptyDraft = await page.evaluate(async () => (await (await fetch(document.querySelector('#editor').dataset.api)).json()).document);
assert.equal(JSON.stringify(savedEmptyDraft).includes('editor-empty'), false, 'editing aids never enter content');
const publicBefore = await (await fetch(origin)).text();
+57
View File
@@ -92,6 +92,11 @@ final class StyleCompiler
sprintf('"%s" is outside its range.', $key),
),
'font' => $this->require(1 === preg_match('/^[a-z][a-z0-9-]{0,39}$/D', $text), sprintf('"%s" is not a font key.', $key)),
// A share of nothing is a column that cannot be seen, so zero is refused with the rest.
'fractions' => $this->require(
1 === preg_match(StyleSchema::FRACTIONS, $text) && !in_array(0.0, array_map(floatval(...), explode(' ', $text)), true),
sprintf('"%s" is not a list of column shares.', $key),
),
'media' => $this->require('none' === $text || 1 === preg_match('/^[a-f0-9]{32}$/D', $text), sprintf('"%s" is not a media ID.', $key)),
default => $this->require(false, 'Unknown style type.'),
};
@@ -112,6 +117,9 @@ final class StyleCompiler
if ('image' === ($block['type'] ?? null)) {
$css .= $this->imageAlignment((string) $block['id'], $block['style'], $parent);
}
if ('row' === ($block['type'] ?? null)) {
$css .= $this->columnTracks((string) $block['id'], $block['style'], is_array($block['layout'] ?? null) ? $block['layout'] : [], count($block['children'] ?? []));
}
}
$walk($block['children'] ?? [], $block);
}
@@ -461,6 +469,55 @@ final class StyleCompiler
return $chosen;
}
/**
* The column shares of a row: "2 1" becomes two tracks of 2fr and 1fr. Shares inherit from the
* wider device like every other style. A device whose layout stacks the columns - "one" from
* the classic tokens or a single grid column - gets one track instead: the desktop rule carries
* an id and would otherwise outrank the class that stacks the columns on a phone.
*/
private function columnTracks(string $id, array $style, array $layout, int $count): string
{
$css = $previous = '';
$widths = null;
$stacked = false;
foreach (['desktop', 'tablet', 'mobile'] as $device) {
$values = is_array($style[$device] ?? null) ? $style[$device] : [];
$widths = $values['columnWidths'] ?? $widths;
if (isset($values['gridColumns'])) {
$stacked = 1 === (int) $values['gridColumns'];
} elseif (isset($layout['design'][$device]['columns'])) {
$stacked = 'one' === $layout['design'][$device]['columns'];
}
if (null === $widths || $count < 2) {
continue;
}
$rule = sprintf('#%s{grid-template-columns:%s}', $id, $stacked ? 'minmax(0,1fr)' : $this->tracks((string) $widths, $count));
if ($rule === $previous) {
continue;
}
$css .= isset(self::BREAKPOINTS[$device])
? sprintf('@media (max-width:%dpx){%s}', self::BREAKPOINTS[$device], $rule)
: $rule;
$previous = $rule;
}
return $css;
}
/** One track per column: a column added later gets the average share, surplus shares are dropped. */
private function tracks(string $widths, int $count): string
{
$shares = array_values(array_filter(array_map(floatval(...), explode(' ', $widths)), static fn (float $share): bool => $share > 0));
$shares = array_slice($shares, 0, $count);
$average = [] === $shares ? 1.0 : array_sum($shares) / count($shares);
while (count($shares) < $count) {
$shares[] = $average;
}
$format = static fn (float $share): string => rtrim(rtrim(number_format($share, 1, '.', ''), '0'), '.');
return implode(' ', array_map(static fn (float $share): string => sprintf('minmax(0,%sfr)', $format($share)), $shares));
}
private function grid(array $values): string
{
return isset($values['gridColumns'])
+5
View File
@@ -27,6 +27,8 @@ final class StyleSchema
*/
public const LENGTH = '/^(0|-?\d{1,5}(\.\d{1,3})?(px|rem|em|%|vw|vh|ch|dvh|svh|lvh|dvw))$/D';
public const LENGTH_AUTO = '/^(auto|none|0|-?\d{1,5}(\.\d{1,3})?(px|rem|em|%|vw|vh|ch|dvh|svh|lvh|dvw))$/D';
/** Column shares of a row, up to twelve numbers separated by blanks: "2 1" or "66.7 33.3". */
public const FRACTIONS = '/^\d{1,3}(\.\d)?( \d{1,3}(\.\d)?){0,11}$/D';
/**
* group – where the property appears in the editor
@@ -152,6 +154,9 @@ final class StyleSchema
'stretch' => 'Dehnen', 'flex-start' => 'Anfang', 'center' => 'Mitte', 'flex-end' => 'Ende', 'baseline' => 'Grundlinie',
]],
'gridColumns' => ['group' => 'layout', 'type' => 'number', 'css' => null, 'label' => 'Spalten', 'min' => 1, 'max' => 12, 'step' => 1],
// Die Anteile der Spalten einer Zeile: "2 1" ist zwei Drittel zu einem Drittel. Gesetzt wird
// das vor allem durch Ziehen der Spaltengrenze in der Vorschau des Editors.
'columnWidths' => ['group' => 'layout', 'type' => 'fractions', 'css' => null, 'label' => 'Spaltenbreiten'],
'gap' => ['group' => 'layout', 'type' => 'length', 'css' => 'gap', 'label' => 'Abstand zwischen Elementen'],
'order' => ['group' => 'layout', 'type' => 'number', 'css' => 'order', 'label' => 'Reihenfolge', 'min' => -20, 'max' => 20, 'step' => 1],
'rowGap' => ['group' => 'layout', 'type' => 'length', 'css' => 'row-gap', 'label' => 'Abstand zwischen Zeilen'],
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Tests;
use App\Content\StyleCompiler;
use App\Domain\InvalidDocument;
use PHPUnit\Framework\TestCase;
/**
* Umut: "bei Rows die Breite ändern, am besten per Drag and Drop im Editor". The editor writes
* the shares of a row's columns; this is what the server makes of them.
*/
final class ColumnWidthsTest extends TestCase
{
public function testSharesBecomeTracksAndStackWhereTheLayoutStacks(): void
{
$css = (new StyleCompiler())->compileDocument(['blocks' => [[
'id' => 'zeile', 'type' => 'row',
'layout' => ['design' => ['desktop' => ['columns' => 'two', 'gap' => 'medium'], 'mobile' => ['columns' => 'one']]],
'style' => ['desktop' => ['columnWidths' => '66.7 33.3']],
'children' => [['id' => 'a', 'type' => 'column'], ['id' => 'b', 'type' => 'column']],
]]]);
// The desktop rule carries an id and would win over the class that stacks a phone, so
// the phone gets a single track of its own.
self::assertSame(
'#zeile{grid-template-columns:minmax(0,66.7fr) minmax(0,33.3fr)}@media (max-width:767px){#zeile{grid-template-columns:minmax(0,1fr)}}',
$css,
);
}
public function testSharesArePaddedOrCutToTheColumnsAndCanDifferPerDevice(): void
{
$css = (new StyleCompiler())->compileDocument(['blocks' => [[
'id' => 'zeile', 'type' => 'row',
'style' => [
'desktop' => ['columnWidths' => '2 1'],
'tablet' => ['columnWidths' => '1 1 1 1'],
'mobile' => ['gridColumns' => 1],
],
'children' => [['id' => 'a', 'type' => 'column'], ['id' => 'b', 'type' => 'column'], ['id' => 'c', 'type' => 'column']],
]]]);
// A column added after the drag gets the average share; a surplus share is dropped.
self::assertStringContainsString('#zeile{grid-template-columns:minmax(0,2fr) minmax(0,1fr) minmax(0,1.5fr)}', $css);
self::assertStringContainsString('@media (max-width:1024px){#zeile{grid-template-columns:minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)}}', $css);
self::assertStringContainsString('@media (max-width:767px){#zeile{grid-template-columns:minmax(0,1fr)}}', $css);
// A single column has nothing to share, and only rows have columns.
self::assertSame('', (new StyleCompiler())->compileDocument(['blocks' => [
['id' => 'einzeln', 'type' => 'row', 'style' => ['desktop' => ['columnWidths' => '2 1']], 'children' => [['id' => 'a', 'type' => 'column']]],
]]));
}
public function testOnlyListsOfPositiveSharesAreAccepted(): void
{
$compiler = new StyleCompiler();
foreach (['2 1', '66.7 33.3', '25 50 25', '1'] as $good) {
$compiler->validate(['desktop' => ['columnWidths' => $good]]);
}
foreach (['2 0', '2,1', '2 1', ' 2 1', '2fr 1fr', '1 1 1 1 1 1 1 1 1 1 1 1 1', '1000 1', '1.25 1'] as $bad) {
try {
$compiler->validate(['desktop' => ['columnWidths' => $bad]]);
self::fail(sprintf('"%s" darf keine Spaltenaufteilung sein.', $bad));
} catch (InvalidDocument $e) {
self::assertStringContainsString('column shares', $e->getMessage());
}
}
}
}
+4
View File
@@ -25,6 +25,10 @@ test('design fields follow block type without hiding existing stored values', ()
assert.equal(relevantProperty(image, 'objectFit', { group: 'image' }), true);
assert.equal(relevantProperty(text, 'fontSize', { group: 'text' }), true);
assert.equal(relevantProperty(text, 'gridColumns', { group: 'layout' }), false);
// Column shares belong to a row and to nothing else - not even to the column itself.
assert.equal(relevantProperty(createBlock('row'), 'columnWidths', { group: 'layout' }), true);
assert.equal(relevantProperty(createBlock('column'), 'columnWidths', { group: 'layout' }), false);
assert.equal(relevantProperty(text, 'columnWidths', { group: 'layout' }), false);
image.style = { mobile: { fontSize: '14px' } };
assert.equal(relevantProperty(image, 'fontSize', { group: 'text' }), true);
});