Syncova. Folio mit Docker-Publishing einrichten
All checks were successful
Docker-Image veröffentlichen / publish (push) Successful in 4m8s

This commit is contained in:
Jerrit Fritzsche 2026-11-26 03:51:13 +01:00
commit 6255fc4845
49 changed files with 7541 additions and 0 deletions

6
.dockerignore Normal file
View File

@ -0,0 +1,6 @@
node_modules
dist
.git
.env
data
*.log

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
BIND_ADDRESS=127.0.0.1
HOST_PORT=4170
PUBLIC_BASE_URL=http://localhost:4170
DEMO_MODE=false
SAMPLE_DATA=false
ADMIN_USERNAME=admin
ADMIN_PASSWORD=
POSTGRES_PASSWORD=

View File

@ -0,0 +1,53 @@
name: Docker-Image veröffentlichen
on:
push:
branches: [main]
workflow_dispatch:
env:
REGISTRY: git.jfritzsche.de
IMAGE: git.jfritzsche.de/jf/syncova-folio
jobs:
publish:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- name: Quellcode auschecken
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Docker-Image bauen
run: |
set -eu
docker build --pull \
--label "org.opencontainers.image.title=Syncova. Folio" \
--label "org.opencontainers.image.source=https://git.jfritzsche.de/jf/syncova-folio" \
--label "org.opencontainers.image.revision=${GITHUB_SHA}" \
--tag "${IMAGE}:sha-${GITHUB_SHA}" \
--tag "${IMAGE}:latest" .
- name: Image in der Gitea-Registry veröffentlichen
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -eu
: "${REGISTRY_TOKEN:?Das Actions-Secret REGISTRY_TOKEN fehlt}"
DOCKER_CONFIG="$(mktemp -d)"
export DOCKER_CONFIG
cleanup() {
docker logout "${REGISTRY}" >/dev/null 2>&1 || true
rm -rf -- "${DOCKER_CONFIG}"
}
trap cleanup EXIT
printf '%s' "${REGISTRY_TOKEN}" | docker login "${REGISTRY}" --username jf --password-stdin
docker push "${IMAGE}:sha-${GITHUB_SHA}"
main_ref="$(git ls-remote --exit-code origin refs/heads/main)"
main_commit="${main_ref%%[[:space:]]*}"
if [ "${main_commit}" = "${GITHUB_SHA}" ]; then
docker push "${IMAGE}:latest"
fi

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
node_modules/
dist/
.env
data/
*.log

24
Dockerfile Normal file
View File

@ -0,0 +1,24 @@
FROM node:24-bookworm-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --no-audit --no-fund
COPY . .
RUN npm run build && npm prune --omit=dev --no-audit --no-fund
FROM node:24-bookworm-slim
RUN node -e "const fs=require('node:fs'); fs.mkdirSync('/etc/ssl/certs',{recursive:true}); fs.writeFileSync('/etc/ssl/certs/ca-certificates.crt',require('node:tls').rootCertificates.join('\n')+'\n')" \
&& sed -i -e 's|http://deb.debian.org/debian-security|https://deb.debian.org/debian-security|' -e 's|http://deb.debian.org/debian$|https://mirror.netcologne.de/debian|' /etc/apt/sources.list.d/debian.sources \
&& apt-get -o APT::Update::Error-Mode=any -o Acquire::Retries=3 -o Acquire::https::Timeout=20 update \
&& apt-get -o Acquire::Retries=2 -o Acquire::https::Timeout=20 install -y --no-install-recommends chromium fonts-liberation ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
ENV NODE_ENV=production PORT=4170 DATA_DIR=/data CHROMIUM_PATH=/usr/bin/chromium
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package.json ./
COPY --chown=node:node server ./server
COPY --chown=node:node shared ./shared
RUN mkdir /data && chown node:node /data
USER node
EXPOSE 4170
CMD ["node", "server/index.js"]

81
README.md Normal file
View File

@ -0,0 +1,81 @@
# Syncova. Folio
Syncova. Folio ist eine selbst gehostete Webanwendung für digitale Magazine und Broschüren. Browser-Anwendung, API und Publishing-Worker laufen in einem Container. PostgreSQL läuft in einem zweiten Container. Schrift, UI, Blätteranimation, Medien und PDF-Erzeugung kommen aus dem lokalen Stack.
## Lokal starten
Voraussetzung ist Docker mit Compose. Kopiere `.env.example` nach `.env` und setze dort den gewünschten `ADMIN_USERNAME`, ein `ADMIN_PASSWORD` mit mindestens 12 Zeichen sowie ein eigenes `POSTGRES_PASSWORD`.
```sh
docker compose up -d --build
docker compose ps
```
Melde dich unter [localhost:4170](http://localhost:4170) mit dem Benutzernamen und Passwort aus `.env` an. Veröffentlichte Ausgaben sind über ihre Reader-Links ohne Studio-Anmeldung erreichbar. Für eine separate lokale Demo kannst du `DEMO_MODE=true` und `SAMPLE_DATA=true` setzen. [NACHTKAUF](http://localhost:4170/ausgabe/nachtkauf) ist die zwölfseitige Vorlage für den freien Editor. Öffne im Magazinmenü **Als Vorlage kopieren**, um einen eigenständigen bearbeitbaren Entwurf anzulegen.
Mit `docker compose down` lässt sich der Stack anhalten und später mit denselben Daten starten. Die Volumes `folio_postgres` und `folio_files` enthalten alle Daten. `docker compose down -v` löscht beide Volumes einschließlich Ausgaben, Medien und Entwürfen.
## Redaktion und Veröffentlichung
1. Lege ein Magazin an. Ziehe Elemente aus der Seitenleiste auf die freie A4-Fläche. Ziehe direkt am Element zum Verschieben, an den Eckgriffen zum Skalieren und am runden Griff zum Drehen. Tippen fügt einen Baustein ein und Ziehen auf der Seite funktioniert auch mit Touch. Die Ebenenliste wählt verdeckte Elemente aus und steuert die Reihenfolge. Ein Doppelklick bearbeitet Text direkt. Die Pfeiltasten bewegen das fokussierte Element um einen Seitenpixel, mit Umschalt um zehn. Position und Größe sind zusätzlich im Inspektor verfügbar. An bestehenden Flusslayouts reicht eine Ziehbewegung oder **Seite frei bearbeiten**, um das Layout zu übernehmen.
2. **Entwurf speichern** legt eine neue Version an. Der Versionsverlauf bietet Vorschau und Wiederherstellung. Beim Speichern landen entfernte Seiten und Elemente im Papierkorb. Dort lassen sich auch gelöschte Magazine, Mediendateien und Galerien wiederherstellen.
3. **Vorschau** zeigt den aktuellen Entwurf inklusive ungespeicherter Änderungen. Unter **Veröffentlichen** lässt sich die Ausgabe sofort oder zu einem geplanten Zeitpunkt in der Browser-Zeitzone einplanen.
4. Der Worker validiert den gespeicherten Stand, erzeugt HTML und rendert ein A4-PDF mit Chromium. Enthält eine Seite zu viel Inhalt, meldet die Veröffentlichung den Seitentitel. Die bisherige Ausgabe bleibt bis zur erfolgreichen Fertigstellung erreichbar. Hochgeladene Videos werden im Flipbook abgespielt. Im PDF steht an ihrer Stelle ein Hinweis auf die Online-Ausgabe.
5. Unter **Veröffentlichungen** erscheinen Status, Fehler und Zeitpunkte. **Link & Einbettung** liefert die URL und den iframe-Code. Der öffentliche Reader bietet Blättern per Touch oder Maus, Pfeiltasten, Zoom, Inhaltsverzeichnis, Seitensprung, Vollbild und PDF-Download.
Der öffentliche Reader setzt keine Cookies. Er erhöht je Ladevorgang einen Aufrufzähler und bei einer erfolgreichen PDF-Übertragung den Downloadzähler. Die Anwendung speichert dafür aggregierte Zahlen je Magazin. Admin-Sitzungen verwenden im geschützten Modus ein separates Sitzungscookie.
## Deployment vorbereiten
Kopiere `.env.example` nach `.env` und setze `PUBLIC_BASE_URL` auf die tatsächliche HTTPS-Adresse. Konfiguriere `ADMIN_USERNAME`, `ADMIN_PASSWORD` und `POSTGRES_PASSWORD` und belasse `DEMO_MODE=false` und `SAMPLE_DATA=false`. Nach Änderungen an den Studio-Zugangsdaten übernimmt `docker compose up -d` die geänderte Umgebung. Bei einer bestehenden PostgreSQL-Installation muss eine Änderung von `POSTGRES_PASSWORD` auch in der Datenbank angewendet werden.
Leite HTTPS mit einem Reverse Proxy an Port `4170` weiter. Läuft der Proxy auf dem Docker-Host, kann `BIND_ADDRESS=127.0.0.1` bestehen bleiben. Das Studio verwendet `PUBLIC_BASE_URL` für öffentliche Links und Einbettungen. Die Datenbank hat keinen veröffentlichten Host-Port. Für Backups sichere sowohl PostgreSQL als auch das Dateivolume, damit Snapshots und zugehörige Dateien zusammen wiederherstellbar sind.
Gitea Actions baut bei einem Push nach `main` das Docker-Image. Die Registry erhält einen Tag `sha-<vollständiger Commit-SHA>` für jeden erfolgreichen Build. `latest` verweist auf den zuletzt veröffentlichten Stand von `main`. Der Workflow verwendet das Actions-Secret `REGISTRY_TOKEN` mit Schreibzugriff auf die Registry und kann auf `main` auch manuell gestartet werden.
```sh
docker pull git.jfritzsche.de/jf/syncova-folio:latest
```
## Technische Entscheidungen
- React mit Vite und shadcn/ui-Komponenten auf Radix für die Oberfläche.
- Frei positionierbare Bausteine mit gemeinsamem HTML-Renderer für Vorschau und Publikation. Der Baustein **HTML & CSS** unterstützt eigene statische Layouts, Tabellen, Listen, SVG-Grafiken und Inline-Stile. CSS bleibt auf seinen Rahmen beschränkt. Skripte, Formularübermittlungen und externe Medienquellen sind im Rahmen gesperrt. Eigene Bilder und Videos stehen über die Medienbausteine zur Verfügung.
- PostgreSQL für Entwürfe, Versionen, Warteschlange und Zähler. Ein Docker-Volume enthält Uploads und erzeugte Dateien.
- StPageFlip für die Animation und Chromium für die PDF-Erzeugung. Die Anwendung benötigt zur Laufzeit keine externen Dienste. Redaktionell gesetzte Links führen erst beim Anklicken zu ihrem Ziel.
## Beispielcover
Die drei JPEG-Dateien in `server/demo/` stammen aus einem Triptychon des eingebauten ImageGen-Tools.
<details>
<summary>ImageGen-Prompt</summary>
> Generate one wide landscape 3:2 image, seamless grid of EXACTLY THREE flush and equal-width vertical photography panels, no gaps or borders. It will be split into three separate cover photos for a sophisticated German editorial magazine studio. Left third: rugged dramatic Italian Dolomites at blue hour with a placid alpine lake, pale mist, dark pine forest at its shores and moody teal blue tones, distant jagged mountain centrally framed. Center third: architectural interior with terracotta orange monumental stair and arch, warm tactile plaster, strong oblique sun with angular shadows, contemporary Mediterranean minimalism. Right third: bright glossy Sicilian yellow and orange citrus fruit on fresh deep-green branches, late afternoon garden, cinematic dark forest green on upper half. Distinct editorial fine art photography in each region, rich film tones, highly art-directed, credible, restrained. Fill full bleed to outer edges. Absolutely no lettering, text, people, UI, frames, watermarks or logos.
</details>
### NACHTKAUF
Die neun JPEG-Motive und der daraus geschnittene stumme WebM-Film liegen in [`server/demo/nightkauf/`](server/demo/nightkauf/). Das Atrium und beide Fotobögen wurden mit dem eingebauten ImageGen-Tool erzeugt.
<details>
<summary>Cover · Atrium</summary>
> A single portrait 2:3 full-bleed editorial photograph for a fictional luxury night department store catalog, designed to be typeset later. Surreal yet photorealistic architectural photograph of a midnight-black mirrored atrium with a single luminous chartreuse circular halo framing a brutalist staircase, one small distant silhouette at the entrance, liquid chrome reflections, hard shadows, museum installation, 35mm film grain, elevated avant-garde fashion art direction. Composition centered with dark negative space on the top quarter and lower edge for type overlay. Palette near-black, cold silver, bright acid chartreuse #dcfc36. No letters, numerals, logos, watermarks or borders.
</details>
<details>
<summary>Fotobogen · Objekte und Mode</summary>
> One 3:2 landscape photographic contact sheet. EXACTLY four equal flush rectangular photo quadrants in a 2 by 2 grid with no spacing or margins, each a different luxury object editorial shot, suitable to be cropped individually. Top left: singular sculptural molten chrome table lamp in the form of a liquid silver dome on a glossy charcoal plinth, hard specular light. Top right: a large crumpled black technical nylon couture jacket on a torso mannequin with face out of frame in chartreuse spotlight. Bottom left: extravagant black cherry tart dusted with sugar, bright red candied cherries in an oval chrome dish, vermilion studio background. Bottom right: bright electric lavender satin clutch bag with a single polished metal handle floating against deep ultramarine, rich folds. Photorealistic high-fashion store editorial, coherent analog film and directional light. Each scene stays in its own quadrant. Absolutely no text, numerals, logos, borders, or watermarks.
</details>
<details>
<summary>Fotobogen · Bar, Duft und Architektur</summary>
> One 3:2 landscape contact sheet of four equal separate flush photo quadrants in a 2 by 2 grid, no dividers/gaps; each photograph for an avant-garde midnight department store lookbook. Top left: neon acid green aperitif with a spiral lemon peel in tall stemmed glass on black lacquer, boutique bar, film grain. Top right: architectural chrome escalators in a dimly lit brutalist department store, acid green horizontal lighting and dark forest shadows. Bottom left: two transparent sculptural perfume bottles with tinted deep cobalt glass and water reflections, no labels, highly editorial. Bottom right: ceiling of a futuristic mirrored fashion store in rich copper with hanging dark chrome spherical lights, industrial editorial photograph. Sophisticated architectural still life, real material textures, clean subjects. No letters, numbers, logos, text, people, or watermarks.
</details>

47
compose.yaml Normal file
View File

@ -0,0 +1,47 @@
name: syncova-folio
services:
app:
image: syncova-folio:1.1.1
build: .
init: true
restart: unless-stopped
ports:
- '${BIND_ADDRESS:-127.0.0.1}:${HOST_PORT:-4170}:4170'
environment:
DATABASE_HOST: db
DATABASE_NAME: folio
DATABASE_USER: folio
DATABASE_PASSWORD: ${POSTGRES_PASSWORD:-folio-local-development}
PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:4170}
DEMO_MODE: ${DEMO_MODE:-false}
SAMPLE_DATA: ${SAMPLE_DATA:-false}
ADMIN_USERNAME: ${ADMIN_USERNAME:-admin}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
volumes:
- folio_files:/data
depends_on:
db:
condition: service_healthy
healthcheck:
test: [CMD, node, -e, "fetch('http://localhost:4170/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
db:
image: postgres:17-bookworm
restart: unless-stopped
environment:
POSTGRES_DB: folio
POSTGRES_USER: folio
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-folio-local-development}
volumes:
- folio_postgres:/var/lib/postgresql/data
healthcheck:
test: [CMD-SHELL, pg_isready -U folio -d folio]
interval: 5s
timeout: 5s
retries: 12
volumes:
folio_files:
folio_postgres:

15
index.html Normal file
View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f8f9fd" />
<meta name="description" content="Syncova. Folio für digitale Magazine und Broschüren." />
<link rel="icon" href="/folio.svg" type="image/svg+xml" />
<title>Syncova. Folio</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

4238
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

35
package.json Normal file
View File

@ -0,0 +1,35 @@
{
"name": "syncova-folio",
"version": "1.1.1",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"start": "node server/index.js"
},
"dependencies": {
"@fontsource-variable/manrope": "^5.2.8",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-slot": "^1.2.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"express": "^5.1.0",
"file-type": "^21.0.0",
"lucide-react": "^0.562.0",
"multer": "^2.0.2",
"page-flip": "^2.0.7",
"parse5": "^8.1.1",
"pg": "^8.16.3",
"puppeteer-core": "^25.19.0",
"qrcode": "^1.5.4",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.11.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@vitejs/plugin-react": "^5.1.2",
"vite": "^7.3.0"
}
}

1
public/folio.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><rect width="48" height="48" rx="13" fill="#5345e4"/><path d="M11 14c5 0 9 1 13 4 4-3 8-4 13-4v20c-5 0-9 1-13 4-4-3-8-4-13-4Z" fill="none" stroke="#fff" stroke-width="2.5" stroke-linejoin="round"/><path d="M24 18v20" stroke="#fff" stroke-width="2.5"/></svg>

After

Width:  |  Height:  |  Size: 318 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

173
server/demo/nachtkauf.js Normal file
View File

@ -0,0 +1,173 @@
import { makeBlock, makePage } from '../../shared/magazine.js';
export const nightAssets = {
atrium: 'Nächtliches Atrium mit leuchtendem Ring', chromlampe: 'Chromlampe Liquid No. 04',
nylonjacke: 'Matt schwarze Nylonjacke im Neonschein', kirschtarte: 'Kirschtarte auf poliertem Silber',
satintasche: 'Violette Satintasche mit Bügel', aperitif: 'Chartreusefarbener Aperitif im Stielglas',
rolltreppen: 'Rolltreppen in einem schwach beleuchteten Kaufhaus', parfum: 'Kobaltblaue Parfumflakons auf Wasser',
spiegelsaal: 'Spiegelsaal mit dunklen Kugelleuchten', film: 'NACHTKAUF · Sechs Sekunden nach Ladenschluss',
};
const acid = '#e3fa44';
const black = '#10110e';
const white = '#f7f5ea';
const lilac = '#d0b9ff';
const blue = '#231bbb';
const red = '#aa1423';
function item(type, x, y, width, height, properties = {}, appearance, angle = 0) {
return { ...makeBlock(type), ...properties, frame: { x, y, width, height, angle }, ...(appearance && { appearance }) };
}
function text(value, x, y, width, height, options = {}) {
const { color, size = 28, font = 'sans', weight = 400, leading = 1.17, tracking = 0, align = 'left', angle = 0 } = options;
return item('text', x, y, width, height, { text: value, align, style: 'body' }, { color, fontSize: size, font, weight, leading, tracking }, angle);
}
const label = (value, x, y, width, color) => text(value, x, y, width, 35, { size: 17, color, font: 'mono', weight: 700, tracking: 1.8 });
const headline = (value, x, y, width, height, color, size = 112, options = {}) => text(value, x, y, width, height, { size, color, weight: 900, leading: .89, tracking: -6, ...options });
const box = (color, x, y, width, height, options = {}) => item('shape', x, y, width, height, { shape: options.shape || 'rectangle' }, { fill: color, ...options.paint }, options.angle);
const line = (color, x, y, width) => box(color, x, y, width, 12, { shape: 'line' });
const html = (markup, x, y, width, height) => item('html', x, y, width, height, { markup });
const page = (title, background, color, blocks) => ({ ...makePage(title), background, color, blocks });
export function nightkaufDraft(media, online) {
const photo = (name, x, y, width, height, options = {}) => item('image', x, y, width, height, { mediaId: media[name], alt: nightAssets[name] }, { fit: 'cover', position: options.position || 'center', radius: options.radius, opacity: options.opacity }, options.angle);
const footer = (number, color) => [line(color, 45, 1045, 704), label('NACHTKAUF / 23:59', 45, 1066, 383, color), label(`SEITE ${number}`, 644, 1066, 120, color)];
return {
title: 'NACHTKAUF', issue: '23:59 · Das Kaufhaus nach Ladenschluss',
description: 'Ein fiktives Nachtkaufhaus in zwölf Seiten. Mode, Objekte und ein Abend, der um 23:59 erst beginnt.', cover: media.atrium,
pages: [
page('Cover · 23:59', black, white, [
photo('atrium', 0, 0, 794, 1122),
box(black, 0, 0, 794, 245, { paint: { opacity: 73 } }),
line(acid, 46, 42, 702), label('JOURNAL 01 / NUR BEI NACHT', 46, 63, 590, acid),
headline('NACHTKAUF', 41, 107, 725, 145, acid, 112, { tracking: -8 }),
box(acid, 544, 835, 186, 128, { shape: 'ellipse', angle: -12 }),
text('23:59', 562, 870, 148, 52, { color: black, size: 38, tracking: -1, weight: 900, align: 'center', angle: -12 }),
box(black, 0, 976, 794, 146, { paint: { opacity: 81 } }),
text('DAS KAUFHAUS NACH LADENSCHLUSS.', 48, 1008, 670, 57, { color: white, size: 32, weight: 800, tracking: -1.2 }),
label('MODE / OBJEKTE / BAR / DUFT', 49, 1064, 688, acid),
]),
page('Willkommen nach Ladenschluss', acid, black, [
label('EDITORIAL', 45, 48, 300, black),
headline('DIE NACHT\nIST OFFEN.', 42, 129, 718, 251, black, 106, { tracking: -7 }),
photo('rolltreppen', 86, 437, 614, 404, { angle: -5 }),
box(lilac, 490, 721, 226, 92, { angle: 9 }),
label('AB 23:59', 535, 752, 195, black),
text('Das Licht ist runtergedimmt, die Rolltreppen laufen noch. Ein Kaufhaus für Dinge, die im Tageslicht zu laut wären.', 51, 875, 681, 128, { size: 28, font: 'serif', leading: 1.25 }),
...footer('02', black),
]),
page('Etagenplan · Drei Stockwerke', blue, white, [
label('ORIENTIERUNG IM HAUS', 46, 49, 500, lilac),
headline('WAS WO\nPASSIERT.', 43, 119, 711, 252, white, 115),
box(lilac, 44, 409, 703, 490),
html(`<style>
body{background:#d0b9ff;color:#191622;font-family:Arial,sans-serif;padding:4vw}
table{width:100%;border-collapse:collapse} caption{text-align:left;font:bold 2.8vw monospace;padding:1vw 0 4vw}
td{padding:3.6vw 1.4vw;border-top:.3vw solid #191622;font-size:3.25vw;vertical-align:top}
strong{display:block;font-size:5.1vw;line-height:1.04;letter-spacing:-.08em} td:first-child{width:18%;font:700 3.5vw monospace}
td:last-child{text-align:right;font:700 2.65vw monospace;white-space:nowrap} small{display:block;margin-top:1vw}
</style><table><caption>ETAGEN / ROUTE</caption><tbody>
<tr><td>02</td><td><strong>Bar & Duft</strong><small>Rouge, Nachtbar und Blue Noise.</small></td><td>S. 07–10</td></tr>
<tr><td>01</td><td><strong>Mode & Editionen</strong><small>After Hours und Mondseide.</small></td><td>S. 05–06</td></tr>
<tr><td>00</td><td><strong>Objekte</strong><small>Das Atelier für Licht und Metall.</small></td><td>S. 04</td></tr>
</tbody></table>`, 44, 409, 703, 490),
text('Erst nach oben. Dann der Neugier nach.', 45, 926, 680, 60, { size: 33, color: white, font: 'serif' }),
...footer('03', lilac),
]),
page('Objekte · Liquid No. 04', white, black, [
photo('chromlampe', 0, 280, 794, 515),
label('LICHTOBJEKT / 00', 44, 49, 473, black),
headline('LIQUID', 34, 119, 684, 183, black, 150, { tracking: -10 }),
box(acid, 484, 672, 248, 130, { angle: -6 }),
headline('340 €', 513, 709, 210, 78, black, 53, { tracking: -3, angle: -6 }),
text('No. 04 / Tischleuchte', 45, 828, 682, 60, { size: 43, font: 'serif', tracking: -1.8 }),
text('Polierter Metallguss, warmes Licht. Eine Leuchte, die selbst ausgeschaltet etwas im Raum verändert.', 46, 904, 689, 97, { size: 24, leading: 1.35 }),
...footer('04', black),
]),
page('Mode · After Hours', black, white, [
photo('nylonjacke', 0, 0, 794, 805, { position: 'right' }),
box(black, 0, 0, 794, 162, { paint: { opacity: 55 } }),
label('MODE / 01 / NACHTUNIFORM', 45, 43, 590, acid),
box(black, -23, 516, 646, 241, { angle: -5, paint: { opacity: 92 } }),
headline('AFTER\nHOURS', 44, 540, 544, 237, white, 110, { angle: -5 }),
label('01.02 / JACKE AUS TECHNISCHEM NYLON', 46, 845, 680, acid),
text('Überzeichnete Silhouette, matte Oberfläche. Lässt sich hoch schließen, wenn die Stadt abkühlt.', 44, 908, 490, 110, { size: 26, color: white, leading: 1.27 }),
text('280 €', 539, 914, 207, 63, { size: 46, color: acid, weight: 900, align: 'right', tracking: -2 }),
...footer('05', acid),
]),
page('Edition · Mondseide', lilac, black, [
label('TASCHE AUS SATIN / 01.03', 44, 47, 656, blue),
box(white, 97, 213, 575, 695, { angle: 7 }),
photo('satintasche', 63, 295, 664, 480, { angle: -7 }),
headline('MOND\nSEIDE', 40, 102, 670, 252, black, 122, { font: 'serif', weight: 700, angle: -6, tracking: -7 }),
box(acid, 520, 733, 210, 134, { shape: 'ellipse', angle: 9 }),
text('160 €', 550, 776, 145, 53, { size: 38, weight: 900, align: 'center', angle: 9 }),
text('Satin in Violett mit einem Bügel aus poliertem Stahl. Für alles, was man nachts wirklich braucht.', 51, 915, 684, 97, { font: 'serif', size: 26, leading: 1.25 }),
...footer('06', blue),
]),
page('Patisserie · Rouge', red, white, [
photo('kirschtarte', 0, 0, 794, 661), box(red, 0, 0, 794, 220, { paint: { opacity: 87 } }),
label('PATISSERIE / 02', 46, 44, 420, white),
headline('ROUGE.', 41, 99, 718, 167, white, 140, { tracking: -9 }),
text('Süßes zum Schluss.', 45, 700, 694, 62, { size: 49, color: white, font: 'serif', tracking: -2.7 }),
html(`<style>
body{background:#aa1423;color:#f7f5ea;font-family:Arial,sans-serif}
table{width:100%;border-collapse:collapse} td{padding:2.25vw 0;border-bottom:1px solid #f7f5ea90;font-size:4.1vw}
td:last-child{text-align:right;font-weight:700} tr:first-child td{border-top:1px solid #f7f5ea90}
</style><table aria-label="Patisserie-Karte"><tbody><tr><td>Schwarzkirschtarte</td><td>12 €</td></tr><tr><td>Vanillecreme mit rosa Pfeffer</td><td>9 €</td></tr><tr><td>Espresso doppio</td><td>4 €</td></tr></tbody></table>`, 45, 794, 704, 188),
...footer('07', white),
]),
page('Nachtbar · Grüner Blitz', black, acid, [
label('NACHTBAR / 02', 45, 50, 520, acid),
box(lilac, 19, 370, 697, 499, { angle: 8 }),
photo('aperitif', 45, 264, 704, 592, { angle: -3 }),
headline('GRÜNER\nBLITZ', 41, 120, 700, 243, acid, 112),
box(acid, 500, 779, 252, 83, { angle: -7 }),
text('NACHTDRINK / 14 €', 511, 805, 232, 39, { color: black, size: 22, font: 'mono', weight: 700, align: 'center', angle: -7 }),
text('Kräuter, Zitrone und ein bitteres Finish. Auch alkoholfrei erhältlich.', 44, 919, 697, 100, { color: white, size: 27, font: 'serif', leading: 1.26 }),
...footer('08', acid),
]),
page('Galerie · Blue Noise', blue, white, [
label('DUFTATELIER / 02', 45, 48, 519, lilac),
headline('BLUE\nNOISE', 41, 118, 710, 279, white, 130, { tracking: -7 }),
item('gallery', 44, 410, 705, 442, { mediaIds: [media.parfum, media.spiegelsaal, media.chromlampe, media.aperitif], height: 30 }, { fit: 'cover' }),
box(acid, 479, 780, 247, 85, { angle: -8 }),
label('PARFUM / 96 €', 507, 808, 218, black),
text('Kalter Stein, Wacholder und dunkles Holz. Vier Bilder zu einem Duft.', 45, 901, 694, 99, { color: white, size: 28, font: 'serif', leading: 1.23 }),
...footer('09', lilac),
]),
page('Film · Sechs Sekunden nach Ladenschluss', black, acid, [
label('BEWEGTBILD / NACHTKAUF JOURNAL', 46, 48, 670, acid),
headline('SECHS\nSEKUNDEN.', 40, 115, 705, 248, acid, 113, { tracking: -7 }),
box(lilac, 32, 400, 730, 460, { angle: -4 }),
item('video', 44, 411, 706, 447, { mediaId: media.film, posterMediaId: media.spiegelsaal, text: 'NACHTKAUF / 23:59 · Motion Study' }, { color: white, fill: black, fontSize: 17 }),
text('Ein Blick durch das Haus, bevor es wieder hell wird.', 45, 920, 690, 82, { color: white, size: 29, font: 'serif' }),
...footer('10', acid),
]),
page('Einlass · Die Nachtkarte', acid, black, [
label('NACHTKAUF / EINTRITT', 45, 47, 450, black),
headline('DIE NACHT-\nKARTE', 43, 120, 710, 241, black, 109, { tracking: -6.5 }),
box(black, 44, 404, 703, 309, { angle: -2 }),
text('23:59 – 03:00', 75, 445, 644, 97, { size: 66, color: acid, weight: 900, tracking: -4, angle: -2 }),
text('Die digitale Ausgabe passt in jede Jackentasche. Scanne den Code oder öffne das Flipbook direkt.', 79, 553, 580, 119, { size: 30, color: white, font: 'serif', leading: 1.2, angle: -2 }),
item('qr', 49, 761, 195, 231, { text: 'Online-Ausgabe', url: online }, { color: black, fontSize: 16 }),
item('button', 287, 785, 396, 80, { text: 'Flipbook öffnen', url: online }, { fill: black, color: acid, fontSize: 27, weight: 700, radius: 8 }),
item('social', 292, 902, 391, 64, { text: 'Visuelle Inspiration · Instagram', url: 'https://www.instagram.com/' }, { color: black, fontSize: 22 }),
...footer('11', black),
]),
page('Rückseite · Bis morgen Nacht', black, white, [
photo('spiegelsaal', 0, 0, 794, 1122),
box(black, 0, 0, 794, 1122, { paint: { opacity: 47 } }),
label('NACHTKAUF JOURNAL / ENDE', 46, 52, 665, acid),
box(acid, 434, 266, 320, 320, { shape: 'ellipse', paint: { opacity: 86 } }),
headline('BIS\nMORGEN\nNACHT.', 42, 386, 716, 456, white, 151, { tracking: -10.5 }),
box(black, 0, 944, 794, 178, { paint: { opacity: 82 } }),
text('Ein fiktives Kaufhaus. Ein Beispiel für freie Gestaltung in Syncova. Folio.', 48, 977, 660, 68, { font: 'serif', size: 27, color: white }),
label('AUSGABE 01 / 23:59', 50, 1064, 683, acid),
]),
],
};
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

BIN
server/demo/saison.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

BIN
server/demo/weitblick.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

149
server/index.js Normal file
View File

@ -0,0 +1,149 @@
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { join } from 'node:path';
import express from 'express';
import { z, ZodError } from 'zod';
import { magazines } from './magazines.js';
import { library } from './library.js';
import { HttpError, idSchema } from './model.js';
import { releasePath, startPublishing } from './publisher.js';
import { seed, seedNightkauf } from './seed.js';
import { adminPassword, adminUsername, demoMode, pool, publicBase, setup, uploadPath } from './storage.js';
const app = express();
const dist = fileURLToPath(new URL('../dist/', import.meta.url));
const port = Number(process.env.PORT || 4170);
const cookie = 'folio_session';
const sessionAge = 12 * 60 * 60 * 1000;
const cookieOptions = { httpOnly: true, secure: publicBase.protocol === 'https:', sameSite: 'strict', path: '/api/admin' };
const hash = (value) => createHash('sha256').update(value).digest('hex');
let attemptWindow = 0;
let failures = 0;
app.disable('x-powered-by');
app.use((req, res, next) => {
const reader = req.path.startsWith('/ausgabe/');
res.set('X-Content-Type-Options', 'nosniff');
res.set('Referrer-Policy', 'no-referrer');
res.set('Content-Security-Policy', `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; media-src 'self'; frame-src 'self' about:; object-src 'none'; base-uri 'none'; form-action 'self'${reader ? '' : "; frame-ancestors 'none'"}`);
if (req.path.startsWith('/api')) res.set('Cache-Control', 'no-store');
next();
});
app.use('/api', express.json({ limit: '16mb' }));
app.get('/api/health', async (_req, res) => {
await pool.query('SELECT 1');
res.json({ ok: true });
});
const admin = express.Router();
app.use('/api/admin', admin);
admin.use((req, _res, next) => {
if (['GET', 'HEAD'].includes(req.method) || req.get('X-Folio-Request') === 'studio') return next();
next(new HttpError(403, 'Ungültige Anfrage.'));
});
function tokenFrom(req) {
const match = req.headers.cookie?.match(/(?:^|;\s*)folio_session=([a-f0-9]{64})(?:;|$)/);
return match ? hash(match[1]) : '';
}
async function authorized(req) {
if (demoMode) return true;
const token = tokenFrom(req);
if (!token) return false;
return (await pool.query('SELECT 1 FROM sessions WHERE digest=$1 AND expires_at>now()', [token])).rowCount > 0;
}
admin.get('/session', async (req, res) => res.json({ authorized: await authorized(req), demo: demoMode }));
admin.post('/login', async (req, res) => {
const { username, password } = z.object({
username: z.string().trim().min(1).max(128),
password: z.string().max(1024),
}).parse(req.body);
if (demoMode) return res.json({ authorized: true, demo: true });
if (Date.now() >= attemptWindow) {
failures = 0;
attemptWindow = Date.now() + 60_000;
}
if (failures >= 10) throw new HttpError(429, 'Zu viele Anmeldeversuche. Versuche es in einer Minute erneut.');
const usernameMatches = timingSafeEqual(Buffer.from(hash(username)), Buffer.from(hash(adminUsername)));
const passwordMatches = timingSafeEqual(Buffer.from(hash(password)), Buffer.from(hash(adminPassword)));
if (!usernameMatches || !passwordMatches) {
failures += 1;
throw new HttpError(401, 'Benutzername oder Passwort stimmt nicht.');
}
const token = randomBytes(32).toString('hex');
await pool.query('DELETE FROM sessions WHERE expires_at<=now()');
await pool.query('INSERT INTO sessions (digest,expires_at) VALUES ($1,$2)', [hash(token), new Date(Date.now() + sessionAge)]);
res.cookie(cookie, token, { ...cookieOptions, maxAge: sessionAge }).json({ authorized: true, demo: false });
});
admin.use(async (req, _res, next) => {
if (!(await authorized(req))) throw new HttpError(401, 'Bitte melde dich an.');
next();
});
admin.post('/logout', async (req, res) => {
await pool.query('DELETE FROM sessions WHERE digest=$1', [tokenFrom(req)]);
res.clearCookie(cookie, cookieOptions).status(204).end();
});
admin.use(magazines, library);
async function publicRelease(slug) {
const result = await pool.query(`SELECT m.id AS magazine_id,r.id,r.pages,r.draft->>'title' AS title,r.draft->>'issue' AS issue
FROM magazines m JOIN releases r ON r.id=m.current_release WHERE m.slug=$1 AND m.deleted_at IS NULL AND r.state='ready'`, [slug]);
if (!result.rowCount) throw new HttpError(404, 'Diese Ausgabe ist nicht verfügbar.');
return result.rows[0];
}
app.get('/api/public/:slug', async (req, res) => {
const publication = await publicRelease(req.params.slug);
const base = `/api/public/${req.params.slug}`;
res.json({ pages: publication.pages, title: publication.title, issue: publication.issue, pdf: `${base}/pdf` });
});
app.post('/api/public/:slug/view', async (req, res) => {
await pool.query('UPDATE magazines SET views=views+1 WHERE slug=$1 AND deleted_at IS NULL AND current_release IS NOT NULL', [req.params.slug]);
res.status(204).end();
});
app.get('/api/public/:slug/media/:release/:media', async (req, res) => {
const result = await pool.query(`SELECT f.* FROM magazines m JOIN releases r ON r.magazine_id=m.id
JOIN media f ON f.id=ANY(r.media_ids) WHERE m.slug=$1 AND m.deleted_at IS NULL AND m.current_release IS NOT NULL
AND r.id=$2 AND r.state='ready' AND f.id=$3`, [req.params.slug, idSchema.parse(req.params.release), idSchema.parse(req.params.media)]);
if (!result.rowCount) throw new HttpError(404, 'Datei nicht gefunden.');
res.type(result.rows[0].mime).sendFile(uploadPath(result.rows[0]), { cacheControl: false });
});
app.get('/api/public/:slug/pdf', async (req, res, next) => {
const publication = await publicRelease(req.params.slug);
res.download(releasePath(publication.id, 'pdf'), `${req.params.slug}.pdf`, { acceptRanges: false, cacheControl: false }, (error) => {
if (error) return next(error);
if (req.method === 'GET') pool.query('UPDATE magazines SET downloads=downloads+1 WHERE id=$1', [publication.magazine_id])
.catch((err) => console.error('Downloadzähler:', err.message));
});
});
app.get('/ausgabe/:slug/html', async (req, res) => {
const publication = await publicRelease(req.params.slug);
res.set('Cache-Control', 'no-store').sendFile(releasePath(publication.id, 'html'));
});
app.use('/api', (_req, _res, next) => next(new HttpError(404, 'Diese Adresse gibt es nicht.')));
app.use(express.static(dist, { index: false, maxAge: '1h' }));
app.get('/{*spa}', (_req, res) => res.set('Cache-Control', 'no-cache').sendFile(join(dist, 'index.html')));
app.use((error, _req, res, next) => {
if (res.headersSent) return next(error);
if (error instanceof ZodError) return res.status(422).json({ error: error.issues[0]?.message || 'Prüfe die eingegebenen Werte.' });
if (error.code === 'LIMIT_FILE_SIZE') return res.status(413).json({ error: 'Dateien dürfen bis zu 100 MB groß sein.' });
const status = error instanceof HttpError || [400, 404, 413, 416].includes(error.status) ? error.status : 500;
if (status === 500) console.error(error);
res.status(status).json({ error: status === 500 ? 'Der Server konnte die Anfrage nicht verarbeiten.' : error.message });
});
await setup();
await seed();
await seedNightkauf();
const stopPublishing = startPublishing();
const server = app.listen(port, '0.0.0.0', () => console.log(`Syncova. Folio auf Port ${port}`));
function stop() {
stopPublishing();
server.close(() => void pool.end());
}
process.once('SIGTERM', stop);
process.once('SIGINT', stop);

91
server/library.js Normal file
View File

@ -0,0 +1,91 @@
import fs from 'node:fs/promises';
import { Router } from 'express';
import multer from 'multer';
import { fileTypeFromFile } from 'file-type';
import { z } from 'zod';
import { HttpError, idSchema } from './model.js';
import { audit, pool, stagingDir, transaction, uploadPath } from './storage.js';
const upload = multer({ dest: stagingDir, limits: { fileSize: 100 * 1024 * 1024, files: 1, fields: 0 } });
const formats = {
'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif',
'video/mp4': 'mp4', 'video/webm': 'webm',
};
export const library = Router();
library.get('/media', async (_req, res) => {
const [files, galleries] = await Promise.all([
pool.query('SELECT id,name,mime,bytes,created_at FROM media WHERE deleted_at IS NULL ORDER BY created_at DESC,name'),
pool.query('SELECT id,name,media_ids,created_at FROM galleries WHERE deleted_at IS NULL ORDER BY created_at DESC,name'),
]);
res.json({ files: files.rows, galleries: galleries.rows });
});
library.post('/media', upload.single('file'), async (req, res) => {
if (!req.file) throw new HttpError(400, 'Wähle eine Datei aus.');
const temp = req.file.path;
let saved;
try {
const fileType = await fileTypeFromFile(temp).catch(() => null);
const mime = fileType?.mime;
const extension = formats[mime];
if (!extension) throw new HttpError(415, 'Unterstützt werden JPG, PNG, WebP, GIF, AVIF, MP4 und WebM.');
const file = { id: crypto.randomUUID(), extension };
const name = Buffer.from(req.file.originalname, 'latin1').toString('utf8').replace(/[\u0000-\u001f]/g, '').slice(0, 200) || 'Datei';
const finalPath = uploadPath(file);
await fs.rename(temp, finalPath);
try {
saved = await transaction(async (db) => {
const result = await db.query('INSERT INTO media (id,name,mime,extension,bytes) VALUES ($1,$2,$3,$4,$5) RETURNING *',
[file.id, name, mime, extension, req.file.size]);
await audit(db, 'uploaded', `„${name}“ hochgeladen`);
return result.rows[0];
});
} finally {
if (!saved) await fs.rm(finalPath, { force: true });
}
res.status(201).json(saved);
} finally {
await fs.rm(temp, { force: true });
}
});
library.get('/media/:id/file', async (req, res) => {
const result = await pool.query('SELECT * FROM media WHERE id=$1 AND deleted_at IS NULL', [idSchema.parse(req.params.id)]);
if (!result.rowCount) throw new HttpError(404, 'Datei nicht gefunden.');
res.type(result.rows[0].mime).sendFile(uploadPath(result.rows[0]), { cacheControl: false });
});
const gallerySchema = z.object({ name: z.string().trim().min(1).max(100), mediaIds: z.array(idSchema).min(1).max(12) });
async function saveGallery(req, res) {
const id = req.params.id ? idSchema.parse(req.params.id) : crypto.randomUUID();
const gallery = gallerySchema.parse(req.body);
const ids = [...new Set(gallery.mediaIds)];
const item = await transaction(async (db) => {
const found = await db.query("SELECT id FROM media WHERE id=ANY($1) AND deleted_at IS NULL AND mime LIKE 'image/%'", [ids]);
if (found.rowCount !== ids.length) throw new HttpError(422, 'Wähle Bilder aus der Medienbibliothek aus.');
const result = req.params.id
? await db.query('UPDATE galleries SET name=$2,media_ids=$3 WHERE id=$1 AND deleted_at IS NULL RETURNING *', [id, gallery.name, ids])
: await db.query('INSERT INTO galleries (id,name,media_ids) VALUES ($1,$2,$3) RETURNING *', [id, gallery.name, ids]);
if (!result.rowCount) throw new HttpError(404, 'Galerie nicht gefunden.');
await audit(db, 'edited', `Galerie „${gallery.name}“ gespeichert`);
return result.rows[0];
});
res.status(req.params.id ? 200 : 201).json(item);
}
library.post('/galleries', saveGallery);
library.put('/galleries/:id', saveGallery);
for (const [route, table] of [['media', 'media'], ['galleries', 'galleries']]) {
library.delete(`/${route}/:id`, async (req, res) => {
await transaction(async (db) => {
const result = await db.query(`UPDATE ${table} SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL RETURNING name`,
[idSchema.parse(req.params.id)]);
if (!result.rowCount) throw new HttpError(404, 'Eintrag nicht gefunden.');
await audit(db, 'deleted', `„${result.rows[0].name}“ in den Papierkorb verschoben`);
});
res.status(204).end();
});
}

233
server/magazines.js Normal file
View File

@ -0,0 +1,233 @@
import { Router } from 'express';
import { z } from 'zod';
import { renderPages } from '../shared/magazine.js';
import { baseDraft, draftSchema, HttpError, idSchema, metadata, slugFor, validatePublication } from './model.js';
import { audit, pool, publicBase, transaction } from './storage.js';
const revisionSchema = z.number().int().positive();
const columns = `m.*, r.published_at, r.revision AS published_revision, q.id AS job_id,
q.state AS job_state, q.publish_at AS job_at, q.error AS job_error`;
const joins = `LEFT JOIN releases r ON r.id=m.current_release
LEFT JOIN LATERAL (SELECT id,state,publish_at,error FROM releases WHERE magazine_id=m.id ORDER BY created_at DESC,id DESC LIMIT 1) q ON true`;
function format(row) {
return {
id: row.id, slug: row.slug, ...row.draft, revision: row.revision, updatedAt: row.updated_at,
publicUrl: new URL(`/ausgabe/${row.slug}`, publicBase).href, publishedAt: row.published_at,
publishedRevision: row.published_revision, job: row.job_id ? { id: row.job_id, state: row.job_state, at: row.job_at, error: row.job_error } : null,
views: Number(row.views), downloads: Number(row.downloads),
};
}
async function find(db, id, lock = false) {
const sql = lock ? 'SELECT * FROM magazines m' : `SELECT ${columns} FROM magazines m ${joins}`;
const result = await db.query(`${sql} WHERE m.id=$1 AND m.deleted_at IS NULL${lock ? ' FOR UPDATE' : ''}`, [id]);
if (!result.rowCount) throw new HttpError(404, 'Magazin nicht gefunden.');
return result.rows[0];
}
async function trashItem(db, magazineId, pageId, index, item) {
await db.query('INSERT INTO removed_items (id,magazine_id,page_id,sort_index,item) VALUES ($1,$2,$3,$4,$5)',
[crypto.randomUUID(), magazineId, pageId, index, item]);
}
async function save(db, current, draft, reason) {
const pages = new Map(draft.pages.map((page) => [page.id, page]));
for (const [index, page] of current.draft.pages.entries()) {
const newPage = pages.get(page.id);
if (!newPage) {
await trashItem(db, current.id, null, index, page);
continue;
}
const blocks = new Set(newPage.blocks.map((block) => block.id));
for (const [position, block] of page.blocks.entries()) {
if (!blocks.has(block.id)) await trashItem(db, current.id, page.id, position, block);
}
}
const restoredIds = draft.pages.flatMap((page) => [page.id, ...page.blocks.map((block) => block.id)]);
await db.query("UPDATE removed_items SET restored_at=now() WHERE magazine_id=$1 AND restored_at IS NULL AND item->>'id'=ANY($2::text[])", [current.id, restoredIds]);
const revision = current.revision + 1;
await db.query('UPDATE magazines SET draft=$2,revision=$3,updated_at=now() WHERE id=$1', [current.id, draft, revision]);
await db.query('INSERT INTO versions (magazine_id,revision,draft,reason) VALUES ($1,$2,$3,$4)', [current.id, revision, draft, reason]);
await audit(db, 'edited', `„${draft.title}“ · ${reason.toLowerCase()}`);
return revision;
}
function assertRevision(row, revision) {
if (row.revision !== revision) throw new HttpError(409, 'Der Entwurf wurde geändert. Lade das Magazin neu, bevor du weiterarbeitest.');
}
export const magazines = Router();
magazines.get('/dashboard', async (_req, res) => {
const [result, activity, storage, publications] = await Promise.all([
pool.query(`SELECT ${columns} FROM magazines m ${joins} WHERE m.deleted_at IS NULL ORDER BY m.updated_at DESC,m.id`),
pool.query('SELECT * FROM activity ORDER BY id DESC LIMIT 20'),
pool.query(`SELECT (SELECT COALESCE(SUM(bytes),0) FROM media) + (SELECT COALESCE(SUM(bytes),0) FROM releases) AS bytes,
(SELECT count(*) FROM media WHERE deleted_at IS NULL) AS files`),
pool.query(`SELECT r.id,r.magazine_id,r.draft->>'title' AS title,r.revision,r.state,r.publish_at,r.published_at,r.error,
m.current_release=r.id AS is_current,m.slug FROM releases r JOIN magazines m ON m.id=r.magazine_id
WHERE m.deleted_at IS NULL ORDER BY r.created_at DESC LIMIT 100`),
]);
res.json({ magazines: result.rows.map(format), activity: activity.rows, publications: publications.rows,
storage: { bytes: Number(storage.rows[0].bytes), files: Number(storage.rows[0].files) } });
});
magazines.post('/magazines', async (req, res) => {
const fields = metadata.pick({ title: true, issue: true, description: true }).parse(req.body);
const draft = baseDraft(fields.title, fields.issue, fields.description);
const id = crypto.randomUUID();
await transaction(async (db) => {
const base = slugFor(fields.title);
const result = await db.query('INSERT INTO magazines (id,slug,draft) VALUES ($1,$2,$3) ON CONFLICT (slug) DO NOTHING', [id, base, draft]);
if (!result.rowCount) await db.query('INSERT INTO magazines (id,slug,draft) VALUES ($1,$2,$3)', [id, `${base}-${id}`, draft]);
await db.query("INSERT INTO versions (magazine_id,revision,draft,reason) VALUES ($1,1,$2,'Angelegt')", [id, draft]);
await audit(db, 'created', `„${draft.title}“ angelegt`);
});
res.status(201).json(format(await find(pool, id)));
});
magazines.get('/magazines/:id', async (req, res) => res.json(format(await find(pool, idSchema.parse(req.params.id)))));
magazines.post('/magazines/:id/duplicate', async (req, res) => {
const source = await find(pool, idSchema.parse(req.params.id));
const id = crypto.randomUUID();
const title = `${source.draft.title.slice(0, 92).trimEnd()} · Kopie`;
const draft = { ...source.draft, title, pages: source.draft.pages.map((page) => ({ ...page, id: crypto.randomUUID(),
blocks: page.blocks.map((item) => ({ ...item, id: crypto.randomUUID() })) })) };
await transaction(async (db) => {
await db.query('INSERT INTO magazines (id,slug,draft) VALUES ($1,$2,$3)', [id, `${slugFor(title)}-${id}`, draft]);
await db.query("INSERT INTO versions (magazine_id,revision,draft,reason) VALUES ($1,1,$2,'Aus Vorlage angelegt')", [id, draft]);
await audit(db, 'created', `„${title}“ aus Vorlage angelegt`);
});
res.status(201).json(format(await find(pool, id)));
});
magazines.put('/magazines/:id', async (req, res) => {
const id = idSchema.parse(req.params.id);
const { draft, revision } = z.object({ draft: draftSchema, revision: revisionSchema }).parse(req.body);
const result = await transaction(async (db) => {
const current = await find(db, id, true);
assertRevision(current, revision);
await save(db, current, draft, 'Entwurf gespeichert');
return format(await find(db, id));
});
res.json(result);
});
magazines.post('/magazines/:id/preview', async (req, res) => {
await find(pool, idSchema.parse(req.params.id));
const draft = draftSchema.parse(req.body);
const pages = await renderPages(draft, (id) => `/api/admin/media/${id}/file`);
res.json({ title: draft.title, issue: draft.issue, pages });
});
magazines.get('/magazines/:id/versions', async (req, res) => {
const id = idSchema.parse(req.params.id);
await find(pool, id);
const result = await pool.query('SELECT revision,reason,created_at,draft FROM versions WHERE magazine_id=$1 ORDER BY revision DESC', [id]);
res.json(result.rows);
});
magazines.post('/magazines/:id/versions/:version/restore', async (req, res) => {
const id = idSchema.parse(req.params.id);
const revision = revisionSchema.parse(req.body.revision);
const version = z.coerce.number().int().positive().parse(req.params.version);
const result = await transaction(async (db) => {
const current = await find(db, id, true);
assertRevision(current, revision);
const history = await db.query('SELECT draft FROM versions WHERE magazine_id=$1 AND revision=$2', [id, version]);
if (!history.rowCount) throw new HttpError(404, 'Version nicht gefunden.');
await save(db, current, history.rows[0].draft, `Version ${version} wiederhergestellt`);
return format(await find(db, id));
});
res.json(result);
});
magazines.delete('/magazines/:id', async (req, res) => {
const id = idSchema.parse(req.params.id);
await transaction(async (db) => {
const row = await find(db, id, true);
await db.query('UPDATE magazines SET deleted_at=now() WHERE id=$1', [id]);
await db.query("UPDATE releases SET state='cancelled' WHERE magazine_id=$1 AND state='queued'", [id]);
await audit(db, 'deleted', `„${row.draft.title}“ in den Papierkorb verschoben`);
});
res.status(204).end();
});
magazines.post('/magazines/:id/releases', async (req, res) => {
const id = idSchema.parse(req.params.id);
const { at, revision } = z.object({ at: z.iso.datetime().nullish(), revision: revisionSchema }).parse(req.body);
if (at && Date.parse(at) <= Date.now()) throw new HttpError(422, 'Wähle einen Zeitpunkt in der Zukunft.');
const release = await transaction(async (db) => {
const current = await find(db, id, true);
assertRevision(current, revision);
await validatePublication(db, current.draft);
const job = crypto.randomUUID();
await db.query("UPDATE releases SET state='cancelled' WHERE magazine_id=$1 AND state='queued'", [id]);
await db.query('INSERT INTO releases (id,magazine_id,revision,draft,publish_at) VALUES ($1,$2,$3,$4,$5)',
[job, id, revision, current.draft, at || new Date()]);
await audit(db, 'scheduled', `„${current.draft.title}“ · ${at ? 'Veröffentlichung geplant' : 'Veröffentlichung gestartet'}`);
return job;
});
res.status(202).json({ id: release });
});
magazines.delete('/releases/:id', async (req, res) => {
const id = idSchema.parse(req.params.id);
await transaction(async (db) => {
const result = await db.query("UPDATE releases SET state='cancelled' WHERE id=$1 AND state='queued' RETURNING draft", [id]);
if (!result.rowCount) throw new HttpError(409, 'Diese Veröffentlichung kann nicht mehr abgebrochen werden.');
await audit(db, 'cancelled', `„${result.rows[0].draft.title}“ · Veröffentlichung abgebrochen`);
});
res.status(204).end();
});
magazines.delete('/magazines/:id/publication', async (req, res) => {
const id = idSchema.parse(req.params.id);
await transaction(async (db) => {
const row = await find(db, id, true);
await db.query('UPDATE magazines SET current_release=NULL WHERE id=$1', [id]);
await audit(db, 'unpublished', `„${row.draft.title}“ offline genommen`);
});
res.status(204).end();
});
magazines.get('/trash', async (_req, res) => {
const [magazines, items, files, galleries] = await Promise.all([
pool.query("SELECT id,draft->>'title' AS title,deleted_at FROM magazines WHERE deleted_at IS NOT NULL ORDER BY deleted_at DESC"),
pool.query(`SELECT i.id,i.page_id,i.item,i.deleted_at,m.draft->>'title' AS magazine FROM removed_items i
JOIN magazines m ON m.id=i.magazine_id WHERE i.restored_at IS NULL AND m.deleted_at IS NULL ORDER BY i.deleted_at DESC`),
pool.query('SELECT id,name,deleted_at FROM media WHERE deleted_at IS NOT NULL ORDER BY deleted_at DESC'),
pool.query('SELECT id,name,deleted_at FROM galleries WHERE deleted_at IS NOT NULL ORDER BY deleted_at DESC'),
]);
res.json({ magazines: magazines.rows, items: items.rows, files: files.rows, galleries: galleries.rows });
});
magazines.post('/trash/:kind/:id/restore', async (req, res) => {
const id = idSchema.parse(req.params.id);
const kind = z.enum(['magazine', 'item', 'media', 'gallery']).parse(req.params.kind);
await transaction(async (db) => {
if (kind === 'item') {
const result = await db.query('SELECT * FROM removed_items WHERE id=$1 AND restored_at IS NULL', [id]);
if (!result.rowCount) throw new HttpError(404, 'Eintrag nicht gefunden.');
const entry = result.rows[0];
const current = await find(db, entry.magazine_id, true);
const stillDeleted = await db.query('SELECT 1 FROM removed_items WHERE id=$1 AND restored_at IS NULL', [id]);
if (!stillDeleted.rowCount) throw new HttpError(409, 'Der Eintrag wurde bereits wiederhergestellt.');
const draft = structuredClone(current.draft);
const targetPage = draft.pages.find((page) => page.id === entry.page_id);
if (entry.page_id && !targetPage) throw new HttpError(409, 'Stelle zuerst die zugehörige Seite wieder her.');
const target = targetPage ? targetPage.blocks : draft.pages;
target.splice(entry.sort_index, 0, entry.item);
await save(db, current, draftSchema.parse(draft), targetPage ? 'Element wiederhergestellt' : 'Seite wiederhergestellt');
return;
}
const table = { magazine: 'magazines', media: 'media', gallery: 'galleries' }[kind];
const label = kind === 'magazine' ? "draft->>'title'" : 'name';
const result = await db.query(`UPDATE ${table} SET deleted_at=NULL WHERE id=$1 AND deleted_at IS NOT NULL RETURNING ${label} AS label`, [id]);
if (!result.rowCount) throw new HttpError(404, 'Eintrag nicht gefunden.');
await audit(db, 'restored', `„${result.rows[0].label}“ wiederhergestellt`);
});
res.status(204).end();
});

91
server/model.js Normal file
View File

@ -0,0 +1,91 @@
import { z } from 'zod';
import { makePage, safeUrl } from '../shared/magazine.js';
export const idSchema = z.uuid();
const color = z.string().regex(/^#[0-9a-f]{6}$/i);
const frame = z.object({ x: z.number().int().min(-5000).max(5000), y: z.number().int().min(-5000).max(5000),
width: z.number().int().min(12).max(1588), height: z.number().int().min(12).max(2244), angle: z.number().min(-180).max(180) });
const appearance = z.object({
color: color.optional(), fill: color.optional(), stroke: color.optional(), strokeWidth: z.number().min(0).max(100).optional(),
radius: z.number().min(0).max(800).optional(), opacity: z.number().min(0).max(100).optional(),
font: z.enum(['sans', 'serif', 'mono']).optional(), fontSize: z.number().min(6).max(360).optional(),
weight: z.number().int().min(100).max(900).optional(), leading: z.number().min(.5).max(4).optional(), tracking: z.number().min(-40).max(75).optional(),
fit: z.enum(['cover', 'contain', 'fill']).optional(), position: z.enum(['center', 'top', 'bottom', 'left', 'right']).optional(),
});
const block = z.discriminatedUnion('type', [
z.object({ type: z.literal('text'), text: z.string().max(6000), style: z.enum(['body', 'title', 'heading', 'caption']), align: z.enum(['left', 'center', 'right']) }),
z.object({ type: z.literal('image'), mediaId: z.union([idSchema, z.literal('')]), alt: z.string().max(200), height: z.number().min(12).max(135) }),
z.object({ type: z.literal('gallery'), mediaIds: z.array(idSchema).max(12), height: z.number().min(12).max(100) }),
z.object({ type: z.literal('video'), mediaId: z.union([idSchema, z.literal('')]), posterMediaId: z.union([idSchema, z.literal('')]).optional(), text: z.string().max(200) }),
z.object({ type: z.literal('shape'), shape: z.enum(['rectangle', 'ellipse', 'line']) }),
z.object({ type: z.literal('html'), markup: z.string().max(60000) }),
...['button', 'qr', 'social'].map((type) => z.object({ type: z.literal(type), text: z.string().max(200), url: z.string().max(500) })),
].map((schema) => schema.extend({ id: idSchema, width: z.enum(['full', 'half']), frame: frame.optional(), appearance: appearance.optional() })));
export const metadata = z.object({
title: z.string().trim().min(1, 'Gib deinem Magazin einen Titel.').max(100),
issue: z.string().trim().max(100), description: z.string().trim().max(1000),
cover: z.union([idSchema, z.literal('')]),
});
export const draftSchema = metadata.extend({
pages: z.array(z.object({
id: idSchema, title: z.string().trim().min(1, 'Jede Seite benötigt einen Titel.').max(100),
layout: z.enum(['free', 'single', 'columns', 'cover']), background: color, color,
blocks: z.array(block).max(60),
})).max(120),
}).refine((draft) => {
const ids = draft.pages.flatMap((page) => [page.id, ...page.blocks.map((item) => item.id)]);
return new Set(ids).size === ids.length;
}, 'Seiten und Elemente müssen eindeutige IDs haben.');
export const baseDraft = (title, issue = '', description = '') => ({
title, issue, description, cover: '', pages: [makePage('Titelseite')],
});
export function slugFor(title) {
return title.toLowerCase().replaceAll('ß', 'ss').normalize('NFKD').replace(/\p{M}/gu, '')
.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 65).replace(/-$/, '') || 'magazin';
}
export class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
export async function validatePublication(db, draft) {
const document = draftSchema.parse(draft);
if (!document.pages.length) throw new HttpError(422, 'Lege mindestens eine Seite an.');
const expected = new Map();
if (document.cover) expected.set(document.cover, 'image/');
for (const page of document.pages) {
const label = `„${page.title}“`;
if (!page.blocks.length) throw new HttpError(422, `${label} ist leer.`);
for (const item of page.blocks) {
if (item.type === 'text' && !item.text.trim()) throw new HttpError(422, `${label} enthält ein leeres Textfeld.`);
if (item.type === 'html' && !item.markup.trim()) throw new HttpError(422, `${label} enthält einen leeren HTML-Block.`);
if (['button', 'qr', 'social'].includes(item.type) && !safeUrl(item.url, item.type === 'social')) {
throw new HttpError(422, `${label} enthält einen ungültigen Link.`);
}
if (['button', 'social'].includes(item.type) && !item.text.trim()) {
throw new HttpError(422, `${label} enthält einen Link ohne Beschriftung.`);
}
const ids = item.type === 'gallery' ? item.mediaIds : [item.mediaId].filter(Boolean);
if (['image', 'gallery', 'video'].includes(item.type) && !ids.length) {
throw new HttpError(422, `${label} enthält ein Element ohne Medium.`);
}
const refs = ids.map((id) => [id, item.type === 'video' ? 'video/' : 'image/']);
if (item.posterMediaId) refs.push([item.posterMediaId, 'image/']);
for (const [id, kind] of refs) {
if (expected.has(id) && expected.get(id) !== kind) throw new HttpError(422, `${label} verwendet ein Medium im falschen Format.`);
expected.set(id, kind);
}
}
}
const result = await db.query('SELECT * FROM media WHERE id = ANY($1) AND deleted_at IS NULL', [[...expected.keys()]]);
if (result.rowCount !== expected.size) throw new HttpError(422, 'Ein verwendetes Medium fehlt oder liegt im Papierkorb.');
if (result.rows.some((file) => !file.mime.startsWith(expected.get(file.id)))) throw new HttpError(422, 'Ein verwendetes Medium hat das falsche Format.');
return result.rows;
}

119
server/publisher.js Normal file
View File

@ -0,0 +1,119 @@
import fs from 'node:fs/promises';
import { join } from 'node:path';
import puppeteer from 'puppeteer-core';
import { escapeHtml, renderPages } from '../shared/magazine.js';
import { validatePublication } from './model.js';
import { audit, pool, releaseDir, transaction, uploadPath } from './storage.js';
const width = 794;
const height = 1122;
const styles = await fs.readFile(new URL('../shared/publication.css', import.meta.url), 'utf8');
const paper = `@page{size:${width}px ${height}px;margin:0}body{margin:0}.print-sheet{width:${width}px;height:${height}px;break-after:page}.print-sheet:last-child{break-after:auto}`;
function documentHtml(title, pages) {
return `<!doctype html><html lang="de"><head><meta charset="utf-8"><title>${escapeHtml(title)}</title><style>${styles}\n${paper}</style></head><body>${pages.map(({ html }) => `<section class="print-sheet">${html}</section>`).join('')}</body></html>`;
}
async function createPdf(draft, files) {
const origin = 'http://folio-render.invalid';
const imageMap = new Map(files.filter((file) => file.mime.startsWith('image/')).map((file) => [file.id, file]));
const pages = await renderPages(draft, (id) => `${origin}/image/${id}`, true);
const browser = await puppeteer.launch({
executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium',
args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-background-networking'],
headless: true,
});
try {
const page = await browser.newPage();
await page.setJavaScriptEnabled(false);
await page.setRequestInterception(true);
page.on('request', async (request) => {
const url = new URL(request.url());
if (['data:', 'about:'].includes(url.protocol)) return request.continue();
const file = url.origin === origin && imageMap.get(url.pathname.slice('/image/'.length));
if (!file) return request.abort();
try {
await request.respond({ status: 200, contentType: file.mime, body: await fs.readFile(uploadPath(file)) });
} catch {
if (!request.isInterceptResolutionHandled()) await request.abort();
}
});
await page.setViewport({ width, height });
await page.setContent(documentHtml(draft.title, pages), { waitUntil: 'load', timeout: 30000 });
const invalid = await page.evaluate(() => [...document.querySelectorAll('.folio-page')].findIndex((sheet) =>
(!sheet.querySelector('.folio-layout-free') && sheet.scrollHeight > sheet.clientHeight + 2) || [...sheet.querySelectorAll('img')].some((img) => !img.naturalWidth)));
if (invalid !== -1) throw new Error(`„${pages[invalid].title}“ ist zu voll oder enthält ein Bild, das sich nicht laden lässt.`);
return await page.pdf({ printBackground: true, preferCSSPageSize: true, timeout: 30000 });
} finally {
await browser.close();
}
}
export const releasePath = (release, format) => join(releaseDir, `${release}.${format}`);
async function writeArtifact(path, contents) {
const temp = `${path}.tmp`;
await fs.writeFile(temp, contents);
await fs.rename(temp, path);
}
async function publish(job) {
const pdfPath = releasePath(job.id, 'pdf');
const htmlPath = releasePath(job.id, 'html');
let committed = false;
try {
const files = await validatePublication(pool, job.draft);
const pages = await renderPages(job.draft, (id) => `/api/public/${job.slug}/media/${job.id}/${id}`);
const html = documentHtml(job.draft.title, pages);
const pdf = await createPdf(job.draft, files);
await writeArtifact(htmlPath, html);
await writeArtifact(pdfPath, pdf);
committed = await transaction(async (db) => {
const magazine = await db.query('SELECT deleted_at FROM magazines WHERE id=$1 FOR UPDATE', [job.magazine_id]);
if (magazine.rows[0]?.deleted_at) return false;
const update = await db.query(`UPDATE releases SET state='ready',pages=$2,media_ids=$3,bytes=$4,published_at=now()
WHERE id=$1 AND state='queued' RETURNING id`, [job.id, JSON.stringify(pages), files.map((file) => file.id), Buffer.byteLength(html) + pdf.length]);
if (!update.rowCount) return false;
await db.query('UPDATE magazines SET current_release=$2 WHERE id=$1', [job.magazine_id, job.id]);
await audit(db, 'published', `„${job.draft.title}“ veröffentlicht`);
return true;
});
} catch (error) {
console.error('Veröffentlichung:', error.message);
await transaction(async (db) => {
const updated = await db.query("UPDATE releases SET state='failed',error=$2 WHERE id=$1 AND state='queued'", [job.id, error.message.slice(0, 500)]);
if (updated.rowCount) await audit(db, 'failed', `Veröffentlichung von „${job.draft.title}“ fehlgeschlagen`);
});
} finally {
if (!committed) await Promise.all([pdfPath, htmlPath, `${pdfPath}.tmp`, `${htmlPath}.tmp`].map((path) => fs.rm(path, { force: true })));
}
}
export function startPublishing() {
let timer;
let stopped = false;
const run = async () => {
let db;
let locked = false;
try {
db = await pool.connect();
locked = (await db.query('SELECT pg_try_advisory_lock(918401) AS locked')).rows[0].locked;
while (locked && !stopped) {
const result = await db.query(`SELECT r.*,m.slug FROM releases r JOIN magazines m ON m.id=r.magazine_id
WHERE r.state='queued' AND r.publish_at <= now() AND m.deleted_at IS NULL ORDER BY r.publish_at,r.created_at LIMIT 1`);
if (!result.rowCount) break;
await publish(result.rows[0]);
}
} catch (error) {
console.error('Publishing-Worker:', error.message);
} finally {
if (db) {
const unlockError = locked ? await db.query('SELECT pg_advisory_unlock(918401)').then(() => undefined).catch((error) => error) : undefined;
db.release(unlockError);
}
if (!stopped) timer = setTimeout(run, 2500);
}
};
void run();
return () => { stopped = true; clearTimeout(timer); };
}

74
server/schema.sql Normal file
View File

@ -0,0 +1,74 @@
CREATE TABLE IF NOT EXISTS magazines (
id uuid PRIMARY KEY,
slug text UNIQUE NOT NULL,
draft jsonb NOT NULL,
revision integer NOT NULL DEFAULT 1,
current_release uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
views bigint NOT NULL DEFAULT 0,
downloads bigint NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS versions (
magazine_id uuid NOT NULL REFERENCES magazines(id),
revision integer NOT NULL,
draft jsonb NOT NULL,
reason text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (magazine_id, revision)
);
CREATE TABLE IF NOT EXISTS releases (
id uuid PRIMARY KEY,
magazine_id uuid NOT NULL REFERENCES magazines(id),
revision integer NOT NULL,
draft jsonb NOT NULL,
publish_at timestamptz NOT NULL,
state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','ready','failed','cancelled')),
pages jsonb,
media_ids uuid[] NOT NULL DEFAULT '{}',
bytes bigint NOT NULL DEFAULT 0,
error text,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX IF NOT EXISTS releases_due ON releases (publish_at) WHERE state = 'queued';
CREATE INDEX IF NOT EXISTS releases_magazine ON releases (magazine_id, created_at DESC);
CREATE TABLE IF NOT EXISTS media (
id uuid PRIMARY KEY,
name text NOT NULL,
mime text NOT NULL,
extension text NOT NULL,
bytes bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
CREATE TABLE IF NOT EXISTS galleries (
id uuid PRIMARY KEY,
name text NOT NULL,
media_ids uuid[] NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
CREATE TABLE IF NOT EXISTS removed_items (
id uuid PRIMARY KEY,
magazine_id uuid NOT NULL REFERENCES magazines(id),
page_id uuid,
sort_index integer NOT NULL,
item jsonb NOT NULL,
deleted_at timestamptz NOT NULL DEFAULT now(),
restored_at timestamptz
);
CREATE TABLE IF NOT EXISTS activity (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
message text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS sessions (
digest text PRIMARY KEY,
expires_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key text PRIMARY KEY
);

88
server/seed.js Normal file
View File

@ -0,0 +1,88 @@
import fs from 'node:fs/promises';
import { makeBlock, makePage } from '../shared/magazine.js';
import { baseDraft } from './model.js';
import { audit, publicBase, transaction, uploadPath } from './storage.js';
import { nightAssets, nightkaufDraft } from './demo/nachtkauf.js';
const editions = [
{ slug: 'weitblick', title: 'Weitblick', issue: 'Ausgabe 04 · Das Alpenheft', cover: 'Dolomiten am Morgen', color: '#0e2e39', pages: ['Jenseits der Baumgrenze', 'Am stillen Ufer', 'Unterwegs im Fels', 'Ein letzter Blick'], text: 'Zwischen dunklem Wasser und kühlem Fels beginnt der Tag langsam. Ein Heft über die Landschaften, die uns den Atem anhalten lassen.' },
{ slug: 'form-und-raum', title: 'Form & Raum', issue: 'Ausgabe 02 · Architektur', cover: 'Treppenhaus aus Terrakotta', color: '#682f1c', pages: ['Räume im Licht', 'Material und Handwerk', 'Der Blick nach draußen'], text: 'Sonnenlicht wandert über Terrakotta, und mit ihm verändert sich der Raum. Diese Ausgabe folgt dem Zusammenspiel von Material, Form und Zeit.' },
{ slug: 'saison', title: 'Saison', issue: 'Ausgabe 01 · Eine Reise nach Süden', cover: 'Zitrusgarten in Sizilien', color: '#243722', pages: ['Im Zitrusgarten', 'Von Baum zu Tisch'], text: 'Wo Zitronen und Orangen wachsen, erzählt jede Jahreszeit eine eigene Geschichte. Wir folgen den Früchten vom Garten bis auf den Tisch.' },
];
const text = (value, style = 'body') => ({ ...makeBlock('text'), text: value, style });
const picture = (mediaId, alt, height) => ({ ...makeBlock('image'), mediaId, alt, height });
export async function seed() {
if (process.env.SAMPLE_DATA !== 'true') return;
await transaction(async (db) => {
const flag = await db.query("INSERT INTO settings (key) VALUES ('sample-v1') ON CONFLICT DO NOTHING RETURNING key");
if (!flag.rowCount) return;
const coverIds = [];
for (const [index, edition] of editions.entries()) {
const media = { id: crypto.randomUUID(), extension: 'jpg' };
const bytes = await fs.readFile(new URL(`./demo/${edition.slug}.jpg`, import.meta.url));
await fs.writeFile(uploadPath(media), bytes);
const id = crypto.randomUUID();
coverIds.push(media.id);
const draft = baseDraft(edition.title, edition.issue, edition.text);
draft.cover = media.id;
draft.pages = [
{ ...makePage('Titelseite'), layout: 'cover', background: edition.color, color: '#fff9ed', blocks: [text(edition.issue, 'caption'), text(edition.title, 'title'), picture(media.id, edition.cover, 92)] },
...edition.pages.map((title, number) => ({ ...makePage(title), layout: 'single', blocks: [text(edition.title, 'caption'), text(title, 'heading'), picture(media.id, edition.cover, number === 0 ? 58 : 43), text(edition.text)] })),
];
await db.query("INSERT INTO media (id,name,mime,extension,bytes) VALUES ($1,$2,'image/jpeg','jpg',$3)", [media.id, edition.cover, bytes.length]);
await db.query('INSERT INTO magazines (id,slug,draft,views,downloads,updated_at) VALUES ($1,$2,$3,$4,$5,now() - $6::interval)',
[id, edition.slug, draft, index === 0 ? 2841 : 0, index === 0 ? 186 : 0, `${index} days`]);
await db.query("INSERT INTO versions (magazine_id,revision,draft,reason) VALUES ($1,1,$2,'Angelegt')", [id, draft]);
await audit(db, 'created', `„${edition.title}“ angelegt`);
if (index === 0 || index === 2) {
await db.query('INSERT INTO releases (id,magazine_id,revision,draft,publish_at) VALUES ($1,$2,1,$3,now() + $4::interval)',
[crypto.randomUUID(), id, draft, index === 0 ? '0 days' : '7 days']);
}
}
await db.query('INSERT INTO galleries (id,name,media_ids) VALUES ($1,$2,$3)', [crypto.randomUUID(), 'Beispielcover', coverIds]);
});
}
export async function seedNightkauf() {
if (process.env.SAMPLE_DATA !== 'true') return;
const paths = [];
try {
await transaction(async (db) => {
const flag = await db.query("INSERT INTO settings (key) VALUES ('sample-nachtkauf-v1') ON CONFLICT DO NOTHING RETURNING key");
if (!flag.rowCount) return;
const media = {};
for (const [key, name] of Object.entries(nightAssets)) {
const video = key === 'film';
const file = { id: crypto.randomUUID(), extension: video ? 'webm' : 'jpg' };
const filename = video ? 'nachtkauf-film.webm' : `${key}.jpg`;
const data = await fs.readFile(new URL(`./demo/nightkauf/${filename}`, import.meta.url));
const path = uploadPath(file);
paths.push(path);
await fs.writeFile(path, data);
await db.query('INSERT INTO media (id,name,mime,extension,bytes) VALUES ($1,$2,$3,$4,$5)',
[file.id, name, video ? 'video/webm' : 'image/jpeg', file.extension, data.length]);
media[key] = file.id;
}
const id = crypto.randomUUID();
const gallery = ['parfum', 'spiegelsaal', 'chromlampe', 'aperitif'].map((key) => media[key]);
await db.query('INSERT INTO galleries (id,name,media_ids) VALUES ($1,$2,$3)', [crypto.randomUUID(), 'NACHTKAUF · Blue Noise', gallery]);
let slug = 'nachtkauf';
let draft = nightkaufDraft(media, new URL(`/ausgabe/${slug}`, publicBase).href);
const inserted = await db.query('INSERT INTO magazines (id,slug,draft) VALUES ($1,$2,$3) ON CONFLICT (slug) DO NOTHING', [id, slug, draft]);
if (!inserted.rowCount) {
slug = `nachtkauf-${id.slice(0, 8)}`;
draft = nightkaufDraft(media, new URL(`/ausgabe/${slug}`, publicBase).href);
await db.query('INSERT INTO magazines (id,slug,draft) VALUES ($1,$2,$3)', [id, slug, draft]);
}
await db.query("INSERT INTO versions (magazine_id,revision,draft,reason) VALUES ($1,1,$2,'Beispielbroschüre angelegt')", [id, draft]);
await db.query('INSERT INTO releases (id,magazine_id,revision,draft,publish_at) VALUES ($1,$2,1,$3,now())', [crypto.randomUUID(), id, draft]);
await audit(db, 'created', '„NACHTKAUF“ als bearbeitbare Beispielbroschüre angelegt');
});
} catch (error) {
await Promise.all(paths.map((path) => fs.rm(path, { force: true })));
throw error;
}
}

54
server/storage.js Normal file
View File

@ -0,0 +1,54 @@
import fs from 'node:fs/promises';
import { resolve, join } from 'node:path';
import pg from 'pg';
export const root = resolve(process.env.DATA_DIR || './data');
export const uploadDir = join(root, 'uploads');
export const stagingDir = join(root, 'staging');
export const releaseDir = join(root, 'releases');
export const uploadPath = (file) => join(uploadDir, `${file.id}.${file.extension}`);
export const publicBase = new URL(process.env.PUBLIC_BASE_URL || 'http://localhost:4170');
export const demoMode = process.env.DEMO_MODE === 'true';
export const adminUsername = process.env.ADMIN_USERNAME?.trim() || 'admin';
export const adminPassword = process.env.ADMIN_PASSWORD || '';
export const pool = new pg.Pool(process.env.DATABASE_URL ? { connectionString: process.env.DATABASE_URL } : {
host: process.env.DATABASE_HOST || '127.0.0.1',
database: process.env.DATABASE_NAME || 'folio',
user: process.env.DATABASE_USER || 'folio',
password: process.env.DATABASE_PASSWORD || 'folio-local-development',
});
pool.on('error', (error) => console.error('PostgreSQL:', error.message));
export async function setup() {
if (!['http:', 'https:'].includes(publicBase.protocol) || publicBase.pathname !== '/' || publicBase.search || publicBase.hash || publicBase.username || publicBase.password) {
throw new Error('PUBLIC_BASE_URL benötigt eine HTTP(S)-Adresse ohne Unterpfad.');
}
if (demoMode && !['localhost', '127.0.0.1', '[::1]'].includes(publicBase.hostname)) {
throw new Error('Der Beispielmodus ist auf lokale URLs beschränkt.');
}
if (!demoMode && adminPassword.length < 12) throw new Error('Setze ADMIN_PASSWORD auf mindestens 12 Zeichen.');
if (!demoMode && adminUsername.length > 128) throw new Error('ADMIN_USERNAME darf höchstens 128 Zeichen enthalten.');
await Promise.all([uploadDir, stagingDir, releaseDir].map((path) => fs.mkdir(path, { recursive: true })));
await transaction(async (db) => {
await db.query('SELECT pg_advisory_xact_lock(918402)');
await db.query(await fs.readFile(new URL('./schema.sql', import.meta.url), 'utf8'));
});
}
export async function transaction(work) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
export const audit = (db, kind, message) => db.query('INSERT INTO activity (kind,message) VALUES ($1,$2)', [kind, message]);

68
shared/free-layout.js Normal file
View File

@ -0,0 +1,68 @@
export const pageWidth = 794;
export const pageHeight = 1122;
export const minFrame = 12;
const dimensions = {
text: [448, 100], image: [380, 296], gallery: [480, 260], button: [224, 61],
qr: [170, 197], video: [440, 280], social: [232, 56], shape: [245, 158], html: [462, 240],
};
export const fontFamilies = { sans: 'Arial, sans-serif', serif: 'Georgia, serif', mono: 'monospace' };
export const designLength = (value) => `${value * 100 / pageWidth}cqw`;
export function initialFrame(type, index = 0) {
const [width, height] = dimensions[type] || dimensions.text;
const offset = (index % 11) * 23;
return { x: 63 + offset, y: 63 + offset, width, height, angle: 0 };
}
const clamp = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, Math.round(value)));
export function moveFrame(frame, x, y) {
return { ...frame, x: clamp(x, minFrame - frame.width, pageWidth - minFrame), y: clamp(y, minFrame - frame.height, pageHeight - minFrame) };
}
export function resizeFrame(frame, corner, dx, dy) {
const west = corner.includes('w');
const north = corner.includes('n');
const width = clamp(frame.width + (west ? -dx : dx), minFrame, pageWidth * 2);
const height = clamp(frame.height + (north ? -dy : dy), minFrame, pageHeight * 2);
const radians = frame.angle * Math.PI / 180;
const dw = (west ? -1 : 1) * (width - frame.width) / 2;
const dh = (north ? -1 : 1) * (height - frame.height) / 2;
return {
...frame, width, height,
x: Math.round(frame.x + (frame.width - width) / 2 + dw * Math.cos(radians) - dh * Math.sin(radians)),
y: Math.round(frame.y + (frame.height - height) / 2 + dw * Math.sin(radians) + dh * Math.cos(radians)),
};
}
export function frameStyle(frame) {
return {
left: `${frame.x * 100 / pageWidth}%`, top: `${frame.y * 100 / pageHeight}%`,
width: `${frame.width * 100 / pageWidth}%`, height: `${frame.height * 100 / pageHeight}%`,
transform: frame.angle ? `rotate(${frame.angle}deg)` : undefined,
};
}
export function appearanceStyle(appearance = {}) {
return {
'--item-ink': appearance.color,
'--item-fill': appearance.fill,
'--item-font': fontFamilies[appearance.font],
'--item-size': appearance.fontSize === undefined ? undefined : designLength(appearance.fontSize),
'--item-weight': appearance.weight,
'--item-leading': appearance.leading,
'--item-tracking': appearance.tracking === undefined ? undefined : designLength(appearance.tracking),
'--item-fit': appearance.fit,
'--item-position': appearance.position,
'--item-border': appearance.stroke,
'--item-stroke': appearance.strokeWidth ? designLength(appearance.strokeWidth) : undefined,
'--item-radius': appearance.radius ? designLength(appearance.radius) : undefined,
opacity: appearance.opacity === undefined ? undefined : appearance.opacity / 100,
};
}
export function cssText(rules) {
return Object.entries(rules).filter(([, value]) => value !== undefined).map(([property, value]) => `${property}:${value}`).join(';');
}

39
shared/inline-html.js Normal file
View File

@ -0,0 +1,39 @@
import { parseFragment, serialize } from 'parse5';
const tags = new Set(`a abbr address article aside b bdi bdo blockquote br button caption cite code col colgroup
data dd del details dfn div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr
i img input ins kbd label legend li main mark meter nav ol optgroup option p picture pre progress q rp rt ruby s
samp section select small span strong style sub summary sup table tbody td textarea tfoot th thead time tr u ul var wbr
svg g path rect circle ellipse line polyline polygon defs lineargradient radialgradient stop text tspan`.split(/\s+/));
const attributes = new Set(`alt aria-hidden aria-label class colspan controls datetime dir fill for height id lang max min
multiple name open placeholder readonly reversed role rowspan scope selected start step style tabindex title type value width
viewbox d x y x1 y1 x2 y2 cx cy r rx ry points transform stroke stroke-width stroke-linecap stroke-linejoin fill-rule
offset stop-color stop-opacity gradientunits`.split(/\s+/));
function safeLink(value) {
try {
return ['http:', 'https:', 'mailto:', 'tel:'].includes(new URL(value).protocol);
} catch {
return false;
}
}
function clean(node) {
if (node.nodeName === '#text') return true;
if (!node.tagName || !tags.has(node.tagName.toLowerCase())) return false;
node.attrs = node.attrs.filter(({ name, value, namespace }) => {
if (namespace) return false;
if (name === 'href') return node.tagName === 'a' && safeLink(value);
if (name === 'src') return node.tagName === 'img' && /^data:image\/(png|jpeg|gif|webp|avif);base64,[a-z0-9+/=]+$/i.test(value);
return attributes.has(name.toLowerCase());
});
if (node.tagName === 'a') node.attrs.push({ name: 'target', value: '_blank' }, { name: 'rel', value: 'noopener noreferrer' });
node.childNodes = node.childNodes.filter(clean);
return true;
}
export function htmlDocument(markup) {
const tree = parseFragment(markup);
tree.childNodes = tree.childNodes.filter(clean);
return `<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; form-action 'none'; base-uri 'none'"><style>*{box-sizing:border-box}body{margin:0;font-family:Arial,sans-serif;overflow:hidden}img,svg{max-width:100%}a{color:inherit}</style></head><body>${serialize(tree)}</body></html>`;
}

112
shared/magazine.js Normal file
View File

@ -0,0 +1,112 @@
import QRCode from 'qrcode';
import { appearanceStyle, cssText, frameStyle, initialFrame } from './free-layout.js';
export const blockTypes = {
text: 'Text', image: 'Bild', gallery: 'Galerie', button: 'Button',
qr: 'QR-Code', video: 'Video', social: 'Social-Media-Link', shape: 'Form', html: 'HTML & CSS',
};
export function makeBlock(type) {
const defaults = {
text: { text: 'Hier steht dein Text.', style: 'body', align: 'left' },
image: { mediaId: '', alt: '', height: 46 },
gallery: { mediaIds: [], height: 29 },
button: { text: 'Mehr erfahren', url: '' },
qr: { text: '', url: '' },
video: { mediaId: '', posterMediaId: '', text: '' },
social: { text: 'Instagram', url: '' },
shape: { shape: 'rectangle', appearance: { fill: '#ddd7ff' } },
html: { markup: '<h2>Eigener Inhalt</h2>\n<p>Hier kannst du HTML und CSS einfügen.</p>' },
};
return { id: crypto.randomUUID(), type, width: 'full', ...defaults[type] };
}
export function makePage(title = 'Neue Seite') {
return { id: crypto.randomUUID(), title, layout: 'free', background: '#fffefa', color: '#20202b', blocks: [] };
}
export function escapeHtml(value = '') {
return String(value).replace(/[&<>"']/g, (character) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
})[character]);
}
export function safeUrl(value, webOnly = false) {
try {
const parsed = new URL(value);
return (webOnly ? ['https:', 'http:'] : ['https:', 'http:', 'mailto:', 'tel:']).includes(parsed.protocol)
? parsed.href : '';
} catch {
return '';
}
}
export function mediaRefs(draft) {
return [draft.cover, ...draft.pages.flatMap((page) => page.blocks.flatMap((block) =>
block.type === 'gallery' ? block.mediaIds : [block.mediaId, block.posterMediaId]))].filter(Boolean);
}
export function pageStyle(page) {
return `--paper:${page.background};--ink:${page.color}`;
}
export async function renderBlock(block, mediaUrl, forPdf = false) {
const text = escapeHtml(block.text);
const media = (id) => escapeHtml(mediaUrl(id));
const href = escapeHtml(safeUrl(block.url, block.type === 'social'));
const link = (label, kind) => href
? `<a class="folio-${kind}" href="${href}" target="_blank" rel="noopener noreferrer">${label}</a>`
: `<span class="folio-placeholder">${label || 'Link hinzufügen'}</span>`;
const placeholder = (label) => `<div class="folio-placeholder">${label}</div>`;
switch (block.type) {
case 'text': {
const tag = block.style === 'title' ? 'h1' : block.style === 'heading' ? 'h2' : 'p';
const align = ['left', 'center', 'right'].includes(block.align) ? block.align : 'left';
return `<${tag} class="folio-text folio-${block.style}" style="text-align:${align}">${text}</${tag}>`;
}
case 'image':
return block.mediaId
? `<img class="folio-image" src="${media(block.mediaId)}" alt="${escapeHtml(block.alt)}" style="height:${block.height}cqw">`
: placeholder('Bild auswählen');
case 'gallery':
return block.mediaIds.length
? `<div class="folio-gallery" style="--gallery-height:${block.height}cqw">${block.mediaIds.map((id, index) => `<img src="${media(id)}" alt="Galeriebild ${index + 1}">`).join('')}</div>`
: placeholder('Galeriebilder auswählen');
case 'button': return link(text, 'button');
case 'social': return link(text, 'social');
case 'shape': return `<div class="folio-shape folio-shape-${block.shape}" aria-hidden="true"></div>`;
case 'html': {
const { htmlDocument } = await import('./inline-html.js');
return `<iframe class="folio-html" title="HTML-Inhalt" sandbox="allow-popups allow-popups-to-escape-sandbox" srcdoc="${escapeHtml(htmlDocument(block.markup))}"></iframe>`;
}
case 'video': {
if (!block.mediaId) return placeholder('Video auswählen');
const poster = block.posterMediaId ? media(block.posterMediaId) : '';
return `<figure class="folio-video">${forPdf
? `<div class="folio-video-print">${poster ? `<img src="${poster}" alt="">` : ''}<span>Video in der Online-Ausgabe ansehen</span></div>`
: `<video controls playsinline preload="metadata" src="${media(block.mediaId)}"${poster ? ` poster="${poster}"` : ''} aria-label="${text || 'Video'}"></video>`}${text ? `<figcaption>${text}</figcaption>` : ''}</figure>`;
}
case 'qr':
if (!href) return placeholder('QR-Ziel eingeben');
return `<figure class="folio-qr"><img src="${await QRCode.toDataURL(safeUrl(block.url), { margin: 2, width: 384 })}" alt="QR-Code">${text ? `<figcaption>${text}</figcaption>` : ''}</figure>`;
default: return '';
}
}
export async function renderPages(draft, mediaUrl, forPdf = false) {
return Promise.all(draft.pages.map(async (page) => {
const blocks = await Promise.all(page.blocks.map(async (block, index) => {
const positioning = page.layout === 'free' ? ` style="${frameStyleText(block.frame || initialFrame(block.type, index))}"` : '';
return `<div class="folio-block folio-width-${block.width}"${positioning}><div class="folio-item-content" style="${escapeHtml(cssText(appearanceStyle(block.appearance)))}">${await renderBlock(block, mediaUrl, forPdf)}</div></div>`;
}));
return {
id: page.id, title: page.title,
html: `<article class="folio-page" style="${pageStyle(page)}" aria-label="${escapeHtml(page.title)}"><div class="folio-content folio-layout-${page.layout}">${blocks.join('')}</div></article>`,
};
}));
}
function frameStyleText(frame) {
return escapeHtml(cssText(frameStyle(frame)));
}

51
shared/publication.css Normal file
View File

@ -0,0 +1,51 @@
.folio-page { box-sizing: border-box; height: 100%; width: 100%; overflow: hidden; container-type: inline-size; color: var(--ink, #20202b); background: var(--paper, #fffefa); font-family: Arial, sans-serif; text-align: left; }
.folio-page *, .folio-page *::before, .folio-page *::after { box-sizing: border-box; }
.folio-content { display: grid; grid-template-columns: minmax(0, 1fr); align-content: start; gap: 4cqw; padding: 8cqw; min-height: 100%; }
.folio-layout-columns { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.folio-layout-cover { padding: 0; gap: 0; }
.folio-layout-cover > :not(:has(.folio-image)) { margin: 3cqw 8cqw; }
.folio-width-full { grid-column: 1 / -1; }
.folio-block { min-width: 0; }
.folio-text { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; font-size: 3.65cqw; line-height: 1.48; }
.folio-title, .folio-heading { font-family: Georgia, serif; font-weight: 500; letter-spacing: -.05em; line-height: 1.08; }
.folio-title { font-size: 10cqw; }
.folio-heading { font-size: 6.5cqw; }
.folio-caption { font-size: 2.65cqw; text-transform: uppercase; letter-spacing: .15em; }
.folio-image { width: 100%; display: block; object-fit: cover; }
.folio-gallery { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.3cqw; }
.folio-gallery img { display: block; object-fit: cover; width: 100%; height: var(--gallery-height, 29cqw); }
.folio-gallery img:only-child { grid-column: 1 / -1; }
.folio-button, .folio-social, .folio-placeholder { display: inline-block; font-size: 3.3cqw; overflow-wrap: anywhere; }
.folio-button { background: var(--ink, #20202b); color: var(--paper, #fffefa); border-radius: .8cqw; padding: 2.4cqw 3.2cqw; text-decoration: none; }
.folio-social { color: inherit; text-underline-offset: .4em; }
.folio-placeholder { background: #eae9f5; color: #555375; padding: 3cqw; border-radius: 1cqw; }
.folio-video, .folio-qr { margin: 0; font-size: 3cqw; }
.folio-video video, .folio-video-print { width: 100%; height: 48cqw; background: #191923; }
.folio-video video { display: block; object-fit: contain; }
.folio-video-print { display: grid; place-items: center; position: relative; isolation: isolate; padding: 3cqw; color: #fff; text-align: center; }
.folio-video-print img { display: block; position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }
.folio-video-print span { display: block; padding: 1.2cqw 2cqw; background: #191923d9; border-radius: .5cqw; }
.folio-qr img { width: 25cqw; display: block; }
.folio-video figcaption, .folio-qr figcaption { margin-top: 1.3cqw; }
.folio-item-content { color: var(--item-ink, inherit); background: var(--item-fill, transparent); border: var(--item-stroke, 0) solid var(--item-border, currentColor); border-radius: var(--item-radius, 0); }
.folio-layout-free { position: relative; height: 100%; padding: 0; display: block; overflow: hidden; }
.folio-layout-free > .folio-block { position: absolute; }
.folio-layout-free .folio-item-content { width: 100%; height: 100%; overflow: hidden; }
.folio-layout-free .folio-body { font-family: var(--item-font, Arial, sans-serif); font-size: var(--item-size, 3.65cqw); font-weight: var(--item-weight, 400); line-height: var(--item-leading, 1.48); letter-spacing: var(--item-tracking, normal); }
.folio-layout-free .folio-title, .folio-layout-free .folio-heading { font-family: var(--item-font, Georgia, serif); font-weight: var(--item-weight, 500); line-height: var(--item-leading, 1.08); letter-spacing: var(--item-tracking, -.05em); }
.folio-layout-free .folio-title { font-size: var(--item-size, 10cqw); }
.folio-layout-free .folio-heading { font-size: var(--item-size, 6.5cqw); }
.folio-layout-free .folio-caption { font-family: var(--item-font, Arial, sans-serif); font-size: var(--item-size, 2.65cqw); font-weight: var(--item-weight, 400); line-height: var(--item-leading, 1.48); letter-spacing: var(--item-tracking, .15em); }
.folio-layout-free .folio-image { height: 100% !important; object-fit: var(--item-fit, cover); object-position: var(--item-position, center); }
.folio-layout-free .folio-gallery { height: 100%; grid-auto-rows: minmax(0, 1fr); }
.folio-layout-free .folio-gallery img { height: 100%; object-fit: var(--item-fit, cover); object-position: var(--item-position, center); }
.folio-layout-free .folio-video, .folio-layout-free .folio-qr { display: flex; flex-direction: column; height: 100%; font-size: var(--item-size, 2.4cqw); }
.folio-layout-free .folio-video video, .folio-layout-free .folio-video-print { height: auto; flex: 1; min-height: 0; }
.folio-layout-free .folio-qr img { width: auto; max-width: 100%; flex: 1; min-height: 0; object-fit: contain; object-position: left center; }
.folio-layout-free .folio-button, .folio-layout-free .folio-social { font-family: var(--item-font, Arial, sans-serif); font-size: var(--item-size, 3.3cqw); font-weight: var(--item-weight, 500); }
.folio-layout-free .folio-button { display: grid; place-items: center; text-align: center; width: 100%; height: 100%; padding: .9cqw; background: var(--item-fill, var(--ink)); color: var(--item-ink, var(--paper)); }
.folio-shape, .folio-html { width: 100%; height: 100%; display: block; border: 0; }
.folio-shape-ellipse { border-radius: 100%; background: var(--item-fill, #ddd7ff); }
.folio-shape-line { position: relative; top: 37%; height: 26%; background: var(--item-fill, #ddd7ff); }
.folio-shape-rectangle { background: var(--item-fill, #ddd7ff); }
.folio-layout-free .folio-item-content:has(.folio-shape-ellipse, .folio-shape-line) { background: none; }

48
src/api.js Normal file
View File

@ -0,0 +1,48 @@
export async function api(path, options = {}) {
const request = { ...options, headers: { ...(path.startsWith('/admin/') && { 'X-Folio-Request': 'studio' }), ...options.headers } };
if (options.body !== undefined && !(options.body instanceof FormData)) {
request.headers['Content-Type'] = 'application/json';
request.body = JSON.stringify(options.body);
}
const res = await fetch(`/api${path}`, request);
if (res.status === 204) return null;
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error(data?.error || 'Die Verbindung zum Studio ist fehlgeschlagen.');
return data;
}
export const admin = (path, options) => api(`/admin${path}`, options);
export const mediaUrl = (id) => `/api/admin/media/${id}/file`;
export const formatNumber = (value) => new Intl.NumberFormat('de-DE').format(value);
export const formatDate = (value, withTime = false) => value ? new Intl.DateTimeFormat('de-DE', {
day: '2-digit', month: 'short', year: 'numeric', ...(withTime && { hour: '2-digit', minute: '2-digit' }),
}).format(new Date(value)) : '–';
export function bytesLabel(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 ** 2) return `${formatNumber(Math.round(bytes / 1024))} KB`;
if (bytes < 1024 ** 3) return `${formatNumber(Math.round(bytes / 1024 ** 2 * 10) / 10)} MB`;
return `${formatNumber(Math.round(bytes / 1024 ** 3 * 10) / 10)} GB`;
}
export function statusFor(magazine) {
if (magazine.job?.state === 'queued') return Date.parse(magazine.job.at) > Date.now() ? 'scheduled' : 'processing';
if (magazine.publishedAt) return 'published';
if (magazine.job?.state === 'failed') return 'failed';
return 'draft';
}
export const statusLabels = { published: 'Veröffentlicht', draft: 'Entwurf', scheduled: 'Geplant', processing: 'In Verarbeitung', failed: 'Fehlgeschlagen', cancelled: 'Abgebrochen', archived: 'Archiviert' };
export async function copyText(value) {
if (navigator.clipboard?.writeText) return navigator.clipboard.writeText(value);
const input = document.createElement('textarea');
input.value = value;
input.style.position = 'fixed';
input.style.opacity = '0';
document.body.appendChild(input);
input.select();
const copied = document.execCommand('copy');
input.remove();
if (!copied) throw new Error('Kopiere den Text aus dem Eingabefeld.');
}

173
src/dashboard.jsx Normal file
View File

@ -0,0 +1,173 @@
import { useMemo, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Activity, BookOpen, CalendarDays, CloudUpload, Copy, Download, ExternalLink, Eye, Globe2, HardDrive, Image, LayoutGrid, LibraryBig, Link2, List, Pencil, Plus, Search, Trash2 } from 'lucide-react';
import { admin, bytesLabel, copyText, formatDate, formatNumber, mediaUrl, statusFor, statusLabels } from './api.js';
import { Button, Dialog, Empty, ErrorMessage, Field, Menu } from './ui.jsx';
export const Badge = ({ status }) => <span className={`badge badge-${status}`}><i />{statusLabels[status] || status}</span>;
const filters = [['all', 'Alle Magazine'], ['published', 'Veröffentlicht'], ['draft', 'Entwürfe'], ['scheduled', 'Geplant']];
export function PageTitle({ title, description, children }) {
return <div className="page-title"><div><h1>{title}</h1><p>{description}</p></div>{children}</div>;
}
export function Metrics({ data }) {
const rows = data.magazines;
const metrics = [
{ label: 'Magazine', number: rows.length, detail: `${rows.filter((mag) => statusFor(mag) === 'draft').length} im Entwurf`, Icon: BookOpen, tone: 'purple' },
{ label: 'Veröffentlicht', number: rows.filter((mag) => mag.publishedAt).length, detail: `${rows.filter((mag) => statusFor(mag) === 'scheduled').length} geplant`, Icon: Globe2, tone: 'green' },
{ label: 'Aufrufe', number: rows.reduce((sum, mag) => sum + mag.views, 0), detail: 'Über alle Magazine', Icon: Eye, tone: 'blue' },
{ label: 'PDF-Downloads', number: rows.reduce((sum, mag) => sum + mag.downloads, 0), detail: 'Über alle Magazine', Icon: Download, tone: 'orange' },
];
return <section className="metrics" aria-label="Kennzahlen">{metrics.map(({ Icon, label, number, detail, tone }) =>
<div className="metric" key={label}><div className={`metric-icon tone-${tone}`}><Icon size={20} strokeWidth={1.85} /></div><div className="metric-label">{label}</div><strong>{formatNumber(number)}</strong><div className="metric-detail">{detail}</div></div>)}</section>;
}
function Cover({ magazine }) {
return <div className={`cover ${magazine.cover ? 'cover-photo' : 'cover-plain'} cover-${magazine.slug}`}>
{magazine.cover && <img src={mediaUrl(magazine.cover)} alt="" />}
<div className="cover-type"><span>{magazine.issue || 'Magazin'}</span><strong>{magazine.title}</strong></div>
</div>;
}
function MagazineActions({ magazine, remove, share, duplicate }) {
return <Menu label={`Aktionen für ${magazine.title}`}>
<Link to={`/magazine/${magazine.id}/editor`}><Pencil size={15} /> Bearbeiten</Link>
<button onClick={() => duplicate(magazine)}><Copy size={15} /> Als Vorlage kopieren</button>
{magazine.publishedAt && <a href={magazine.publicUrl} target="_blank" rel="noreferrer"><ExternalLink size={15} /> Ausgabe öffnen</a>}
{magazine.publishedAt && <button onClick={() => share(magazine)}><Link2 size={15} /> Link & Einbettung</button>}
<button className="menu-danger" onClick={() => remove(magazine)}><Trash2 size={15} /> In den Papierkorb</button>
</Menu>;
}
function MagazineCard({ magazine, remove, share, duplicate }) {
return <article className="mag-card">
<Link className="mag-cover-link" to={`/magazine/${magazine.id}/editor`} aria-label={`${magazine.title} bearbeiten`}><Cover magazine={magazine} /></Link>
<div className="mag-card-details">
<div className="mag-card-top"><Badge status={statusFor(magazine)} /><MagazineActions magazine={magazine} remove={remove} share={share} duplicate={duplicate} /></div>
<Link className="mag-title" to={`/magazine/${magazine.id}/editor`}>{magazine.title}</Link>
<p>{magazine.issue || 'Ohne Ausgabenbezeichnung'}</p>
<div className="mag-card-foot"><span><LibraryBig size={14} /> {magazine.pages.length} Seiten</span><span><CalendarDays size={14} /> {formatDate(magazine.updatedAt)}</span></div>
</div>
</article>;
}
export function ShareDialog({ magazine, close, notify }) {
const url = magazine?.publicUrl;
const embed = url ? `<iframe src="${url}?embed=1" title="${magazine.title.replace(/[&<>"]/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[character])}" width="100%" height="640" loading="lazy" allowfullscreen></iframe>` : '';
async function copy(value) {
try { await copyText(value); notify('In die Zwischenablage kopiert.'); } catch (error) { notify(error.message, true); }
}
return <Dialog title="Ausgabe teilen" description={magazine?.title} open={!!magazine} onOpenChange={(open) => !open && close()}>
<Field label="Öffentlicher Link"><input value={url || ''} readOnly onFocus={(ev) => ev.target.select()} /></Field>
<div className="inline-actions"><Button variant="outline" onClick={() => copy(url)}><Link2 size={16} /> Link kopieren</Button><Button asChild variant="ghost"><a href={url} target="_blank" rel="noreferrer"><ExternalLink size={16} /> Öffnen</a></Button></div>
<Field label="HTML zum Einbetten"><textarea value={embed} readOnly rows={4} onFocus={(ev) => ev.target.select()} /></Field>
<div className="dialog-actions"><Button onClick={() => copy(embed)}>Embed-Code kopieren</Button></div>
</Dialog>;
}
function ActivityPanel({ activities }) {
return <section className="panel activity-panel"><div className="panel-heading"><span className="panel-icon"><Activity size={18} /></span><div><h2>Letzte Aktivitäten</h2><p>Was im Studio zuletzt passiert ist</p></div></div>
{activities.length ? <ul className="activity-list">{activities.slice(0, 5).map((item) => <li key={item.id}><span className={`activity-dot activity-${item.kind}`} /><span>{item.message}</span><time dateTime={item.created_at}>{formatDate(item.created_at, true)}</time></li>)}</ul> : <p className="panel-empty">Noch keine Einträge.</p>}
</section>;
}
function StoragePanel({ storage }) {
return <section className="panel storage-panel"><div className="panel-heading"><span className="panel-icon"><HardDrive size={18} /></span><div><h2>Speicherverbrauch</h2><p>Medien und Ausgaben</p></div></div>
<strong>{bytesLabel(storage.bytes)}</strong><span>{storage.files} aktive Mediendateien</span>
<Button asChild variant="outline" size="sm"><Link to="/medien"><Image size={15} /> Medienbibliothek</Link></Button>
</section>;
}
export function Dashboard({ data, refresh, create, notify }) {
const navigate = useNavigate();
const [filter, setFilter] = useState('all');
const [query, setQuery] = useState('');
const [asList, setAsList] = useState(false);
const [sharing, setSharing] = useState(null);
const [removing, setRemoving] = useState(null);
const [busy, setBusy] = useState(false);
const magazines = useMemo(() => data.magazines.filter((mag) => {
const matches = filter === 'all' || (filter === 'published' ? !!mag.publishedAt : statusFor(mag) === filter);
return matches && `${mag.title} ${mag.issue} ${mag.description}`.toLocaleLowerCase('de').includes(query.trim().toLocaleLowerCase('de'));
}), [data, filter, query]);
async function remove() {
setBusy(true);
try {
await admin(`/magazines/${removing.id}`, { method: 'DELETE' });
await refresh(); setRemoving(null); notify('Magazin in den Papierkorb verschoben.');
} catch (error) { notify(error.message, true); } finally { setBusy(false); }
}
async function duplicate(magazine) {
try {
const copy = await admin(`/magazines/${magazine.id}/duplicate`, { method: 'POST' });
notify('Vorlage als Entwurf kopiert.');
navigate(`/magazine/${copy.id}/editor`);
} catch (error) { notify(error.message, true); }
}
return <>
<PageTitle title="Magazine" description="Erstelle, verwalte und veröffentliche deine digitalen Magazine."><Button onClick={create}><Plus size={19} /> Neues Magazin</Button></PageTitle>
<Metrics data={data} />
<section className="magazines-section">
<div className="section-heading"><h2>Deine Magazine</h2></div>
<div className="collection-toolbar">
<div className="tabs" aria-label="Magazine filtern">{filters.map(([value, label]) => <button key={value} className={filter === value ? 'tab active' : 'tab'} onClick={() => setFilter(value)} aria-pressed={filter === value}>{label}{value === 'all' && <span>{data.magazines.length}</span>}</button>)}</div>
<div className="toolbar-right"><label className="search-field"><Search size={17} /><input value={query} onChange={(ev) => setQuery(ev.target.value)} placeholder="Magazine suchen …" aria-label="Magazine suchen" /></label><div className="view-switch"><Button size="icon" variant="ghost" className={!asList ? 'selected' : ''} aria-pressed={!asList} aria-label="Rasteransicht" onClick={() => setAsList(false)}><LayoutGrid size={17} /></Button><Button size="icon" variant="ghost" className={asList ? 'selected' : ''} aria-pressed={asList} aria-label="Listenansicht" onClick={() => setAsList(true)}><List size={18} /></Button></div></div>
</div>
{!magazines.length ? <Empty icon={BookOpen} title={data.magazines.length ? 'Keine passenden Magazine' : 'Dein erstes Magazin'} text={data.magazines.length ? 'Passe die Suche oder den Filter an.' : 'Lege ein Magazin an und gestalte deine erste Ausgabe.'}>{!data.magazines.length && <Button onClick={create}><Plus size={17} /> Magazin anlegen</Button>}</Empty>
: asList ? <div className="table-wrap"><table><thead><tr><th>Magazin</th><th>Status</th><th>Seiten</th><th>Bearbeitet</th><th aria-label="Aktionen" /></tr></thead><tbody>{magazines.map((mag) => <tr key={mag.id}><td><Link className="table-link" to={`/magazine/${mag.id}/editor`}>{mag.title}</Link><small>{mag.issue}</small></td><td><Badge status={statusFor(mag)} /></td><td>{mag.pages.length}</td><td>{formatDate(mag.updatedAt)}</td><td><MagazineActions magazine={mag} remove={setRemoving} share={setSharing} duplicate={duplicate} /></td></tr>)}</tbody></table></div>
: <div className="mag-grid">{magazines.map((mag) => <MagazineCard key={mag.id} magazine={mag} remove={setRemoving} share={setSharing} duplicate={duplicate} />)}</div>}
</section>
<div className="dashboard-bottom"><ActivityPanel activities={data.activity} /><StoragePanel storage={data.storage} /></div>
<ShareDialog magazine={sharing} close={() => setSharing(null)} notify={notify} />
<Dialog title="Magazin in den Papierkorb verschieben?" description={removing ? `„${removing.title}“ lässt sich aus dem Papierkorb wiederherstellen.` : ''} open={!!removing} onOpenChange={(open) => !open && setRemoving(null)}>
<div className="dialog-actions"><Button variant="outline" onClick={() => setRemoving(null)}>Abbrechen</Button><Button variant="danger" onClick={remove} disabled={busy}><Trash2 size={16} /> Verschieben</Button></div>
</Dialog>
</>;
}
export function Publications({ data, notify, refresh }) {
const [sharing, setSharing] = useState(null);
const [cancel, setCancel] = useState(null);
const [busy, setBusy] = useState(false);
async function apply() {
setBusy(true);
try {
await admin(cancel.is_current ? `/magazines/${cancel.magazine_id}/publication` : `/releases/${cancel.id}`, { method: 'DELETE' });
await refresh(); setCancel(null); notify('Veröffentlichungen aktualisiert.');
} catch (error) { notify(error.message, true); } finally { setBusy(false); }
}
return <><PageTitle title="Veröffentlichungen" description="Verfolge geplante, laufende und abgeschlossene Ausgaben." />
{!data.publications.length ? <Empty icon={CloudUpload} title="Noch keine Veröffentlichungen" text="Starte die Veröffentlichung im Editor eines Magazins." /> : <div className="table-wrap"><table><thead><tr><th>Ausgabe</th><th>Status</th><th>Zeitpunkt</th><th>Version</th><th aria-label="Aktionen" /></tr></thead><tbody>{data.publications.map((release) => {
const status = release.state === 'ready' ? release.is_current ? 'published' : 'archived' : release.state === 'queued' ? Date.parse(release.publish_at) > Date.now() ? 'scheduled' : 'processing' : release.state;
const mag = data.magazines.find((item) => item.id === release.magazine_id);
return <tr key={release.id}><td><Link className="table-link" to={`/magazine/${release.magazine_id}/editor`}>{release.title}</Link>{release.error && <small className="table-error">{release.error}</small>}</td><td><Badge status={status} /></td><td>{formatDate(release.published_at || release.publish_at, true)}</td><td>Version {release.revision}</td><td>{(release.is_current || release.state === 'queued') && <Menu>{release.is_current && <button onClick={() => setSharing(mag)}><Link2 size={15} /> Link & Einbettung</button>}<button className="menu-danger" onClick={() => setCancel(release)}>{release.is_current ? 'Offline nehmen' : 'Abbrechen'}</button></Menu>}</td></tr>;
})}</tbody></table></div>}
<ShareDialog magazine={sharing} close={() => setSharing(null)} notify={notify} />
<Dialog title={cancel?.is_current ? 'Ausgabe offline nehmen?' : 'Veröffentlichung abbrechen?'} description={cancel?.title} open={!!cancel} onOpenChange={(open) => !open && setCancel(null)}><div className="dialog-actions"><Button variant="outline" onClick={() => setCancel(null)}>Zurück</Button><Button variant="danger" onClick={apply} disabled={busy}>Bestätigen</Button></div></Dialog>
</>;
}
export function Statistics({ data }) {
const sorted = [...data.magazines].sort((a, b) => b.views - a.views);
return <><PageTitle title="Statistiken" description="Aufrufe und PDF-Downloads pro Magazin. Die Zählung im Reader ist cookiefrei." /><Metrics data={data} />
<section className="statistics-section"><h2>Magazine im Überblick</h2>{sorted.length ? <div className="table-wrap"><table><thead><tr><th>Magazin</th><th>Aufrufe</th><th>PDF-Downloads</th><th>Status</th></tr></thead><tbody>{sorted.map((mag) => <tr key={mag.id}><td><Link className="table-link" to={`/magazine/${mag.id}/editor`}>{mag.title}</Link></td><td>{formatNumber(mag.views)}</td><td>{formatNumber(mag.downloads)}</td><td><Badge status={statusFor(mag)} /></td></tr>)}</tbody></table></div> : <Empty icon={Eye} title="Noch keine Aufrufzahlen" />}</section>
<div className="dashboard-bottom"><ActivityPanel activities={data.activity} /><StoragePanel storage={data.storage} /></div>
</>;
}
export function NewMagazine({ open, close, created }) {
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
async function submit(ev) {
ev.preventDefault(); setBusy(true); setError('');
const body = Object.fromEntries(new FormData(ev.currentTarget));
try { created(await admin('/magazines', { method: 'POST', body })); } catch (err) { setError(err.message); } finally { setBusy(false); }
}
return <Dialog title="Neues Magazin" description="Lege eine Ausgabe an und gestalte sie im Editor." open={open} onOpenChange={(state) => { if (!state) { setError(''); close(); } }}>
<form onSubmit={submit} className="dialog-form"><Field label="Magazintitel"><input name="title" placeholder="z. B. Weitblick" required maxLength={100} autoFocus /></Field><Field label="Ausgabenbezeichnung"><input name="issue" placeholder="z. B. Ausgabe 01 · Frühling" maxLength={100} /></Field><Field label="Beschreibung"><textarea name="description" placeholder="Worum geht es in dieser Ausgabe?" rows={3} maxLength={1000} /></Field><ErrorMessage>{error}</ErrorMessage><div className="dialog-actions"><Button variant="outline" onClick={close}>Abbrechen</Button><Button type="submit" disabled={busy}><Plus size={17} /> Magazin anlegen</Button></div></form>
</Dialog>;
}

255
src/editor.jsx Normal file
View File

@ -0,0 +1,255 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { AlignLeft, ArrowDown, ArrowLeft, ArrowUp, BookOpen, CalendarClock, ChevronDown, CircleHelp, CloudUpload, Code2, Eye, GripVertical, History, Image, Images, Link2, MousePointerClick, Plus, QrCode, Redo2, Save, Settings2, Square, Trash2, Undo2, Video } from 'lucide-react';
import { blockTypes, makeBlock, makePage } from '../shared/magazine.js';
import { initialFrame, moveFrame } from '../shared/free-layout.js';
import { admin, formatDate, statusFor } from './api.js';
import { Badge, ShareDialog } from './dashboard.jsx';
import { Layers, LayerStyles } from './element-style.jsx';
import { dragKey, FreeCanvas } from './free-canvas.jsx';
import { MediaPicker } from './media.jsx';
import { Preview } from './reader.jsx';
import { Button, Dialog, Empty, ErrorMessage, Field } from './ui.jsx';
const blockIcons = { text: AlignLeft, image: Image, gallery: Images, button: MousePointerClick, qr: QrCode, video: Video, social: Link2, shape: Square, html: Code2 };
const layoutOptions = [['single', 'Eine Spalte'], ['columns', 'Zwei Spalten'], ['cover', 'Randloses Motiv']];
const snapshot = ({ title, issue, description, cover, pages }) => ({ title, issue, description, cover, pages });
function move(items, from, to) {
if (from < 0 || to < 0 || from >= items.length || to >= items.length || from === to) return items;
const next = [...items];
const [entry] = next.splice(from, 1);
next.splice(to, 0, entry);
return next;
}
function startDrag(ev, type, value) {
ev.dataTransfer.effectAllowed = type === 'new' ? 'copy' : 'move';
ev.dataTransfer.setData(dragKey, JSON.stringify({ type, value }));
}
function getDrag(ev) {
try { return JSON.parse(ev.dataTransfer.getData(dragKey)); } catch { return null; }
}
function PageSettings({ page, update, convert }) {
return <>
<Field label="Seitentitel" hint="Wird im Inhaltsverzeichnis angezeigt."><input value={page.title} maxLength={100} onChange={(ev) => update({ title: ev.target.value })} /></Field>
{page.layout === 'free' ? <div className="free-layout-label"><MousePointerClick size={15} /> Freie Seitenfläche</div> : <><Field label="Seitenlayout"><select value={page.layout} onChange={(ev) => update({ layout: ev.target.value })}>{layoutOptions.map(([value, label]) => <option key={value} value={value}>{label}</option>)}</select></Field><Button variant="outline" onClick={convert}>Seite frei bearbeiten</Button></>}
<div className="color-settings"><Field label="Hintergrund"><input type="color" value={page.background} onChange={(ev) => update({ background: ev.target.value })} /></Field><Field label="Textfarbe"><input type="color" value={page.color} onChange={(ev) => update({ color: ev.target.value })} /></Field></div>
</>;
}
function BlockSettings({ block, page, update, pick, pickPoster }) {
const type = block.type;
return <>
{type === 'text' && <><Field label="Text"><textarea rows={6} value={block.text} maxLength={6000} onChange={(ev) => update({ text: ev.target.value })} /></Field>
<Field label="Textstil"><select value={block.style} onChange={(ev) => update({ style: ev.target.value })}><option value="body">Fließtext</option><option value="title">Titel</option><option value="heading">Überschrift</option><option value="caption">Kleine Überschrift</option></select></Field>
<Field label="Ausrichtung"><select value={block.align} onChange={(ev) => update({ align: ev.target.value })}><option value="left">Links</option><option value="center">Zentriert</option><option value="right">Rechts</option></select></Field></>}
{['image', 'video', 'gallery'].includes(type) && <Button variant="outline" onClick={pick}>{type === 'video' ? <Video size={16} /> : <Image size={16} />}{type === 'gallery' ? `${block.mediaIds.length} Bilder auswählen` : block.mediaId ? `${blockTypes[type]} ersetzen` : `${blockTypes[type]} auswählen`}</Button>}
{type === 'video' && <div className="inline-actions"><Button variant="outline" size="sm" onClick={pickPoster}><Image size={15} /> {block.posterMediaId ? 'Standbild ersetzen' : 'Standbild wählen'}</Button>{block.posterMediaId && <Button variant="ghost" size="sm" onClick={() => update({ posterMediaId: '' })}>Entfernen</Button>}</div>}
{type === 'image' && <Field label="Alternativtext"><input value={block.alt} maxLength={200} onChange={(ev) => update({ alt: ev.target.value })} /></Field>}
{page.layout !== 'free' && ['image', 'gallery'].includes(type) && <Field label={`Bildhöhe · ${block.height} % der Seitenbreite`}><input type="range" min="12" max={type === 'image' ? 135 : 100} value={block.height} onChange={(ev) => update({ height: Number(ev.target.value) })} /></Field>}
{['button', 'qr', 'video', 'social'].includes(type) && <Field label="Beschriftung"><input value={block.text} maxLength={200} onChange={(ev) => update({ text: ev.target.value })} /></Field>}
{['button', 'qr', 'social'].includes(type) && <Field label="Ziel-URL"><input value={block.url} type="url" maxLength={500} placeholder="https://…" onChange={(ev) => update({ url: ev.target.value })} /></Field>}
{page.layout === 'columns' && <Field label="Breite"><select value={block.width} onChange={(ev) => update({ width: ev.target.value })}><option value="full">Über beide Spalten</option><option value="half">Eine Spalte</option></select></Field>}
{type === 'shape' && <Field label="Form"><select value={block.shape} onChange={(ev) => update({ shape: ev.target.value })}><option value="rectangle">Rechteck</option><option value="ellipse">Ellipse</option><option value="line">Linie</option></select></Field>}
{type === 'html' && <Field label="HTML & CSS" hint="HTML und CSS innerhalb des Rahmens. Nutze Stilregeln oder einen <style>-Block."><textarea className="html-source" rows={9} spellCheck={false} maxLength={60000} value={block.markup} onChange={(ev) => update({ markup: ev.target.value })} /></Field>}
{page.layout === 'free' && <LayerStyles block={block} page={page} update={update} />}
</>;
}
export function Editor({ notify, refreshDashboard, dashboard }) {
const { id } = useParams();
const navigate = useNavigate();
const [saved, setSaved] = useState(null);
const [editor, setEditor] = useState({ draft: null, past: [], future: [] });
const { draft, past, future } = editor;
const convertRef = useRef(null);
const [pageId, setPageId] = useState(null);
const [blockId, setBlockId] = useState(null);
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const savingGate = useRef(false);
const [preview, setPreview] = useState(null);
const [picker, setPicker] = useState(null);
const [details, setDetails] = useState(false);
const [versions, setVersions] = useState(null);
const [versionError, setVersionError] = useState('');
const [publishing, setPublishing] = useState(false);
const [share, setShare] = useState(false);
const [publishMode, setPublishMode] = useState('now');
const [publishTime, setPublishTime] = useState('');
const [publishError, setPublishError] = useState('');
const [leaving, setLeaving] = useState(false);
const [removePage, setRemovePage] = useState(null);
const [busy, setBusy] = useState(false);
const dirty = !!saved && JSON.stringify(snapshot(saved)) !== JSON.stringify(draft);
const page = draft?.pages.find((item) => item.id === pageId) || draft?.pages[0];
const block = page?.blocks.find((item) => item.id === blockId);
const status = dashboard?.magazines.find((item) => item.id === id) || saved;
useEffect(() => {
const controller = new AbortController();
admin(`/magazines/${id}`, { signal: controller.signal }).then((mag) => {
setSaved(mag); setEditor({ draft: snapshot(mag), past: [], future: [] }); setPageId(mag.pages[0]?.id);
}).catch((err) => { if (!controller.signal.aborted) setError(err.message); });
return () => controller.abort();
}, [id]);
useEffect(() => {
if (!dirty) return;
const protect = (ev) => { ev.preventDefault(); ev.returnValue = ''; };
window.addEventListener('beforeunload', protect);
return () => window.removeEventListener('beforeunload', protect);
}, [dirty]);
async function saveDraft(showNotice = true) {
if (savingGate.current) throw new Error('Der Entwurf wird bereits gespeichert.');
if (!dirty) return saved;
savingGate.current = true; setSaving(true);
try {
const result = await admin(`/magazines/${id}`, { method: 'PUT', body: { revision: saved.revision, draft } });
setSaved(result);
setEditor((current) => current.draft === draft ? { ...current, draft: snapshot(result) } : current);
void refreshDashboard();
if (showNotice) notify('Entwurf gespeichert.');
return result;
} finally { savingGate.current = false; setSaving(false); }
}
function store() { void saveDraft().catch((err) => notify(err.message, true)); }
function undo() {
setEditor((current) => current.past.length ? { draft: current.past.at(-1), past: current.past.slice(0, -1), future: [current.draft, ...current.future] } : current);
}
function redo() {
setEditor((current) => current.future.length ? { draft: current.future[0], past: [...current.past, current.draft], future: current.future.slice(1) } : current);
}
useEffect(() => {
const shortcut = (ev) => {
if (!draft || !(ev.ctrlKey || ev.metaKey)) return;
const key = ev.key.toLowerCase();
if (key === 's') { ev.preventDefault(); store(); }
if (['z', 'y'].includes(key) && !ev.target.closest?.('input,textarea,select,[contenteditable]')) {
ev.preventDefault(); if (ev.shiftKey || key === 'y') redo(); else undo();
}
};
window.addEventListener('keydown', shortcut);
return () => window.removeEventListener('keydown', shortcut);
});
function changeDraft(update) {
setEditor((current) => {
const next = update(current.draft);
if (JSON.stringify(next) === JSON.stringify(current.draft)) return current;
return { draft: next, past: [...current.past.slice(-49), current.draft], future: [] };
});
}
const patchDraft = (fields) => changeDraft((active) => ({ ...active, ...fields }));
function updatePage(fields) {
changeDraft((active) => ({ ...active, pages: active.pages.map((item) => item.id === page.id ? { ...item, ...fields } : item) }));
}
function updateBlock(fields) {
updatePage({ blocks: page.blocks.map((item) => item.id === blockId ? { ...item, ...fields } : item) });
}
function choosePage(item) { setPageId(item?.id); setBlockId(null); }
function newPage() {
if (draft.pages.length >= 120) { notify('Ein Magazin kann bis zu 120 Seiten haben.', true); return; }
const item = makePage(`Seite ${draft.pages.length + 1}`);
patchDraft({ pages: [...draft.pages, item] }); choosePage(item);
}
function addBlock(type, position, source) {
if (!page || !blockTypes[type]) return;
if (page.blocks.length >= 60) { notify('Eine Seite kann bis zu 60 Elemente enthalten.', true); return; }
const item = makeBlock(type);
const document = source || convertRef.current?.() || page;
const frame = initialFrame(type, document.blocks.length);
item.frame = position ? moveFrame(frame, position.x - Math.min(30, frame.width / 2), position.y - Math.min(20, frame.height / 2)) : frame;
updatePage({ ...document, layout: 'free', blocks: [...document.blocks, item] }); setBlockId(item.id);
}
function duplicateBlock() {
if (page.blocks.length >= 60) { notify('Eine Seite kann bis zu 60 Elemente enthalten.', true); return; }
const document = convertRef.current?.() || page;
const original = document.blocks.find((item) => item.id === blockId);
const frame = original.frame || initialFrame(original.type);
const copy = { ...original, id: crypto.randomUUID(), frame: moveFrame(frame, frame.x + 16, frame.y + 16) };
updatePage({ ...document, blocks: [...document.blocks, copy] }); setBlockId(copy.id);
}
function deletePage() {
const current = draft.pages.findIndex((item) => item.id === removePage.id);
const pages = draft.pages.filter((item) => item.id !== removePage.id);
patchDraft({ pages }); setRemovePage(null); choosePage(pages[Math.min(current, pages.length - 1)]);
}
async function openPreview(content = draft) {
setBusy(true);
try { setPreview(await admin(`/magazines/${id}/preview`, { method: 'POST', body: content })); } catch (err) { notify(err.message, true); } finally { setBusy(false); }
}
async function openVersions() {
setVersions([]); setVersionError('');
try { setVersions(await admin(`/magazines/${id}/versions`)); } catch (err) { setVersionError(err.message); }
}
async function restore(version) {
setBusy(true); setVersionError('');
try {
const mag = await admin(`/magazines/${id}/versions/${version}/restore`, { method: 'POST', body: { revision: saved.revision } });
setSaved(mag); setEditor({ draft: snapshot(mag), past: [], future: [] }); choosePage(mag.pages[0]); setVersions(null); void refreshDashboard(); notify(`Version ${version} wiederhergestellt.`);
} catch (err) { setVersionError(err.message); } finally { setBusy(false); }
}
async function publish(ev) {
ev.preventDefault(); setBusy(true); setPublishError('');
try {
const at = publishMode === 'schedule' ? new Date(publishTime).toISOString() : null;
const mag = await saveDraft(false);
await admin(`/magazines/${id}/releases`, { method: 'POST', body: { at, revision: mag.revision } });
await refreshDashboard(); setPublishing(false); notify(at ? 'Veröffentlichung eingeplant.' : 'Ausgabe wird für die Veröffentlichung verarbeitet.');
} catch (err) { setPublishError(err.message); } finally { setBusy(false); }
}
if (!draft) return <div className="reader-loading"><Empty icon={BookOpen} title={error || 'Editor wird geladen …'}><Button asChild variant="outline"><Link to="/">Zurück zu den Magazinen</Link></Button></Empty></div>;
const activePage = draft.pages.findIndex((item) => item.id === page?.id);
const pickerInitial = picker === 'cover' ? [draft.cover] : picker === 'poster' ? [block?.posterMediaId] : picker === 'gallery' ? block?.mediaIds : [block?.mediaId];
return <div className="editor">
<header className="editor-header">
<Button size="icon" variant="ghost" aria-label="Zurück zu den Magazinen" onClick={() => dirty ? setLeaving(true) : navigate('/')}><ArrowLeft size={20} /></Button>
<div className="editor-heading"><button onClick={() => setDetails(true)} title="Magazin-Einstellungen" className="editor-title">{draft.title || 'Magazin'}<ChevronDown size={15} /></button><div className="editor-meta"><Badge status={statusFor(status)} /><span>{dirty ? 'Ungespeichert' : `Version ${saved.revision}`}</span></div></div>
<div className="editor-header-actions"><Button variant="ghost" size="icon" title="Rückgängig" aria-label="Rückgängig" disabled={!past.length} onClick={undo}><Undo2 size={18} /></Button><Button variant="ghost" size="icon" title="Wiederholen" aria-label="Wiederholen" disabled={!future.length} onClick={redo}><Redo2 size={18} /></Button><Button variant="ghost" size="icon" title="Versionen" aria-label="Versionen" onClick={openVersions}><History size={19} /></Button>{status.publishedAt && <Button variant="ghost" size="icon" title="Link & Einbettung" aria-label="Link & Einbettung" onClick={() => setShare(true)}><Link2 size={19} /></Button>}<Button variant="outline" onClick={() => openPreview()} disabled={busy}><Eye size={17} /><span>Vorschau</span></Button><Button variant="outline" onClick={store} disabled={!dirty || saving}><Save size={17} /><span>{saving ? 'Speichert …' : 'Entwurf speichern'}</span></Button><Button onClick={() => { setPublishing(true); setPublishError(''); }} disabled={saving}><CloudUpload size={18} /><span>Veröffentlichen</span></Button></div>
</header>
{status.job?.state === 'failed' && <div className="editor-warning"><ErrorMessage>{status.job.error}</ErrorMessage></div>}
<div className="editor-body">
<aside className="editor-left">
<div className="editor-panel-header"><h2>Seiten <span>{draft.pages.length}</span></h2><Button size="icon" variant="ghost" title="Seite hinzufügen" aria-label="Seite hinzufügen" onClick={newPage}><Plus size={19} /></Button></div>
<div className="editor-pages">{draft.pages.map((item, index) => <div key={item.id} className={`editor-page-row ${page?.id === item.id ? 'active' : ''}`} onDragOver={(ev) => { if (ev.dataTransfer.types.includes(dragKey)) ev.preventDefault(); }} onDrop={(ev) => {
ev.preventDefault(); const drag = getDrag(ev);
if (drag?.type === 'page') patchDraft({ pages: move(draft.pages, draft.pages.findIndex((entry) => entry.id === drag.value), index) });
}}><span className="page-grip" draggable onDragStart={(ev) => startDrag(ev, 'page', item.id)} title="Seite ziehen"><GripVertical size={15} /></span><button className="editor-page-button" onClick={() => choosePage(item)} aria-pressed={page?.id === item.id}><span>{index + 1}</span>{item.title || 'Ohne Titel'}</button></div>)}</div>
{page && <div className="page-order"><Button size="icon" variant="ghost" aria-label="Seite nach oben" title="Seite nach oben" disabled={activePage <= 0} onClick={() => patchDraft({ pages: move(draft.pages, activePage, activePage - 1) })}><ArrowUp size={15} /></Button><Button size="icon" variant="ghost" aria-label="Seite nach unten" title="Seite nach unten" disabled={activePage === draft.pages.length - 1} onClick={() => patchDraft({ pages: move(draft.pages, activePage, activePage + 1) })}><ArrowDown size={15} /></Button><Button size="icon" variant="ghost" aria-label="Seite entfernen" title="Seite entfernen" className="danger-text" onClick={() => setRemovePage(page)}><Trash2 size={16} /></Button></div>}
<div className="editor-panel-header elements-heading"><h2>Elemente</h2></div><div className="elements-grid">{Object.entries(blockTypes).map(([type, label]) => { const Icon = blockIcons[type]; return <button key={type} className="element-tile" disabled={!page} draggable={!!page} onDragStart={(ev) => startDrag(ev, 'new', type)} onClick={() => addBlock(type)}><Icon size={18} /><span>{label}</span></button>; })}</div>
<p className="editor-tip"><CircleHelp size={15} /> Elemente ziehen. Pfeiltasten verschieben sie um 1 px.</p>
</aside>
<FreeCanvas page={page} number={activePage + 1} blockId={blockId} select={setBlockId} commit={updatePage} add={addBlock} addPage={newPage} convertRef={convertRef} />
<aside className="editor-inspector">
{page && <Layers key={page.id} page={page} blockId={blockId} select={setBlockId} shift={(from, to) => {
const document = convertRef.current?.() || page;
updatePage({ ...document, blocks: move(document.blocks, from, to) });
}} duplicate={duplicateBlock} remove={() => { updatePage({ blocks: page.blocks.filter((item) => item.id !== blockId) }); setBlockId(null); }} />}
<div className="editor-panel-header"><h2>{block ? blockTypes[block.type] : 'Seiteneinstellungen'}</h2>{block && <Button size="icon" variant="ghost" aria-label="Seiteneinstellungen" title="Seiteneinstellungen" onClick={() => setBlockId(null)}><Settings2 size={17} /></Button>}</div>
<div className="inspector-body">{block ? <BlockSettings key={block.id} block={block} page={page} update={updateBlock} pick={() => setPicker(block.type)} pickPoster={() => setPicker('poster')} /> : page ? <PageSettings page={page} update={updatePage} convert={() => { const document = convertRef.current?.(); if (document) updatePage(document); }} /> : <p>Lege eine Seite an, um ihr Layout zu bearbeiten.</p>}</div>
</aside>
</div>
{picker && <MediaPicker kind={['cover', 'poster'].includes(picker) ? 'image' : picker} initial={(pickerInitial || []).filter(Boolean)} close={() => setPicker(null)} select={(ids) => { if (picker === 'cover') patchDraft({ cover: ids[0] }); else updateBlock(picker === 'gallery' ? { mediaIds: ids } : picker === 'poster' ? { posterMediaId: ids[0] } : { mediaId: ids[0] }); setPicker(null); }} />}
<Preview book={preview} close={() => setPreview(null)} />
<ShareDialog magazine={share ? status : null} close={() => setShare(false)} notify={notify} />
<Dialog title="Magazin-Einstellungen" open={details && picker !== 'cover'} onOpenChange={(open) => !open && setDetails(false)}>
<div className="dialog-form"><Field label="Titel"><input value={draft.title} maxLength={100} onChange={(ev) => patchDraft({ title: ev.target.value })} /></Field><Field label="Ausgabenbezeichnung"><input value={draft.issue} maxLength={100} onChange={(ev) => patchDraft({ issue: ev.target.value })} /></Field><Field label="Beschreibung"><textarea rows={3} value={draft.description} maxLength={1000} onChange={(ev) => patchDraft({ description: ev.target.value })} /></Field><div className="inline-actions"><Button variant="outline" onClick={() => setPicker('cover')}><Image size={16} /> {draft.cover ? 'Cover ersetzen' : 'Cover auswählen'}</Button>{draft.cover && <Button variant="ghost" onClick={() => patchDraft({ cover: '' })}>Cover entfernen</Button>}</div><div className="dialog-actions"><Button onClick={() => setDetails(false)}>Fertig</Button></div></div>
</Dialog>
<Dialog title="Versionsverlauf" description={dirty ? 'Beim Wiederherstellen gehen die ungespeicherten Änderungen verloren.' : 'Eine Wiederherstellung erstellt eine neue Entwurfsversion.'} open={versions !== null} onOpenChange={(open) => !open && setVersions(null)} className="dialog-wide">
<ErrorMessage>{versionError}</ErrorMessage><div className="versions-list">{versions?.map((version) => <div key={version.revision}><History size={17} /><div><strong>Version {version.revision}</strong><small>{version.reason} · {formatDate(version.created_at, true)}</small></div><Button size="icon" variant="ghost" title="Version ansehen" aria-label={`Version ${version.revision} ansehen`} onClick={() => { setVersions(null); void openPreview(version.draft); }}><Eye size={18} /></Button><Button size="sm" variant="outline" disabled={busy || version.revision === saved.revision} onClick={() => restore(version.revision)}>{version.revision === saved.revision ? 'Aktuell' : 'Wiederherstellen'}</Button></div>)}{!versions?.length && !versionError && <p>Versionen werden geladen …</p>}</div>
</Dialog>
<Dialog title="Ausgabe veröffentlichen" description={dirty ? 'Der aktuelle Entwurf wird vor der Veröffentlichung gespeichert.' : `Version ${saved.revision} wird als Flipbook und PDF bereitgestellt.`} open={publishing} onOpenChange={(open) => !open && !busy && setPublishing(false)}>
<form className="dialog-form" onSubmit={publish}><div className="publish-options"><label><input type="radio" name="schedule" checked={publishMode === 'now'} onChange={() => setPublishMode('now')} /><CloudUpload size={19} /><span><strong>Jetzt veröffentlichen</strong><small>Die Ausgabe wird nach der Verarbeitung sichtbar.</small></span></label><label><input type="radio" name="schedule" checked={publishMode === 'schedule'} onChange={() => setPublishMode('schedule')} /><CalendarClock size={19} /><span><strong>Veröffentlichung planen</strong><small>Datum und Uhrzeit festlegen.</small></span></label></div>{publishMode === 'schedule' && <Field label="Datum und Uhrzeit" hint="Die Zeitzone dieses Geräts wird verwendet."><input type="datetime-local" required value={publishTime} onChange={(ev) => setPublishTime(ev.target.value)} /></Field>}<ErrorMessage>{publishError}</ErrorMessage><div className="dialog-actions"><Button variant="outline" disabled={busy} onClick={() => setPublishing(false)}>Abbrechen</Button><Button type="submit" disabled={busy}>{busy ? 'Wird vorbereitet …' : publishMode === 'now' ? 'Veröffentlichen' : 'Einplanen'}</Button></div></form>
</Dialog>
<Dialog title="Editor verlassen?" description="Dein Entwurf hat ungespeicherte Änderungen." open={leaving} onOpenChange={setLeaving}><div className="dialog-actions"><Button variant="ghost" onClick={() => setLeaving(false)}>Weiter bearbeiten</Button><Button variant="outline" onClick={() => navigate('/')}>Verwerfen</Button><Button disabled={saving} onClick={() => saveDraft(false).then(() => navigate('/')).catch((err) => notify(err.message, true))}>Speichern und verlassen</Button></div></Dialog>
<Dialog title="Seite entfernen?" description={removePage ? `„${removePage.title}“ wandert beim Speichern in den Papierkorb.` : ''} open={!!removePage} onOpenChange={(open) => !open && setRemovePage(null)}><div className="dialog-actions"><Button variant="outline" onClick={() => setRemovePage(null)}>Abbrechen</Button><Button variant="danger" onClick={deletePage}>Seite entfernen</Button></div></Dialog>
</div>;
}

49
src/element-style.jsx Normal file
View File

@ -0,0 +1,49 @@
import { ArrowDown, ArrowDownToLine, ArrowUp, ArrowUpToLine, Copy, Layers3, Trash2 } from 'lucide-react';
import { blockTypes } from '../shared/magazine.js';
import { initialFrame } from '../shared/free-layout.js';
import { Button, Field } from './ui.jsx';
function OptionalNumber({ label, value, update, min, max, step = 1, placeholder = 'Auto' }) {
return <Field label={label}><input type="number" value={value ?? ''} placeholder={placeholder} min={min} max={max} step={step}
onChange={(ev) => update(ev.target.value === '' ? undefined : Math.min(max, Math.max(min, Number(ev.target.value))))} /></Field>;
}
export function LayerStyles({ block, page, update }) {
const appearance = block.appearance || {};
const frame = block.frame || initialFrame(block.type, page.blocks.findIndex((item) => item.id === block.id));
const set = (key, value) => update({ appearance: { ...appearance, [key]: value } });
const typography = ['text', 'button', 'social', 'qr', 'video'].includes(block.type);
const names = { x: 'X', y: 'Y', width: 'Breite', height: 'Höhe', angle: 'Drehung (°)' };
const colorFields = [['color', 'Textfarbe'], ['fill', 'Fläche'], ['stroke', 'Kontur']].filter(([key]) => typography || key !== 'color');
return <>
<details className="inspector-section" open={block.type === 'shape' || undefined}><summary>Stil</summary><div className="inspector-options">
{typography && <><Field label="Schrift"><select value={appearance.font || ''} onChange={(ev) => set('font', ev.target.value || undefined)}><option value="">Standard</option><option value="sans">Serifenlos</option><option value="serif">Serifen</option><option value="mono">Monospace</option></select></Field>
<div className="inspector-grid"><OptionalNumber label="Schriftgröße" value={appearance.fontSize} update={(value) => set('fontSize', value)} min={6} max={360} /><Field label="Schriftgewicht"><select value={appearance.weight ?? ''} onChange={(ev) => set('weight', ev.target.value ? Number(ev.target.value) : undefined)}><option value="">Standard</option><option value="400">Normal</option><option value="500">Medium</option><option value="700">Fett</option><option value="900">Schwarz</option></select></Field></div>
{block.type === 'text' && <div className="inspector-grid"><OptionalNumber label="Zeilenhöhe" value={appearance.leading} update={(value) => set('leading', value)} min={.5} max={4} step={.05} /><OptionalNumber label="Zeichenabstand" value={appearance.tracking} update={(value) => set('tracking', value)} min={-40} max={75} /></div>}
</>}
{['image', 'gallery'].includes(block.type) && <><Field label="Bildausschnitt"><select value={appearance.fit || 'cover'} onChange={(ev) => set('fit', ev.target.value)}><option value="cover">Rahmen füllen</option><option value="contain">Ganzes Bild</option><option value="fill">Strecken</option></select></Field><Field label="Motiv ausrichten"><select value={appearance.position || 'center'} onChange={(ev) => set('position', ev.target.value)}><option value="center">Mitte</option><option value="top">Oben</option><option value="bottom">Unten</option><option value="left">Links</option><option value="right">Rechts</option></select></Field></>}
<div className="layer-colors">{colorFields.map(([key, label]) => <div key={key}><Field label={label}><input type="color" value={appearance[key] || (key === 'color' ? page.color : '#ffffff')} onChange={(ev) => set(key, ev.target.value)} /></Field>{appearance[key] && <button className="field-clear" onClick={() => set(key, undefined)}>Zurücksetzen</button>}</div>)}</div>
<div className="inspector-grid"><OptionalNumber label="Konturbreite" value={appearance.strokeWidth} update={(value) => set('strokeWidth', value)} min={0} max={100} /><OptionalNumber label="Eckenradius" value={appearance.radius} update={(value) => set('radius', value)} min={0} max={800} /></div>
<Field label={`Deckkraft · ${appearance.opacity ?? 100} %`}><input type="range" min="0" max="100" value={appearance.opacity ?? 100} onChange={(ev) => set('opacity', Number(ev.target.value))} /></Field>
</div></details>
<details className="inspector-section"><summary>Position & Größe</summary><div className="inspector-grid inspector-options">{[['x', -5000, 5000], ['y', -5000, 5000], ['width', 12, 1588], ['height', 12, 2244], ['angle', -180, 180]].map(([key, min, max]) =>
<OptionalNumber key={key} label={names[key]} value={frame[key]} update={(value) => { if (value !== undefined) update({ frame: { ...frame, [key]: Math.round(value) } }); }} min={min} max={max} />)}</div></details>
</>;
}
export function Layers({ page, blockId, select, shift, duplicate, remove }) {
const index = page.blocks.findIndex((item) => item.id === blockId);
const buttons = [
[ArrowUp, 'Eine Ebene nach vorn', index + 1, index === page.blocks.length - 1],
[ArrowDown, 'Eine Ebene nach hinten', index - 1, index === 0],
[ArrowUpToLine, 'Ganz nach vorn', page.blocks.length - 1, index === page.blocks.length - 1],
[ArrowDownToLine, 'Ganz nach hinten', 0, index === 0],
];
return <section className="layers"><div className="editor-panel-header"><h2><Layers3 size={16} /> Ebenen <span>{page.blocks.length}</span></h2></div>
<div className="layers-list">{page.blocks.slice().reverse().map((item) => {
const title = item.text?.trim().split('\n')[0] || item.alt || blockTypes[item.type];
return <button key={item.id} type="button" className={item.id === blockId ? 'active' : ''} aria-pressed={item.id === blockId} title={title} onClick={() => select(item.id)}><strong>{title}</strong><small>{blockTypes[item.type]}</small></button>;
})}{!page.blocks.length && <small>Noch keine Elemente.</small>}</div>
{index >= 0 && <div className="layers-actions">{buttons.map(([Icon, label, target, disabled]) => <Button key={label} size="icon" variant="ghost" aria-label={label} title={label} disabled={disabled} onClick={() => shift(index, target)}><Icon size={15} /></Button>)}<Button size="icon" variant="ghost" aria-label="Element duplizieren" title="Element duplizieren" onClick={duplicate}><Copy size={15} /></Button><Button size="icon" variant="ghost" className="danger-text" aria-label="Element entfernen" title="Element entfernen" onClick={remove}><Trash2 size={15} /></Button></div>}
</section>;
}

183
src/free-canvas.jsx Normal file
View File

@ -0,0 +1,183 @@
import { memo, useEffect, useRef, useState } from 'react';
import { FileText, Minus, Plus, RotateCw } from 'lucide-react';
import { blockTypes, renderBlock } from '../shared/magazine.js';
import { appearanceStyle, frameStyle, initialFrame, moveFrame, pageHeight, pageWidth, resizeFrame } from '../shared/free-layout.js';
import { mediaUrl } from './api.js';
import { Button, Empty } from './ui.jsx';
export const dragKey = 'application/x-folio-editor';
const corners = { nw: 'oben links', ne: 'oben rechts', sw: 'unten links', se: 'unten rechts' };
const CanvasContent = memo(function CanvasContent({ block }) {
const [html, setHtml] = useState('');
useEffect(() => {
let active = true;
renderBlock(block, mediaUrl).then((value) => { if (active) setHtml(value); }).catch(() => {
if (active) setHtml('<div class="folio-placeholder">Element kann nicht angezeigt werden.</div>');
});
return () => { active = false; };
}, [block]);
return <div className="folio-item-content" style={appearanceStyle(block.appearance)} inert dangerouslySetInnerHTML={{ __html: html }} />;
});
function StoryText({ block, close, save }) {
return <textarea className={`canvas-inline-text folio-text folio-${block.style}`} aria-label="Text direkt bearbeiten" autoFocus defaultValue={block.text} maxLength={6000}
style={{ ...appearanceStyle(block.appearance), textAlign: block.align }}
onPointerDown={(ev) => ev.stopPropagation()}
onKeyDown={(ev) => {
if (ev.key === 'Escape') { ev.preventDefault(); close(); }
if ((ev.ctrlKey || ev.metaKey) && ev.key === 'Enter') { ev.preventDefault(); save(ev.currentTarget.value); }
}}
onBlur={(ev) => save(ev.target.value)} />;
}
export function FreeCanvas({ page, number, blockId, select, commit, add, addPage, convertRef }) {
const paper = useRef(null);
const gesture = useRef(null);
const lastClick = useRef(null);
const [livePage, setLivePage] = useState(null);
const [inline, setInline] = useState(null);
const [zoom, setZoom] = useState(100);
const visiblePage = livePage || page;
const free = visiblePage?.layout === 'free';
const activeBlock = visiblePage?.blocks.find((block) => block.id === blockId);
function freePage() {
if (page.layout === 'free') return {
...page, blocks: page.blocks.map((block, index) => block.frame ? block : { ...block, frame: initialFrame(block.type, index) }),
};
const bounds = paper.current.getBoundingClientRect();
const scale = pageWidth / bounds.width;
const elements = new Map([...paper.current.querySelectorAll('[data-canvas-block]')].map((node) => [node.dataset.canvasBlock, node]));
return { ...page, layout: 'free', blocks: page.blocks.map((block, index) => {
const rect = elements.get(block.id)?.getBoundingClientRect();
const frame = rect?.width ? { x: Math.round((rect.left - bounds.left) * scale), y: Math.round((rect.top - bounds.top) * scale),
width: Math.max(12, Math.min(1588, Math.round(rect.width * scale))), height: Math.max(12, Math.min(2244, Math.ceil(rect.height * scale) + 2)), angle: 0 }
: initialFrame(block.type, index);
return { ...block, frame };
}) };
}
useEffect(() => {
convertRef.current = page ? freePage : null;
return () => { convertRef.current = null; };
});
function choose(id) {
setInline(null);
select(id);
}
function pointerStart(ev, id, action = 'move') {
if (ev.button !== 0 || !ev.isPrimary || (inline === id && action === 'move')) return;
ev.stopPropagation();
choose(id);
const source = freePage();
const frame = source.blocks.find((item) => item.id === id).frame;
const bounds = paper.current.getBoundingClientRect();
const scale = bounds.width / pageWidth;
const center = { x: bounds.left + (frame.x + frame.width / 2) * scale, y: bounds.top + (frame.y + frame.height / 2) * scale };
gesture.current = { id, action, source, frame, scale, center, x: ev.clientX, y: ev.clientY, pointerType: ev.pointerType, live: null };
ev.currentTarget.setPointerCapture(ev.pointerId);
}
function pointerMove(ev) {
const g = gesture.current;
if (!g) return;
const dx = (ev.clientX - g.x) / g.scale;
const dy = (ev.clientY - g.y) / g.scale;
if (!g.live && Math.hypot(dx, dy) < 1) return;
let frame;
if (g.action === 'move') frame = moveFrame(g.frame, g.frame.x + dx, g.frame.y + dy);
else if (g.action === 'rotate') {
const original = Math.atan2(g.y - g.center.y, g.x - g.center.x);
const current = Math.atan2(ev.clientY - g.center.y, ev.clientX - g.center.x);
const next = Math.round(g.frame.angle + (current - original) * 180 / Math.PI);
const angle = ev.shiftKey ? Math.round(next / 15) * 15 : next;
frame = { ...g.frame, angle: ((angle + 540) % 360) - 180 };
} else {
const a = g.frame.angle * Math.PI / 180;
frame = resizeFrame(g.frame, g.action, dx * Math.cos(a) + dy * Math.sin(a), -dx * Math.sin(a) + dy * Math.cos(a));
}
g.live = { ...g.source, blocks: g.source.blocks.map((block) => block.id === g.id ? { ...block, frame } : block) };
setLivePage(g.live);
}
function pointerEnd(cancelled = false) {
if (!gesture.current) return;
const g = gesture.current;
gesture.current = null;
setLivePage(null);
if (cancelled || g.live || g.action !== 'move') {
lastClick.current = null;
if (!cancelled && g.live) commit(g.live);
return;
}
if (g.pointerType !== 'mouse' || g.source.blocks.find((block) => block.id === g.id).type !== 'text') return;
const now = performance.now();
const last = lastClick.current;
if (last?.id === g.id && now - last.at < 450 && Math.hypot(last.x - g.x, last.y - g.y) < 5) {
setInline(g.id);
lastClick.current = null;
} else lastClick.current = { id: g.id, x: g.x, y: g.y, at: now };
}
function keyMove(ev) {
const vector = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[ev.key];
if (!vector || !blockId || ev.target.closest('textarea,input,select,button')) return;
const active = page.blocks.find((block) => block.id === blockId);
if (!active) return;
ev.preventDefault();
const document = freePage();
const step = ev.shiftKey ? 10 : 1;
document.blocks = document.blocks.map((block) => block.id === active.id
? { ...block, frame: moveFrame(block.frame, block.frame.x + vector[0] * step, block.frame.y + vector[1] * step) } : block);
commit(document);
}
function drop(ev) {
ev.preventDefault();
const data = ev.dataTransfer.getData(dragKey);
if (!data) return;
let payload;
try { payload = JSON.parse(data); } catch { return; }
const { type, value } = payload || {};
if (type !== 'new' || !blockTypes[value]) return;
const bounds = paper.current.getBoundingClientRect();
const scale = pageWidth / bounds.width;
add(value, { x: (ev.clientX - bounds.left) * scale, y: (ev.clientY - bounds.top) * scale }, freePage());
paper.current.focus({ preventScroll: true });
}
return <main className="editor-canvas" aria-label="Gestaltungsfläche">
<div className="canvas-caption"><div><FileText size={15} /> {page ? `${number} · ${page.title}` : 'Seitenfläche'}</div>{page && <div className="canvas-tools"><span>A4</span><div className="canvas-zoom"><Button size="icon" variant="ghost" aria-label="Editoransicht verkleinern" onClick={() => setZoom(Math.max(50, zoom - 25))} disabled={zoom <= 50}><Minus size={15} /></Button><button onClick={() => setZoom(100)} title="Auf Standardgröße zurücksetzen">{zoom} %</button><Button size="icon" variant="ghost" aria-label="Editoransicht vergrößern" onClick={() => setZoom(Math.min(225, zoom + 25))} disabled={zoom >= 225}><Plus size={15} /></Button></div></div>}</div>
{!page ? <Empty icon={FileText} title="Keine Seite ausgewählt"><Button onClick={addPage}><Plus size={16} /> Seite anlegen</Button></Empty> : <div className="canvas-scroll" style={{ '--zoom-percent': `${zoom}%`, '--zoom-width': `${zoom * 5.6}px` }}>
<div className="canvas-paper"><article ref={paper} tabIndex={0} aria-label={`${page.title} bearbeiten`} className="folio-page editor-paper" style={{ '--paper': page.background, '--ink': page.color }}
onPointerDown={(ev) => { if (!ev.target.closest('[data-canvas-block],.canvas-selection')) choose(null); }} onPointerMove={pointerMove}
onPointerUp={() => pointerEnd()} onPointerCancel={() => pointerEnd(true)} onLostPointerCapture={() => pointerEnd(true)} onKeyDown={keyMove}
onDragOver={(ev) => { if (ev.dataTransfer.types.includes(dragKey)) { ev.preventDefault(); ev.dataTransfer.dropEffect = 'copy'; } }} onDrop={drop}>
<div className={`folio-content folio-layout-${visiblePage.layout}`}>
{visiblePage.blocks.map((block, index) => {
const renderedBlock = page.blocks.find((item) => item.id === block.id) || block;
return <div key={block.id} data-canvas-block={block.id} className={`canvas-frame folio-block folio-width-${block.width} ${block.id === blockId ? 'selected' : ''}`} role="button" tabIndex={0}
style={free ? frameStyle(block.frame || initialFrame(block.type, index)) : undefined} aria-label={`${blockTypes[block.type]} bearbeiten`} aria-pressed={block.id === blockId}
onPointerDown={(ev) => { pointerStart(ev, block.id); paper.current.focus({ preventScroll: true }); }}
onKeyDown={(ev) => { if (ev.target === ev.currentTarget && ['Enter', ' '].includes(ev.key)) { ev.preventDefault(); choose(block.id); if (ev.key === 'Enter' && block.type === 'text') setInline(block.id); } }}
onDoubleClick={() => { if (block.type === 'text') { select(block.id); setInline(block.id); } }}>
<CanvasContent block={renderedBlock} />
{inline === block.id && <StoryText block={renderedBlock} close={() => setInline(null)} save={(text) => {
setInline(null);
if (text !== renderedBlock.text) commit({ ...page, blocks: page.blocks.map((item) => item.id === block.id ? { ...item, text } : item) });
}} />}
</div>;
})}
{!page.blocks.length && <div className="canvas-placeholder"><Plus size={24} /><strong>Elemente hier ablegen</strong><span>Ziehe einen Baustein aus der Seitenleiste auf die Seite.</span></div>}
</div>
{free && activeBlock && inline !== activeBlock.id && <div className="canvas-selection" style={frameStyle(activeBlock.frame || initialFrame(activeBlock.type, visiblePage.blocks.indexOf(activeBlock)))}>
{Object.entries(corners).map(([corner, label]) => <button key={corner} type="button" className={`canvas-grip grip-${corner}`} aria-label={`Größe ändern ${label}`} onPointerDown={(ev) => pointerStart(ev, activeBlock.id, corner)} />)}
<button type="button" className="canvas-rotate" aria-label="Element drehen" title="Ziehen zum Drehen" onPointerDown={(ev) => pointerStart(ev, activeBlock.id, 'rotate')}><RotateCw size={12} /></button>
</div>}
</article></div>
</div>}
</main>;
}

9
src/main.jsx Normal file
View File

@ -0,0 +1,9 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import '@fontsource-variable/manrope';
import '../shared/publication.css';
import './styles.css';
import { App } from './studio.jsx';
createRoot(document.getElementById('root')).render(<BrowserRouter><App /></BrowserRouter>);

143
src/media.jsx Normal file
View File

@ -0,0 +1,143 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileVideo, Image, Images, Pencil, Plus, RotateCcw, Search, Trash2, Upload } from 'lucide-react';
import { blockTypes } from '../shared/magazine.js';
import { admin, bytesLabel, formatDate, mediaUrl } from './api.js';
import { PageTitle } from './dashboard.jsx';
import { Button, Dialog, Empty, ErrorMessage, Field, Menu } from './ui.jsx';
const supported = 'image/jpeg,image/png,image/gif,image/webp,image/avif,video/mp4,video/webm';
const isImage = (file) => file.mime.startsWith('image/');
export function useLibrary() {
const [library, setLibrary] = useState({ files: [], galleries: [] });
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
async function reload() {
try { setLibrary(await admin('/media')); setError(''); } catch (err) { setError(err.message); } finally { setLoading(false); }
}
useEffect(() => { void reload(); }, []);
return { ...library, loading, error, reload };
}
export async function uploadFile(file) {
const body = new FormData(); body.append('file', file);
return admin('/media', { method: 'POST', body });
}
function Thumb({ file }) {
return file && isImage(file) ? <img src={mediaUrl(file.id)} alt="" loading="lazy" /> : <FileVideo size={27} />;
}
export function MediaPicker({ kind, initial = [], select, close }) {
const [ids, setIds] = useState(initial);
const [search, setSearch] = useState('');
const [mode, setMode] = useState('files');
const [error, setError] = useState('');
const [uploading, setUploading] = useState(false);
const library = useLibrary();
const multi = kind === 'gallery';
const files = library.files.filter((file) => (kind === 'video' ? !isImage(file) : isImage(file)) && file.name.toLowerCase().includes(search.toLowerCase()));
async function upload(ev) {
const file = ev.target.files[0];
if (!file) return;
setUploading(true); setError('');
try {
const saved = await uploadFile(file);
await library.reload();
setIds((current) => multi ? [...current.slice(0, 11), saved.id] : [saved.id]);
setMode('files'); setSearch('');
} catch (err) { setError(err.message); } finally { setUploading(false); ev.target.value = ''; }
}
function toggle(id) { setIds((current) => multi ? current.includes(id) ? current.filter((item) => item !== id) : [...current, id].slice(0, 12) : [id]); }
return <Dialog title={kind === 'video' ? 'Video auswählen' : multi ? 'Galeriebilder auswählen' : 'Bild auswählen'} open onOpenChange={(open) => !open && close()} className="dialog-wide">
<div className="picker-top"><label className="search-field"><Search size={16} /><input aria-label="Medien suchen" placeholder="Medien suchen …" value={search} onChange={(ev) => setSearch(ev.target.value)} /></label><label className="button button-outline button-default upload-label"><Upload size={16} /> {uploading ? 'Lädt …' : 'Hochladen'}<input type="file" accept={kind === 'video' ? 'video/mp4,video/webm' : 'image/jpeg,image/png,image/gif,image/webp,image/avif'} onChange={upload} disabled={uploading} /></label></div>
{multi && <div className="tabs"><button className={`tab ${mode === 'files' ? 'active' : ''}`} onClick={() => setMode('files')}>Bilder</button><button className={`tab ${mode === 'galleries' ? 'active' : ''}`} onClick={() => setMode('galleries')}>Gespeicherte Galerien</button></div>}
<ErrorMessage>{error || library.error}</ErrorMessage>
{mode === 'files' ? files.length ? <div className="picker-grid">{files.map((file) => <button className={`picker-item ${ids.includes(file.id) ? 'selected' : ''}`} aria-pressed={ids.includes(file.id)} key={file.id} onClick={() => toggle(file.id)}><div className="file-thumb"><Thumb file={file} />{ids.includes(file.id) && <span className="picker-check"><Check size={14} /></span>}</div><span>{file.name}</span></button>)}</div> : <p className="panel-empty">{library.loading ? 'Medien werden geladen …' : 'Keine passenden Medien.'}</p>
: <div className="gallery-picker">{library.galleries.filter((item) => item.name.toLowerCase().includes(search.toLowerCase())).map((gallery) => <button key={gallery.id} onClick={() => { setIds(gallery.media_ids.filter((id) => library.files.some((file) => file.id === id))); setMode('files'); setSearch(''); }}><Images size={19} /><strong>{gallery.name}</strong><span>{gallery.media_ids.length} Bilder</span></button>)}{!library.galleries.length && <p className="panel-empty">Noch keine gespeicherten Galerien.</p>}</div>}
<div className="dialog-actions"><Button variant="outline" onClick={close}>Abbrechen</Button><Button disabled={uploading || !ids.length || ids.some((id) => !library.files.some((file) => file.id === id))} onClick={() => select(ids)}><Check size={16} /> {multi ? `${ids.length} übernehmen` : 'Übernehmen'}</Button></div>
</Dialog>;
}
export function MediaLibrary({ refreshDashboard, notify }) {
const library = useLibrary();
const fileInput = useRef(null);
const [query, setQuery] = useState('');
const [type, setType] = useState('all');
const [uploading, setUploading] = useState(false);
const [gallery, setGallery] = useState(null);
const [remove, setRemove] = useState(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const files = library.files.filter((file) => (type === 'all' || (type === 'images' ? isImage(file) : !isImage(file))) && file.name.toLowerCase().includes(query.toLowerCase()));
async function upload(ev) {
const selected = Array.from(ev.target.files);
ev.target.value = '';
if (!selected.length) return;
setUploading(true); setError('');
let count = 0;
const errors = [];
for (const file of selected) {
try { await uploadFile(file); count += 1; } catch (err) { errors.push(`${file.name} · ${err.message}`); }
}
await Promise.all([library.reload(), refreshDashboard()]);
if (count) notify(`${count} ${count === 1 ? 'Datei hochgeladen' : 'Dateien hochgeladen'}.`);
setError(errors.join('\n')); setUploading(false);
}
async function saveGallery(ev) {
ev.preventDefault(); setBusy(true); setError('');
try {
await admin(gallery.id ? `/galleries/${gallery.id}` : '/galleries', { method: gallery.id ? 'PUT' : 'POST', body: { name: gallery.name, mediaIds: gallery.mediaIds } });
await Promise.all([library.reload(), refreshDashboard()]); setGallery(null); notify('Galerie gespeichert.');
} catch (err) { setError(err.message); } finally { setBusy(false); }
}
async function trash() {
setBusy(true);
try {
await admin(`/${remove.type}/${remove.id}`, { method: 'DELETE' });
await Promise.all([library.reload(), refreshDashboard()]); setRemove(null); notify('In den Papierkorb verschoben.');
} catch (err) { notify(err.message, true); } finally { setBusy(false); }
}
return <><PageTitle title="Medienbibliothek" description="Verwalte Bilder, Videos und Galerien für deine Magazine."><Button onClick={() => fileInput.current.click()} disabled={uploading}><Upload size={18} /> {uploading ? 'Wird hochgeladen …' : 'Dateien hochladen'}</Button></PageTitle>
<input type="file" className="sr-only" ref={fileInput} multiple accept={supported} onChange={upload} tabIndex={-1} aria-hidden="true" />
{!gallery && <ErrorMessage>{error || library.error}</ErrorMessage>}
<div className="collection-toolbar media-toolbar"><div className="tabs">{[['all', 'Alle Dateien'], ['images', 'Bilder'], ['videos', 'Videos'], ['galleries', 'Galerien']].map(([value, label]) => <button key={value} className={`tab ${type === value ? 'active' : ''}`} onClick={() => setType(value)} aria-pressed={type === value}>{label}</button>)}</div><label className="search-field"><Search size={17} /><input value={query} onChange={(ev) => setQuery(ev.target.value)} placeholder="Medien suchen …" aria-label="Medien suchen" /></label></div>
{type === 'galleries' ? <><div className="section-heading library-section"><h2>Gespeicherte Galerien</h2><Button variant="outline" onClick={() => { setGallery({ name: '', mediaIds: [] }); setError(''); }}><Plus size={17} /> Galerie anlegen</Button></div>
{library.galleries.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())).length ? <div className="media-grid">{library.galleries.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())).map((item) => <article className="media-card" key={item.id}><button className="file-thumb" aria-label={`${item.name} bearbeiten`} onClick={() => setGallery({ id: item.id, name: item.name, mediaIds: item.media_ids.filter((id) => library.files.some((file) => file.id === id)) })}><Thumb file={library.files.find((file) => file.id === item.media_ids[0])} /></button><div className="media-description"><div><strong>{item.name}</strong><small>{item.media_ids.length} Bilder</small></div><Menu><button onClick={() => setGallery({ id: item.id, name: item.name, mediaIds: item.media_ids.filter((id) => library.files.some((file) => file.id === id)) })}><Pencil size={15} /> Bearbeiten</button><button onClick={() => setRemove({ ...item, type: 'galleries' })} className="menu-danger"><Trash2 size={15} /> In den Papierkorb</button></Menu></div></article>)}</div> : <Empty icon={Images} title="Keine Galerien" text="Wähle Bilder aus der Bibliothek und speichere sie als Galerie." />}</>
: files.length ? <div className="media-grid">{files.map((file) => <article className="media-card" key={file.id}><a className="file-thumb" href={mediaUrl(file.id)} target="_blank" rel="noreferrer" aria-label={`${file.name} öffnen`}><Thumb file={file} /></a><div className="media-description"><div><strong title={file.name}>{file.name}</strong><small>{bytesLabel(Number(file.bytes))} · {isImage(file) ? 'Bild' : 'Video'}</small></div><Menu><a href={mediaUrl(file.id)} target="_blank" rel="noreferrer">Datei öffnen</a><button onClick={() => setRemove({ ...file, type: 'media' })} className="menu-danger"><Trash2 size={15} /> In den Papierkorb</button></Menu></div></article>)}</div> : <Empty icon={Image} title={library.loading ? 'Medien werden geladen …' : 'Keine passenden Dateien'} text="Lade Bilder oder Videos für deine Magazine hoch." />}
<Dialog title={gallery?.id ? 'Galerie bearbeiten' : 'Galerie anlegen'} open={!!gallery} onOpenChange={(open) => !open && setGallery(null)} className="dialog-wide">
{gallery && <form onSubmit={saveGallery} className="dialog-form"><Field label="Galeriename"><input value={gallery.name} onChange={(ev) => setGallery({ ...gallery, name: ev.target.value })} required maxLength={100} /></Field><div className="picker-grid">{library.files.filter(isImage).map((file) => <button type="button" className={`picker-item ${gallery.mediaIds.includes(file.id) ? 'selected' : ''}`} key={file.id} aria-pressed={gallery.mediaIds.includes(file.id)} onClick={() => setGallery({ ...gallery, mediaIds: gallery.mediaIds.includes(file.id) ? gallery.mediaIds.filter((id) => id !== file.id) : [...gallery.mediaIds, file.id].slice(0, 12) })}><div className="file-thumb"><Thumb file={file} />{gallery.mediaIds.includes(file.id) && <span className="picker-check"><Check size={14} /></span>}</div><span>{file.name}</span></button>)}</div><ErrorMessage>{error}</ErrorMessage><div className="dialog-actions"><Button variant="outline" onClick={() => setGallery(null)}>Abbrechen</Button><Button type="submit" disabled={busy || !gallery.mediaIds.length}>Galerie speichern</Button></div></form>}
</Dialog>
<Dialog title="In den Papierkorb verschieben?" description={remove?.name} open={!!remove} onOpenChange={(open) => !open && setRemove(null)}><div className="dialog-actions"><Button variant="outline" onClick={() => setRemove(null)}>Abbrechen</Button><Button variant="danger" onClick={trash} disabled={busy}>Verschieben</Button></div></Dialog>
</>;
}
export function Trash({ notify, refreshDashboard }) {
const [rows, setRows] = useState(null);
const [error, setError] = useState('');
const [busy, setBusy] = useState('');
async function load() {
try { setRows(await admin('/trash')); setError(''); } catch (err) { setError(err.message); }
}
useEffect(() => { void load(); }, []);
async function restore(kind, id) {
setBusy(id);
try {
await admin(`/trash/${kind}/${id}/restore`, { method: 'POST' });
await Promise.all([load(), refreshDashboard()]); notify('Eintrag wiederhergestellt.');
} catch (err) { notify(err.message, true); } finally { setBusy(''); }
}
const items = rows ? [
...rows.magazines.map((item) => ({ ...item, kind: 'magazine', label: 'Magazin' })),
...rows.items.map((item) => ({ ...item, kind: 'item', title: item.page_id ? blockTypes[item.item.type] : item.item.title, label: `${item.page_id ? 'Element' : 'Seite'} · ${item.magazine}` })),
...rows.files.map((item) => ({ ...item, kind: 'media', title: item.name, label: 'Mediendatei' })),
...rows.galleries.map((item) => ({ ...item, kind: 'gallery', title: item.name, label: 'Galerie' })),
].sort((a, b) => Date.parse(b.deleted_at) - Date.parse(a.deleted_at)) : [];
return <><PageTitle title="Papierkorb" description="Stelle gelöschte Magazine, Seiten, Elemente und Medien wieder her." /><ErrorMessage>{error}</ErrorMessage>
{!rows ? <p className="panel-empty">Papierkorb wird geladen …</p> : items.length ? <div className="table-wrap"><table><thead><tr><th>Name</th><th>Typ</th><th>Gelöscht am</th><th aria-label="Aktionen" /></tr></thead><tbody>{items.map((item) => <tr key={item.id}><td><strong>{item.title}</strong></td><td>{item.label}</td><td>{formatDate(item.deleted_at, true)}</td><td><Button size="sm" variant="outline" disabled={!!busy} onClick={() => restore(item.kind, item.id)}><RotateCcw size={15} /> Wiederherstellen</Button></td></tr>)}</tbody></table></div> : <Empty icon={Trash2} title="Der Papierkorb ist leer" />}
</>;
}

145
src/reader.jsx Normal file
View File

@ -0,0 +1,145 @@
import { useEffect, useRef, useState } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { BookOpen, ChevronLeft, ChevronRight, Download, List, Maximize, Minimize, Minus, Plus } from 'lucide-react';
import { PageFlip } from 'page-flip';
import { api } from './api.js';
import { Button, Dialog, Empty } from './ui.jsx';
export function Reader({ book, embed = false, preview = false }) {
const root = useRef(null);
const stage = useRef(null);
const mount = useRef(null);
const instance = useRef(null);
const pageRef = useRef(0);
const [size, setSize] = useState(null);
const [page, setPage] = useState(0);
const [input, setInput] = useState('1');
const [zoom, setZoom] = useState(1);
const [toc, setToc] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const count = book.pages.length;
useEffect(() => {
const observer = new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
setSize((previous) => previous?.width === Math.floor(width) && previous?.height === Math.floor(height)
? previous : { width: Math.floor(width), height: Math.floor(height) });
});
observer.observe(stage.current);
return () => observer.disconnect();
}, []);
const spread = count > 1 && size?.width >= 720;
const gutter = spread ? 2 : 1;
const pageWidth = size ? Math.max(120, Math.floor(Math.min(544, (size.width - 18) / gutter, (size.height - 12) * 794 / 1122) * zoom)) : 0;
const pageHeight = Math.round(pageWidth * 1122 / 794);
useEffect(() => {
if (!pageWidth || !count) return;
const node = document.createElement('div');
node.className = 'book-instance';
node.style.width = `${pageWidth * gutter}px`;
node.style.height = `${pageHeight}px`;
mount.current.append(node);
const sheets = book.pages.map((sheet) => {
const wrapper = document.createElement('div');
wrapper.className = 'book-sheet';
wrapper.innerHTML = sheet.html;
for (const item of wrapper.querySelectorAll('a, video')) {
for (const event of ['mousedown', 'touchstart', 'pointerdown']) item.addEventListener(event, (ev) => ev.stopPropagation());
}
node.append(wrapper);
return wrapper;
});
const flip = new PageFlip(node, {
width: pageWidth, height: pageHeight, size: 'fixed', usePortrait: !spread, autoSize: false,
startPage: Math.min(pageRef.current, count - 1), showCover: spread, maxShadowOpacity: 0.45,
flippingTime: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 140 : 720,
mobileScrollSupport: zoom === 1, showPageCorners: zoom === 1,
disableFlipByClick: false, clickEventForward: true,
});
const onPage = (index) => {
pageRef.current = index;
setPage(index); setInput(String(index + 1));
};
flip.on('flip', (ev) => onPage(ev.data));
flip.loadFromHTML(sheets);
onPage(flip.getCurrentPageIndex());
instance.current = flip;
return () => { instance.current = null; flip.destroy(); };
}, [book.pages, count, gutter, pageWidth, pageHeight, spread, zoom]);
useEffect(() => {
function key(ev) {
if (ev.target.closest?.('input,textarea,select,video') || ev.altKey || ev.metaKey || ev.ctrlKey) return;
if (ev.key === 'ArrowRight') { ev.preventDefault(); instance.current?.flipNext(); }
if (ev.key === 'ArrowLeft') { ev.preventDefault(); instance.current?.flipPrev(); }
if (ev.key === 'Escape' && !document.fullscreenElement) setFullscreen(false);
}
function syncFullscreen() { setFullscreen(document.fullscreenElement === root.current); }
document.addEventListener('keydown', key);
document.addEventListener('fullscreenchange', syncFullscreen);
return () => { document.removeEventListener('keydown', key); document.removeEventListener('fullscreenchange', syncFullscreen); };
}, []);
function jump(index) {
const next = Math.min(count - 1, Math.max(0, index));
const flip = instance.current;
if (flip) {
flip.turnToPage(next);
const active = flip.getCurrentPageIndex();
pageRef.current = active; setPage(active); setInput(String(active + 1));
}
setToc(false);
}
async function toggleFullscreen() {
if (document.fullscreenElement) { await document.exitFullscreen(); return; }
if (fullscreen) { setFullscreen(false); return; }
try {
if (!root.current.requestFullscreen) throw new Error();
await root.current.requestFullscreen();
} catch { setFullscreen(true); }
}
const atEnd = page >= count - (spread && page > 0 && page % 2 === 1 ? 2 : 1);
const solo = spread && zoom <= 1 && (page === 0 ? 'cover' : page === count - 1 && count % 2 === 0 ? 'back' : '');
return <section ref={root} className={`reader ${preview ? 'reader-preview' : ''} ${embed ? 'reader-embed' : ''} ${fullscreen ? 'reader-fullscreen' : ''}`} aria-label="Magazin-Reader">
{!preview && <header className="reader-header"><div className="reader-brand"><BookOpen size={22} /><div><strong>{book.title}</strong>{book.issue && <span>{book.issue}</span>}</div></div>{book.pdf && <Button size="sm" variant="outline" asChild><a href={book.pdf} download><Download size={16} /><span>PDF-Download</span></a></Button>}</header>}
<div className="reader-workspace">
<div className={`book-stage${zoom > 1 ? ' pannable' : ''}`} ref={stage} aria-label="Blätterbare Seiten"><div className="book-center" data-solo={solo || undefined} style={{ '--sheet-width': `${pageWidth}px`, '--book-width': `${pageWidth * gutter + 12}px`, '--book-height': `${pageHeight + 10}px` }} ref={mount} />{!count && <Empty icon={BookOpen} title="Der Entwurf hat noch keine Seiten" />}</div>
{toc && <aside className="reader-toc"><h3>Inhaltsverzeichnis</h3><ol>{book.pages.map((sheet, index) => <li key={sheet.id}><button className={page === index ? 'active' : ''} onClick={() => jump(index)}><span>{index + 1}</span>{sheet.title}</button></li>)}</ol></aside>}
</div>
<footer className="reader-controls">
<Button variant="ghost" size="icon" aria-label="Inhaltsverzeichnis" title="Inhaltsverzeichnis" aria-expanded={toc} onClick={() => setToc(!toc)}><List size={19} /></Button>
<div className="reader-navigation"><Button variant="ghost" size="icon" aria-label="Vorherige Seite" disabled={page === 0} onClick={() => instance.current?.flipPrev()}><ChevronLeft size={21} /></Button>
<form onSubmit={(ev) => { ev.preventDefault(); jump((Number(input) || 1) - 1); }}><input type="number" min="1" max={count || 1} value={input} onChange={(ev) => setInput(ev.target.value)} aria-label="Zu Seite springen" /> <span>/ {count}</span></form>
<Button variant="ghost" size="icon" aria-label="Nächste Seite" disabled={atEnd || !count} onClick={() => instance.current?.flipNext()}><ChevronRight size={21} /></Button></div>
<div className="zoom-controls"><Button variant="ghost" size="icon" aria-label="Verkleinern" onClick={() => setZoom(Math.max(.75, zoom - .25))} disabled={zoom <= .75}><Minus size={17} /></Button><button className="zoom-level" title="Zoom zurücksetzen" onClick={() => setZoom(1)}>{Math.round(zoom * 100)} %</button><Button variant="ghost" size="icon" aria-label="Vergrößern" disabled={zoom >= 2} onClick={() => setZoom(Math.min(2, zoom + .25))}><Plus size={17} /></Button><Button variant="ghost" size="icon" aria-label={fullscreen ? 'Vollbild verlassen' : 'Vollbild'} onClick={toggleFullscreen}>{fullscreen ? <Minimize size={17} /> : <Maximize size={17} />}</Button></div>
</footer>
</section>;
}
export function PublicReader() {
const { slug } = useParams();
const [params] = useSearchParams();
const [book, setBook] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
const controller = new AbortController();
const path = `/public/${encodeURIComponent(slug)}`;
api(path, { signal: controller.signal, credentials: 'omit' }).then((result) => {
if (controller.signal.aborted) return;
setBook(result);
document.title = `${result.title} · Syncova. Folio`;
void api(`${path}/view`, { method: 'POST', credentials: 'omit', keepalive: true }).catch(() => {});
}).catch((err) => { if (!controller.signal.aborted) setError(err.message); });
return () => { controller.abort(); document.title = 'Syncova. Folio'; };
}, [slug]);
return book ? <Reader book={book} embed={params.get('embed') === '1'} /> : <div className="reader-loading"><Empty icon={BookOpen} title={error || 'Ausgabe wird geladen …'} /></div>;
}
export function Preview({ book, close }) {
return <Dialog title="Vorschau" description={book?.title} open={!!book} onOpenChange={(open) => !open && close()} className="dialog-preview">{book && <Reader book={book} preview />}</Dialog>;
}

144
src/studio.jsx Normal file
View File

@ -0,0 +1,144 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, NavLink, Navigate, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom';
import { BarChart3, BookOpen, CheckCircle2, ChevronRight, CircleAlert, CloudUpload, Image, LockKeyhole, LogOut, Menu as MenuIcon, Trash2 } from 'lucide-react';
import { admin } from './api.js';
import { Dashboard, NewMagazine, Publications, Statistics } from './dashboard.jsx';
import { Editor } from './editor.jsx';
import { MediaLibrary, Trash } from './media.jsx';
import { PublicReader } from './reader.jsx';
import { Button, Empty, ErrorMessage, Field } from './ui.jsx';
const pages = [
{ to: '/', title: 'Magazine', Icon: BookOpen },
{ to: '/veroeffentlichungen', title: 'Veröffentlichungen', Icon: CloudUpload },
{ to: '/medien', title: 'Medienbibliothek', Icon: Image },
{ to: '/statistiken', title: 'Statistiken', Icon: BarChart3 },
{ to: '/papierkorb', title: 'Papierkorb', Icon: Trash2 },
];
function Brand() {
return <Link className="brand" to="/"><img src="/folio.svg" alt="" /><span><strong>Syncova.<span> Folio</span></strong><small>Publishing-Workspace</small></span></Link>;
}
function Login({ onLogin, error }) {
const [message, setMessage] = useState(error || '');
const [busy, setBusy] = useState(false);
async function submit(ev) {
ev.preventDefault(); setBusy(true); setMessage('');
const credentials = new FormData(ev.currentTarget);
try {
onLogin(await admin('/login', { method: 'POST', body: {
username: credentials.get('username'), password: credentials.get('password'),
} }));
}
catch (err) { setMessage(err.message); } finally { setBusy(false); }
}
return <div className="login-page"><div className="login-card"><Brand /><h1>Studio öffnen</h1><p>Melde dich an, um deine Magazine zu verwalten.</p>
<form className="dialog-form" onSubmit={submit}>
<Field label="Benutzername"><input name="username" autoComplete="username" maxLength={128} required autoFocus /></Field>
<Field label="Passwort"><input type="password" name="password" autoComplete="current-password" maxLength={1024} required /></Field>
<ErrorMessage>{message}</ErrorMessage><Button type="submit" disabled={busy}><LockKeyhole size={17} /> Anmelden</Button>
</form>
</div></div>;
}
function Shell({ demo, logout, children }) {
const { pathname } = useLocation();
const [mobileOpen, setMobileOpen] = useState(false);
const title = pages.find((page) => page.to === pathname)?.title || 'Magazine';
return <div className="shell">
{mobileOpen && <button className="sidebar-overlay" aria-label="Menü schließen" onClick={() => setMobileOpen(false)} />}
<aside className={`sidebar ${mobileOpen ? 'mobile-open' : ''}`}>
<div className="sidebar-brand"><Brand /></div>
<nav className="sidebar-nav" aria-label="Studio-Navigation"><div className="nav-label">Arbeitsbereich</div>{pages.map(({ to, title, Icon }) =>
<NavLink key={to} to={to} end onClick={() => setMobileOpen(false)}><Icon size={19} strokeWidth={1.85} /><span>{title}</span></NavLink>)}</nav>
<div className="sidebar-footer"><div className="studio-mark">SF</div><div><strong>Syncova. Folio</strong><span>{demo ? 'Lokaler Beispielmodus' : 'Administration'}</span></div>{!demo && <Button size="icon" variant="ghost" aria-label="Abmelden" title="Abmelden" onClick={logout}><LogOut size={17} /></Button>}</div>
</aside>
<div className="shell-body">
<header className="topbar"><Button className="mobile-menu" size="icon" variant="ghost" aria-label="Menü öffnen" aria-expanded={mobileOpen} onClick={() => setMobileOpen(!mobileOpen)}><MenuIcon size={22} /></Button><div className="breadcrumbs"><Link to="/">Arbeitsbereich</Link><ChevronRight size={15} /><strong>{title}</strong></div>{demo && <span className="workspace-tag"><i /> Lokaler Workspace</span>}</header>
<main className="main-content">{children}</main>
</div>
</div>;
}
function EditorRoute(props) {
const { id } = useParams();
return <Editor key={id} {...props} />;
}
function Studio() {
const [session, setSession] = useState(null);
const [loginError, setLoginError] = useState('');
const [data, setData] = useState(null);
const [dataError, setDataError] = useState('');
const [newMagazine, setNewMagazine] = useState(false);
const [notice, setNotice] = useState(null);
const timer = useRef(null);
const navigate = useNavigate();
const location = useLocation();
const notify = useCallback((text, error = false) => {
setNotice({ text, error }); clearTimeout(timer.current); timer.current = setTimeout(() => setNotice(null), error ? 7000 : 4000);
}, []);
useEffect(() => () => clearTimeout(timer.current), []);
useEffect(() => {
const controller = new AbortController();
admin('/session', { signal: controller.signal }).then(setSession).catch((err) => {
if (!controller.signal.aborted) { setLoginError(err.message); setSession({ authorized: false }); }
});
return () => controller.abort();
}, []);
const refresh = useCallback(async () => {
try { setData(await admin('/dashboard')); setDataError(''); }
catch (err) {
setDataError(err.message);
const next = await admin('/session').catch(() => null);
if (next && !next.authorized) setSession(next);
}
}, []);
useEffect(() => {
if (session?.authorized) void refresh();
}, [session, refresh, location.pathname]);
const queued = data?.publications.some((release) => release.state === 'queued');
useEffect(() => {
if (!session?.authorized || !queued) return;
const poll = setInterval(refresh, 5000);
return () => clearInterval(poll);
}, [session, queued, refresh]);
async function logout() {
try { await admin('/logout', { method: 'POST' }); setSession({ authorized: false }); setData(null); navigate('/'); }
catch (err) { notify(err.message, true); }
}
if (!session) return <div className="reader-loading"><Empty icon={BookOpen} title="Studio wird geladen …" /></div>;
if (!session.authorized) return <Login onLogin={setSession} error={loginError} />;
const fallback = !data && <Empty icon={BookOpen} title={dataError || 'Magazine werden geladen …'}>{dataError && <Button onClick={refresh} variant="outline">Erneut versuchen</Button>}</Empty>;
return <>
<Routes>
<Route path="/magazine/:id/editor" element={<EditorRoute dashboard={data} notify={notify} refreshDashboard={refresh} />} />
<Route path="*" element={<Shell demo={session.demo} logout={logout}>
<ErrorMessage>{data ? dataError : ''}</ErrorMessage>
{fallback || <Routes>
<Route path="/" element={<Dashboard data={data} refresh={refresh} create={() => setNewMagazine(true)} notify={notify} />} />
<Route path="/veroeffentlichungen" element={<Publications data={data} notify={notify} refresh={refresh} />} />
<Route path="/medien" element={<MediaLibrary notify={notify} refreshDashboard={refresh} />} />
<Route path="/statistiken" element={<Statistics data={data} />} />
<Route path="/papierkorb" element={<Trash notify={notify} refreshDashboard={refresh} />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>}
</Shell>} />
</Routes>
<NewMagazine open={newMagazine} close={() => setNewMagazine(false)} created={(magazine) => { setNewMagazine(false); notify('Magazin angelegt.'); navigate(`/magazine/${magazine.id}/editor`); }} />
{notice && <div className={`toast ${notice.error ? 'toast-error' : ''}`} role="status">{notice.error ? <CircleAlert size={19} /> : <CheckCircle2 size={19} />}{notice.text}</div>}
</>;
}
export function App() {
return <Routes><Route path="/ausgabe/:slug" element={<PublicReader />} /><Route path="*" element={<Studio />} /></Routes>;
}

475
src/styles.css Normal file
View File

@ -0,0 +1,475 @@
:root {
font-family: 'Manrope Variable', Manrope, sans-serif;
color: #191b2e;
background: #f8f9fd;
font-synthesis: none;
--background: #f8f9fd;
--card: #fff;
--foreground: #191b2e;
--muted: #656a82;
--border: #e7e8f0;
--primary: #5345e4;
--primary-hover: #4537ce;
--primary-soft: #eeecff;
--focus: #8a81f2;
--radius: 12px;
--shadow: 0 2px 4px #20204505, 0 1px 2px #20204504;
}
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; min-width: 320px; font-size: 16px; line-height: 1.5; }
button, input, textarea, select { font: inherit; }
button, input, select, textarea, summary { -webkit-tap-highlight-color: transparent; }
button { cursor: pointer; }
button:disabled { cursor: default; }
a { color: inherit; text-decoration: none; }
button:focus-visible, a:focus-visible, summary:focus-visible, [tabindex]:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; }
input, textarea, select { max-width: 100%; }
textarea { resize: vertical; }
h1, h2, h3, p { margin: 0; }
svg { flex-shrink: 0; vertical-align: middle; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.button { display: inline-flex; align-items: center; justify-content: center; gap: 8px; border: 1px solid transparent; border-radius: 9px; font-weight: 750; font-size: .875rem; line-height: 1.2; white-space: nowrap; transition: background .15s, color .15s, border-color .15s, box-shadow .15s; }
.button-default { padding: 0 15px; min-height: 42px; }
.button-sm { padding: 0 11px; min-height: 34px; font-size: .8125rem; }
.button-icon { padding: 0; width: 36px; height: 36px; }
.button-primary { color: #fff; background: var(--primary); box-shadow: 0 2px 4px #4e40db2e; }
.button-primary:hover { background: var(--primary-hover); }
.button-outline { color: var(--foreground); background: #fff; border-color: var(--border); box-shadow: var(--shadow); }
.button-outline:hover { background: #f8f8fe; border-color: #d8d7ec; }
.button-ghost { color: var(--muted); background: transparent; }
.button-ghost:hover { color: var(--foreground); background: #f1f1fb; }
.button-danger { color: #fff; background: #b93b55; }
.button-danger:hover { background: #a42e47; }
.button:disabled { opacity: .47; }
.danger-text { color: #ad3854; }
.danger-text:hover { color: #ad3854; background: #fff1f4; }
.shell { min-height: 100dvh; display: grid; grid-template-columns: 236px minmax(0, 1fr); }
.sidebar { position: sticky; top: 0; height: 100dvh; background: #fff; border-right: 1px solid var(--border); display: flex; flex-direction: column; z-index: 10; }
.sidebar-brand { padding: 28px 22px; }
.brand { display: inline-flex; align-items: center; gap: 11px; }
.brand img { display: block; width: 41px; height: 41px; }
.brand strong { display: block; font-size: 1.16rem; font-weight: 850; letter-spacing: -.055em; line-height: 1.14; }
.brand strong span { font-weight: 680; }
.brand small { display: block; font-size: .675rem; font-weight: 650; color: var(--muted); margin-top: 4px; }
.sidebar-nav { display: grid; gap: 5px; padding: 16px 13px; }
.nav-label { color: #7b8094; letter-spacing: .1em; text-transform: uppercase; font-weight: 800; font-size: .66rem; padding: 0 11px 9px; }
.sidebar-nav a { display: flex; align-items: center; padding: 0 11px; min-height: 43px; gap: 10px; border-radius: 8px; font-size: .875rem; font-weight: 710; color: #545970; }
.sidebar-nav a:hover { background: #f6f5fc; color: var(--primary-hover); }
.sidebar-nav a.active { background: var(--primary-soft); color: #4736cc; font-weight: 800; }
.sidebar-footer { display: flex; align-items: center; gap: 10px; margin: auto 14px 0; padding: 17px 3px 24px; border-top: 1px solid var(--border); }
.studio-mark { background: #eeeafb; color: #5641b9; border-radius: 10px; width: 35px; height: 35px; display: grid; place-items: center; flex-shrink: 0; font-size: .76rem; font-weight: 820; }
.sidebar-footer strong, .sidebar-footer span { display: block; }
.sidebar-footer strong { font-size: .81rem; font-weight: 820; }
.sidebar-footer span { color: var(--muted); font-size: .7rem; margin-top: 2px; }
.sidebar-footer .button { margin-left: auto; }
.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; height: 65px; border-bottom: 1px solid var(--border); background: #fff; padding: 0 33px; }
.breadcrumbs { display: flex; align-items: center; gap: 9px; font-size: .85rem; color: var(--muted); }
.breadcrumbs a:hover { color: var(--primary-hover); }
.breadcrumbs strong { color: var(--foreground); font-weight: 820; }
.breadcrumbs svg { color: #9499aa; }
.workspace-tag { display: inline-flex; align-items: center; gap: 7px; color: #5b6375; background: #f7f8fc; border: 1px solid #edeef3; border-radius: 7px; padding: 5px 9px; font-weight: 740; font-size: .72rem; white-space: nowrap; }
.workspace-tag i { width: 6px; height: 6px; border-radius: 50%; background: #3da682; }
.mobile-menu, .sidebar-overlay { display: none; }
.main-content { padding: 34px 33px 46px; max-width: 1510px; margin: 0 auto; }
.page-title { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 27px; }
.page-title h1 { font-size: clamp(2.15rem, 3vw, 2.75rem); letter-spacing: -.065em; font-weight: 850; line-height: 1.1; margin: 0 0 9px; }
.page-title p { color: var(--muted); font-size: .94rem; }
.page-title > .button { padding-inline: 16px; min-height: 43px; }
.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
.metric { position: relative; background: #fff; border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); padding: 17px 16px 15px; min-width: 0; }
.metric-icon { width: 36px; height: 36px; display: grid; place-items: center; border-radius: 9px; margin-bottom: 10px; }
.tone-purple { background: #eeeafe; color: #5f4de2; }
.tone-green { background: #e3f7ed; color: #21865f; }
.tone-blue { background: #e8f0ff; color: #3a67ce; }
.tone-orange { background: #fff0e4; color: #b65e23; }
.metric-label { color: #5a6079; font-size: .83rem; font-weight: 760; }
.metric strong { display: block; color: var(--foreground); font-size: 1.95rem; line-height: 1.22; letter-spacing: -.055em; font-weight: 850; margin: 2px 0 3px; font-variant-numeric: tabular-nums; }
.metric-detail { font-size: .73rem; color: #777c92; font-weight: 620; }
.magazines-section { margin-top: 30px; }
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.section-heading h2, .statistics-section h2 { font-size: 1.34rem; line-height: 1.3; letter-spacing: -.042em; font-weight: 840; }
.collection-toolbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 15px; }
.tabs { display: flex; align-items: center; gap: 3px; min-width: 0; }
.tab { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 37px; padding: 0 11px; border: 1px solid transparent; background: transparent; border-radius: 8px; color: #62677f; font-size: .81rem; font-weight: 750; white-space: nowrap; }
.tab:hover { background: #f0effa; }
.tab.active { color: #4734cd; background: #eeebff; }
.tab span { padding: 0 5px; border-radius: 5px; background: #ded8ff; font-size: .69rem; }
.toolbar-right { display: flex; align-items: center; gap: 8px; }
.search-field { display: inline-flex; align-items: center; gap: 8px; color: #797e95; border: 1px solid var(--border); background: #fff; border-radius: 8px; padding: 0 10px; min-height: 37px; min-width: 0; }
.search-field:focus-within { border-color: var(--focus); box-shadow: 0 0 0 2px #eae7ff; }
.search-field input { border: 0; background: transparent; color: var(--foreground); outline: none; font-size: .81rem; width: 148px; min-width: 0; height: 34px; }
.search-field input::placeholder { color: #7b8095; }
.view-switch { display: flex; padding: 3px; gap: 2px; background: #fff; border-radius: 8px; border: 1px solid var(--border); }
.view-switch .button { width: 29px; height: 29px; border-radius: 5px; }
.view-switch .selected { background: #eeebff; color: var(--primary-hover); }
.mag-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.mag-card { min-width: 0; border: 1px solid var(--border); border-radius: 13px; background: #fff; box-shadow: var(--shadow); transition: box-shadow .18s, border-color .18s; }
.mag-card:hover { border-color: #dcd9f1; box-shadow: 0 5px 18px #2a256c0d; }
.mag-cover-link { display: block; }
.cover { position: relative; height: clamp(150px, 15.2vw, 236px); isolation: isolate; overflow: hidden; border-radius: 12px 12px 0 0; color: #fff; background: #242740; display: flex; align-items: flex-end; }
.cover img, .cover::after { position: absolute; inset: 0; width: 100%; height: 100%; z-index: -2; }
.cover img { display: block; object-fit: cover; object-position: 50% 51%; transition: transform .4s; }
.mag-card:hover .cover img { transform: scale(1.035); }
.cover::after { content: ''; z-index: -1; background: linear-gradient(0deg, #0b1525bb, #0b152505 90%); }
.cover-type { padding: 16px 18px; max-width: 100%; }
.cover-type span { display: block; max-width: 100%; font-size: .62rem; letter-spacing: .12em; text-transform: uppercase; font-weight: 820; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
.cover-type strong { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; font: 500 clamp(2rem, 3.6vw, 3.4rem)/.99 Georgia, serif; letter-spacing: -.055em; overflow-wrap: anywhere; margin-top: 7px; }
.cover-weitblick { background: #163b4d; }
.cover-weitblick img { object-position: 50% 39%; }
.cover-form-und-raum { background: #8f462a; }
.cover-form-und-raum img { object-position: 50% 55%; }
.cover-form-und-raum::after { background: linear-gradient(0deg, #3d180ba6, #59220a10 95%); }
.cover-form-und-raum strong { font-family: 'Manrope Variable', sans-serif; font-weight: 780; letter-spacing: -.085em; }
.cover-saison { background: #203d2b; }
.cover-saison img { object-position: 50% 63%; }
.cover-saison::after { background: linear-gradient(0deg, #14291ecc, #14291e0c 100%); }
.cover-saison strong { font-style: italic; }
.cover-nachtkauf img { object-position: center 53%; }
.cover-nachtkauf .cover-type strong { color: #e3fa44; font-family: 'Manrope Variable', sans-serif; font-weight: 900; letter-spacing: -.085em; }
.cover-plain { background: radial-gradient(ellipse at 90% 10%, #bfaeff, transparent 70%), linear-gradient(135deg, #5041ab, #2d235e); }
.mag-card-details { padding: 10px 14px 0; }
.mag-card-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
.mag-card-top .menu .button { width: 30px; height: 30px; }
.badge { display: inline-flex; align-items: center; gap: 6px; border-radius: 30px; width: fit-content; padding: 3px 8px; font-size: .69rem; font-weight: 830; line-height: 1.45; white-space: nowrap; color: #565b70; background: #eff0f5; }
.badge i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: .86; }
.badge-published { color: #167253; background: #e5f7ee; }
.badge-scheduled { color: #925915; background: #fff1da; }
.badge-processing { color: #5442ca; background: #eeebff; }
.badge-failed { color: #a62d4b; background: #ffedf2; }
.mag-title { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 1.1rem; letter-spacing: -.04em; font-weight: 840; width: fit-content; max-width: 100%; }
.mag-title:hover, .table-link:hover { color: var(--primary-hover); }
.mag-card-details p { color: var(--muted); font-size: .79rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px; }
.mag-card-foot { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 5px 10px; color: #686e85; border-top: 1px solid #eff0f5; padding: 10px 0; margin-top: 11px; font-size: .72rem; font-weight: 670; }
.mag-card-foot span { display: inline-flex; align-items: center; gap: 5px; }
.dashboard-bottom { display: grid; grid-template-columns: minmax(0, 1.65fr) minmax(0, 1fr); gap: 16px; margin-top: 23px; }
.panel { border: 1px solid var(--border); border-radius: var(--radius); background: #fff; box-shadow: var(--shadow); padding: 16px; min-width: 0; }
.panel-heading { display: flex; align-items: center; gap: 10px; }
.panel-icon { display: grid; place-items: center; width: 34px; height: 34px; border-radius: 8px; background: #f0edfc; color: #6650c6; }
.panel-heading h2 { font-size: .99rem; letter-spacing: -.025em; font-weight: 830; }
.panel-heading p, .panel-empty { color: var(--muted); font-size: .78rem; }
.panel-empty { padding: 15px 0; }
.activity-list { margin: 12px 0 0; padding: 0; list-style: none; }
.activity-list li { display: flex; align-items: center; gap: 8px; border-top: 1px solid #f1f1f6; padding: 9px 0 4px; font-size: .78rem; font-weight: 650; }
.activity-list li + li { margin-top: 5px; }
.activity-list time { font-size: .69rem; color: var(--muted); margin-left: auto; flex-shrink: 0; }
.activity-dot { width: 7px; height: 7px; border-radius: 50%; background: #9285e6; flex-shrink: 0; }
.activity-published { background: #42a081; }
.activity-failed, .activity-deleted { background: #c85d72; }
.storage-panel strong { display: block; font-size: 1.65rem; font-weight: 850; letter-spacing: -.05em; margin: 14px 0 0; }
.storage-panel > span { display: block; font-size: .77rem; color: var(--muted); margin-bottom: 12px; }
.statistics-section { margin-top: 28px; }
.statistics-section h2 { margin-bottom: 13px; }
.menu { position: relative; display: inline-block; }
.menu summary { list-style: none; cursor: pointer; }
.menu summary::-webkit-details-marker { display: none; }
.menu[open] summary { background: #f2f0fd; color: var(--primary-hover); }
.menu-popover { position: absolute; top: calc(100% + 4px); right: 0; z-index: 7; display: grid; gap: 2px; width: max-content; max-width: min(250px, 72vw); min-width: 166px; padding: 5px; border: 1px solid var(--border); border-radius: 9px; background: #fff; box-shadow: 0 8px 25px #29234d1a; }
.menu-popover button, .menu-popover a { display: flex; align-items: center; gap: 8px; text-align: left; color: inherit; padding: 8px; background: none; border: 0; border-radius: 5px; font-size: .8rem; font-weight: 700; }
.menu-popover button:hover, .menu-popover a:hover { background: #f5f3fd; }
.menu-popover .menu-danger { color: #a92c4b; }
.table-wrap { background: #fff; border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); overflow-x: auto; }
.table-wrap:has(details[open]) { padding-bottom: 82px; }
table { border-collapse: collapse; width: 100%; text-align: left; font-size: .86rem; }
th, td { height: 49px; padding: 11px 15px; border-bottom: 1px solid var(--border); }
th { height: 43px; white-space: nowrap; font-weight: 820; color: #5c6177; background: #fcfcfe; }
tr:last-child td { border-bottom: 0; }
td small { display: block; font-size: .77rem; color: var(--muted); margin-top: 3px; }
td .table-error { color: #a62d4b; }
.table-link { font-weight: 800; }
.empty { display: grid; justify-items: center; align-content: center; gap: 8px; padding: 35px 18px; min-height: 170px; text-align: center; border: 1px dashed #dddcec; border-radius: var(--radius); background: #fff; }
.empty-icon { display: grid; place-items: center; color: #5d50cc; width: 48px; height: 48px; border-radius: 12px; background: #f0edff; }
.empty h3 { font-size: 1.04rem; }
.empty p { font-size: .86rem; color: var(--muted); }
.empty .button { margin-top: 6px; }
.dialog-overlay { position: fixed; inset: 0; background: #17152e66; backdrop-filter: blur(3px); z-index: 20; animation: fade-in .15s ease-out; }
.dialog { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(450px, calc(100vw - 26px)); max-height: calc(100dvh - 26px); overflow: auto; background: #fff; border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 20px 70px #20173833; z-index: 21; padding: 22px; animation: fade-in .15s ease-out; }
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
.dialog-wide { width: min(670px, calc(100vw - 26px)); }
.dialog-title { padding-right: 28px; font-size: 1.35rem; font-weight: 850; letter-spacing: -.043em; }
.dialog-description { color: var(--muted); margin: 4px 22px 15px 0; font-size: .87rem; }
.dialog-title + .field, .dialog-title + .dialog-form, .dialog-title + .picker-top { margin-top: 14px; }
.dialog-close { position: absolute; right: 13px; top: 13px; width: 34px; height: 34px; display: grid; place-items: center; background: transparent; color: var(--muted); border: 0; border-radius: 7px; }
.dialog-close:hover { background: #f3f1fb; }
.dialog-form { display: grid; gap: 13px; }
.field { display: grid; gap: 6px; font-size: .84rem; font-weight: 800; }
.field small { color: var(--muted); font-size: .72rem; font-weight: 600; }
.field :is(input, select, textarea):not([type=radio], [type=checkbox], [type=range]) { display: block; width: 100%; min-height: 38px; padding: 8px 10px; border: 1px solid #dfe0eb; border-radius: 8px; background: #fff; color: var(--foreground); outline: 0; font-size: .88rem; font-weight: 620; }
.field :is(input, select, textarea):focus { border-color: var(--focus); box-shadow: 0 0 0 2px #eae7ff; }
.field textarea::placeholder, .field input::placeholder { color: #85899e; }
.field input[type=color] { cursor: pointer; }
.field input[type=range] { accent-color: var(--primary); width: 100%; }
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
.inline-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-block: 9px; }
.error-message { color: #9d2d4a; background: #fff1f4; border: 1px solid #f5dbe3; padding: 9px 10px; border-radius: 8px; font-size: .82rem; white-space: pre-line; }
.toast { position: fixed; z-index: 100; right: 19px; bottom: 19px; display: flex; align-items: center; gap: 9px; max-width: min(420px, calc(100vw - 38px)); background: #fff; border: 1px solid #e4e1fa; border-radius: 11px; color: #30246e; box-shadow: 0 8px 30px #24204821; padding: 11px 14px; font-size: .83rem; font-weight: 740; animation: fade-in .2s ease-out; }
.toast-error { color: #9d2d4a; border-color: #f5dbe3; }
.media-toolbar { margin-bottom: 20px; }
.media-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 15px; }
.media-card { background: #fff; border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); min-width: 0; }
.file-thumb { position: relative; display: grid; place-items: center; width: 100%; aspect-ratio: 1.6; overflow: hidden; background: #efedfb; color: #6455ba; border: 0; border-radius: 11px 11px 0 0; }
.file-thumb img { display: block; width: 100%; height: 100%; position: absolute; inset: 0; object-fit: cover; object-position: center; }
.media-description { display: flex; align-items: center; justify-content: space-between; gap: 5px; padding: 8px 8px 10px 11px; }
.media-description > div:first-child { min-width: 0; }
.media-description strong, .media-description small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.media-description strong { font-size: .83rem; }
.media-description small { color: var(--muted); font-size: .73rem; margin-top: 2px; }
.library-section { margin-top: 19px; }
.picker-top { display: flex; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
.picker-top .search-field { flex: 1; }
.picker-top .search-field input { width: 100%; }
.picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(123px, 1fr)); gap: 8px; max-height: 350px; overflow: auto; padding: 3px; margin-block: 8px; }
.picker-item { display: grid; gap: 6px; text-align: left; border: 1px solid var(--border); color: var(--foreground); border-radius: 9px; padding: 3px; background: #fff; min-width: 0; }
.picker-item.selected { border-color: var(--primary); box-shadow: 0 0 0 1px var(--primary); }
.picker-item .file-thumb { border-radius: 6px; }
.picker-item > span { font-size: .73rem; padding: 0 4px 3px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
.picker-check { position: absolute; top: 5px; right: 5px; display: grid; place-items: center; background: var(--primary); color: #fff; width: 23px; height: 23px; border-radius: 50%; }
.upload-label { position: relative; overflow: hidden; cursor: pointer; }
.upload-label:focus-within { outline: 2px solid var(--focus); }
.upload-label input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
.gallery-picker { margin-block: 8px; display: grid; gap: 6px; }
.gallery-picker button { display: flex; align-items: center; gap: 8px; border: 1px solid var(--border); border-radius: 8px; padding: 9px; background: #fff; text-align: left; color: var(--foreground); }
.gallery-picker button:hover { background: #f8f6ff; }
.gallery-picker button span { margin-left: auto; color: var(--muted); font-size: .77rem; }
.login-page, .reader-loading { min-height: 100dvh; display: grid; place-items: center; padding: 16px; }
.login-page { background: radial-gradient(at 12% 10%, #ebe6ff, transparent 48%), #f8f9fd; }
.login-card { max-width: 420px; width: 100%; padding: 27px; border: 1px solid var(--border); border-radius: 17px; box-shadow: 0 10px 40px #25204e12; background: #fff; }
.login-card h1 { font-size: 1.75rem; letter-spacing: -.05em; margin-top: 22px; }
.login-card p { margin-block: 6px 16px; color: var(--muted); font-size: .9rem; }
.editor { min-height: 100dvh; display: grid; grid-template-rows: auto 1fr; }
.editor:has(.editor-warning) { grid-template-rows: auto auto 1fr; }
.editor-header { z-index: 3; position: sticky; top: 0; display: flex; align-items: center; gap: 10px; padding: 10px 18px; min-height: 67px; border-bottom: 1px solid var(--border); background: #fff; }
.editor-heading { min-width: 0; }
.editor-title { border: 0; padding: 0; background: none; color: var(--foreground); font-size: 1rem; font-weight: 850; letter-spacing: -.03em; display: inline-flex; align-items: center; gap: 4px; max-width: 100%; text-align: left; overflow-wrap: anywhere; }
.editor-title:hover { color: var(--primary-hover); }
.editor-meta { margin-top: 3px; display: flex; align-items: center; gap: 6px; font-size: .7rem; font-weight: 700; color: var(--muted); }
.editor-header-actions { display: flex; align-items: center; gap: 7px; margin-left: auto; }
.editor-warning { padding: 8px 15px; }
.editor-body { display: grid; grid-template-columns: minmax(178px, 215px) minmax(0, 1fr) minmax(212px, 260px); min-height: 0; }
.editor-left, .editor-inspector { background: #fff; min-width: 0; }
.editor-left { border-right: 1px solid var(--border); }
.editor-inspector { border-left: 1px solid var(--border); }
.editor-panel-header { display: flex; align-items: center; justify-content: space-between; min-height: 50px; padding: 10px 12px; border-bottom: 1px solid #f0f1f7; }
.editor-panel-header h2 { font-size: .9rem; font-weight: 830; }
.editor-panel-header h2 span { color: #7568b3; font-size: .71rem; margin-left: 4px; }
.editor-panel-header .button { width: 29px; height: 29px; }
.editor-pages { display: grid; gap: 4px; margin: 8px; max-height: 32dvh; overflow: auto; padding: 2px; }
.editor-page-row { display: flex; min-width: 0; min-height: 34px; align-items: center; background: #faf9fd; border: 1px solid #eeedf5; border-radius: 7px; }
.editor-page-row.active { border-color: #dcd5ff; background: #f0edff; color: #4734b9; }
.page-grip { cursor: grab; color: #8b87a2; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 32px; }
.editor-page-button { flex: 1; text-align: left; border: 0; border-radius: 5px; color: inherit; background: none; padding: 5px 5px 5px 0; font-size: .76rem; font-weight: 750; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.editor-page-button span { color: #7a70a9; margin-right: 6px; font-variant-numeric: tabular-nums; }
.page-order { display: flex; gap: 5px; padding: 0 9px 8px; }
.page-order .button { width: 30px; height: 30px; }
.page-order .button:last-child { margin-left: auto; }
.elements-heading { border-top: 1px solid #f0f1f7; }
.elements-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; padding: 10px 8px; }
.element-tile { display: grid; place-items: center; gap: 5px; min-height: 57px; border: 1px solid var(--border); border-radius: 8px; background: #fff; color: #5746ba; padding: 7px 3px; cursor: grab; }
.element-tile span { font-size: .68rem; font-weight: 780; color: #53536c; text-align: center; }
.element-tile:hover { background: #f7f4ff; border-color: #dcd6ff; }
.element-tile:disabled { opacity: .45; }
.editor-tip { display: flex; gap: 6px; align-items: flex-start; color: var(--muted); font-size: .69rem; margin: 2px 9px 12px; }
.editor-canvas { background: #eeeff7; background-image: radial-gradient(#d9daeb 1px, transparent 1px); background-size: 15px 15px; padding: 18px 19px 33px; min-width: 0; }
.canvas-caption { display: flex; justify-content: space-between; gap: 7px; align-items: center; color: #646a83; width: min(100%, 560px); margin: 0 auto 9px; font-size: .78rem; font-weight: 780; }
.canvas-caption > div:first-child { display: flex; align-items: center; gap: 6px; min-width: 0; overflow-wrap: anywhere; }
.canvas-tools, .canvas-zoom { display: flex; align-items: center; gap: 7px; }
.canvas-tools span { color: #797e98; }
.canvas-zoom { padding: 2px; gap: 0; border: 1px solid #dddced; border-radius: 7px; background: #ffffffa8; }
.canvas-zoom .button { width: 25px; height: 24px; }
.canvas-zoom button:not(.button) { border: 0; background: none; color: inherit; padding: 0 5px; white-space: nowrap; font-size: .69rem; }
.canvas-scroll { overflow-x: auto; padding: 8px 7px 23px; scrollbar-color: #aeadc7 transparent; }
.canvas-paper { width: min(var(--zoom-percent, 100%), var(--zoom-width, 560px)); aspect-ratio: 794 / 1122; margin-inline: auto; box-shadow: 0 8px 25px #211c4726; }
.editor-paper { position: relative; overflow: hidden; isolation: isolate; outline: none; }
.editor-paper:focus-visible { outline-offset: 4px; }
.canvas-frame { position: relative; cursor: grab; touch-action: none; user-select: none; }
.canvas-frame:active { cursor: grabbing; }
.canvas-frame:hover { outline: 1px solid #957bf8; outline-offset: -1px; }
.canvas-frame.selected:not(.folio-layout-free > *) { outline: 2px solid #7862f0; outline-offset: -1px; }
.canvas-frame .folio-item-content { pointer-events: none; }
.canvas-selection { position: absolute; border: 2px solid #694cf5; box-shadow: inset 0 0 0 1px #ffffffba; z-index: 1; pointer-events: none; }
.canvas-grip, .canvas-rotate { position: absolute; pointer-events: auto; touch-action: none; background: #fff; border: 2px solid #694cf5; padding: 0; }
.canvas-grip { width: 13px; height: 13px; border-radius: 3px; }
.grip-nw { top: -4px; left: -4px; cursor: nwse-resize; }
.grip-ne { top: -4px; right: -4px; cursor: nesw-resize; }
.grip-sw { bottom: -4px; left: -4px; cursor: nesw-resize; }
.grip-se { bottom: -4px; right: -4px; cursor: nwse-resize; }
.canvas-rotate { top: -10px; left: 50%; transform: translateX(-50%); width: 21px; height: 21px; border-radius: 50%; display: grid; place-items: center; cursor: grab; color: #6245dc; }
.canvas-inline-text { position: absolute; inset: 0; width: 100%; height: 100%; resize: none; border: 1px solid #694cf5; background: var(--item-fill, var(--paper)); color: var(--item-ink, var(--ink)); outline: none; padding: 0; }
.canvas-placeholder { display: grid; justify-items: center; align-content: center; grid-column: 1 / -1; text-align: center; gap: 6px; min-height: 34cqw; padding: 12px; margin: 9px; border: 2px dashed #dad2f5; border-radius: 10px; color: #6f61b4; font: 700 clamp(.75rem, 3.25cqw, 1rem)/1.32 'Manrope Variable', sans-serif; }
.folio-layout-free > .canvas-placeholder { margin: 12cqw 8cqw 0; pointer-events: none; }
.canvas-placeholder span { font-size: .85em; font-weight: 550; }
.inspector-body { padding: 13px 11px; display: grid; gap: 13px; }
.inspector-body p { font-size: .8rem; color: var(--muted); }
.color-settings { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.layers { border-bottom: 1px solid var(--border); }
.layers h2 { display: flex; align-items: center; gap: 5px; }
.layers h2 svg { color: #6453c8; }
.layers-list { display: grid; gap: 3px; max-height: 24dvh; min-height: 47px; margin: 7px 7px 3px; padding: 2px; overflow: auto; }
.layers-list > small { align-self: center; font-size: .72rem; color: var(--muted); padding: 4px; }
.layers-list button { display: flex; justify-content: space-between; align-items: center; min-width: 0; gap: 6px; min-height: 31px; border-radius: 6px; border: 1px solid transparent; padding: 4px 6px; text-align: left; background: #f8f8fc; color: #312c48; }
.layers-list button:hover, .layers-list button.active { border-color: #e2dbff; background: #eeebff; color: #503bc0; }
.layers-list strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-weight: 750; font-size: .72rem; }
.layers-list small { white-space: nowrap; color: #68627e; font-size: .64rem; }
.layers-actions { display: flex; flex-wrap: wrap; gap: 3px; padding: 4px 7px 7px; }
.layers-actions .button { width: 26px; height: 29px; }
.layer-colors { display: grid; grid-template-columns: repeat(auto-fit, minmax(53px, 1fr)); gap: 5px; }
.layer-colors .field { font-size: .72rem; }
.layer-colors .field input { padding: 4px; }
.field-clear { background: none; border: none; color: var(--primary-hover); padding: 3px 0 0; font-size: .63rem; }
.inspector-section { background: #faf9fe; border: 1px solid var(--border); border-radius: 8px; }
.inspector-section summary { padding: 9px 8px; cursor: pointer; font-size: .79rem; font-weight: 800; }
.inspector-options { display: grid; gap: 9px; padding: 0 7px 8px; }
.inspector-grid { display: grid; gap: 5px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.inspector-grid .field { font-size: .72rem; min-width: 0; }
.inspector-grid .field :is(input, select) { padding: 5px; }
.field .html-source { font-family: monospace; font-size: .77rem; tab-size: 2; }
.free-layout-label { display: inline-flex; gap: 6px; align-items: center; color: #513cc6; font-size: .79rem; font-weight: 775; }
.publish-options { display: grid; gap: 7px; }
.publish-options label { display: flex; align-items: center; gap: 8px; border: 1px solid var(--border); border-radius: 9px; padding: 9px; cursor: pointer; }
.publish-options label:has(:checked) { border-color: #cfc4ff; background: #f6f3ff; }
.publish-options input { accent-color: var(--primary); }
.publish-options span { display: grid; gap: 1px; font-size: .85rem; }
.publish-options small, .versions-list small { color: var(--muted); font-size: .72rem; }
.versions-list { display: grid; gap: 6px; }
.versions-list > div { display: flex; align-items: center; gap: 9px; border: 1px solid var(--border); border-radius: 8px; padding: 7px; }
.versions-list > div > div { flex: 1; min-width: 0; display: grid; font-size: .85rem; }
.reader { min-height: 360px; width: 100%; height: 100dvh; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; background: #eaeaf2; color: var(--foreground); }
.reader-header, .reader-controls { display: flex; align-items: center; min-width: 0; background: #fff; border-color: var(--border); }
.reader-header { border-bottom: 1px solid var(--border); padding: 10px 15px; justify-content: space-between; gap: 10px; }
.reader-brand { min-width: 0; display: flex; align-items: center; gap: 9px; }
.reader-brand svg { color: var(--primary); }
.reader-brand > div { min-width: 0; }
.reader-brand strong, .reader-brand span { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.reader-brand strong { font-size: .99rem; letter-spacing: -.03em; }
.reader-brand span { color: var(--muted); font-size: .71rem; }
.reader-workspace { position: relative; min-width: 0; min-height: 0; background: radial-gradient(ellipse at 50% 40%, #faf9fe, #e7e6f0 80%); }
.book-stage { position: absolute; inset: 0; overflow: hidden; overscroll-behavior: contain; }
.book-stage.pannable { overflow: auto; }
.book-center { display: grid; place-items: center; width: max(100%, var(--book-width, 0px)); height: max(100%, var(--book-height, 0px)); }
.book-stage:has(.empty) .book-center { display: none; }
.book-instance { display: block; filter: drop-shadow(0 8px 13px #211d3b33); transition: transform .25s ease-out; }
.book-center[data-solo=cover] .book-instance { transform: translateX(calc(var(--sheet-width) * -.5)); }
.book-center[data-solo=back] .book-instance { transform: translateX(calc(var(--sheet-width) * .5)); }
.book-sheet { background: #fffcf6; }
.stf__item:not([style*="display: none"]) { will-change: transform; }
.book-sheet .folio-page { border: 1px solid #18183f10; }
.reader-controls { justify-content: center; gap: 12px; border-top: 1px solid var(--border); padding: 6px 9px; min-height: 49px; }
.reader-navigation, .zoom-controls { display: flex; align-items: center; gap: 4px; }
.reader-navigation form { display: flex; align-items: center; gap: 5px; font-size: .8rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
.reader-navigation input { border: 1px solid var(--border); border-radius: 6px; width: 42px; height: 30px; text-align: center; color: inherit; font-size: .8rem; font-weight: 750; appearance: textfield; }
.reader-navigation input::-webkit-inner-spin-button { appearance: none; }
.zoom-controls .button { width: 31px; }
.zoom-level { border: 0; background: none; color: #585b73; font-size: .74rem; font-weight: 800; padding: 3px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.reader-toc { position: absolute; z-index: 10; bottom: 6px; left: 8px; width: min(285px, calc(100% - 16px)); max-height: calc(100% - 12px); overflow: auto; background: #fff; border: 1px solid var(--border); border-radius: 10px; padding: 12px; box-shadow: 0 6px 25px #28224728; }
.reader-toc h3 { font-size: .94rem; margin-bottom: 6px; }
.reader-toc ol { padding: 0; margin: 0; list-style: none; }
.reader-toc button { display: flex; align-items: baseline; gap: 7px; width: 100%; text-align: left; font-size: .8rem; background: none; border: none; color: #33324a; padding: 6px; border-radius: 6px; }
.reader-toc button:hover, .reader-toc button.active { background: #f1edff; color: #4c37bd; }
.reader-toc button span { color: #7669aa; }
.reader-embed .reader-header { padding-block: 7px; }
.dialog-preview { width: min(1100px, calc(100vw - 26px)); padding: 13px; overflow: hidden; }
.dialog-preview .dialog-title { font-size: 1.15rem; }
.dialog-preview .dialog-description { margin-bottom: 8px; }
.reader-preview { min-height: 225px; height: min(72dvh, 800px); grid-template-rows: minmax(0, 1fr) auto; border: 1px solid var(--border); border-radius: 9px; overflow: hidden; }
.reader-fullscreen, .reader:fullscreen { position: fixed; inset: 0; z-index: 30; width: 100%; height: 100dvh; border: 0; border-radius: 0; }
.dialog:has(.reader-fullscreen) { position: fixed; inset: 0; transform: none; width: 100%; height: 100dvh; max-height: none; padding: 0; border: 0; border-radius: 0; }
@media (max-width: 1110px) {
.shell { grid-template-columns: 204px minmax(0, 1fr); }
.topbar { padding-inline: 22px; }
.main-content { padding-inline: 22px; }
.metric { padding-inline: 12px; }
.metrics, .mag-grid { gap: 12px; }
.cover-type { padding-inline: 12px; }
.media-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.editor-body { grid-template-columns: 171px minmax(0, 1fr) 204px; }
}
@media (max-width: 870px) {
.shell { display: block; }
.sidebar { position: fixed; inset: 0 auto 0 0; width: 236px; visibility: hidden; transform: translateX(-100%); transition: transform .2s ease, visibility .2s; z-index: 14; }
.sidebar.mobile-open { visibility: visible; transform: translateX(0); }
.sidebar-overlay { display: block; position: fixed; inset: 0; z-index: 13; background: #201b3d60; border: 0; }
.mobile-menu { display: inline-flex; }
.topbar { justify-content: flex-start; padding-inline: 14px; height: 56px; }
.workspace-tag { margin-left: auto; }
.main-content { padding-top: 24px; }
.cover { height: clamp(128px, 22vw, 210px); }
.cover-type strong { font-size: clamp(1.8rem, 5vw, 3.4rem); }
.editor-header { padding-inline: 8px; }
.editor-header-actions .button { gap: 5px; padding-inline: 9px; }
.editor-header-actions .button-icon { padding: 0; }
}
@media (max-width: 670px) {
.main-content { padding-inline: 14px; }
.page-title { align-items: flex-start; gap: 13px; margin-bottom: 18px; }
.page-title p { font-size: .84rem; }
.page-title > .button { padding-inline: 9px; min-height: 39px; font-size: .75rem; }
.metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.metric { padding: 10px; }
.metric-icon { margin-bottom: 6px; }
.metric strong { font-size: 1.55rem; }
.magazines-section { margin-top: 21px; }
.collection-toolbar { flex-wrap: wrap; gap: 7px; }
.tabs { flex-wrap: wrap; }
.tab { padding-inline: 7px; }
.collection-toolbar .tabs { flex-wrap: nowrap; overflow-x: auto; scrollbar-width: thin; }
.collection-toolbar .tab { flex-shrink: 0; font-size: .75rem; padding-inline: 6px; }
.toolbar-right { width: 100%; }
.toolbar-right .search-field { flex: 1; }
.toolbar-right .search-field input { width: 100%; }
.mag-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
.mag-card-details { padding-inline: 9px; }
.cover { height: clamp(130px, 29vw, 200px); }
.cover-type { padding: 9px; }
.cover-type strong { font-size: clamp(1.45rem, 5.65vw, 2.6rem); }
.cover-type span { font-size: .51rem; }
.dashboard-bottom { grid-template-columns: 1fr; gap: 9px; margin-top: 14px; }
.media-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
.editor-header { flex-wrap: wrap; gap: 6px; position: relative; }
.editor-header-actions { width: 100%; justify-content: flex-end; gap: 4px; }
.editor-header-actions .button { min-height: 35px; font-size: .72rem; padding-inline: 5px; }
.editor-header-actions .button-icon { width: 29px; height: 29px; }
.editor-header-actions .button svg { width: 14px; height: 14px; }
.editor-body { grid-template-columns: 1fr 1fr; align-content: start; }
.editor-left { grid-column: 1 / -1; border-bottom: 1px solid var(--border); }
.editor-panel-header { padding: 6px 8px; min-height: 38px; }
.editor-pages { display: flex; overflow: auto; margin: 4px; }
.editor-page-row { flex: 0 0 auto; max-width: 165px; }
.page-order { padding-bottom: 4px; }
.elements-grid { display: flex; padding: 5px; overflow-x: auto; }
.element-tile { min-width: 62px; min-height: 47px; }
.editor-tip { margin-bottom: 6px; }
.editor-canvas, .editor-inspector { grid-column: 1 / -1; }
.editor-canvas { padding: 9px 11px 14px; }
.canvas-caption { width: min(100%, 460px); }
.canvas-grip { width: 20px; height: 20px; }
.canvas-rotate { width: 24px; height: 24px; }
.inspector-body { padding: 10px; }
}
@media (max-width: 390px) {
.mag-grid { grid-template-columns: 1fr; }
.cover { height: 175px; }
.cover-type strong { font-size: 2.35rem; }
.workspace-tag { display: none; }
.reader-controls { gap: 5px; padding-inline: 4px; }
.reader-controls .button-icon { width: 28px; }
.reader-header .button { padding-inline: 6px; }
.editor-header-actions { flex-wrap: wrap; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; }
}

55
src/ui.jsx Normal file
View File

@ -0,0 +1,55 @@
import { forwardRef, useEffect, useRef } from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { Slot } from '@radix-ui/react-slot';
import { cva } from 'class-variance-authority';
import { clsx } from 'clsx';
import { Ellipsis, X } from 'lucide-react';
const buttonVariants = cva('button', {
variants: { variant: { default: 'button-primary', outline: 'button-outline', ghost: 'button-ghost', danger: 'button-danger' }, size: { default: 'button-default', sm: 'button-sm', icon: 'button-icon' } },
defaultVariants: { variant: 'default', size: 'default' },
});
export const Button = forwardRef(function Button({ className, variant, size, asChild = false, ...props }, ref) {
const Component = asChild ? Slot : 'button';
return <Component className={clsx(buttonVariants({ variant, size }), className)} ref={ref} {...(!asChild && { type: 'button' })} {...props} />;
});
export function Dialog({ title, description, open, onOpenChange, children, className }) {
return <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="dialog-overlay" />
<DialogPrimitive.Content className={clsx('dialog', className)} {...(!description && { 'aria-describedby': undefined })}>
<DialogPrimitive.Title className="dialog-title">{title}</DialogPrimitive.Title>
{description && <DialogPrimitive.Description className="dialog-description">{description}</DialogPrimitive.Description>}
<DialogPrimitive.Close className="dialog-close" aria-label="Schließen"><X size={19} /></DialogPrimitive.Close>
{children}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>;
}
export function Menu({ children, label = 'Weitere Aktionen' }) {
const ref = useRef(null);
useEffect(() => {
const close = (ev) => {
if (ref.current && (ev.key === 'Escape' || (ev.type === 'pointerdown' && !ref.current.contains(ev.target)))) ref.current.open = false;
};
window.addEventListener('pointerdown', close);
window.addEventListener('keydown', close);
return () => {
window.removeEventListener('pointerdown', close);
window.removeEventListener('keydown', close);
};
}, []);
return <details className="menu" ref={ref}>
<summary className="button button-icon button-ghost" aria-label={label} title={label}><Ellipsis size={20} /></summary>
<div className="menu-popover" onClick={(ev) => {
if (ev.target.closest('button,a')) ref.current.open = false;
}}>{children}</div>
</details>;
}
export const Field = ({ label, children, hint }) => <label className="field"><span>{label}</span>{children}{hint && <small>{hint}</small>}</label>;
export const ErrorMessage = ({ children }) => children ? <div className="error-message" role="alert">{children}</div> : null;
export const Empty = ({ icon: Icon, title, text, children }) => <div className="empty"><div className="empty-icon"><Icon size={24} /></div><h3>{title}</h3>{text && <p>{text}</p>}{children}</div>;

7
vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: { proxy: { '/api': 'http://127.0.0.1:4170' } },
});