Initial Syncova Display import
This commit is contained in:
commit
ddb81203c9
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
data
|
||||
.git
|
||||
18
.env.example
Normal file
18
.env.example
Normal file
@ -0,0 +1,18 @@
|
||||
# Erststart. Ein separates, zufälliges Passwort pro Feld verwenden.
|
||||
POSTGRES_PASSWORD=
|
||||
ADMIN_EMAIL=admin@syncova.de
|
||||
ADMIN_PASSWORD=
|
||||
ADMIN_NAME=Administration
|
||||
|
||||
# Erreichbarkeit des Webservers im LAN.
|
||||
BIND_ADDRESS=0.0.0.0
|
||||
HTTP_PORT=8080
|
||||
|
||||
# Hinter einem HTTPS-Reverse-Proxy COOKIE_SECURE=true setzen.
|
||||
COOKIE_SECURE=false
|
||||
# Nur bei einem vertrauenswürdigen Proxy mit passender Anzahl von Proxy-Hops setzen.
|
||||
TRUST_PROXY_HOPS=
|
||||
|
||||
# Beispielbildschirm und Galerie beim ersten Start anlegen.
|
||||
SEED_DEMO=true
|
||||
MAX_UPLOAD_MB=100
|
||||
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
data/
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
@ -0,0 +1,23 @@
|
||||
FROM node:24-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY index.html tsconfig.json vite.config.ts ./
|
||||
COPY src ./src
|
||||
COPY public ./public
|
||||
RUN npm run check && npm run build && npm prune --omit=dev
|
||||
|
||||
FROM node:24-bookworm-slim
|
||||
ENV NODE_ENV=production PORT=8080 DATA_DIR=/var/lib/syncova XDG_CACHE_HOME=/tmp
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends poppler-utils fonts-dejavu-core fonts-liberation \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& install -d -o node -g node -m 0750 /var/lib/syncova
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/package.json ./
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY server ./server
|
||||
USER node
|
||||
EXPOSE 8080
|
||||
CMD ["node", "server/index.js"]
|
||||
66
README.md
Normal file
66
README.md
Normal file
@ -0,0 +1,66 @@
|
||||
# Syncova Display
|
||||
|
||||
Selbst gehostete Infobildschirme für Schulen, Foyers und Wartebereiche. Die Verwaltung und der Kiosk-Player verwenden React, Vite und shadcn/ui. Der Webserver speichert Konfiguration und Benutzerkonten in PostgreSQL. Mediendateien liegen im lokalen Dateisystem.
|
||||
|
||||
## Start mit Docker Compose
|
||||
|
||||
Voraussetzungen sind Docker Engine und Docker Compose. Im Projektverzeichnis:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
In `.env` ein separates zufälliges Datenbankpasswort sowie E-Mail-Adresse und Passwort des ersten Administrationskontos eintragen. Das Admin-Passwort benötigt mindestens zwölf Zeichen. `SEED_DEMO=false` startet mit einer leeren Mediathek und ohne Beispielbildschirm.
|
||||
|
||||
```sh
|
||||
docker compose up -d --build
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
Die Verwaltung läuft unter `http://<server>:8080/admin`. Beim Erststart wird das Administrationskonto in PostgreSQL angelegt. Danach werden Konto und Passwort in der Verwaltung gepflegt. `ADMIN_PASSWORD` kann nach dem Erststart aus `.env` entfernt werden. Die App und PostgreSQL sind separate Dienste. Web- und Datenbankzugriff lassen sich damit unabhängig betreiben. Der Standardport bindet an alle Netzwerkschnittstellen, damit die Monitore über das LAN zugreifen können.
|
||||
|
||||
Für HTTPS hinter einem Reverse-Proxy `COOKIE_SECURE=true` setzen. Wenn der Proxy direkt auf demselben Rechner läuft, kann der Hostport mit `BIND_ADDRESS=127.0.0.1` auf Loopback beschränkt werden. Einen Proxy mit konsistentem Hostnamen verwenden, damit kopierte Kiosk-Links dieselbe Adresse benutzen. `TRUST_PROXY_HOPS` nur passend zur tatsächlichen Proxy-Kette setzen, da die Login-Drosselung die Client-IP verwendet.
|
||||
|
||||
## Bildschirme einrichten
|
||||
|
||||
1. PDFs und Bilder in der **Mediathek** hochladen.
|
||||
2. Unter **Bildschirme** einen Bildschirm erstellen und eines der vier Layouts auswählen. Die Bereiche lassen sich umsortieren.
|
||||
3. HTML, PDF, Bildergalerie oder Uhr hinzufügen. Für jeden Bereich sind Titel und ein optionales Sichtbarkeitsfenster einstellbar. Die dargestellte Uhr verwendet die Zeitzone des Bildschirms. Die Zeiteingaben im Editor verwenden die lokale Zeitzone des Verwaltungsbrowsers.
|
||||
4. Den Entwurf speichern oder ihn mit **Veröffentlichen** für den Kiosk freigeben. Die Entwurfsvorschau reagiert sofort auf Änderungen. Veröffentlichte Geräte fragen etwa alle 15 Sekunden nach einem geänderten Stand.
|
||||
5. Den Kiosk-Link auf dem Raspberry Pi öffnen, zum Beispiel mit Chromium in einer grafischen Sitzung.
|
||||
|
||||
```sh
|
||||
chromium --kiosk 'http://server:8080/display/DEIN-KIOSK-LINK'
|
||||
```
|
||||
|
||||
Der Kiosk-Link ist der Zugriffsschlüssel für den veröffentlichten Bildschirm und seine Medien. Jede Person mit dem Link kann die Anzeige öffnen. Der Link kann in der Verwaltung erneuert werden. Die dort angezeigte Verbindung beruht auf einem Abruf der Anzeige innerhalb der letzten 75 Sekunden. Redaktion und Administration können Bildschirme und Medien verwalten. Administrationskonten können zusätzlich Benutzer und Rollen pflegen.
|
||||
|
||||
HTML kann als Quelltext eingegeben oder aus einer lokalen HTML-Datei übernommen werden. Überschriften, Listen, Tabellen, Bilder und eine Auswahl an Inline-Formatierungen werden unterstützt. JavaScript und interaktive HTML-Elemente werden aus Inhalten entfernt.
|
||||
|
||||
## PDF-Wiedergabe und Raspberry Pi
|
||||
|
||||
Im fortlaufenden PDF-Modus werden Tempo und Randpause je Bereich eingestellt. Nach der Pause am Ende springt die Anzeige zum Anfang und wartet erneut die eingestellte Randpause. Alternativ gibt es einen zeitgesteuerten Seitenwechsel und eine feste erste Seite. Auto-Scroll kann auch bei HTML-Inhalten aktiviert werden.
|
||||
|
||||
Poppler liest beim Upload die Seitenmaße und rendert einzelne PDF-Seiten bei Bedarf. Der Server speichert die gerenderten JPEGs im Medien-Volume. Der Browser lädt im Scrollmodus die sichtbaren und angrenzenden Seiten in einer passenden Auflösung. Bilder werden beim Upload zusätzlich als WebP für die Wiedergabe aufbereitet. Damit arbeitet der Kiosk mit gewöhnlichen Bildern und benötigt weder ein Browser-PDF-Plugin noch das vollständige Originaldokument. Der Standardwert pro Upload beträgt 100 MB (`MAX_UPLOAD_MB`). PDFs können bis zu 500 Seiten enthalten und müssen unverschlüsselt sein.
|
||||
|
||||
## Persistenz und Sicherung
|
||||
|
||||
- **`postgres`** enthält Benutzer, Sitzungen, Bildschirme und Metadaten.
|
||||
- **`media`** enthält die Originaldateien und die abgeleiteten Bilddateien.
|
||||
- `docker compose down` behält beide Volumes. `docker compose down -v` löscht sie.
|
||||
- Für eine konsistente Sicherung den App-Dienst kurz anhalten, PostgreSQL mit `pg_dump` exportieren und das Medien-Volume separat sichern. Bei einer Wiederherstellung gehören beide Sicherungen zusammen. Der Sicherungsstand und die Medien sollten vor dem Wiederstart verfügbar sein.
|
||||
|
||||
## Lokale Entwicklung
|
||||
|
||||
Benötigt werden Node.js 24, eine PostgreSQL-Instanz sowie `pdfinfo` und `pdftoppm` aus Poppler. `DATABASE_URL` oder die üblichen `PG*`-Variablen und die Erststartwerte `ADMIN_EMAIL` und `ADMIN_PASSWORD` setzen. Für einen anderen lokalen Dateipfad kann `DATA_DIR` gesetzt werden. Standard ist `./data`.
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run check
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Für Änderungen an der Oberfläche kann zusätzlich `npm run dev` gestartet werden. Der Vite-Server leitet API-Anfragen an Port 8080 weiter.
|
||||
|
||||
Die Auswahl der Wiedergabefunktionen orientiert sich an der [IServ-Dokumentation zum Infobildschirm](https://doku.iserv.de/modules/infodisplay/). Die Oberfläche verwendet Komponenten aus dem [shadcn/ui-Registry](https://ui.shadcn.com/docs/installation/vite).
|
||||
9
components.json
Normal file
9
components.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": { "config": "", "css": "src/styles.css", "baseColor": "slate", "cssVariables": true },
|
||||
"iconLibrary": "lucide",
|
||||
"aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib" }
|
||||
}
|
||||
57
compose.yaml
Normal file
57
compose.yaml
Normal file
@ -0,0 +1,57 @@
|
||||
name: syncova-display
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
ports:
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${HTTP_PORT:-8080}:8080"
|
||||
environment:
|
||||
PGHOST: postgres
|
||||
PGDATABASE: syncova
|
||||
PGUSER: syncova
|
||||
PGPASSWORD: "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD in .env setzen}"
|
||||
ADMIN_NAME: "${ADMIN_NAME:-Administration}"
|
||||
ADMIN_EMAIL: "${ADMIN_EMAIL:-}"
|
||||
ADMIN_PASSWORD: "${ADMIN_PASSWORD:-}"
|
||||
COOKIE_SECURE: "${COOKIE_SECURE:-false}"
|
||||
TRUST_PROXY_HOPS: "${TRUST_PROXY_HOPS:-}"
|
||||
SEED_DEMO: "${SEED_DEMO:-true}"
|
||||
MAX_UPLOAD_MB: "${MAX_UPLOAD_MB:-100}"
|
||||
volumes:
|
||||
- media:/var/lib/syncova
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
start_period: 30s
|
||||
|
||||
postgres:
|
||||
image: postgres:17-bookworm
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: syncova
|
||||
POSTGRES_USER: syncova
|
||||
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:?POSTGRES_PASSWORD in .env setzen}"
|
||||
volumes:
|
||||
- postgres:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U syncova -d syncova"]
|
||||
interval: 5s
|
||||
timeout: 4s
|
||||
retries: 20
|
||||
|
||||
volumes:
|
||||
postgres:
|
||||
media:
|
||||
14
index.html
Normal file
14
index.html
Normal file
@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="de" class="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#10131a" />
|
||||
<meta name="description" content="Syncova Display – Infobildschirme und Inhalte zentral verwalten." />
|
||||
<title>Syncova Display</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
5784
package-lock.json
generated
Normal file
5784
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
45
package.json
Normal file
45
package.json
Normal file
@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "syncova-display",
|
||||
"version": "1.0.0",
|
||||
"description": "Selbst gehostete Infobildschirme mit Webverwaltung und Raspberry-Pi-Kiosk",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"start": "node --env-file-if-exists=.env server/index.js",
|
||||
"dev": "vite --host 0.0.0.0",
|
||||
"check": "tsc --noEmit"
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"compression": "^1.8.2",
|
||||
"dompurify": "^3.5.0",
|
||||
"express": "^5.3.0",
|
||||
"helmet": "^8.3.0",
|
||||
"lucide-react": "^1.79.0",
|
||||
"multer": "^2.5.0",
|
||||
"pg": "^8.23.1",
|
||||
"radix-ui": "^1.8.1",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"sanitize-html": "^2.18.2",
|
||||
"sharp": "^0.35.5",
|
||||
"tailwind-merge": "^3.7.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@types/node": "^26.6.7",
|
||||
"@types/react": "^19.3.1",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.3.0",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.3.8"
|
||||
},
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
}
|
||||
BIN
public/campus-preview.webp
Normal file
BIN
public/campus-preview.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
70
server/config.js
Normal file
70
server/config.js
Normal file
@ -0,0 +1,70 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import sanitizeHtml from 'sanitize-html'
|
||||
|
||||
export const storage = resolve(process.env.DATA_DIR || './data')
|
||||
export const uploadLimit = Number(process.env.MAX_UPLOAD_MB || 100) * 1024 * 1024
|
||||
if (!Number.isSafeInteger(uploadLimit) || uploadLimit < 1024 * 1024) {
|
||||
throw new Error('MAX_UPLOAD_MB muss mindestens 1 sein.')
|
||||
}
|
||||
|
||||
export const layoutLimits = { single: 1, split: 2, focus: 3, grid: 8 }
|
||||
const title = z.string().trim().min(1).max(100)
|
||||
const timeZone = z.string().max(80).refine(value => {
|
||||
try { new Intl.DateTimeFormat('de', { timeZone: value }); return true } catch { return false }
|
||||
})
|
||||
const schedule = {
|
||||
from: z.iso.datetime().nullable().default(null),
|
||||
until: z.iso.datetime().nullable().default(null),
|
||||
}
|
||||
const scroll = z.object({
|
||||
enabled: z.boolean(),
|
||||
speed: z.number().int().min(10).max(220),
|
||||
pause: z.number().min(0).max(30),
|
||||
})
|
||||
const htmlOptions = {
|
||||
allowedTags: [...sanitizeHtml.defaults.allowedTags, 'h1', 'h2', 'img', 'mark'],
|
||||
allowedAttributes: { '*': ['class', 'style'], img: ['src', 'alt', 'width', 'height'], td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan', 'scope'] },
|
||||
allowedSchemes: ['https'],
|
||||
allowProtocolRelative: false,
|
||||
allowedStyles: {
|
||||
'*': {
|
||||
color: [/^#[0-9a-f]{3,8}$/i], 'background-color': [/^#[0-9a-f]{3,8}$/i],
|
||||
'text-align': [/^(left|right|center|justify)$/], 'font-size': [/^\d+(\.\d+)?(rem|em|px|%)$/],
|
||||
'font-weight': [/^(normal|bold|[1-9]00)$/],
|
||||
},
|
||||
},
|
||||
transformTags: { a: 'span' },
|
||||
allowedClasses: { '*': ['eyebrow'] },
|
||||
}
|
||||
const widgetBase = { id: z.uuid(), title, showTitle: z.boolean(), ...schedule }
|
||||
const widget = z.discriminatedUnion('type', [
|
||||
z.object({ ...widgetBase, type: z.literal('html'), html: z.string().max(100_000).transform(value => sanitizeHtml(value, htmlOptions)), scroll }),
|
||||
z.object({ ...widgetBase, type: z.literal('pdf'), assetId: z.uuid(), mode: z.enum(['scroll', 'pages', 'static']), seconds: z.number().int().min(2).max(120), scroll }),
|
||||
z.object({ ...widgetBase, type: z.literal('gallery'), assetIds: z.array(z.uuid()).min(1).max(60), seconds: z.number().int().min(2).max(120), fit: z.enum(['cover', 'contain']) }),
|
||||
z.object({ ...widgetBase, type: z.literal('clock'), seconds: z.boolean(), date: z.boolean() }),
|
||||
])
|
||||
export const boardSchema = z.object({
|
||||
name: title,
|
||||
location: z.string().trim().max(100),
|
||||
layout: z.enum(['single', 'split', 'focus', 'grid']),
|
||||
theme: z.enum(['midnight', 'light', 'forest']),
|
||||
showHeader: z.boolean(),
|
||||
showClock: z.boolean(),
|
||||
timeZone,
|
||||
widgets: z.array(widget).max(8),
|
||||
}).refine(board => board.widgets.length <= layoutLimits[board.layout], { message: 'Das Layout bietet zu wenig Platz.', path: ['layout'] })
|
||||
.refine(board => new Set(board.widgets.map(item => item.id)).size === board.widgets.length, { message: 'Bereichs-IDs müssen eindeutig sein.', path: ['widgets'] })
|
||||
.refine(board => board.widgets.every(item => !item.from || !item.until || Date.parse(item.from) < Date.parse(item.until)), { message: 'Das Ende muss nach dem Start liegen.', path: ['widgets'] })
|
||||
|
||||
export const email = z.string().trim().toLowerCase().max(254).pipe(z.email())
|
||||
export const password = z.string().min(12).max(256)
|
||||
export const userSchema = z.object({ name: title, email, role: z.enum(['admin', 'editor']), active: z.boolean().default(true) })
|
||||
|
||||
export function references(board) {
|
||||
return new Map(board.widgets.flatMap(item => {
|
||||
if (item.type === 'pdf') return [[item.assetId, 'pdf']]
|
||||
if (item.type === 'gallery') return item.assetIds.map(id => [id, 'image'])
|
||||
return []
|
||||
}))
|
||||
}
|
||||
98
server/db.js
Normal file
98
server/db.js
Normal file
@ -0,0 +1,98 @@
|
||||
import { randomBytes, randomUUID } from 'node:crypto'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import pg from 'pg'
|
||||
import { boardSchema, email, password, references } from './config.js'
|
||||
import { hashPassword } from './security.js'
|
||||
import { importDemoImage } from './media.js'
|
||||
|
||||
export const pool = new pg.Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 10,
|
||||
connectionTimeoutMillis: 5000,
|
||||
})
|
||||
pool.on('error', error => console.error('PostgreSQL:', error.message))
|
||||
export const boardColumns = 'id, token, draft, published, revision, published_revision, created_at, updated_at, last_seen'
|
||||
export const assetColumns = 'id, name, kind, bytes, metadata, created_at'
|
||||
export const userColumns = 'id, name, email, role, active, created_at'
|
||||
export const newToken = () => randomBytes(24).toString('base64url')
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(status, message) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export async function transaction(action) {
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
const result = await action(client)
|
||||
await client.query('COMMIT')
|
||||
return result
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK')
|
||||
throw error
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
}
|
||||
|
||||
export async function setReferences(client, boardId, board, live) {
|
||||
const assets = references(board)
|
||||
if (assets.size) {
|
||||
const { rows } = await client.query('SELECT id, kind FROM assets WHERE id = ANY($1::uuid[]) FOR KEY SHARE', [[...assets.keys()]])
|
||||
if (rows.length !== assets.size || rows.some(asset => assets.get(asset.id) !== asset.kind)) {
|
||||
throw new HttpError(422, 'Mindestens eine Mediendatei fehlt oder hat den falschen Typ.')
|
||||
}
|
||||
}
|
||||
await client.query('DELETE FROM board_assets WHERE board_id=$1 AND live=$2', [boardId, live])
|
||||
if (assets.size) {
|
||||
await client.query('INSERT INTO board_assets (board_id, asset_id, live) SELECT $1, asset_id, $3 FROM unnest($2::uuid[]) AS asset_id', [boardId, [...assets.keys()], live])
|
||||
}
|
||||
}
|
||||
|
||||
async function seedDemo(client) {
|
||||
const assetId = randomUUID()
|
||||
const image = await importDemoImage(assetId)
|
||||
if (image) {
|
||||
await client.query('INSERT INTO assets (id, name, kind, bytes, metadata) VALUES ($1,$2,$3,$4,$5)', [assetId, 'Campus-Atrium.webp', 'image', image.bytes, image.metadata])
|
||||
}
|
||||
const widget = { showTitle: false, from: null, until: null }
|
||||
const board = boardSchema.parse({
|
||||
name: 'Campus-Lobby', location: 'Haupteingang · Erdgeschoss',
|
||||
layout: 'focus', theme: 'midnight', showHeader: true, showClock: true, timeZone: 'Europe/Berlin',
|
||||
widgets: [
|
||||
{ ...widget, id: randomUUID(), type: 'html', title: 'Willkommen', scroll: { enabled: false, speed: 42, pause: 3 },
|
||||
html: '<p class="eyebrow">CAMPUS AKTUELL</p><h1>Willkommen<br>auf dem Campus.</h1><p>Termine, Hinweise und Eindrücke aus unserem Schulalltag.</p>' },
|
||||
...(image ? [{ ...widget, id: randomUUID(), type: 'gallery', title: 'Campus-Galerie', assetIds: [assetId], seconds: 8, fit: 'cover' }] : []),
|
||||
{ ...widget, id: randomUUID(), type: 'html', title: 'Studienberatung', scroll: { enabled: false, speed: 42, pause: 3 },
|
||||
html: '<p class="eyebrow">SERVICE</p><h2>Studienberatung</h2><p>Montag bis Freitag · 09:00–15:00 Uhr</p>' },
|
||||
],
|
||||
})
|
||||
const id = randomUUID()
|
||||
await client.query('INSERT INTO boards (id,token,draft,published,published_revision) VALUES ($1,$2,$3,$3,1)', [id, newToken(), board])
|
||||
await setReferences(client, id, board, false)
|
||||
await setReferences(client, id, board, true)
|
||||
}
|
||||
|
||||
export async function initialise() {
|
||||
const schema = await readFile(new URL('./schema.sql', import.meta.url), 'utf8')
|
||||
await transaction(async client => {
|
||||
await client.query('SELECT pg_advisory_xact_lock(701826124)')
|
||||
await client.query(schema)
|
||||
const { rows: [result] } = await client.query('SELECT EXISTS (SELECT 1 FROM users) AS configured')
|
||||
if (result.configured) return
|
||||
|
||||
const parsedEmail = email.safeParse(process.env.ADMIN_EMAIL)
|
||||
const parsedPassword = password.safeParse(process.env.ADMIN_PASSWORD)
|
||||
if (!parsedEmail.success || !parsedPassword.success) {
|
||||
throw new Error('Für den Erststart ADMIN_EMAIL und ADMIN_PASSWORD (mindestens 12 Zeichen) setzen.')
|
||||
}
|
||||
|
||||
await client.query("INSERT INTO users (id,name,email,password,role) VALUES ($1,$2,$3,$4,'admin')", [
|
||||
randomUUID(), process.env.ADMIN_NAME?.trim().slice(0, 100) || 'Administration', parsedEmail.data, await hashPassword(parsedPassword.data),
|
||||
])
|
||||
if (process.env.SEED_DEMO !== 'false') await seedDemo(client)
|
||||
})
|
||||
}
|
||||
BIN
server/demo/campus.webp
Normal file
BIN
server/demo/campus.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 324 KiB |
331
server/index.js
Normal file
331
server/index.js
Normal file
@ -0,0 +1,331 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { rm } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import compression from 'compression'
|
||||
import express from 'express'
|
||||
import helmet from 'helmet'
|
||||
import multer from 'multer'
|
||||
import { z } from 'zod'
|
||||
import { boardSchema, email, password, uploadLimit, userSchema } from './config.js'
|
||||
import { assetColumns, boardColumns, HttpError, initialise, newToken, pool, setReferences, transaction, userColumns } from './db.js'
|
||||
import { mediaDir, prepareStorage, renderPage, saveUpload, staging } from './media.js'
|
||||
import { getSession, hashPassword, limitLogin, makeSession, sessionCookie, sessionHash, sessionLifetime, sessionOptions, verifyPassword } from './security.js'
|
||||
|
||||
const app = express()
|
||||
const port = Number(process.env.PORT || 8080)
|
||||
const dist = fileURLToPath(new URL('../dist', import.meta.url))
|
||||
const uuid = z.uuid()
|
||||
const boardSave = z.object({ board: boardSchema, revision: z.number().int().positive(), publish: z.boolean().default(false) })
|
||||
const revisionSchema = z.object({ revision: z.number().int().positive() })
|
||||
const safeUser = user => ({ id: user.id, name: user.name, email: user.email, role: user.role, active: user.active, created_at: user.created_at })
|
||||
const upload = multer({ dest: staging, limits: { fileSize: uploadLimit, files: 1, fields: 0, parts: 2 }, defParamCharset: 'utf8' })
|
||||
let uploads = 0
|
||||
|
||||
app.disable('x-powered-by')
|
||||
if (process.env.TRUST_PROXY_HOPS) app.set('trust proxy', Number(process.env.TRUST_PROXY_HOPS))
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
imgSrc: ["'self'", 'data:', 'https:'],
|
||||
scriptSrc: ["'self'"], styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
frameAncestors: ["'self'"], upgradeInsecureRequests: null,
|
||||
},
|
||||
},
|
||||
referrerPolicy: { policy: 'no-referrer' },
|
||||
strictTransportSecurity: sessionOptions.secure,
|
||||
xFrameOptions: { action: 'sameorigin' },
|
||||
}))
|
||||
app.use(compression())
|
||||
app.use('/api', (req, res, next) => {
|
||||
res.set('Cache-Control', 'no-store')
|
||||
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && ['cross-site', 'same-site'].includes(req.get('Sec-Fetch-Site'))) {
|
||||
return next(new HttpError(403, 'Die Anfrage stammt von einer fremden Seite.'))
|
||||
}
|
||||
next()
|
||||
})
|
||||
app.use('/api', express.json({ limit: '1mb' }))
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
await pool.query('SELECT 1')
|
||||
res.json({ status: 'ok' })
|
||||
})
|
||||
|
||||
async function requireUser(req, _res, next) {
|
||||
const token = getSession(req)
|
||||
if (!token) throw new HttpError(401, 'Bitte melde dich an.')
|
||||
const { rows: [user] } = await pool.query(
|
||||
'SELECT u.* FROM users u JOIN sessions s ON s.user_id=u.id WHERE s.token_hash=$1 AND s.expires_at > now() AND u.active',
|
||||
[sessionHash(token)],
|
||||
)
|
||||
if (!user) throw new HttpError(401, 'Deine Sitzung ist abgelaufen. Bitte melde dich erneut an.')
|
||||
req.user = user
|
||||
next()
|
||||
}
|
||||
|
||||
function requireAdmin(req, _res, next) {
|
||||
if (req.user.role !== 'admin') throw new HttpError(403, 'Diese Aktion erfordert ein Administrationskonto.')
|
||||
next()
|
||||
}
|
||||
|
||||
app.post('/api/auth/login', limitLogin, async (req, res) => {
|
||||
const parsed = z.object({ email, password: z.string().min(1).max(256) }).safeParse(req.body)
|
||||
if (!parsed.success) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
||||
const { rows: [user] } = await pool.query('SELECT * FROM users WHERE email=$1', [parsed.data.email])
|
||||
const valid = await verifyPassword(parsed.data.password, user?.password)
|
||||
if (!valid || !user?.active) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
||||
const token = makeSession()
|
||||
await transaction(async client => {
|
||||
const { rowCount } = await client.query('SELECT id FROM users WHERE id=$1 AND password=$2 AND active FOR SHARE', [user.id, user.password])
|
||||
if (!rowCount) throw new HttpError(401, 'E-Mail oder Passwort stimmt nicht.')
|
||||
await client.query('DELETE FROM sessions WHERE expires_at <= now()')
|
||||
await client.query('INSERT INTO sessions (token_hash,user_id,expires_at) VALUES ($1,$2,$3)', [sessionHash(token), user.id, new Date(Date.now() + sessionLifetime)])
|
||||
})
|
||||
res.cookie(sessionCookie, token, { ...sessionOptions, maxAge: sessionLifetime }).json(safeUser(user))
|
||||
})
|
||||
|
||||
app.get('/api/auth/me', requireUser, (req, res) => res.json(safeUser(req.user)))
|
||||
app.post('/api/auth/logout', async (req, res) => {
|
||||
const token = getSession(req)
|
||||
if (token) await pool.query('DELETE FROM sessions WHERE token_hash=$1', [sessionHash(token)])
|
||||
res.clearCookie(sessionCookie, sessionOptions).status(204).end()
|
||||
})
|
||||
app.put('/api/auth/password', requireUser, async (req, res) => {
|
||||
const input = z.object({ current: z.string().min(1).max(256), password }).parse(req.body)
|
||||
if (!await verifyPassword(input.current, req.user.password)) throw new HttpError(422, 'Das bisherige Passwort stimmt nicht.')
|
||||
const hashed = await hashPassword(input.password)
|
||||
const tokenHash = sessionHash(getSession(req))
|
||||
await transaction(async client => {
|
||||
const result = await client.query('UPDATE users SET password=$1 WHERE id=$2 AND password=$3', [hashed, req.user.id, req.user.password])
|
||||
if (!result.rowCount) throw new HttpError(409, 'Das Passwort wurde zwischenzeitlich geändert.')
|
||||
await client.query('DELETE FROM sessions WHERE user_id=$1 AND token_hash<>$2', [req.user.id, tokenHash])
|
||||
})
|
||||
res.status(204).end()
|
||||
})
|
||||
|
||||
app.get('/api/boards', requireUser, async (_req, res) => {
|
||||
const { rows } = await pool.query(`SELECT ${boardColumns} FROM boards ORDER BY updated_at DESC, id`)
|
||||
res.json(rows)
|
||||
})
|
||||
app.post('/api/boards', requireUser, async (req, res) => {
|
||||
const board = boardSchema.parse(req.body)
|
||||
const id = randomUUID()
|
||||
const result = await transaction(async client => {
|
||||
const { rows: [row] } = await client.query(`INSERT INTO boards (id,token,draft) VALUES ($1,$2,$3) RETURNING ${boardColumns}`, [id, newToken(), board])
|
||||
await setReferences(client, id, board, false)
|
||||
return row
|
||||
})
|
||||
res.status(201).json(result)
|
||||
})
|
||||
|
||||
app.put('/api/boards/:id', requireUser, async (req, res) => {
|
||||
const id = uuid.parse(req.params.id)
|
||||
const { board, revision, publish } = boardSave.parse(req.body)
|
||||
if (publish && !board.widgets.length) throw new HttpError(422, 'Füge vor dem Veröffentlichen mindestens einen Bereich hinzu.')
|
||||
const result = await transaction(async client => {
|
||||
const { rows: [current] } = await client.query('SELECT revision FROM boards WHERE id=$1 FOR UPDATE', [id])
|
||||
if (!current) throw new HttpError(404, 'Der Bildschirm wurde nicht gefunden.')
|
||||
if (current.revision !== revision) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet. Öffne ihn erneut, um den aktuellen Stand zu laden.')
|
||||
await setReferences(client, id, board, false)
|
||||
if (publish) await setReferences(client, id, board, true)
|
||||
const { rows: [row] } = await client.query(`UPDATE boards SET draft=$2, revision=revision+1, updated_at=now(),
|
||||
published=CASE WHEN $3 THEN $2 ELSE published END,
|
||||
published_revision=CASE WHEN $3 THEN revision+1 ELSE published_revision END
|
||||
WHERE id=$1 RETURNING ${boardColumns}`, [id, board, publish])
|
||||
return row
|
||||
})
|
||||
res.json(result)
|
||||
})
|
||||
app.post('/api/boards/:id/token', requireUser, async (req, res) => {
|
||||
const { revision } = revisionSchema.parse(req.body)
|
||||
const { rows: [row] } = await pool.query(`UPDATE boards SET token=$2, last_seen=NULL, updated_at=now() WHERE id=$1 AND revision=$3 RETURNING ${boardColumns}`, [uuid.parse(req.params.id), newToken(), revision])
|
||||
if (!row) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
||||
res.json(row)
|
||||
})
|
||||
app.post('/api/boards/:id/unpublish', requireUser, async (req, res) => {
|
||||
const id = uuid.parse(req.params.id)
|
||||
const { revision } = revisionSchema.parse(req.body)
|
||||
const result = await transaction(async client => {
|
||||
const { rows: [row] } = await client.query(`UPDATE boards SET published=NULL, published_revision=NULL,
|
||||
updated_at=now(), revision=revision+1, last_seen=NULL WHERE id=$1 AND revision=$2 RETURNING ${boardColumns}`, [id, revision])
|
||||
if (!row) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
||||
await client.query('DELETE FROM board_assets WHERE board_id=$1 AND live', [id])
|
||||
return row
|
||||
})
|
||||
res.json(result)
|
||||
})
|
||||
app.delete('/api/boards/:id', requireUser, async (req, res) => {
|
||||
const { revision } = revisionSchema.parse(req.body)
|
||||
const result = await pool.query('DELETE FROM boards WHERE id=$1 AND revision=$2', [uuid.parse(req.params.id), revision])
|
||||
if (!result.rowCount) throw new HttpError(409, 'Der Bildschirm wurde anderweitig bearbeitet.')
|
||||
res.status(204).end()
|
||||
})
|
||||
|
||||
app.get('/api/assets', requireUser, async (_req, res) => {
|
||||
const { rows } = await pool.query(`SELECT ${assetColumns} FROM assets ORDER BY created_at DESC`)
|
||||
res.json(rows)
|
||||
})
|
||||
function limitUploads(_req, res, next) {
|
||||
if (uploads >= 3) throw new HttpError(503, 'Es laufen bereits mehrere Uploads. Bitte versuche es gleich erneut.')
|
||||
uploads++
|
||||
res.once('close', () => { uploads-- })
|
||||
next()
|
||||
}
|
||||
app.post('/api/assets', requireUser, limitUploads, upload.single('file'), async (req, res) => {
|
||||
if (!req.file) throw new HttpError(422, 'Wähle eine Datei aus.')
|
||||
const id = randomUUID()
|
||||
try {
|
||||
let asset
|
||||
try { asset = await saveUpload(req.file, id) } catch (error) {
|
||||
if (error.syscall && !error.cmd) throw error
|
||||
throw new HttpError(422, error.cmd ? 'Die PDF-Datei konnte nicht gelesen werden. Prüfe, ob sie intakt und unverschlüsselt ist.' : error.message)
|
||||
}
|
||||
const { rows: [row] } = await pool.query(
|
||||
`INSERT INTO assets (id,name,kind,bytes,metadata) VALUES ($1,$2,$3,$4,$5) RETURNING ${assetColumns}`,
|
||||
[id, asset.name, asset.kind, asset.bytes, asset.metadata],
|
||||
)
|
||||
res.status(201).json(row)
|
||||
} catch (error) {
|
||||
await rm(mediaDir(id), { recursive: true, force: true })
|
||||
throw error
|
||||
} finally {
|
||||
await rm(req.file.path, { force: true })
|
||||
}
|
||||
})
|
||||
app.delete('/api/assets/:id', requireUser, async (req, res) => {
|
||||
const id = uuid.parse(req.params.id)
|
||||
try {
|
||||
const result = await pool.query('DELETE FROM assets WHERE id=$1', [id])
|
||||
if (!result.rowCount) throw new HttpError(404, 'Die Datei wurde nicht gefunden.')
|
||||
} catch (error) {
|
||||
if (error.code === '23503' || error.code === '23001') {
|
||||
throw new HttpError(409, 'Die Datei wird in einem Entwurf oder auf einem veröffentlichten Bildschirm verwendet.')
|
||||
}
|
||||
throw error
|
||||
}
|
||||
await rm(mediaDir(id), { recursive: true, force: true }).catch(error => console.error('Datei löschen:', error))
|
||||
res.status(204).end()
|
||||
})
|
||||
|
||||
async function findAsset(id, token) {
|
||||
const columns = assetColumns.split(', ').map(column => `a.${column}`).join(', ')
|
||||
const result = token
|
||||
? await pool.query(`SELECT ${columns} FROM assets a JOIN board_assets r ON r.asset_id=a.id AND r.live
|
||||
JOIN boards b ON b.id=r.board_id WHERE b.token=$1 AND a.id=$2 AND b.published IS NOT NULL`, [token, id])
|
||||
: await pool.query(`SELECT ${assetColumns} FROM assets WHERE id=$1`, [id])
|
||||
if (!result.rows[0]) throw new HttpError(404, 'Die Datei wurde nicht gefunden.')
|
||||
return result.rows[0]
|
||||
}
|
||||
|
||||
async function sendMedia(req, res) {
|
||||
const token = req.params.token ? parseToken(req.params.token) : null
|
||||
const asset = await findAsset(uuid.parse(req.params.id), token)
|
||||
const item = String(req.params.item)
|
||||
res.set('Cache-Control', 'private, no-cache')
|
||||
const etag = `"${asset.id}-${item}"`
|
||||
res.set('ETag', etag)
|
||||
if (asset.kind === 'image' && item === 'image') return res.type('webp').sendFile(join(mediaDir(asset.id), 'display.webp'))
|
||||
const pageRequest = item.match(/^page-(\d+)-(800|1600|2400)$/)
|
||||
if (asset.kind !== 'pdf' || !pageRequest || Number(pageRequest[1]) < 1 || Number(pageRequest[1]) > asset.metadata.pages.length) {
|
||||
throw new HttpError(404, 'Die Seite wurde nicht gefunden.')
|
||||
}
|
||||
if (req.fresh) return res.status(304).end()
|
||||
const file = await renderPage(asset.id, Number(pageRequest[1]), Number(pageRequest[2]))
|
||||
res.type('jpeg').sendFile(file)
|
||||
}
|
||||
|
||||
function parseToken(value) {
|
||||
if (!/^[\w-]{32}$/.test(value)) throw new HttpError(404, 'Die Anzeige wurde nicht gefunden.')
|
||||
return value
|
||||
}
|
||||
app.get('/api/media/:id/:item', requireUser, sendMedia)
|
||||
app.get('/api/display/:token/media/:id/:item', sendMedia)
|
||||
app.get('/api/display/:token', async (req, res) => {
|
||||
const token = parseToken(req.params.token)
|
||||
const { rows: [row] } = await pool.query(`SELECT b.id, b.published AS board,
|
||||
(b.last_seen IS NULL OR b.last_seen < now() - interval '25 seconds') AS record_visit,
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('id', a.id, 'name', a.name, 'kind', a.kind, 'metadata', a.metadata) ORDER BY a.id)
|
||||
FROM assets a JOIN board_assets r ON r.asset_id=a.id WHERE r.board_id=b.id AND r.live), '[]'::jsonb) AS assets
|
||||
FROM boards b WHERE b.token=$1 AND b.published IS NOT NULL`, [token])
|
||||
if (!row) throw new HttpError(404, 'Diese Anzeige ist nicht veröffentlicht oder der Link wurde erneuert.')
|
||||
if (row.record_visit) {
|
||||
await pool.query("UPDATE boards SET last_seen=now() WHERE id=$1 AND token=$2 AND published IS NOT NULL AND (last_seen IS NULL OR last_seen < now() - interval '25 seconds')", [row.id, token])
|
||||
}
|
||||
const body = JSON.stringify({ board: row.board, assets: row.assets })
|
||||
const etag = `"${createHash('sha256').update(body).digest('base64url')}"`
|
||||
res.set('Cache-Control', 'private, no-cache')
|
||||
res.set('ETag', etag)
|
||||
if (req.get('If-None-Match') === etag) return res.status(304).end()
|
||||
res.type('json').send(body)
|
||||
})
|
||||
|
||||
app.get('/api/users', requireUser, requireAdmin, async (_req, res) => {
|
||||
const { rows } = await pool.query(`SELECT ${userColumns} FROM users ORDER BY created_at`)
|
||||
res.json(rows)
|
||||
})
|
||||
const userEdit = userSchema.extend({ password: password.optional() })
|
||||
app.post('/api/users', requireUser, requireAdmin, async (req, res) => {
|
||||
const input = userEdit.required({ password: true }).parse(req.body)
|
||||
const { rows: [row] } = await pool.query(
|
||||
`INSERT INTO users (id,name,email,role,active,password) VALUES ($1,$2,$3,$4,$5,$6) RETURNING ${userColumns}`,
|
||||
[randomUUID(), input.name, input.email, input.role, input.active, await hashPassword(input.password)],
|
||||
)
|
||||
res.status(201).json(row)
|
||||
})
|
||||
app.put('/api/users/:id', requireUser, requireAdmin, async (req, res) => {
|
||||
const id = uuid.parse(req.params.id)
|
||||
const input = userEdit.parse(req.body)
|
||||
const hashed = input.password ? await hashPassword(input.password) : null
|
||||
const user = await transaction(async client => {
|
||||
await client.query('SELECT pg_advisory_xact_lock(701826125)')
|
||||
const { rows: [actor] } = await client.query("SELECT id FROM users WHERE id=$1 AND role='admin' AND active", [req.user.id])
|
||||
if (!actor) throw new HttpError(403, 'Deine Berechtigung wurde geändert.')
|
||||
const { rows: [current] } = await client.query('SELECT role,active FROM users WHERE id=$1 FOR UPDATE', [id])
|
||||
if (!current) throw new HttpError(404, 'Das Konto wurde nicht gefunden.')
|
||||
if (current.role === 'admin' && current.active && (input.role !== 'admin' || !input.active)) {
|
||||
const { rows: [other] } = await client.query("SELECT id FROM users WHERE id<>$1 AND role='admin' AND active LIMIT 1", [id])
|
||||
if (!other) throw new HttpError(409, 'Mindestens ein aktives Administrationskonto muss erhalten bleiben.')
|
||||
}
|
||||
const { rows: [row] } = await client.query(`UPDATE users SET name=$2,email=$3,role=$4,active=$5,
|
||||
password=COALESCE($6,password) WHERE id=$1 RETURNING ${userColumns}`, [id, input.name, input.email, input.role, input.active, hashed])
|
||||
if (hashed || !input.active) await client.query('DELETE FROM sessions WHERE user_id=$1', [id])
|
||||
return row
|
||||
})
|
||||
res.json(user)
|
||||
})
|
||||
|
||||
app.use('/api', (_req, _res, next) => next(new HttpError(404, 'Diese Adresse wurde nicht gefunden.')))
|
||||
app.use(express.static(dist, {
|
||||
setHeaders(res, path) {
|
||||
res.set('Cache-Control', path.startsWith(join(dist, 'assets') + '/') ? 'public, max-age=31536000, immutable' : 'no-cache')
|
||||
},
|
||||
}))
|
||||
app.get(['/', '/admin', '/admin/{*section}', '/display/:token'], (_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 z.ZodError) {
|
||||
const issue = error.issues[0]
|
||||
return res.status(422).json({ error: issue.code === 'custom' ? issue.message : 'Prüfe die Eingaben auf fehlende oder ungültige Werte.' })
|
||||
}
|
||||
if (error instanceof multer.MulterError) {
|
||||
return res.status(error.code === 'LIMIT_FILE_SIZE' ? 413 : 422).json({ error: error.code === 'LIMIT_FILE_SIZE'
|
||||
? `Die Datei ist größer als ${uploadLimit / 1024 / 1024} MB.` : 'Es kann genau eine Datei pro Upload verarbeitet werden.' })
|
||||
}
|
||||
if (error.code === '23505') return res.status(409).json({ error: 'Diese E-Mail-Adresse ist bereits vergeben.' })
|
||||
if (error.status >= 400 && error.status < 500) return res.status(error.status).json({ error: error instanceof HttpError ? error.message : 'Die Anfrage konnte nicht verarbeitet werden.' })
|
||||
console.error(error)
|
||||
res.status(error.status === 503 ? 503 : 500).json({ error: error.status === 503 ? 'Die Verarbeitung ist gerade ausgelastet.' : 'Der Server konnte die Anfrage nicht verarbeiten.' })
|
||||
})
|
||||
|
||||
await prepareStorage()
|
||||
await initialise()
|
||||
const server = app.listen(port, process.env.HOST || '0.0.0.0', () => console.log(`Syncova Display läuft auf Port ${port}.`))
|
||||
server.requestTimeout = 300_000
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) {
|
||||
process.once(signal, () => {
|
||||
server.close(() => void pool.end())
|
||||
})
|
||||
}
|
||||
118
server/media.js
Normal file
118
server/media.js
Normal file
@ -0,0 +1,118 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { access, copyFile, mkdir, open, rename, rm, stat } from 'node:fs/promises'
|
||||
import { basename, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { promisify } from 'node:util'
|
||||
import sharp from 'sharp'
|
||||
import { storage } from './config.js'
|
||||
|
||||
const run = promisify(execFile)
|
||||
export const files = join(storage, 'media')
|
||||
export const staging = join(storage, 'incoming')
|
||||
export const mediaDir = id => join(files, id)
|
||||
const original = id => join(mediaDir(id), 'original')
|
||||
const commands = { timeout: 30_000, maxBuffer: 512 * 1024, env: {
|
||||
PATH: process.env.PATH, HOME: process.env.HOME, XDG_CACHE_HOME: process.env.XDG_CACHE_HOME, LC_ALL: 'C',
|
||||
} }
|
||||
const imageOptions = { limitInputPixels: 40_000_000, failOn: 'error' }
|
||||
const pdfLimit = 500
|
||||
|
||||
export async function prepareStorage() {
|
||||
await mkdir(files, { recursive: true, mode: 0o750 })
|
||||
await mkdir(staging, { recursive: true, mode: 0o750 })
|
||||
}
|
||||
|
||||
async function pdfMetadata(path) {
|
||||
const { stdout } = await run('pdfinfo', [path], commands)
|
||||
const count = Number(stdout.match(/^Pages:\s+(\d+)$/m)?.[1])
|
||||
if (!count || count > pdfLimit || /^Encrypted:\s+yes/m.test(stdout)) {
|
||||
throw new Error(`PDFs müssen unverschlüsselt sein und dürfen höchstens ${pdfLimit} Seiten haben.`)
|
||||
}
|
||||
|
||||
const { stdout: details } = await run('pdfinfo', ['-f', '1', '-l', String(count), path], commands)
|
||||
const sizes = [...details.matchAll(/^Page\s+(?:(\d+)\s+)?size:\s*([\d.]+)\s+x\s+([\d.]+)/gm)]
|
||||
const rotations = [...details.matchAll(/^Page\s+(?:(\d+)\s+)?rot:\s*(-?\d+)/gm)]
|
||||
const turns = new Map(rotations.map((match, index) => [Number(match[1] || index + 1), Math.abs(Number(match[2])) % 180 === 90]))
|
||||
if (sizes.length !== count) throw new Error('Die Seitengrößen konnten nicht gelesen werden.')
|
||||
return { pages: sizes.map(([ , page, width, height], index) => {
|
||||
const ratio = turns.get(Number(page || index + 1)) ? Number(height) / Number(width) : Number(width) / Number(height)
|
||||
return Math.max(0.01, Math.min(100, ratio))
|
||||
}) }
|
||||
}
|
||||
|
||||
async function imageMetadata(path, target) {
|
||||
const image = sharp(path, imageOptions)
|
||||
const { format } = await image.metadata()
|
||||
if (!['jpeg', 'png', 'webp', 'gif', 'avif', 'heif'].includes(format)) {
|
||||
throw new Error('Unterstützte Bildformate sind JPEG, PNG, WebP, GIF und AVIF.')
|
||||
}
|
||||
const { width, height } = await image.autoOrient()
|
||||
.resize(1920, 1920, { fit: 'inside', withoutEnlargement: true }).webp({ quality: 82 }).toFile(target)
|
||||
return { width, height }
|
||||
}
|
||||
|
||||
export async function saveUpload(file, id) {
|
||||
const input = await open(file.path)
|
||||
const buffer = Buffer.alloc(1024)
|
||||
try { await input.read(buffer, 0, buffer.length, 0) } finally { await input.close() }
|
||||
const isPdf = buffer.includes('%PDF-')
|
||||
await mkdir(mediaDir(id))
|
||||
const metadata = isPdf
|
||||
? await pdfMetadata(file.path)
|
||||
: await imageMetadata(file.path, join(mediaDir(id), 'display.webp'))
|
||||
await rename(file.path, original(id))
|
||||
const name = basename(file.originalname).replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 240) || 'Datei'
|
||||
return { id, name, kind: isPdf ? 'pdf' : 'image', bytes: file.size, metadata }
|
||||
}
|
||||
|
||||
export async function importDemoImage(id) {
|
||||
const path = fileURLToPath(new URL('./demo/campus.webp', import.meta.url))
|
||||
const file = await stat(path).catch(error => {
|
||||
if (error.code !== 'ENOENT') throw error
|
||||
return null
|
||||
})
|
||||
if (!file) return null
|
||||
await mkdir(mediaDir(id))
|
||||
await copyFile(path, original(id))
|
||||
await copyFile(path, join(mediaDir(id), 'display.webp'))
|
||||
const { width, height } = await sharp(path).metadata()
|
||||
return { bytes: file.size, metadata: { width, height } }
|
||||
}
|
||||
|
||||
const rendering = new Map()
|
||||
const queue = []
|
||||
let running = 0
|
||||
const renderConcurrency = 2
|
||||
|
||||
function dispatch() {
|
||||
while (running < renderConcurrency && queue.length) {
|
||||
const { action, resolve, reject } = queue.shift()
|
||||
running++
|
||||
action().then(resolve, reject).finally(() => { running--; dispatch() })
|
||||
}
|
||||
}
|
||||
|
||||
export async function renderPage(id, page, size) {
|
||||
const target = join(mediaDir(id), `page-${page}-${size}.jpg`)
|
||||
try { await access(target); return target } catch (error) { if (error.code !== 'ENOENT') throw error }
|
||||
if (rendering.has(target)) return rendering.get(target)
|
||||
if (queue.length >= 40) throw Object.assign(new Error('PDF-Renderer ausgelastet.'), { status: 503 })
|
||||
|
||||
const pending = new Promise((resolve, reject) => {
|
||||
queue.push({ resolve, reject, action: async () => {
|
||||
const temp = join(mediaDir(id), `render-${randomUUID()}`)
|
||||
try {
|
||||
await run('pdftoppm', ['-f', String(page), '-l', String(page), '-scale-to', String(size),
|
||||
'-jpeg', '-jpegopt', 'quality=83,optimize=y', '-singlefile', original(id), temp], commands)
|
||||
await rename(temp + '.jpg', target)
|
||||
return target
|
||||
} finally {
|
||||
await rm(temp + '.jpg', { force: true })
|
||||
}
|
||||
} })
|
||||
dispatch()
|
||||
}).finally(() => rendering.delete(target))
|
||||
rendering.set(target, pending)
|
||||
return pending
|
||||
}
|
||||
46
server/schema.sql
Normal file
46
server/schema.sql
Normal file
@ -0,0 +1,46 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
email text NOT NULL UNIQUE,
|
||||
password text NOT NULL,
|
||||
role text NOT NULL CHECK (role IN ('admin', 'editor')),
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS sessions_user_id ON sessions (user_id);
|
||||
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions (expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS assets (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
kind text NOT NULL CHECK (kind IN ('pdf', 'image')),
|
||||
bytes bigint NOT NULL,
|
||||
metadata jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS boards (
|
||||
id uuid PRIMARY KEY,
|
||||
token text NOT NULL UNIQUE,
|
||||
draft jsonb NOT NULL,
|
||||
published jsonb,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
published_revision integer,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_seen timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS board_assets (
|
||||
board_id uuid NOT NULL REFERENCES boards(id) ON DELETE CASCADE,
|
||||
asset_id uuid NOT NULL REFERENCES assets(id) ON DELETE RESTRICT,
|
||||
live boolean NOT NULL,
|
||||
PRIMARY KEY (board_id, asset_id, live)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS board_assets_lookup ON board_assets(asset_id);
|
||||
49
server/security.js
Normal file
49
server/security.js
Normal file
@ -0,0 +1,49 @@
|
||||
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
const derive = promisify(scrypt)
|
||||
const scryptOptions = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
|
||||
const dummyHash = '98a236bb22addb8f79d9780e7e1f85d0:' + '0'.repeat(128)
|
||||
export const sessionHash = token => createHash('sha256').update(token).digest('hex')
|
||||
export const makeSession = () => randomBytes(32).toString('base64url')
|
||||
export const sessionCookie = 'syncova_session'
|
||||
export const sessionOptions = {
|
||||
httpOnly: true, sameSite: 'strict', secure: process.env.COOKIE_SECURE === 'true', path: '/',
|
||||
}
|
||||
export const sessionLifetime = 7 * 24 * 60 * 60 * 1000
|
||||
|
||||
export async function hashPassword(password) {
|
||||
const salt = randomBytes(16).toString('hex')
|
||||
const hash = await derive(password, salt, 64, scryptOptions)
|
||||
return `${salt}:${hash.toString('hex')}`
|
||||
}
|
||||
|
||||
export async function verifyPassword(password, stored = dummyHash) {
|
||||
const [salt, hash] = stored.split(':')
|
||||
const candidate = await derive(password, salt, 64, scryptOptions)
|
||||
return timingSafeEqual(candidate, Buffer.from(hash, 'hex'))
|
||||
}
|
||||
|
||||
export function getSession(req) {
|
||||
return req.headers.cookie?.match(/(?:^|;\s*)syncova_session=([\w-]{43})(?:;|$)/)?.[1]
|
||||
}
|
||||
|
||||
const loginAttempts = new Map()
|
||||
export function limitLogin(req, res, next) {
|
||||
const now = Date.now()
|
||||
if (loginAttempts.size >= 1000) {
|
||||
for (const [key, value] of loginAttempts) if (value.until <= now) loginAttempts.delete(key)
|
||||
}
|
||||
const key = req.ip
|
||||
let attempt = loginAttempts.get(key)
|
||||
if (!attempt || attempt.until <= now) {
|
||||
if (loginAttempts.size >= 10_000) return res.status(429).json({ error: 'Bitte versuche es in einigen Minuten erneut.' })
|
||||
attempt = { count: 0, until: now + 10 * 60 * 1000 }
|
||||
loginAttempts.set(key, attempt)
|
||||
}
|
||||
if (++attempt.count > 12) {
|
||||
res.set('Retry-After', String(Math.ceil((attempt.until - now) / 1000)))
|
||||
return res.status(429).json({ error: 'Zu viele Anmeldeversuche. Bitte warte einige Minuten.' })
|
||||
}
|
||||
next()
|
||||
}
|
||||
67
src/admin-ui.tsx
Normal file
67
src/admin-ui.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import { useEffect, useId, useRef, type ReactNode, type SelectHTMLAttributes } from 'react'
|
||||
import { AlertCircle, ChevronDown, LoaderCircle, MonitorPlay, X } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { SavedBoard } from '@/lib/types'
|
||||
|
||||
export function Brand() {
|
||||
return <div className="brand"><span className="brand-icon"><MonitorPlay size={20} /></span>
|
||||
<div><strong>syncova<span>.</span></strong><small>Display</small></div>
|
||||
</div>
|
||||
}
|
||||
|
||||
export function Status({ board }: { board: SavedBoard }) {
|
||||
const live = !!board.published
|
||||
return <Badge className={cn('status-badge', live ? 'status-live' : 'status-draft')}>
|
||||
<i />{live ? 'Veröffentlicht' : 'Entwurf'}
|
||||
</Badge>
|
||||
}
|
||||
|
||||
export function ButtonProgress({ busy }: { busy: boolean }) {
|
||||
return busy ? <LoaderCircle className="animate-spin" aria-hidden="true" /> : null
|
||||
}
|
||||
|
||||
export function Feedback({ message, kind = 'error' }: { message: string; kind?: 'error' | 'success' }) {
|
||||
if (!message) return null
|
||||
return <div className={`feedback feedback-${kind}`} role={kind === 'error' ? 'alert' : 'status'}>
|
||||
<AlertCircle size={17} aria-hidden="true" /> <span>{message}</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
export function Field({ label, id, hint, children }: { label: string; id: string; hint?: string; children: ReactNode }) {
|
||||
return <div className="form-field">
|
||||
<Label htmlFor={id}>{label}</Label>
|
||||
{children}
|
||||
{hint && <p className="field-hint">{hint}</p>}
|
||||
</div>
|
||||
}
|
||||
|
||||
export function Select({ className, ...props }: SelectHTMLAttributes<HTMLSelectElement>) {
|
||||
return <div className={cn('select-wrap', className)}><select {...props} /><ChevronDown size={16} aria-hidden="true" /></div>
|
||||
}
|
||||
|
||||
export function Toggle({ label, checked, onChange, description }: {
|
||||
label: string; checked: boolean; onChange: (checked: boolean) => void; description?: string
|
||||
}) {
|
||||
return <label className="toggle-row">
|
||||
<span><strong>{label}</strong>{description && <small>{description}</small>}</span>
|
||||
<input type="checkbox" role="switch" checked={checked} onChange={event => onChange(event.target.checked)} />
|
||||
<span className="toggle-track" aria-hidden="true" />
|
||||
</label>
|
||||
}
|
||||
|
||||
export function Dialog({ title, description, onClose, children }: {
|
||||
title: string; description?: string; onClose: () => void; children: ReactNode
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const id = useId()
|
||||
useEffect(() => { const dialog = ref.current!; dialog.showModal(); return () => dialog.close() }, [])
|
||||
return <dialog className="dialog" ref={ref} aria-labelledby={id} onCancel={event => { event.preventDefault(); onClose() }}>
|
||||
<div className="dialog-head"><div><h2 id={id}>{title}</h2>{description && <p>{description}</p>}</div>
|
||||
<Button type="button" variant="ghost" size="icon" aria-label="Schließen" onClick={onClose}><X /></Button>
|
||||
</div>
|
||||
{children}
|
||||
</dialog>
|
||||
}
|
||||
214
src/admin.css
Normal file
214
src/admin.css
Normal file
@ -0,0 +1,214 @@
|
||||
.app-shell { display: grid; grid-template-columns: 236px minmax(0, 1fr); min-height: 100dvh; }
|
||||
.sidebar { display: flex; flex-direction: column; min-width: 0; position: sticky; top: 0; height: 100dvh; background: #151922; border-right: 1px solid #252d39; }
|
||||
.sidebar-brand { display: block; padding: 28px 24px 27px; text-decoration: none; }
|
||||
.brand { display: flex; align-items: center; gap: 11px; width: max-content; }
|
||||
.brand-icon { display: grid; place-items: center; width: 39px; height: 39px; color: #102c27; background: #79e4d2; border-radius: 11px; }
|
||||
.brand strong, .brand small { display: block; line-height: 1.1; }
|
||||
.brand strong { color: #f4f8fe; font-size: 1.25rem; letter-spacing: -.07em; font-weight: 770; }
|
||||
.brand strong span { color: var(--primary); }
|
||||
.brand small { color: var(--muted-foreground); letter-spacing: .07em; font-size: .75rem; margin-top: .16rem; }
|
||||
.sidebar-body { flex: 1; overflow: auto; padding: 5px 13px 20px; }
|
||||
.nav-caption { margin: 18px 11px 9px; color: #92a0b5; font-size: .72rem; text-transform: uppercase; letter-spacing: .09em; font-weight: 670; }
|
||||
.sidebar nav { display: grid; gap: 4px; margin-bottom: 28px; }
|
||||
.sidebar nav a { display: flex; align-items: center; gap: 12px; padding: 11px 12px; border-radius: 8px; color: var(--muted-foreground); font-size: .91rem; font-weight: 540; }
|
||||
.sidebar nav a > svg { width: 17px; height: 17px; flex: none; }
|
||||
.sidebar nav a:hover { background: #222a36; color: var(--foreground); }
|
||||
.sidebar nav a[aria-current] { color: #a0edde; background: #233a3b; font-weight: 650; }
|
||||
.sidebar-user { padding: 17px 13px 17px 16px; border-top: 1px solid var(--border); display: flex; align-items: center; gap: 9px; }
|
||||
.avatar { width: 34px; height: 34px; border-radius: 9px; background: #26403f; color: #acebdd; font-size: .76rem; display: grid; place-items: center; font-weight: 720; flex: none; }
|
||||
.profile-name { min-width: 0; flex: 1; }
|
||||
.profile-name strong, .profile-name small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
|
||||
.profile-name strong { font-size: .85rem; font-weight: 670; }
|
||||
.profile-name small { font-size: .74rem; color: var(--muted-foreground); }
|
||||
.sidebar-user button { color: var(--muted-foreground); }
|
||||
.workspace { min-width: 0; }
|
||||
.topbar { display: flex; min-height: 63px; border-bottom: 1px solid #252d39; align-items: center; justify-content: space-between; gap: 12px; padding: 0 clamp(18px, 3.2vw, 44px); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 11px; font-size: .87rem; color: var(--muted-foreground); min-width: 0; }
|
||||
.breadcrumb > strong { color: #e0e7f1; font-weight: 590; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.breadcrumb > i { font-style: normal; color: #61728b; }
|
||||
.server-status { margin-left: auto; flex: none; display: flex; align-items: center; gap: 8px; color: #aab9c9; font-size: .84rem; }
|
||||
.server-status i { background: #72dcae; width: 7px; height: 7px; border-radius: 50%; box-shadow: 0 0 0 3px #72dcae1c; }
|
||||
.mobile-nav-button { display: none; }
|
||||
.workspace-content { max-width: 1600px; margin: 0 auto; padding: 35px clamp(18px, 3.2vw, 44px) 48px; }
|
||||
.page-heading { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 27px; }
|
||||
.page-heading h1 { font-size: clamp(1.85rem, 3vw, 2.45rem); color: #f5f7fb; letter-spacing: -.055em; line-height: 1.12; font-weight: 730; overflow-wrap: anywhere; }
|
||||
.page-heading p { color: var(--muted-foreground); margin-top: 7px; font-size: .95rem; line-height: 1.5; }
|
||||
.stats { display: grid; gap: 16px; grid-template-columns: repeat(3, minmax(0, 1fr)); margin-bottom: 34px; }
|
||||
.stat-card { padding: 19px 20px; gap: 14px; flex-direction: row; align-items: flex-start; box-shadow: none; }
|
||||
.stat-icon, .row-icon { display: grid; place-items: center; flex: none; width: 40px; height: 40px; border-radius: 9px; color: #8ce3d5; background: #263b43; border: 1px solid #33505a; }
|
||||
.stat-icon.green { color: #8ee2b1; background: #254238; border-color: #33564a; }
|
||||
.stat-icon.violet { color: #c4b4fc; background: #362e4d; border-color: #4a3d66; }
|
||||
.stat-label { color: #c1ccdc; font-size: .89rem; font-weight: 590; }
|
||||
.stat-value { font-size: 1.9rem; letter-spacing: -.065em; line-height: 1.19; font-weight: 740; color: #f1f5fa; margin: 3px 0; }
|
||||
.stat-detail { color: var(--muted-foreground); font-size: .79rem; line-height: 1.35; }
|
||||
.dashboard-split { display: grid; grid-template-columns: minmax(0, 1.18fr) minmax(0, 1fr); gap: 22px; align-items: start; }
|
||||
.section-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 13px; }
|
||||
.section-title h2, .settings-title h2, .settings-card > h2 { font-weight: 690; font-size: 1.15rem; letter-spacing: -.034em; color: #f0f4fa; }
|
||||
.section-title p, .settings-title p { color: var(--muted-foreground); margin-top: 3px; font-size: .86rem; }
|
||||
.table-card { padding: 0; gap: 0; box-shadow: none; min-width: 0; }
|
||||
.table-scroll { overflow-x: auto; }
|
||||
.table-card table { width: 100%; border-collapse: collapse; text-align: left; }
|
||||
.table-card :is(th, td) { padding: 13px 15px; white-space: nowrap; }
|
||||
.table-card th { color: #a2b1c5; font-size: .79rem; font-weight: 640; border-bottom: 1px solid var(--border); }
|
||||
.table-card td { font-size: .87rem; color: #c3cddd; }
|
||||
.table-card tr + tr td { border-top: 1px solid var(--border); }
|
||||
.table-card td:first-child { width: 100%; }
|
||||
.table-card .cell-action { text-align: right; padding-left: 4px; }
|
||||
.table-secondary { display: block; font-size: .74rem; color: var(--muted-foreground); margin-top: 4px; }
|
||||
.primary-cell { color: inherit; display: flex; align-items: center; gap: 10px; text-align: left; min-width: 0; max-width: 100%; }
|
||||
.primary-cell .row-icon { width: 35px; height: 35px; background: #242f3d; border-color: #303e50; color: #a3c2da; }
|
||||
.primary-cell span:last-child { display: grid; min-width: 0; }
|
||||
.primary-cell strong, .primary-cell small { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; max-width: min(240px, 34vw); }
|
||||
.primary-cell strong { color: #ecf2fb; font-weight: 655; }
|
||||
.primary-cell small { font-size: .76rem; color: var(--muted-foreground); margin-top: 2px; }
|
||||
button.primary-cell:hover strong { color: var(--primary); }
|
||||
.status-badge { border-radius: 999px; gap: 6px; padding: 4px 8px; font-size: .74rem; line-height: 1.15; font-weight: 620; border: 1px solid transparent; }
|
||||
.status-badge i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
|
||||
.status-live { color: #a6e9c0; background: #234536; border-color: #365745; }
|
||||
.status-draft { color: #d2c0fc; background: #37314b; border-color: #504360; }
|
||||
.preview-card { padding: 12px; gap: 12px; min-width: 0; box-shadow: none; }
|
||||
.preview-frame { overflow: hidden; background: #111d2b; border: 1px solid #384555; aspect-ratio: 16 / 9; border-radius: 8px; }
|
||||
.preview-foot { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 0 3px 2px; }
|
||||
.preview-foot strong, .preview-foot small { display: block; }
|
||||
.preview-foot strong { font-size: .91rem; font-weight: 660; }
|
||||
.preview-foot small { color: var(--muted-foreground); font-size: .77rem; margin-top: 2px; }
|
||||
.preview-external { flex: none; }
|
||||
.empty-state { min-height: 170px; padding: 22px; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; gap: 7px; }
|
||||
.empty-state > svg { color: #80dace; margin-bottom: 4px; }
|
||||
.empty-state strong { font-size: .95rem; }
|
||||
.empty-state p { color: var(--muted-foreground); font-size: .85rem; max-width: 38ch; }
|
||||
.empty-state button { margin-top: 8px; }
|
||||
.loading-panel { min-height: 170px; display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 9px; color: var(--muted-foreground); }
|
||||
.feedback { padding: 10px 12px; display: flex; align-items: flex-start; gap: 8px; border: 1px solid #344655; border-radius: 8px; background: #202d3c; color: #dcecf8; font-size: .88rem; margin-bottom: 13px; white-space: pre-line; overflow-wrap: anywhere; }
|
||||
.feedback > svg { flex: none; margin-top: 2px; }
|
||||
.feedback-error { color: #ffc6cf; border-color: #6b3c4b; background: #382530; }
|
||||
.feedback-success, .toast { border: 1px solid #3b6453; background: #203d35; color: #b8f5d5; }
|
||||
.toast { display: flex; gap: 8px; align-items: center; position: fixed; z-index: 5; right: 23px; bottom: 22px; padding: 13px 16px; box-shadow: 0 8px 28px #0006; border-radius: 9px; }
|
||||
.dialog { position: fixed; inset: 0; margin: auto; padding: 24px; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: 14px; width: min(480px, calc(100vw - 30px)); max-height: calc(100dvh - 30px); overflow-y: auto; box-shadow: 0 24px 80px #0008; }
|
||||
.dialog::backdrop { background: #080c13bc; }
|
||||
.dialog-head { display: flex; align-items: flex-start; gap: 12px; justify-content: space-between; margin-bottom: 19px; }
|
||||
.dialog-head h2 { font-size: 1.28rem; letter-spacing: -.04em; font-weight: 700; overflow-wrap: anywhere; }
|
||||
.dialog-head p { font-size: .9rem; color: var(--muted-foreground); margin-top: 5px; line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.form-stack { display: grid; gap: 14px; }
|
||||
.form-stack .feedback { margin-bottom: 0; }
|
||||
.form-field { display: grid; min-width: 0; gap: 7px; }
|
||||
.form-field label { font-size: .86rem; line-height: 1.35; font-weight: 620; }
|
||||
.field-hint { color: var(--muted-foreground); font-size: .79rem; line-height: 1.4; }
|
||||
.form-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.select-wrap { position: relative; min-width: 0; }
|
||||
.select-wrap select { appearance: none; height: 36px; width: 100%; color: var(--foreground); background: #242d3a66; border: 1px solid var(--input); border-radius: 7px; padding: 0 33px 0 11px; font-size: .88rem; text-overflow: ellipsis; }
|
||||
.select-wrap > svg { position: absolute; top: 50%; right: 10px; transform: translateY(-50%); pointer-events: none; color: var(--muted-foreground); }
|
||||
.select-wrap select option { background: var(--card); }
|
||||
.toggle-row { display: flex; position: relative; align-items: center; justify-content: space-between; gap: 10px; cursor: pointer; }
|
||||
.toggle-row > span:first-child { display: grid; }
|
||||
.toggle-row strong { font-size: .85rem; font-weight: 600; }
|
||||
.toggle-row small { color: var(--muted-foreground); font-size: .79rem; }
|
||||
.toggle-row > input { opacity: 0; position: absolute; right: 0; width: 34px; height: 20px; cursor: pointer; }
|
||||
.toggle-track { display: block; width: 34px; height: 20px; flex: none; background: #364255; border: 1px solid #4c596b; border-radius: 20px; position: relative; pointer-events: none; }
|
||||
.toggle-track::after { content: ""; display: block; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; background: #d6dfed; border-radius: 50%; }
|
||||
.toggle-row input:checked + .toggle-track { background: #6bd8c7; border-color: #6bd8c7; }
|
||||
.toggle-row input:checked + .toggle-track::after { transform: translateX(14px); background: #173a35; }
|
||||
.toggle-row input:focus-visible + .toggle-track { outline: 2px solid var(--ring); outline-offset: 3px; }
|
||||
.library-drop { display: flex; flex-direction: row; align-items: center; padding: 20px; gap: 15px; border-style: dashed; box-shadow: none; margin-bottom: 28px; }
|
||||
.library-drop strong { font-weight: 680; }
|
||||
.library-drop p { color: var(--muted-foreground); font-size: .87rem; }
|
||||
.library-drop button { margin-left: auto; }
|
||||
.library-tools { display: grid; grid-template-columns: 1fr minmax(120px, 200px) minmax(115px, 150px); }
|
||||
.media-inspect { width: 100%; max-height: 64dvh; object-fit: contain; border-radius: 6px; }
|
||||
.settings-card { padding: 18px; gap: 16px; box-shadow: none; }
|
||||
.settings-title h2 { display: flex; align-items: center; gap: 8px; }
|
||||
.account-card { max-width: 500px; }
|
||||
.back-button { color: var(--muted-foreground); margin: -12px 0 11px -10px; }
|
||||
.heading-actions, .editor-title { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; }
|
||||
.editor-grid { display: grid; grid-template-columns: minmax(0, 1.16fr) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||
.editor-form-column, .editor-side { display: grid; align-items: start; gap: 14px; min-width: 0; }
|
||||
.editor-side { position: sticky; top: 17px; }
|
||||
.editor-preview .settings-title { padding: 2px 4px 3px; }
|
||||
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 13px; }
|
||||
.layout-label { font-size: .86rem; font-weight: 620; margin-bottom: -9px; }
|
||||
.layout-picker { display: grid; gap: 7px; grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.layout-choice { display: grid; justify-items: center; align-content: center; gap: 5px; padding: 8px 3px; border: 1px solid var(--border); border-radius: 7px; color: #becadc; font-size: .8rem; text-align: center; background: #19212c; }
|
||||
.layout-choice.selected { border-color: #47897e; background: #24433f; color: #b9f4e7; }
|
||||
.layout-choice:disabled { opacity: .42; }
|
||||
.layout-icon { display: grid; width: 29px; height: 19px; gap: 2px; border: 1px solid currentColor; border-radius: 3px; padding: 2px; }
|
||||
.layout-icon > i { background: currentColor; opacity: .72; border-radius: 1px; }
|
||||
.layout-icon-split, .layout-icon-grid, .layout-icon-focus { grid-template-columns: 1fr 1fr; }
|
||||
.layout-icon-focus { grid-template-columns: 1.5fr 1fr; }
|
||||
.layout-icon-focus > i:first-child { grid-row: span 2; }
|
||||
.widget-settings .section-title { margin-bottom: 0; }
|
||||
.widget-empty { border: 1px dashed var(--border); border-radius: 9px; }
|
||||
.widget-item { border: 1px solid var(--border); border-radius: 9px; background: #1a222d; }
|
||||
.widget-item-head { display: flex; align-items: center; }
|
||||
.widget-item-head > button { min-width: 0; flex: 1; display: flex; align-items: center; gap: 9px; text-align: left; padding: 8px; }
|
||||
.widget-item-head > button > span:nth-child(2) { flex: 1; min-width: 0; }
|
||||
.widget-item-head strong, .widget-item-head small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.widget-item-head strong { font-size: .88rem; }
|
||||
.widget-item-head small { color: var(--muted-foreground); font-size: .76rem; margin-top: 1px; }
|
||||
.widget-item-head > button > svg { flex: none; color: var(--muted-foreground); }
|
||||
.widget-item-head > button > svg.expanded { transform: rotate(180deg); }
|
||||
.widget-actions { display: flex; padding-right: 6px; }
|
||||
.widget-item-body { border-top: 1px solid var(--border); padding: 13px; }
|
||||
.html-source { min-height: 130px; font-family: ui-monospace, monospace; resize: vertical; }
|
||||
.type-picker { display: grid; gap: 9px; grid-template-columns: 1fr 1fr; }
|
||||
.type-picker button { justify-content: flex-start; min-height: 42px; }
|
||||
.kiosk-link { display: flex; gap: 7px; align-items: center; }
|
||||
.kiosk-link :is(input, .select-wrap) { flex: 1; min-width: 0; }
|
||||
.kiosk-actions { display: flex; gap: 7px; flex-wrap: wrap; }
|
||||
.plain-action, .danger-link { color: #ffafb9; width: max-content; max-width: 100%; white-space: normal; justify-content: start; }
|
||||
.danger-link:hover { color: #ffc4cd; }
|
||||
.gallery-order { display: grid; gap: 3px; }
|
||||
.gallery-order li { display: flex; align-items: center; gap: 3px; padding: 3px 6px; background: #232d3d; border-radius: 5px; }
|
||||
.gallery-order li > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .83rem; }
|
||||
.schedule { border: 1px solid var(--border); border-radius: 7px; padding: 8px; }
|
||||
.schedule summary { display: flex; align-items: center; gap: 7px; font-size: .87rem; font-weight: 600; color: #c8d4e4; }
|
||||
.schedule .form-grid { margin: 9px 0 5px; }
|
||||
|
||||
.login { min-height: 100dvh; display: grid; grid-template-columns: minmax(0, .85fr) minmax(0, 1fr); }
|
||||
.login-main { width: min(380px, calc(100% - 44px)); margin: auto; display: grid; gap: 27px; padding: 40px 0; }
|
||||
.login-copy h1 { font-size: 2.5rem; letter-spacing: -.06em; font-weight: 740; }
|
||||
.login-copy p { color: var(--muted-foreground); margin-top: 5px; }
|
||||
.login-visual { display: grid; place-items: center; padding: 9%; background: radial-gradient(ellipse at 52% 54%, #223f43, #151c28 67%); border-left: 1px solid var(--border); }
|
||||
.login-display { width: min(100%, 610px); aspect-ratio: 16/10; border: 1px solid #577781; border-radius: 16px; background: #111e2c; box-shadow: 0 24px 85px #0008; padding: 5%; display: grid; gap: 10px; grid-template-rows: auto 1fr; }
|
||||
.login-display > div:first-child { display: flex; align-items: center; gap: 10px; font-weight: 650; color: #b7e8df; }
|
||||
.login-display-grid { display: grid; grid-template-columns: 1.6fr 1fr; grid-template-rows: 1fr 1fr; gap: 6px; }
|
||||
.login-display-grid i { border-radius: 8px; background: #223644; border: 1px solid #37525d; }
|
||||
.login-display-grid i:first-child { grid-row: span 2; background: #255448; }
|
||||
.login-display-grid i:nth-child(2) { background-image: url('/campus-preview.webp'); background-size: cover; background-position: center; }
|
||||
@media (max-width: 1060px) {
|
||||
.app-shell { grid-template-columns: 196px minmax(0, 1fr); }
|
||||
.dashboard-split { grid-template-columns: minmax(0, 1fr); }
|
||||
.dashboard-preview { max-width: 640px; }
|
||||
}
|
||||
@media (max-width: 860px) {
|
||||
.editor-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
.editor-side { position: static; }
|
||||
.stat-card { padding: 13px; gap: 9px; }
|
||||
.stat-icon { width: 32px; height: 32px; }
|
||||
}
|
||||
@media (max-width: 680px) {
|
||||
.app-shell { display: block; }
|
||||
.sidebar { position: fixed; left: 0; width: min(255px, 85vw); top: 57px; height: calc(100dvh - 57px); z-index: 3; box-shadow: 10px 0 25px #0007; display: none; }
|
||||
.sidebar.sidebar-open { display: flex; }
|
||||
.mobile-nav-button { display: inline-flex; }
|
||||
.topbar { min-height: 57px; }
|
||||
.breadcrumb > span, .breadcrumb > span + i { display: none; }
|
||||
.server-status { font-size: .75rem; }
|
||||
.workspace-content { padding-top: 24px; }
|
||||
.page-heading { align-items: flex-start; flex-wrap: wrap; margin-bottom: 18px; }
|
||||
.stats { gap: 7px; margin-bottom: 23px; }
|
||||
.stat-card { display: grid; padding: 9px; gap: 6px; }
|
||||
.stat-label { font-size: .76rem; }
|
||||
.stat-detail { font-size: .70rem; }
|
||||
.stat-value { font-size: 1.45rem; }
|
||||
.table-card :is(th, td) { padding: 10px; }
|
||||
.screen-table.compact .table-secondary { white-space: normal; max-width: 110px; }
|
||||
.library-drop { flex-wrap: wrap; }
|
||||
.library-drop button { margin-left: 0; }
|
||||
.library-tools { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
|
||||
.library-tools > div:first-child { grid-column: span 2; }
|
||||
.login { display: flex; }
|
||||
.login-visual { display: none; }
|
||||
}
|
||||
@media (max-width: 380px) {
|
||||
.form-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
464
src/admin.tsx
Normal file
464
src/admin.tsx
Normal file
@ -0,0 +1,464 @@
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import {
|
||||
Activity, ArrowUpRight, Check, FileText, FolderOpen, Image as ImageIcon, LayoutDashboard,
|
||||
LoaderCircle, LogOut, Monitor, MonitorPlay, Plus, RefreshCw, Settings, UploadCloud, Users,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { api, ApiError, errorText, formatDate, formatSize } from '@/lib/api'
|
||||
import { defaultBoard, layouts, type Asset, type SavedBoard, type User } from '@/lib/types'
|
||||
import { Brand, ButtonProgress, Dialog, Feedback, Field, Select, Status, Toggle } from './admin-ui'
|
||||
import BoardEditor from './editor'
|
||||
import Player from './player'
|
||||
import './admin.css'
|
||||
|
||||
const navigation = [
|
||||
{ path: '/admin', label: 'Übersicht', icon: LayoutDashboard },
|
||||
{ path: '/admin/bildschirme', label: 'Bildschirme', icon: Monitor },
|
||||
{ path: '/admin/medien', label: 'Mediathek', icon: FolderOpen },
|
||||
{ path: '/admin/benutzer', label: 'Benutzer', icon: Users },
|
||||
{ path: '/admin/konto', label: 'Mein Konto', icon: Settings },
|
||||
]
|
||||
const adminMedia = (id: string, item: string) => `/api/media/${id}/${item}`
|
||||
const liveLink = (board: SavedBoard) => `/display/${board.token}`
|
||||
const seenRecently = (board: SavedBoard) => !!board.last_seen && Date.now() - Date.parse(board.last_seen) < 75_000
|
||||
|
||||
function Login({ onLogin, loadError }: { onLogin: (user: User) => void; loadError: string }) {
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const data = new FormData(event.currentTarget)
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
onLogin(await api<User>('/auth/login', 'POST', { email: data.get('email'), password: data.get('password') }))
|
||||
} catch (err) { setError(errorText(err)) } finally { setBusy(false) }
|
||||
}
|
||||
return <main className="login">
|
||||
<div className="login-main">
|
||||
<Brand />
|
||||
<div className="login-copy"><h1>Anmelden</h1><p>Verwalte deine Bildschirme und Inhalte an einem Ort.</p></div>
|
||||
<form className="form-stack" onSubmit={submit}>
|
||||
<Feedback message={error || loadError} />
|
||||
<Field id="login-email" label="E-Mail-Adresse"><Input type="email" id="login-email" name="email" autoComplete="username" required placeholder="name@beispiel.de" /></Field>
|
||||
<Field id="login-password" label="Passwort"><Input type="password" id="login-password" name="password" autoComplete="current-password" required /></Field>
|
||||
<Button size="lg" disabled={busy}><ButtonProgress busy={busy} />Anmelden</Button>
|
||||
</form>
|
||||
</div>
|
||||
<div className="login-visual" aria-hidden="true">
|
||||
<div className="login-display"><div><MonitorPlay /><span>Syncova Display</span></div>
|
||||
<div className="login-display-grid"><i /><i /><i /></div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
|
||||
function createPath(value: string) {
|
||||
return value === '/' ? '/admin' : value.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
export default function Admin() {
|
||||
const [user, setUser] = useState<User | null>()
|
||||
const [path, setPath] = useState(createPath(location.pathname))
|
||||
const [boards, setBoards] = useState<SavedBoard[]>([])
|
||||
const [assets, setAssets] = useState<Asset[]>([])
|
||||
const [ready, setReady] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [authError, setAuthError] = useState('')
|
||||
const [newBoard, setNewBoard] = useState(false)
|
||||
const [mobileNav, setMobileNav] = useState(false)
|
||||
const [notice, setNotice] = useState('')
|
||||
const navigate = useCallback((target: string) => {
|
||||
if (location.pathname !== target) history.pushState(null, '', target)
|
||||
setPath(target)
|
||||
setMobileNav(false)
|
||||
scrollTo(0, 0)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const pop = () => setPath(createPath(location.pathname))
|
||||
window.addEventListener('popstate', pop)
|
||||
api<User>('/auth/me').then(setUser, err => {
|
||||
if (!(err instanceof ApiError && err.status === 401)) setAuthError(errorText(err))
|
||||
setUser(null)
|
||||
})
|
||||
return () => window.removeEventListener('popstate', pop)
|
||||
}, [])
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setError('')
|
||||
try {
|
||||
const [nextBoards, nextAssets] = await Promise.all([api<SavedBoard[]>('/boards'), api<Asset[]>('/assets')])
|
||||
setBoards(nextBoards)
|
||||
setAssets(nextAssets)
|
||||
setReady(true)
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) { setReady(false); setUser(null) }
|
||||
else setError(errorText(err))
|
||||
}
|
||||
}, [])
|
||||
const userId = user?.id
|
||||
useEffect(() => { if (userId) void refresh() }, [userId, refresh])
|
||||
useEffect(() => {
|
||||
if (!ready || !userId || !['/admin', '/admin/bildschirme'].includes(path)) return
|
||||
let active = true
|
||||
const timer = setInterval(() => {
|
||||
api<SavedBoard[]>('/boards').then(data => { if (active) setBoards(data) }, () => {})
|
||||
}, 30_000)
|
||||
return () => { active = false; clearInterval(timer) }
|
||||
}, [userId, ready, path])
|
||||
useEffect(() => {
|
||||
if (!notice) return
|
||||
const timer = setTimeout(() => setNotice(''), 3500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [notice])
|
||||
|
||||
function saved(board: SavedBoard) {
|
||||
setBoards(previous => [board, ...previous.filter(item => item.id !== board.id)])
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
setError('')
|
||||
try {
|
||||
await api('/auth/logout', 'POST')
|
||||
setBoards([])
|
||||
setAssets([])
|
||||
setReady(false)
|
||||
setUser(null)
|
||||
} catch (err) { setError(errorText(err)) }
|
||||
}
|
||||
|
||||
if (user === undefined) return <div className="center-state"><LoaderCircle className="animate-spin" />Syncova Display wird geladen</div>
|
||||
if (!user) return <Login onLogin={next => { setAuthError(''); setUser(next) }} loadError={authError} />
|
||||
|
||||
const current = navigation.find(item => item.path === path)
|
||||
?? (path.startsWith('/admin/bildschirme/') ? navigation[1] : navigation[0])
|
||||
const editorId = path.match(/^\/admin\/bildschirme\/([^/]+)$/)?.[1]
|
||||
const activeBoard = boards.find(board => board.id === editorId)
|
||||
const initials = user.name.trim().split(/\s+/).slice(0, 2).map(word => word[0]).join('').toUpperCase()
|
||||
const openBoard = (id: string) => navigate(`/admin/bildschirme/${id}`)
|
||||
const goto = (target: string) => (event: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return
|
||||
event.preventDefault()
|
||||
navigate(target)
|
||||
}
|
||||
|
||||
return <div className="app-shell">
|
||||
<aside className={`sidebar ${mobileNav ? 'sidebar-open' : ''}`}>
|
||||
<a className="sidebar-brand" href="/admin" onClick={goto('/admin')}><Brand /></a>
|
||||
<div className="sidebar-body">
|
||||
<div className="nav-caption">Arbeitsbereich</div>
|
||||
<nav aria-label="Arbeitsbereich">
|
||||
{navigation.slice(0, 3).map(({ path: target, label, icon: Icon }) => <a key={target} href={target}
|
||||
aria-current={current.path === target ? 'page' : undefined} onClick={goto(target)}><Icon />{label}</a>)}
|
||||
</nav>
|
||||
<div className="nav-caption">Verwaltung</div>
|
||||
<nav aria-label="Verwaltung">
|
||||
{navigation.slice(3).filter(item => item.path !== '/admin/benutzer' || user.role === 'admin')
|
||||
.map(({ path: target, label, icon: Icon }) => <a key={target} href={target} aria-current={current.path === target ? 'page' : undefined}
|
||||
onClick={goto(target)}><Icon />{label}</a>)}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="sidebar-user">
|
||||
<div className="avatar">{initials}</div>
|
||||
<div className="profile-name"><strong>{user.name}</strong><small>{user.role === 'admin' ? 'Administration' : 'Redaktion'}</small></div>
|
||||
<Button size="icon-sm" variant="ghost" aria-label="Abmelden" title="Abmelden" onClick={() => void logout()}><LogOut size={17} /></Button>
|
||||
</div>
|
||||
</aside>
|
||||
<div className="workspace">
|
||||
<header className="topbar">
|
||||
<Button className="mobile-nav-button" variant="outline" size="icon-sm" aria-label="Navigation" aria-expanded={mobileNav} onClick={() => setMobileNav(value => !value)}><LayoutDashboard /></Button>
|
||||
<span className="breadcrumb"><span>Arbeitsbereich</span><i>/</i><strong>{current.label}</strong>{activeBoard && <><i>/</i><strong>{activeBoard.draft.name}</strong></>}</span>
|
||||
<span className="server-status"><i /> {error ? 'Verbindung unterbrochen' : 'System bereit'}</span>
|
||||
</header>
|
||||
<main className="workspace-content">
|
||||
<Feedback message={error} />
|
||||
{!ready ? <div className="loading-panel">{error
|
||||
? <Button variant="outline" onClick={() => void refresh()}><RefreshCw /> Erneut versuchen</Button>
|
||||
: <><LoaderCircle className="animate-spin" /> Arbeitsbereich wird geladen</>}</div>
|
||||
: editorId ? activeBoard ? <BoardEditor key={editorId} saved={activeBoard} assets={assets} onSave={saved}
|
||||
onBack={() => navigate('/admin/bildschirme')} onDelete={() => { setBoards(list => list.filter(item => item.id !== editorId)); navigate('/admin/bildschirme') }}
|
||||
notify={setNotice} />
|
||||
: <div className="loading-panel"><p>Dieser Bildschirm wurde nicht gefunden.</p><Button onClick={() => navigate('/admin/bildschirme')}>Zu den Bildschirmen</Button></div>
|
||||
: current.path === '/admin/medien' ? <Library assets={assets} onChange={setAssets} notify={setNotice} />
|
||||
: current.path === '/admin/benutzer' && user.role === 'admin' ? <UsersPage user={user} onAccountChange={setUser} notify={setNotice} />
|
||||
: current.path === '/admin/konto' ? <Account user={user} notify={setNotice} />
|
||||
: current.path === '/admin/bildschirme' ? <section>
|
||||
<PageHeading title="Bildschirme" description="Verwalte Layouts, Inhalte und Kiosk-Links für deine Monitore."
|
||||
action={<Button size="lg" onClick={() => setNewBoard(true)}><Plus /> Bildschirm erstellen</Button>} />
|
||||
<ScreenList boards={boards} onOpen={openBoard} onCreate={() => setNewBoard(true)} />
|
||||
</section>
|
||||
: <Dashboard boards={boards} assets={assets} onOpen={openBoard} onCreate={() => setNewBoard(true)}
|
||||
onViewAll={() => navigate('/admin/bildschirme')} />}
|
||||
</main>
|
||||
</div>
|
||||
{newBoard && <NewBoard onClose={() => setNewBoard(false)} onCreate={board => { saved(board); setNewBoard(false); openBoard(board.id) }} />}
|
||||
{notice && <div className="toast" role="status"><Check size={17} />{notice}</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
export function PageHeading({ title, description, action }: { title: string; description: string; action?: React.ReactNode }) {
|
||||
return <div className="page-heading"><div><h1>{title}</h1><p>{description}</p></div>{action}</div>
|
||||
}
|
||||
|
||||
function Dashboard({ boards, assets, onOpen, onCreate, onViewAll }: {
|
||||
boards: SavedBoard[]; assets: Asset[]; onOpen: (id: string) => void; onCreate: () => void; onViewAll: () => void
|
||||
}) {
|
||||
const published = boards.filter(item => item.published)
|
||||
const seen = published.filter(seenRecently).length
|
||||
const [previewId, setPreviewId] = useState('')
|
||||
const preview = published.find(board => board.id === previewId) ?? published[0]
|
||||
return <section>
|
||||
<PageHeading title="Übersicht" description="Deine Bildschirme, Veröffentlichungen und Medien auf einen Blick."
|
||||
action={<Button size="lg" onClick={onCreate}><Plus /> Bildschirm erstellen</Button>} />
|
||||
<div className="stats">
|
||||
{[
|
||||
{ label: 'Bildschirme', count: boards.length, detail: `${boards.length - published.length} als Entwurf`, icon: Monitor, color: 'teal' },
|
||||
{ label: 'Veröffentlicht', count: published.length, detail: `${seen} kürzlich verbunden`, icon: Activity, color: 'green' },
|
||||
{ label: 'Mediendateien', count: assets.length, detail: `${assets.filter(item => item.kind === 'pdf').length} PDF-Dokumente`, icon: ImageIcon, color: 'violet' },
|
||||
].map(({ label, count, detail, icon: Icon, color }) => <Card className="stat-card" key={label}>
|
||||
<div className={`stat-icon ${color}`}><Icon size={20} /></div>
|
||||
<div><div className="stat-label">{label}</div><div className="stat-value">{count}</div><div className="stat-detail">{detail}</div></div>
|
||||
</Card>)}
|
||||
</div>
|
||||
<div className="dashboard-split">
|
||||
<div className="dashboard-screens">
|
||||
<div className="section-title"><div><h2>Bildschirme</h2><p>Veröffentlichung und Verbindungsstatus.</p></div>
|
||||
{boards.length > 4 && <Button variant="ghost" onClick={onViewAll}>Alle anzeigen</Button>}</div>
|
||||
<ScreenList boards={boards.slice(0, 4)} onOpen={onOpen} onCreate={onCreate} compact />
|
||||
</div>
|
||||
<div className="dashboard-preview">
|
||||
<div className="section-title"><div><h2>Live-Vorschau</h2><p>Aktuell veröffentlichter Inhalt.</p></div></div>
|
||||
<Card className="preview-card">
|
||||
{preview?.published ? <>
|
||||
{published.length > 1 && <Select value={preview.id} aria-label="Bildschirm für die Vorschau" onChange={event => setPreviewId(event.target.value)}>
|
||||
{published.map(board => <option key={board.id} value={board.id}>{board.published?.name}</option>)}</Select>}
|
||||
<div className="preview-frame"><Player key={preview.id} board={preview.published} assets={assets} url={adminMedia} preview /></div>
|
||||
<div className="preview-foot"><div><strong>{preview.published.name}</strong><small>{preview.published.location || 'Infobildschirm'}</small></div>
|
||||
<Button asChild variant="outline" size="icon-sm" className="preview-external"><a href={liveLink(preview)} target="_blank" rel="noreferrer" aria-label="Anzeige öffnen" title="Anzeige öffnen"><ArrowUpRight /></a></Button></div>
|
||||
</> : <div className="empty-state"><MonitorPlay /><strong>Kein Bildschirm veröffentlicht</strong><p>Die Vorschau erscheint nach der ersten Veröffentlichung.</p></div>}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
function ScreenList({ boards, onOpen, onCreate, compact = false }: {
|
||||
boards: SavedBoard[]; onOpen: (id: string) => void; onCreate: () => void; compact?: boolean
|
||||
}) {
|
||||
return <Card className="table-card">
|
||||
{boards.length ? <div className="table-scroll"><table className={compact ? 'screen-table compact' : 'screen-table'}>
|
||||
<thead><tr><th>Bildschirm</th><th>Status</th>{!compact && <><th>Layout</th><th>Geändert</th></>}<th><span className="sr-only">Aktionen</span></th></tr></thead>
|
||||
<tbody>{boards.map(board => <tr key={board.id}>
|
||||
<td><button type="button" className="primary-cell" onClick={() => onOpen(board.id)}>
|
||||
<span className="row-icon"><Monitor size={18} /></span>
|
||||
<span><strong>{board.draft.name}</strong><small>{board.draft.location || 'Infobildschirm'}</small></span>
|
||||
</button></td>
|
||||
<td><Status board={board} />{board.published && <small className="table-secondary">{seenRecently(board) ? 'Gerät verbunden' : 'Kein Gerät verbunden'}</small>}</td>
|
||||
{!compact && <><td>{layouts[board.draft.layout].label}</td><td>{formatDate(board.updated_at)}</td></>}
|
||||
<td className="cell-action"><Button variant="ghost" size="icon-sm" aria-label={`${board.draft.name} bearbeiten`} title="Bearbeiten" onClick={() => onOpen(board.id)}><ArrowUpRight /></Button></td>
|
||||
</tr>)}</tbody>
|
||||
</table></div> : <div className="empty-state"><Monitor /><strong>Noch keine Bildschirme</strong><p>Erstelle einen Bildschirm und füge deine ersten Inhalte hinzu.</p>
|
||||
<Button variant="outline" onClick={onCreate}><Plus /> Bildschirm erstellen</Button></div>}
|
||||
</Card>
|
||||
}
|
||||
|
||||
function NewBoard({ onClose, onCreate }: { onClose: () => void; onCreate: (board: SavedBoard) => void }) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const data = new FormData(event.currentTarget)
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try { onCreate(await api<SavedBoard>('/boards', 'POST', { ...defaultBoard, name: data.get('name'), location: data.get('location') })) }
|
||||
catch (err) { setError(errorText(err)) } finally { setBusy(false) }
|
||||
}
|
||||
return <Dialog title="Bildschirm erstellen" description="Gib dem Bildschirm einen Namen, um sein Layout zu bearbeiten." onClose={() => { if (!busy) onClose() }}>
|
||||
<form className="form-stack" onSubmit={submit}>
|
||||
<Feedback message={error} />
|
||||
<Field id="new-name" label="Name"><Input name="name" id="new-name" required maxLength={100} placeholder="z. B. Foyer" autoFocus /></Field>
|
||||
<Field id="new-location" label="Standort (optional)"><Input name="location" id="new-location" maxLength={100} placeholder="z. B. Erdgeschoss" /></Field>
|
||||
<div className="form-actions"><Button type="button" variant="outline" onClick={onClose} disabled={busy}>Abbrechen</Button><Button disabled={busy}><ButtonProgress busy={busy} /> Erstellen</Button></div>
|
||||
</form>
|
||||
</Dialog>
|
||||
}
|
||||
|
||||
function Library({ assets, onChange, notify }: {
|
||||
assets: Asset[]; onChange: React.Dispatch<React.SetStateAction<Asset[]>>; notify: (value: string) => void
|
||||
}) {
|
||||
const [work, setWork] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [filter, setFilter] = useState('all')
|
||||
const [query, setQuery] = useState('')
|
||||
const [remove, setRemove] = useState<Asset | null>(null)
|
||||
const [inspect, setInspect] = useState<Asset | null>(null)
|
||||
const fileInput = useRef<HTMLInputElement>(null)
|
||||
const locked = useRef(false)
|
||||
const visible = assets.filter(asset => (filter === 'all' || asset.kind === filter) && asset.name.toLowerCase().includes(query.trim().toLowerCase()))
|
||||
async function upload(files: FileList | File[]) {
|
||||
if (locked.current || !files.length) return
|
||||
locked.current = true
|
||||
const failures: string[] = []
|
||||
let count = 0
|
||||
setError('')
|
||||
try {
|
||||
for (const file of Array.from(files)) {
|
||||
setWork(file.name)
|
||||
const data = new FormData()
|
||||
data.set('file', file)
|
||||
try {
|
||||
const uploaded = await api<Asset>('/assets', 'POST', data)
|
||||
onChange(list => [uploaded, ...list])
|
||||
count++
|
||||
} catch (err) { failures.push(`${file.name} · ${errorText(err)}`) }
|
||||
}
|
||||
setError(failures.join('\n'))
|
||||
if (count) notify(count === 1 ? 'Datei hochgeladen.' : `${count} Dateien hochgeladen.`)
|
||||
} finally { locked.current = false; setWork('') }
|
||||
}
|
||||
async function deleteAsset() {
|
||||
if (!remove || locked.current) return
|
||||
locked.current = true
|
||||
setWork('Löschen')
|
||||
setError('')
|
||||
try {
|
||||
await api(`/assets/${remove.id}`, 'DELETE')
|
||||
onChange(list => list.filter(item => item.id !== remove.id))
|
||||
setRemove(null)
|
||||
notify('Datei gelöscht.')
|
||||
} catch (err) { setError(errorText(err)); setRemove(null) } finally { locked.current = false; setWork('') }
|
||||
}
|
||||
return <section>
|
||||
<PageHeading title="Mediathek" description="PDFs und Bilder hochladen, prüfen und in Bildschirmen verwenden."
|
||||
action={<Button size="lg" onClick={() => fileInput.current?.click()} disabled={!!work}><UploadCloud /> Dateien hochladen</Button>} />
|
||||
<input hidden ref={fileInput} type="file" multiple accept=".pdf,image/jpeg,image/png,image/webp,image/gif,image/avif"
|
||||
onChange={event => { if (event.target.files) void upload([...event.target.files]); event.target.value = '' }} />
|
||||
<Feedback message={error} />
|
||||
{work && <div className="feedback" role="status"><LoaderCircle className="animate-spin" size={17} />{work} wird verarbeitet</div>}
|
||||
<Card className="library-drop" onDragOver={event => event.preventDefault()} onDrop={event => { event.preventDefault(); void upload(event.dataTransfer.files) }}>
|
||||
<span className="row-icon"><UploadCloud /></span><div><strong>Dateien hier ablegen</strong><p>PDF, JPEG, PNG, WebP, GIF und AVIF</p></div>
|
||||
<Button variant="outline" onClick={() => fileInput.current?.click()} disabled={!!work}>Dateien auswählen</Button>
|
||||
</Card>
|
||||
<div className="section-title library-tools"><div><h2>Dateien</h2><p>{assets.length} {assets.length === 1 ? 'Datei' : 'Dateien'} gespeichert</p></div>
|
||||
<Input aria-label="Dateien suchen" placeholder="Suchen …" value={query} onChange={event => setQuery(event.target.value)} />
|
||||
<Select aria-label="Dateityp filtern" value={filter} onChange={event => setFilter(event.target.value)}><option value="all">Alle Formate</option><option value="image">Bilder</option><option value="pdf">PDFs</option></Select></div>
|
||||
<Card className="table-card">{visible.length ? <div className="table-scroll"><table>
|
||||
<thead><tr><th>Datei</th><th>Größe</th><th>Hochgeladen</th><th><span className="sr-only">Aktionen</span></th></tr></thead>
|
||||
<tbody>{visible.map(asset => <tr key={asset.id}>
|
||||
<td><button type="button" className="primary-cell" onClick={() => setInspect(asset)}><span className="row-icon">{asset.kind === 'pdf' ? <FileText size={18} /> : <ImageIcon size={18} />}</span>
|
||||
<span><strong>{asset.name}</strong><small>{asset.kind === 'pdf' ? `PDF · ${asset.metadata.pages?.length} Seite(n)` : `${asset.metadata.width} × ${asset.metadata.height} px`}</small></span></button></td>
|
||||
<td>{formatSize(asset.bytes)}</td><td>{formatDate(asset.created_at)}</td>
|
||||
<td className="cell-action"><Button variant="ghost" size="sm" onClick={() => setRemove(asset)} disabled={!!work}>Löschen</Button></td>
|
||||
</tr>)}</tbody></table></div> : <div className="empty-state"><FolderOpen /><strong>{assets.length ? 'Keine passenden Dateien' : 'Noch keine Dateien gespeichert'}</strong></div>}</Card>
|
||||
{remove && <Dialog title="Datei löschen?" description={remove.name} onClose={() => { if (!work) setRemove(null) }}>
|
||||
<div className="form-actions"><Button variant="outline" onClick={() => setRemove(null)} disabled={!!work}>Abbrechen</Button>
|
||||
<Button variant="destructive" onClick={() => void deleteAsset()} disabled={!!work}><ButtonProgress busy={!!work} /> Löschen</Button></div>
|
||||
</Dialog>}
|
||||
{inspect && <Dialog title={inspect.name} description={inspect.kind === 'pdf' ? `Erste Seite · ${inspect.metadata.pages?.length} Seite(n)` : undefined} onClose={() => setInspect(null)}>
|
||||
<img className="media-inspect" alt={inspect.name} src={adminMedia(inspect.id, inspect.kind === 'image' ? 'image' : 'page-1-800')} />
|
||||
</Dialog>}
|
||||
</section>
|
||||
}
|
||||
|
||||
const roleLabels = { admin: 'Administration', editor: 'Redaktion' }
|
||||
|
||||
function UsersPage({ user, onAccountChange, notify }: {
|
||||
user: User; onAccountChange: (user: User) => void; notify: (value: string) => void
|
||||
}) {
|
||||
const [users, setUsers] = useState<User[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [edit, setEdit] = useState<User | 'new' | null>(null)
|
||||
const load = useCallback(() => {
|
||||
setError('')
|
||||
api<User[]>('/users').then(setUsers, err => setError(errorText(err)))
|
||||
}, [])
|
||||
useEffect(load, [load])
|
||||
return <section>
|
||||
<PageHeading title="Benutzer" description="Zugriff auf die Bildschirmverwaltung und Rollen vergeben."
|
||||
action={<Button size="lg" onClick={() => setEdit('new')}><Plus /> Benutzer hinzufügen</Button>} />
|
||||
<Feedback message={error} />
|
||||
<Card className="table-card">{!users ? <div className="loading-panel">{error
|
||||
? <Button variant="outline" onClick={load}><RefreshCw /> Erneut versuchen</Button>
|
||||
: <LoaderCircle className="animate-spin" />}</div> :
|
||||
<div className="table-scroll"><table><thead><tr><th>Konto</th><th>Rolle</th><th>Status</th><th><span className="sr-only">Aktionen</span></th></tr></thead>
|
||||
<tbody>{users.map(item => <tr key={item.id}>
|
||||
<td><div className="primary-cell"><span className="row-icon"><Users size={18} /></span><span><strong>{item.name}{item.id === user.id ? ' (du)' : ''}</strong><small>{item.email}</small></span></div></td>
|
||||
<td>{roleLabels[item.role]}</td><td><Badge className={`status-badge ${item.active ? 'status-live' : 'status-draft'}`}><i />{item.active ? 'Aktiv' : 'Deaktiviert'}</Badge></td>
|
||||
<td className="cell-action"><Button variant="ghost" size="sm" onClick={() => setEdit(item)}>Bearbeiten</Button></td>
|
||||
</tr>)}</tbody>
|
||||
</table></div>}</Card>
|
||||
{edit && <EditUser current={edit === 'new' ? undefined : edit} self={edit !== 'new' && edit.id === user.id}
|
||||
onClose={() => setEdit(null)} onSave={next => {
|
||||
setUsers(list => list?.some(item => item.id === next.id) ? list.map(item => item.id === next.id ? next : item) : [...(list ?? []), next])
|
||||
if (next.id === user.id) onAccountChange(next)
|
||||
setEdit(null)
|
||||
notify('Benutzerkonto gespeichert.')
|
||||
}} />}
|
||||
</section>
|
||||
}
|
||||
|
||||
function EditUser({ current, self, onClose, onSave }: { current?: User; self: boolean; onClose: () => void; onSave: (user: User) => void }) {
|
||||
const [active, setActive] = useState(current?.active ?? true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const data = new FormData(event.currentTarget)
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const payload = { name: data.get('name'), email: data.get('email'), role: data.get('role'), active, password: data.get('password') || undefined }
|
||||
onSave(await api<User>(current ? `/users/${current.id}` : '/users', current ? 'PUT' : 'POST', payload))
|
||||
} catch (err) { setError(errorText(err)) } finally { setBusy(false) }
|
||||
}
|
||||
return <Dialog title={current ? 'Benutzer bearbeiten' : 'Benutzer hinzufügen'} onClose={() => { if (!busy) onClose() }}>
|
||||
<form className="form-stack" onSubmit={submit}>
|
||||
<Feedback message={error} />
|
||||
<Field id="user-name" label="Name"><Input name="name" id="user-name" required maxLength={100} defaultValue={current?.name} autoFocus /></Field>
|
||||
<Field id="user-email" label="E-Mail-Adresse"><Input name="email" id="user-email" type="email" required defaultValue={current?.email} /></Field>
|
||||
<Field id="user-role" label="Rolle" hint="Redaktionskonten können Bildschirme und Medien verwalten.">
|
||||
<Select name="role" id="user-role" defaultValue={current?.role ?? 'editor'}><option value="editor">Redaktion</option><option value="admin">Administration</option></Select>
|
||||
</Field>
|
||||
{!self && <Field id="user-password" label={current ? 'Neues Passwort (optional)' : 'Passwort'} hint="Mindestens 12 Zeichen.">
|
||||
<Input name="password" id="user-password" type="password" minLength={12} maxLength={256} required={!current} autoComplete="new-password" />
|
||||
</Field>}
|
||||
{self ? <p className="field-hint">Dein eigenes Passwort änderst du unter „Mein Konto“.</p> : <Toggle label="Konto aktiv" checked={active} onChange={setActive} />}
|
||||
<div className="form-actions"><Button type="button" variant="outline" onClick={onClose} disabled={busy}>Abbrechen</Button><Button disabled={busy}><ButtonProgress busy={busy} /> Speichern</Button></div>
|
||||
</form>
|
||||
</Dialog>
|
||||
}
|
||||
|
||||
function Account({ user, notify }: { user: User; notify: (value: string) => void }) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const form = event.currentTarget
|
||||
const data = new FormData(form)
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
if (data.get('password') !== data.get('confirm')) { setError('Die beiden neuen Passwörter stimmen nicht überein.'); return }
|
||||
await api('/auth/password', 'PUT', { current: data.get('current'), password: data.get('password') })
|
||||
form.reset()
|
||||
notify('Passwort aktualisiert.')
|
||||
} catch (err) { setError(errorText(err)) } finally { setBusy(false) }
|
||||
}
|
||||
return <section>
|
||||
<PageHeading title="Mein Konto" description={`${user.name} · ${user.email}`} />
|
||||
<Card className="settings-card account-card">
|
||||
<h2>Passwort ändern</h2>
|
||||
<form className="form-stack" onSubmit={submit}>
|
||||
<Feedback message={error} />
|
||||
<Field id="pw-current" label="Bisheriges Passwort"><Input id="pw-current" name="current" type="password" autoComplete="current-password" required /></Field>
|
||||
<Field id="pw-new" label="Neues Passwort" hint="Mindestens 12 Zeichen."><Input id="pw-new" name="password" type="password" autoComplete="new-password" minLength={12} maxLength={256} required /></Field>
|
||||
<Field id="pw-repeat" label="Neues Passwort wiederholen"><Input id="pw-repeat" name="confirm" type="password" autoComplete="new-password" minLength={12} maxLength={256} required /></Field>
|
||||
<div className="form-actions"><Button disabled={busy}><ButtonProgress busy={busy} /> Passwort ändern</Button></div>
|
||||
</form>
|
||||
</Card>
|
||||
</section>
|
||||
}
|
||||
47
src/components/ui/badge.tsx
Normal file
47
src/components/ui/badge.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",
|
||||
outline:
|
||||
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 [a&]:hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
63
src/components/ui/button.tsx
Normal file
63
src/components/ui/button.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
91
src/components/ui/card.tsx
Normal file
91
src/components/ui/card.tsx
Normal file
@ -0,0 +1,91 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
20
src/components/ui/input.tsx
Normal file
20
src/components/ui/input.tsx
Normal file
@ -0,0 +1,20 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
23
src/components/ui/label.tsx
Normal file
23
src/components/ui/label.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label as LabelPrimitive } from "radix-ui"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
17
src/components/ui/textarea.tsx
Normal file
17
src/components/ui/textarea.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Textarea }
|
||||
54
src/display.tsx
Normal file
54
src/display.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { LoaderCircle, MonitorOff } from 'lucide-react'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import Player from './player'
|
||||
import type { BoardPayload } from '@/lib/types'
|
||||
|
||||
export default function Display({ token }: { token: string }) {
|
||||
const [payload, setPayload] = useState<BoardPayload | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
let controller: AbortController
|
||||
let etag = ''
|
||||
let hasContent = false
|
||||
async function refresh() {
|
||||
controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 10_000)
|
||||
try {
|
||||
const response = await fetch(`/api/display/${token}`, {
|
||||
cache: 'no-store', headers: etag ? { 'If-None-Match': etag } : undefined, signal: controller.signal,
|
||||
})
|
||||
if (!active) return
|
||||
if (response.status === 404) {
|
||||
etag = ''
|
||||
hasContent = false
|
||||
setPayload(null)
|
||||
setError('Diese Anzeige ist nicht veröffentlicht oder ihr Link wurde erneuert.')
|
||||
} else if (response.status !== 304) {
|
||||
if (!response.ok) throw new Error('Verbindung')
|
||||
const data: BoardPayload = await response.json()
|
||||
if (!active) return
|
||||
etag = response.headers.get('ETag') || ''
|
||||
hasContent = true
|
||||
setError('')
|
||||
setPayload(data)
|
||||
document.title = `${data.board.name} · Syncova Display`
|
||||
}
|
||||
} catch {
|
||||
if (active && !hasContent) setError('Der Server ist gerade nicht erreichbar.')
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
if (active) timer = setTimeout(refresh, 15_000)
|
||||
}
|
||||
}
|
||||
void refresh()
|
||||
return () => { active = false; clearTimeout(timer); controller?.abort() }
|
||||
}, [token])
|
||||
if (!payload) return <div className="center-state"><Card className="display-state" role="status">
|
||||
{error ? <MonitorOff /> : <LoaderCircle className="animate-spin" />}
|
||||
<strong>{error || 'Anzeige wird geladen'}</strong>
|
||||
</Card></div>
|
||||
return <Player {...payload} url={(id, item) => `/api/display/${token}/media/${id}/${item}`} />
|
||||
}
|
||||
333
src/editor.tsx
Normal file
333
src/editor.tsx
Normal file
@ -0,0 +1,333 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
ArrowDown, ArrowLeft, ArrowUp, ArrowUpRight, ChevronDown, Clock3, CodeXml, Copy, FileText, Image,
|
||||
Link2, Monitor, Plus, Radio, Save, Trash2,
|
||||
} from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { api, errorText } from '@/lib/api'
|
||||
import { layouts, themes, widgetLabels, type Asset, type Board, type SavedBoard, type Scroll, type Widget, type WidgetType } from '@/lib/types'
|
||||
import { ButtonProgress, Dialog, Feedback, Field, Select, Status, Toggle } from './admin-ui'
|
||||
import Player from './player'
|
||||
|
||||
const widgetIcons = { html: CodeXml, pdf: FileText, gallery: Image, clock: Clock3 }
|
||||
const adminMedia = (id: string, item: string) => `/api/media/${id}/${item}`
|
||||
const zones = [...new Set(['UTC', 'Europe/Berlin', ...Intl.supportedValuesOf('timeZone')])]
|
||||
|
||||
function uuid() {
|
||||
if (crypto.randomUUID) return crypto.randomUUID()
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16))
|
||||
bytes[6] = (bytes[6] & 15) | 64
|
||||
bytes[8] = (bytes[8] & 63) | 128
|
||||
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
|
||||
function makeWidget(type: WidgetType): Widget {
|
||||
const common = { id: uuid(), title: widgetLabels[type], showTitle: true, from: null, until: null }
|
||||
const scroll = { enabled: true, speed: 42, pause: 3 }
|
||||
if (type === 'pdf') return { ...common, type, assetId: '', mode: 'scroll', scroll, seconds: 10 }
|
||||
if (type === 'gallery') return { ...common, type, assetIds: [], seconds: 6, fit: 'cover' }
|
||||
if (type === 'clock') return { ...common, type, seconds: false, date: true }
|
||||
return { ...common, type, html: '<h2>Willkommen!</h2>\n<p>Hier steht deine Ankündigung.</p>', scroll: { ...scroll, enabled: false } }
|
||||
}
|
||||
|
||||
export default function BoardEditor({ saved, assets, onSave, onBack, onDelete, notify }: {
|
||||
saved: SavedBoard; assets: Asset[]; onSave: (board: SavedBoard) => void; onBack: () => void;
|
||||
onDelete: () => void; notify: (message: string) => void
|
||||
}) {
|
||||
const [board, setBoard] = useState(saved.draft)
|
||||
const [open, setOpen] = useState<string | null>(null)
|
||||
const [add, setAdd] = useState(false)
|
||||
const [confirm, setConfirm] = useState<'unpublish' | 'rotate' | 'delete' | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const linkRef = useRef<HTMLInputElement>(null)
|
||||
const dirty = JSON.stringify(board) !== JSON.stringify(saved.draft)
|
||||
const capacity = layouts[board.layout].slots
|
||||
const kioskPath = `/display/${saved.token}`
|
||||
const update = (change: Partial<Board>) => setBoard(current => ({ ...current, ...change }))
|
||||
const validation = board.name.trim() ? board.widgets.find(item => !item.title.trim()
|
||||
|| (item.type === 'pdf' && !item.assetId) || (item.type === 'gallery' && !item.assetIds.length)) : undefined
|
||||
useEffect(() => {
|
||||
if (!dirty) return
|
||||
const guard = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
||||
window.addEventListener('beforeunload', guard)
|
||||
return () => window.removeEventListener('beforeunload', guard)
|
||||
}, [dirty])
|
||||
|
||||
function replace(widget: Widget) {
|
||||
setBoard(current => ({ ...current, widgets: current.widgets.map(item => item.id === widget.id ? widget : item) }))
|
||||
}
|
||||
function move(index: number, step: number) {
|
||||
const widgets = [...board.widgets]
|
||||
const [widget] = widgets.splice(index, 1)
|
||||
widgets.splice(index + step, 0, widget)
|
||||
update({ widgets })
|
||||
}
|
||||
|
||||
async function save(publish: boolean) {
|
||||
if (!board.name.trim()) { setError('Gib dem Bildschirm einen Namen.'); return }
|
||||
if (validation) { setOpen(validation.id); setError('Prüfe den Titel und wähle für jeden Medienbereich mindestens eine Datei aus.'); return }
|
||||
const invalidRange = board.widgets.find(item => item.from && item.until && Date.parse(item.from) >= Date.parse(item.until))
|
||||
if (invalidRange) { setOpen(invalidRange.id); setError('Das Ende muss nach dem Start liegen.'); return }
|
||||
if (publish && !board.widgets.length) { setError('Füge mindestens einen Inhalt hinzu, bevor du veröffentlichst.'); return }
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const next = await api<SavedBoard>(`/boards/${saved.id}`, 'PUT', { board, revision: saved.revision, publish })
|
||||
onSave(next)
|
||||
setBoard(next.draft)
|
||||
notify(publish ? 'Bildschirm veröffentlicht.' : 'Entwurf gespeichert.')
|
||||
} catch (err) { setError(errorText(err)) } finally { setBusy(false) }
|
||||
}
|
||||
|
||||
async function runAction(action: NonNullable<typeof confirm>) {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const path = `/boards/${saved.id}`
|
||||
if (action === 'delete') {
|
||||
await api(path, 'DELETE', { revision: saved.revision })
|
||||
onDelete()
|
||||
notify('Bildschirm gelöscht.')
|
||||
} else {
|
||||
const result = await api<SavedBoard>(`${path}/${action === 'rotate' ? 'token' : 'unpublish'}`, 'POST', { revision: saved.revision })
|
||||
onSave(result)
|
||||
notify(action === 'rotate' ? 'Kiosk-Link erneuert.' : 'Veröffentlichung beendet.')
|
||||
}
|
||||
} catch (err) { setError(errorText(err)) } finally { setBusy(false); setConfirm(null) }
|
||||
}
|
||||
|
||||
async function copyLink() {
|
||||
const value = location.origin + kioskPath
|
||||
try {
|
||||
if (navigator.clipboard) await navigator.clipboard.writeText(value)
|
||||
else {
|
||||
linkRef.current?.select()
|
||||
if (!document.execCommand('copy')) throw new Error('Clipboard')
|
||||
}
|
||||
notify('Kiosk-Link kopiert.')
|
||||
} catch {
|
||||
linkRef.current?.focus()
|
||||
linkRef.current?.select()
|
||||
setError('Der Link ist markiert und kann manuell kopiert werden.')
|
||||
}
|
||||
}
|
||||
|
||||
const actions = {
|
||||
rotate: { title: 'Kiosk-Link erneuern?', description: 'Verbundene Geräte müssen anschließend den neuen Link öffnen.', label: 'Link erneuern' },
|
||||
unpublish: { title: 'Veröffentlichung beenden?', description: 'Verbundene Bildschirme blenden den veröffentlichten Stand beim nächsten Abruf aus.', label: 'Veröffentlichung beenden' },
|
||||
delete: { title: 'Bildschirm löschen?', description: 'Der Entwurf und die veröffentlichte Anzeige werden dauerhaft gelöscht. Dateien bleiben in der Mediathek verfügbar.', label: 'Bildschirm löschen' },
|
||||
}
|
||||
|
||||
return <section className="board-editor">
|
||||
<Button variant="ghost" className="back-button" onClick={() => { if (!dirty || window.confirm('Ungespeicherte Änderungen verwerfen?')) onBack() }}><ArrowLeft /> Bildschirme</Button>
|
||||
<div className="page-heading editor-heading">
|
||||
<div><div className="editor-title"><h1>{board.name || 'Bildschirm'}</h1><Status board={saved} /></div>
|
||||
<p>{dirty ? 'Ungespeicherte Änderungen' : saved.published && saved.revision !== saved.published_revision ? 'Ein neuerer Entwurf ist gespeichert.' : 'Layout und Inhalte bearbeiten.'}</p></div>
|
||||
<div className="heading-actions">
|
||||
<Button variant="outline" disabled={busy || !dirty} onClick={() => void save(false)}><Save /> Entwurf speichern</Button>
|
||||
<Button disabled={busy} onClick={() => void save(true)}><ButtonProgress busy={busy} />{!busy && <Radio />} Veröffentlichen</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Feedback message={error} />
|
||||
<div className="editor-grid">
|
||||
<div className="editor-form-column">
|
||||
<Card className="settings-card">
|
||||
<div className="settings-title"><h2>Anzeige</h2><p>Layout und Darstellung des Bildschirms.</p></div>
|
||||
<div className="form-grid">
|
||||
<Field id="board-name" label="Name"><Input id="board-name" value={board.name} maxLength={100} onChange={event => update({ name: event.target.value })} /></Field>
|
||||
<Field id="board-location" label="Standort"><Input id="board-location" value={board.location} maxLength={100} onChange={event => update({ location: event.target.value })} /></Field>
|
||||
<Field id="board-theme" label="Farbschema"><Select id="board-theme" value={board.theme} onChange={event => update({ theme: event.target.value as Board['theme'] })}>
|
||||
{Object.entries(themes).map(([id, label]) => <option key={id} value={id}>{label}</option>)}</Select></Field>
|
||||
<Field id="board-zone" label="Zeitzone"><Select id="board-zone" value={board.timeZone} onChange={event => update({ timeZone: event.target.value })}>
|
||||
{[...new Set([board.timeZone, ...zones])].map(zone => <option key={zone} value={zone}>{zone}</option>)}</Select></Field>
|
||||
</div>
|
||||
<div className="layout-label">Layout</div>
|
||||
<div className="layout-picker">{(Object.keys(layouts) as Board['layout'][]).map(key =>
|
||||
<button type="button" key={key} className={`layout-choice ${board.layout === key ? 'selected' : ''}`}
|
||||
disabled={board.widgets.length > layouts[key].slots} aria-pressed={board.layout === key} onClick={() => update({ layout: key })}>
|
||||
<span className={`layout-icon layout-icon-${key}`}><i />{key !== 'single' && <i />}{key === 'focus' && <i />}{key === 'grid' && <><i /><i /></>}</span>
|
||||
{layouts[key].label}
|
||||
</button>)}</div>
|
||||
<Toggle label="Kopfzeile anzeigen" checked={board.showHeader} onChange={showHeader => update({ showHeader })} />
|
||||
{board.showHeader && <Toggle label="Uhr in der Kopfzeile anzeigen" checked={board.showClock} onChange={showClock => update({ showClock })} />}
|
||||
</Card>
|
||||
<Card className="settings-card widget-settings">
|
||||
<div className="section-title"><div><h2>Inhalte</h2><p>{board.widgets.length} von {capacity} Bereichen belegt</p></div>
|
||||
<Button variant="outline" disabled={board.widgets.length >= capacity} onClick={() => setAdd(true)}><Plus /> Bereich</Button></div>
|
||||
{!board.widgets.length && <div className="empty-state widget-empty"><Monitor /><strong>Keine Inhalte hinzugefügt</strong><p>Wähle HTML, ein PDF-Dokument, eine Galerie oder eine Uhr.</p></div>}
|
||||
{board.widgets.map((item, index) => {
|
||||
const Icon = widgetIcons[item.type]
|
||||
const expanded = open === item.id
|
||||
return <div className="widget-item" key={item.id}>
|
||||
<div className="widget-item-head">
|
||||
<button type="button" aria-expanded={expanded} onClick={() => setOpen(expanded ? null : item.id)}>
|
||||
<span className="row-icon"><Icon size={17} /></span><span><strong>{item.title || widgetLabels[item.type]}</strong><small>{widgetLabels[item.type]}</small></span><ChevronDown className={expanded ? 'expanded' : ''} size={16} /></button>
|
||||
<div className="widget-actions">
|
||||
<Button variant="ghost" size="icon-sm" title="Nach oben" aria-label={`${item.title} nach oben`} disabled={index === 0} onClick={() => move(index, -1)}><ArrowUp /></Button>
|
||||
<Button variant="ghost" size="icon-sm" title="Nach unten" aria-label={`${item.title} nach unten`} disabled={index === board.widgets.length - 1} onClick={() => move(index, 1)}><ArrowDown /></Button>
|
||||
</div>
|
||||
</div>
|
||||
{expanded && <WidgetEditor item={item} assets={assets} onChange={replace}
|
||||
onRemove={() => { setOpen(null); update({ widgets: board.widgets.filter(widget => widget.id !== item.id) }) }} />}
|
||||
</div>
|
||||
})}
|
||||
</Card>
|
||||
</div>
|
||||
<div className="editor-side">
|
||||
<Card className="preview-card editor-preview">
|
||||
<div className="settings-title"><h2>Entwurfsvorschau</h2><p>Darstellung im Format 16:9.</p></div>
|
||||
<div className="preview-frame"><Player board={board} assets={assets} url={adminMedia} preview /></div>
|
||||
</Card>
|
||||
<Card className="settings-card kiosk-card">
|
||||
<div className="settings-title"><h2><Link2 size={18} /> Kiosk-Link</h2><p>Öffne diese Adresse im Vollbildbrowser des Anzeigegeräts.</p></div>
|
||||
<div className="kiosk-link"><Input ref={linkRef} value={location.origin + kioskPath} readOnly aria-label="Kiosk-Adresse" />
|
||||
<Button variant="outline" size="icon" onClick={() => void copyLink()} aria-label="Kiosk-Link kopieren" title="Kopieren"><Copy /></Button></div>
|
||||
<div className="kiosk-actions">
|
||||
{saved.published && <Button asChild variant="outline"><a href={kioskPath} target="_blank" rel="noreferrer"><ArrowUpRight /> Anzeige öffnen</a></Button>}
|
||||
<Button variant="ghost" disabled={busy} onClick={() => setConfirm('rotate')}>Link erneuern</Button>
|
||||
</div>
|
||||
{saved.published && <Button variant="ghost" disabled={busy} className="plain-action" onClick={() => setConfirm('unpublish')}>Veröffentlichung beenden</Button>}
|
||||
</Card>
|
||||
<Button variant="ghost" className="danger-link" disabled={busy} onClick={() => setConfirm('delete')}><Trash2 /> Bildschirm löschen</Button>
|
||||
</div>
|
||||
</div>
|
||||
{add && <Dialog title="Bereich hinzufügen" description="Wähle den Inhaltstyp für diesen Bereich." onClose={() => setAdd(false)}>
|
||||
<div className="type-picker">{(Object.keys(widgetLabels) as WidgetType[]).map(type => {
|
||||
const Icon = widgetIcons[type]
|
||||
return <Button variant="outline" key={type} onClick={() => { const item = makeWidget(type); update({ widgets: [...board.widgets, item] }); setOpen(item.id); setAdd(false) }}><Icon />{widgetLabels[type]}</Button>
|
||||
})}</div>
|
||||
</Dialog>}
|
||||
{confirm && <Dialog title={actions[confirm].title} description={actions[confirm].description} onClose={() => { if (!busy) setConfirm(null) }}>
|
||||
<div className="form-actions"><Button variant="outline" disabled={busy} onClick={() => setConfirm(null)}>Abbrechen</Button>
|
||||
<Button variant="destructive" disabled={busy} onClick={() => void runAction(confirm)}><ButtonProgress busy={busy} /> {actions[confirm].label}</Button></div>
|
||||
</Dialog>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function dateToLocal(date: string | null) {
|
||||
if (!date) return ''
|
||||
const time = new Date(date)
|
||||
return new Date(time.getTime() - time.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
|
||||
}
|
||||
|
||||
function WidgetEditor({ item, assets, onChange, onRemove }: {
|
||||
item: Widget; assets: Asset[]; onChange: (item: Widget) => void; onRemove: () => void
|
||||
}) {
|
||||
const [importError, setImportError] = useState('')
|
||||
const [imageToAdd, setImageToAdd] = useState('')
|
||||
const htmlFile = useRef<HTMLInputElement>(null)
|
||||
const id = item.id
|
||||
let content: ReactNode
|
||||
if (item.type === 'html') content = <>
|
||||
<Field id={id + '-html'} label="HTML-Quelltext" hint="Unterstützt Überschriften, Absätze, Listen, Tabellen und grundlegende Formatierung.">
|
||||
<Textarea id={id + '-html'} className="html-source" spellCheck={false} value={item.html} maxLength={100_000} onChange={event => onChange({ ...item, html: event.target.value })} />
|
||||
</Field>
|
||||
<div><Button variant="outline" size="sm" onClick={() => htmlFile.current?.click()}><CodeXml /> HTML-Datei laden</Button>
|
||||
<input hidden type="file" accept=".html,.htm,text/html" ref={htmlFile} onChange={async event => {
|
||||
const file = event.target.files?.[0]; event.target.value = ''
|
||||
if (!file) return
|
||||
setImportError('')
|
||||
try {
|
||||
const html = await file.text()
|
||||
if (html.length > 100_000) setImportError('Die HTML-Datei darf höchstens 100.000 Zeichen enthalten.')
|
||||
else onChange({ ...item, html })
|
||||
} catch { setImportError('Die HTML-Datei konnte nicht gelesen werden.') }
|
||||
}} />
|
||||
</div>
|
||||
<Feedback message={importError} />
|
||||
<ScrollOptions id={id} value={item.scroll} onChange={scroll => onChange({ ...item, scroll })} />
|
||||
</>
|
||||
else if (item.type === 'pdf') content = <>
|
||||
<Field id={id + '-pdf'} label="PDF-Dokument" hint="PDFs stehen nach dem Upload in der Mediathek zur Auswahl.">
|
||||
<Select id={id + '-pdf'} value={item.assetId} onChange={event => onChange({ ...item, assetId: event.target.value })}>
|
||||
<option value="">PDF auswählen</option>{assets.filter(asset => asset.kind === 'pdf').map(asset => <option key={asset.id} value={asset.id}>{asset.name}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
<Field id={id + '-mode'} label="Wiedergabe">
|
||||
<Select id={id + '-mode'} value={item.mode} onChange={event => onChange({ ...item, mode: event.target.value as typeof item.mode })}>
|
||||
<option value="scroll">Fortlaufend scrollen</option><option value="pages">Seitenwechsel</option><option value="static">Erste Seite anzeigen</option>
|
||||
</Select>
|
||||
</Field>
|
||||
{item.mode === 'scroll' && <ScrollOptions id={id} value={item.scroll} onChange={scroll => onChange({ ...item, scroll })} />}
|
||||
{item.mode === 'pages' && <NumberField id={id + '-seconds'} label="Sekunden pro Seite" min={2} max={120} value={item.seconds} onChange={seconds => onChange({ ...item, seconds })} />}
|
||||
</>
|
||||
else if (item.type === 'gallery') {
|
||||
const available = assets.filter(asset => asset.kind === 'image' && !item.assetIds.includes(asset.id))
|
||||
const image = available.some(asset => asset.id === imageToAdd) ? imageToAdd : ''
|
||||
content = <>
|
||||
<Field id={id + '-image'} label="Bilder" hint="Die Bilder werden in der gezeigten Reihenfolge abgespielt.">
|
||||
<div className="kiosk-link">
|
||||
<Select id={id + '-image'} value={image} onChange={event => setImageToAdd(event.target.value)}>
|
||||
<option value="">Bild aus der Mediathek auswählen</option>{available.map(asset => <option key={asset.id} value={asset.id}>{asset.name}</option>)}
|
||||
</Select>
|
||||
<Button variant="outline" size="icon" disabled={!image || item.assetIds.length >= 60} aria-label="Bild hinzufügen" onClick={() => { onChange({ ...item, assetIds: [...item.assetIds, image] }); setImageToAdd('') }}><Plus /></Button>
|
||||
</div>
|
||||
</Field>
|
||||
{item.assetIds.length > 0 && <ul className="gallery-order">{item.assetIds.map((asset, index) => {
|
||||
const move = (offset: number) => {
|
||||
const ids = [...item.assetIds]
|
||||
ids.splice(index, 1)
|
||||
ids.splice(index + offset, 0, asset)
|
||||
onChange({ ...item, assetIds: ids })
|
||||
}
|
||||
return <li key={asset}><span>{assets.find(file => file.id === asset)?.name ?? 'Datei fehlt'}</span>
|
||||
<Button variant="ghost" size="icon-xs" disabled={index === 0} aria-label="Bild nach oben" onClick={() => move(-1)}><ArrowUp /></Button>
|
||||
<Button variant="ghost" size="icon-xs" disabled={index === item.assetIds.length - 1} aria-label="Bild nach unten" onClick={() => move(1)}><ArrowDown /></Button>
|
||||
<Button variant="ghost" size="icon-xs" aria-label="Bild entfernen" onClick={() => onChange({ ...item, assetIds: item.assetIds.filter(id => id !== asset) })}><Trash2 /></Button>
|
||||
</li>
|
||||
})}</ul>}
|
||||
<div className="form-grid">
|
||||
<NumberField id={id + '-seconds'} label="Sekunden pro Bild" min={2} max={120} value={item.seconds} onChange={seconds => onChange({ ...item, seconds })} />
|
||||
<Field id={id + '-fit'} label="Bildgröße"><Select id={id + '-fit'} value={item.fit} onChange={event => onChange({ ...item, fit: event.target.value as typeof item.fit })}>
|
||||
<option value="cover">Fläche ausfüllen</option><option value="contain">Ganzes Bild zeigen</option></Select></Field>
|
||||
</div>
|
||||
</>
|
||||
} else content = <>
|
||||
<Toggle label="Datum unter der Uhr zeigen" checked={item.date} onChange={date => onChange({ ...item, date })} />
|
||||
<Toggle label="Sekunden anzeigen" checked={item.seconds} onChange={seconds => onChange({ ...item, seconds })} />
|
||||
</>
|
||||
const from = dateToLocal(item.from)
|
||||
const until = dateToLocal(item.until)
|
||||
return <div className="widget-item-body form-stack">
|
||||
<Field id={id + '-title'} label="Bereichstitel"><Input id={id + '-title'} maxLength={100} value={item.title} onChange={event => onChange({ ...item, title: event.target.value })} /></Field>
|
||||
<Toggle label="Titel in der Anzeige zeigen" checked={item.showTitle} onChange={showTitle => onChange({ ...item, showTitle })} />
|
||||
{content}
|
||||
<details className="schedule" key={id}>
|
||||
<summary><Clock3 size={16} /> Zeitsteuerung {item.from || item.until ? <Badge variant="secondary">Geplant</Badge> : null}</summary>
|
||||
<div className="form-grid">
|
||||
<Field id={id + '-from'} label="Sichtbar ab"><Input id={id + '-from'} type="datetime-local" value={from} onChange={event => onChange({
|
||||
...item, from: event.target.value ? new Date(event.target.value).toISOString() : null,
|
||||
})} /></Field>
|
||||
<Field id={id + '-until'} label="Sichtbar bis"><Input id={id + '-until'} type="datetime-local" value={until} onChange={event => onChange({
|
||||
...item, until: event.target.value ? new Date(event.target.value).toISOString() : null,
|
||||
})} /></Field>
|
||||
</div><p className="field-hint">Zeiten beziehen sich auf die lokale Zeitzone dieses Browsers.</p>
|
||||
</details>
|
||||
<Button variant="ghost" className="danger-link" onClick={onRemove}><Trash2 /> Bereich entfernen</Button>
|
||||
</div>
|
||||
}
|
||||
|
||||
function ScrollOptions({ id, value, onChange }: { id: string; value: Scroll; onChange: (value: Scroll) => void }) {
|
||||
return <>
|
||||
<Toggle label="Automatisch scrollen" checked={value.enabled} onChange={enabled => onChange({ ...value, enabled })} />
|
||||
{value.enabled && <div className="form-grid">
|
||||
<NumberField id={id + '-speed'} label="Tempo (px/s)" value={value.speed} min={10} max={220} onChange={speed => onChange({ ...value, speed })} />
|
||||
<NumberField id={id + '-pause'} label="Pause am Rand (s)" value={value.pause} min={0} max={30} onChange={pause => onChange({ ...value, pause })} />
|
||||
</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function NumberField({ id, label, min, max, value, onChange }: {
|
||||
id: string; label: string; min: number; max: number; value: number; onChange: (value: number) => void
|
||||
}) {
|
||||
return <Field id={id} label={label}><Input id={id} type="number" min={min} max={max} value={String(value)} onChange={event => {
|
||||
const next = event.currentTarget.valueAsNumber
|
||||
if (Number.isFinite(next)) onChange(next)
|
||||
}} onBlur={() => { if (value < min || value > max) onChange(Math.min(max, Math.max(min, Math.round(value)))) }} /></Field>
|
||||
}
|
||||
27
src/lib/api.ts
Normal file
27
src/lib/api.ts
Normal file
@ -0,0 +1,27 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(readonly status: number, message: string) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
export async function api<T>(path: string, method = 'GET', body?: unknown): Promise<T> {
|
||||
const multipart = body instanceof FormData
|
||||
const response = await fetch('/api' + path, {
|
||||
method, cache: 'no-store',
|
||||
...(body === undefined ? {} : {
|
||||
headers: multipart ? undefined : { 'Content-Type': 'application/json' },
|
||||
body: multipart ? body : JSON.stringify(body),
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => ({}))
|
||||
throw new ApiError(response.status, payload.error || 'Die Anfrage ist fehlgeschlagen.')
|
||||
}
|
||||
return response.status === 204 ? undefined as T : response.json()
|
||||
}
|
||||
|
||||
export const errorText = (error: unknown) => error instanceof ApiError ? error.message : 'Der Server ist gerade nicht erreichbar. Bitte versuche es erneut.'
|
||||
export const formatDate = (date: string) => new Date(date).toLocaleDateString('de-DE', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
export const formatSize = (bytes: string) => {
|
||||
const size = Number(bytes)
|
||||
return size >= 1024 ** 2 ? `${(size / 1024 ** 2).toLocaleString('de-DE', { maximumFractionDigits: 1 })} MB` : `${Math.ceil(size / 1024)} KB`
|
||||
}
|
||||
60
src/lib/types.ts
Normal file
60
src/lib/types.ts
Normal file
@ -0,0 +1,60 @@
|
||||
export type Scroll = { enabled: boolean; speed: number; pause: number }
|
||||
export type WidgetType = 'html' | 'pdf' | 'gallery' | 'clock'
|
||||
type Common = { id: string; title: string; showTitle: boolean; from: string | null; until: string | null }
|
||||
export type WidgetOf = {
|
||||
html: Common & { type: 'html'; html: string; scroll: Scroll }
|
||||
pdf: Common & { type: 'pdf'; assetId: string; mode: 'scroll' | 'pages' | 'static'; seconds: number; scroll: Scroll }
|
||||
gallery: Common & { type: 'gallery'; assetIds: string[]; seconds: number; fit: 'cover' | 'contain' }
|
||||
clock: Common & { type: 'clock'; seconds: boolean; date: boolean }
|
||||
}
|
||||
export type Widget = WidgetOf[WidgetType]
|
||||
export const layouts = {
|
||||
single: { label: 'Vollfläche', slots: 1 },
|
||||
split: { label: 'Zwei Spalten', slots: 2 },
|
||||
focus: { label: 'Fokus links', slots: 3 },
|
||||
grid: { label: 'Raster', slots: 8 },
|
||||
}
|
||||
export const themes = { midnight: 'Mitternacht', light: 'Tageslicht', forest: 'Waldgrün' }
|
||||
export type Board = {
|
||||
name: string
|
||||
location: string
|
||||
layout: keyof typeof layouts
|
||||
theme: keyof typeof themes
|
||||
showHeader: boolean
|
||||
showClock: boolean
|
||||
timeZone: string
|
||||
widgets: Widget[]
|
||||
}
|
||||
export type SavedBoard = {
|
||||
id: string
|
||||
token: string
|
||||
draft: Board
|
||||
published: Board | null
|
||||
revision: number
|
||||
published_revision: number | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
last_seen: string | null
|
||||
}
|
||||
export type Media = {
|
||||
id: string
|
||||
name: string
|
||||
kind: 'pdf' | 'image'
|
||||
metadata: { pages?: number[]; width?: number; height?: number }
|
||||
}
|
||||
export type Asset = Media & { bytes: string; created_at: string }
|
||||
export type User = {
|
||||
id: string
|
||||
name: string
|
||||
email: string
|
||||
role: 'admin' | 'editor'
|
||||
active: boolean
|
||||
created_at: string
|
||||
}
|
||||
export type BoardPayload = { board: Board; assets: Media[] }
|
||||
|
||||
export const widgetLabels = { html: 'HTML-Inhalt', pdf: 'PDF-Dokument', gallery: 'Bildergalerie', clock: 'Uhr' }
|
||||
export const defaultBoard: Board = {
|
||||
name: '', location: '', layout: 'focus', theme: 'midnight', showHeader: true, showClock: true,
|
||||
timeZone: 'Europe/Berlin', widgets: [],
|
||||
}
|
||||
6
src/lib/utils.ts
Normal file
6
src/lib/utils.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
13
src/main.tsx
Normal file
13
src/main.tsx
Normal file
@ -0,0 +1,13 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { lazy, Suspense } from 'react'
|
||||
import { LoaderCircle } from 'lucide-react'
|
||||
import './styles.css'
|
||||
|
||||
const Display = lazy(() => import('./display'))
|
||||
const Admin = lazy(() => import('./admin'))
|
||||
const token = location.pathname.match(/^\/display\/([^/]+)\/?$/)?.[1]
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<Suspense fallback={<div className="center-state" role="status"><LoaderCircle className="animate-spin" /> Syncova Display wird geladen</div>}>
|
||||
{token ? <Display token={token} /> : <Admin />}
|
||||
</Suspense>,
|
||||
)
|
||||
81
src/player.css
Normal file
81
src/player.css
Normal file
@ -0,0 +1,81 @@
|
||||
.player {
|
||||
--display-bg: #0e1927; --display-panel: #172939; --display-text: #f5fbfd;
|
||||
--display-muted: #a9c2cc; --display-accent: #86e3ce; --display-line: #2b414c;
|
||||
background: var(--display-bg);
|
||||
color: var(--display-text);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1.45%;
|
||||
box-sizing: border-box;
|
||||
container-type: size;
|
||||
width: 100%;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
}
|
||||
.player.theme-light {
|
||||
color-scheme: light; --display-bg: #edf3f4; --display-panel: #fff; --display-text: #183136;
|
||||
--display-muted: #48636d; --display-accent: #0d6c60; --display-line: #ccdddf;
|
||||
}
|
||||
.player.theme-forest {
|
||||
--display-bg: #101e1b; --display-panel: #1a302b; --display-text: #f3fbf2;
|
||||
--display-muted: #bfd0ba; --display-accent: #c6e5a8; --display-line: #42564b;
|
||||
}
|
||||
.player > header { display: flex; align-items: center; justify-content: space-between; gap: 2cqw; padding: .15cqw .15cqw .75cqw; margin-bottom: 1.15cqw; min-height: 0; }
|
||||
.player-brand { display: flex; align-items: center; min-width: 0; gap: 1cqw; }
|
||||
.player-brand > div:last-child { display: grid; min-width: 0; }
|
||||
.player-brand strong { font-size: 1.85cqw; font-weight: 700; letter-spacing: -.045em; line-height: 1.15; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.player-brand small, .player-clock small { font-size: .83cqw; margin-top: .3cqw; color: var(--display-muted); font-weight: 530; }
|
||||
.player-brand small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.player-symbol { flex: none; width: 3.1cqw; height: 3.1cqw; display: grid; place-items: center; color: var(--display-accent); background: color-mix(in srgb, var(--display-accent) 13%, transparent); border-radius: .65cqw; }
|
||||
.player-symbol svg { width: 54%; height: 54%; }
|
||||
.player-clock { display: grid; text-align: right; font-variant-numeric: tabular-nums; line-height: 1.03; color: var(--display-text); flex: none; }
|
||||
.player-clock > span { font-size: 2cqw; font-weight: 690; letter-spacing: -.055em; }
|
||||
.player-grid { flex: 1; min-height: 0; display: grid; gap: 1cqw; grid-template-columns: repeat(var(--widget-columns), minmax(0, 1fr)); grid-template-rows: repeat(var(--widget-rows), minmax(0, 1fr)); }
|
||||
.player-grid.layout-focus:has(> :nth-child(2)) { grid-template-columns: minmax(0, 1.55fr) minmax(0, 1fr); }
|
||||
.player-grid.layout-focus:has(> :nth-child(3)) > :first-child { grid-row: span 2; }
|
||||
.player-grid.layout-grid > :last-child:nth-child(odd) { grid-column: 1 / -1; }
|
||||
.player .player-tile { display: flex; min-height: 0; min-width: 0; flex-direction: column; gap: 0; padding: 0; overflow: hidden; color: var(--display-text); background: var(--display-panel); border: 1px solid var(--display-line); border-radius: .9cqw; box-shadow: none; }
|
||||
.player-tile-title { font-size: 1.05cqw; margin: 0; padding: .8cqw 1.2cqw; color: var(--display-muted); font-weight: 650; border-bottom: 1px solid var(--display-line); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.player-tile-body { position: relative; display: flex; width: 100%; min-height: 0; flex: 1; }
|
||||
.player-html-scroll, .pdf-scroll { width: 100%; height: 100%; overflow: auto; scrollbar-width: none; overscroll-behavior: contain; }
|
||||
.player-html-scroll::-webkit-scrollbar, .pdf-scroll::-webkit-scrollbar { width: 0; height: 0; }
|
||||
.player-html { min-height: 100%; display: flex; flex-direction: column; justify-content: center; padding: 2.15cqw; overflow-wrap: anywhere; font-size: 1.52cqw; line-height: 1.5; }
|
||||
.player-html > * + * { margin-top: .62em; }
|
||||
.player-html .eyebrow { color: var(--display-accent); font-size: .83cqw; font-weight: 760; letter-spacing: .14em; }
|
||||
.player-html h1, .player-html h2, .player-html h3 { font-weight: 720; letter-spacing: -.066em; line-height: 1.03; color: var(--display-text); }
|
||||
.player-html h1 { font-size: 5.05cqw; margin-top: .31em; }
|
||||
.player-html h2 { font-size: 2.82cqw; margin-top: .25em; }
|
||||
.player-html h3 { font-size: 1.9cqw; }
|
||||
.player-html p { color: var(--display-muted); }
|
||||
.player-html ul, .player-html ol { list-style: revert; padding-left: 1.5em; }
|
||||
.player-html pre { white-space: pre-wrap; }
|
||||
.player-html table { border-collapse: collapse; width: 100%; text-align: left; }
|
||||
.player-html td, .player-html th { border: 1px solid var(--display-line); padding: .35em .5em; }
|
||||
.player-html img { max-width: 100%; height: auto; align-self: flex-start; }
|
||||
.player-clock-widget { width: 100%; height: 100%; display: grid; place-content: center; }
|
||||
.player-clock-widget .player-clock { text-align: center; }
|
||||
.player-clock-widget .player-clock > span { font-size: 6cqw; }
|
||||
.player-clock-widget .player-clock small { font-size: 1.3cqw; }
|
||||
.player-gallery, .pdf-slides { position: relative; width: 100%; height: 100%; overflow: hidden; display: grid; place-items: center; background: color-mix(in srgb, var(--display-bg) 85%, #000); }
|
||||
.gallery-frame { position: absolute; inset: 0; }
|
||||
.gallery-incoming { opacity: 0; }
|
||||
.gallery-frame img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.gallery-frame .gallery-contain { object-fit: contain; }
|
||||
.gallery-counter { position: absolute; z-index: 1; bottom: .8cqw; right: .8cqw; padding: .25cqw .55cqw; border-radius: .32cqw; background: #000b; color: #fff; font-size: .8cqw; font-variant-numeric: tabular-nums; }
|
||||
.pdf-slides { padding: 8px; }
|
||||
.pdf-slides > img { position: absolute; inset: .6cqw; width: calc(100% - 1.2cqw); height: calc(100% - 1.2cqw); object-fit: contain; }
|
||||
.pdf-scroll { position: relative; padding: 8px; background: color-mix(in srgb, var(--display-bg) 85%, #000); }
|
||||
.pdf-sheet { position: relative; width: 100%; max-width: 1400px; margin: 0 auto 8px; background: #fff; overflow: hidden; }
|
||||
.pdf-sheet:last-child { margin-bottom: 0; }
|
||||
.pdf-sheet img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
|
||||
.player-media-error, .player-empty { padding: 1cqw; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; gap: .7cqw; font-size: 1.2cqw; color: var(--display-muted); }
|
||||
.pdf-sheet .player-media-error { color: #333; }
|
||||
.player-empty > svg, .player-media-error > svg { width: 1.7cqw; height: 1.7cqw; }
|
||||
.player-preview { height: 100%; }
|
||||
@container (max-aspect-ratio: 4/5) {
|
||||
.player-grid.layout-split, .player-grid.layout-focus:has(> :nth-child(2)) { grid-template-columns: minmax(0, 1fr); grid-auto-rows: minmax(0, 1fr); }
|
||||
.player-grid.layout-focus:has(> :nth-child(3)) > :first-child { grid-row: auto; }
|
||||
.player-brand strong, .player-clock > span { font-size: 3.5cqw; }
|
||||
.player-brand small, .player-clock small { font-size: 1.7cqw; }
|
||||
.player-html { font-size: 2.6cqw; }
|
||||
}
|
||||
284
src/player.tsx
Normal file
284
src/player.tsx
Normal file
@ -0,0 +1,284 @@
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type RefObject } from 'react'
|
||||
import DOMPurify from 'dompurify'
|
||||
import { FileText, ImageOff, Monitor, MonitorPlay } from 'lucide-react'
|
||||
import { Card } from '@/components/ui/card'
|
||||
import type { Board, Media, Scroll, Widget, WidgetOf } from '@/lib/types'
|
||||
import './player.css'
|
||||
|
||||
// The draft editor can preview HTML before it has passed through the server sanitizer.
|
||||
DOMPurify.addHook('uponSanitizeAttribute', (_node, attribute) => {
|
||||
if (attribute.attrName === 'class') attribute.attrValue = attribute.attrValue.split(/\s+/).filter(value => value === 'eyebrow').join(' ')
|
||||
if (attribute.attrName !== 'style') return
|
||||
const styles = attribute.attrValue.split(';').filter(rule =>
|
||||
/^\s*(?:(?:color|background-color):\s*#[0-9a-f]{3,8}|text-align:\s*(?:left|right|center|justify)|font-size:\s*\d+(?:\.\d+)?(?:rem|em|px|%)|font-weight:\s*(?:normal|bold|[1-9]00))\s*$/i.test(rule),
|
||||
)
|
||||
attribute.attrValue = styles.join(';')
|
||||
})
|
||||
|
||||
function useTime(interval: number) {
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
useEffect(() => {
|
||||
setNow(Date.now())
|
||||
const id = setInterval(() => setNow(Date.now()), interval)
|
||||
return () => clearInterval(id)
|
||||
}, [interval])
|
||||
return now
|
||||
}
|
||||
|
||||
function useSchedule(widgets: Widget[]) {
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
useEffect(() => {
|
||||
const dates = widgets.flatMap(item => [item.from, item.until]).filter(Boolean).map(date => Date.parse(date!))
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
function update() {
|
||||
const current = Date.now()
|
||||
setNow(current)
|
||||
const next = Math.min(...dates.filter(date => date > current))
|
||||
if (Number.isFinite(next)) timer = setTimeout(update, Math.min(next - current, 60_000))
|
||||
}
|
||||
if (dates.length) update()
|
||||
return () => clearTimeout(timer)
|
||||
}, [widgets])
|
||||
return now
|
||||
}
|
||||
|
||||
function Clock({ zone, seconds = false, date = false }: { zone: string; seconds?: boolean; date?: boolean }) {
|
||||
const now = useTime(seconds ? 1000 : 4000)
|
||||
const format = useMemo(() => new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: zone, hour: '2-digit', minute: '2-digit', second: seconds ? '2-digit' : undefined,
|
||||
}), [zone, seconds])
|
||||
const day = useMemo(() => new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: zone, weekday: 'long', day: 'numeric', month: 'long',
|
||||
}), [zone])
|
||||
return <time className="player-clock" dateTime={new Date(now).toISOString()}>
|
||||
<span>{format.format(now)}</span>{date && <small>{day.format(now)}</small>}
|
||||
</time>
|
||||
}
|
||||
|
||||
function useAutoScroll(ref: RefObject<HTMLDivElement | null>, options: Scroll, identity: string, status?: RefObject<Set<number>>) {
|
||||
const { enabled, speed, pause } = options
|
||||
useEffect(() => {
|
||||
const box = ref.current
|
||||
if (!box) return
|
||||
box.scrollTop = 0
|
||||
if (!enabled) return
|
||||
let start = performance.now()
|
||||
let nextMove = start + pause * 1000
|
||||
let bottomReached: number | null = null
|
||||
let position = 0
|
||||
let frame: number
|
||||
const tick = (now: number) => {
|
||||
frame = requestAnimationFrame(tick)
|
||||
const elapsed = Math.min(100, now - start)
|
||||
start = now
|
||||
const bottom = box.scrollHeight - box.clientHeight
|
||||
if (bottom <= 1 || now < nextMove) return
|
||||
if (Math.abs(box.scrollTop - position) > 2) position = box.scrollTop
|
||||
if (position < bottom - 1) {
|
||||
bottomReached = null
|
||||
if (status) {
|
||||
// Find the last page at the viewport edge before moving into it.
|
||||
const edge = position + box.clientHeight + 6
|
||||
let low = 0
|
||||
let high = box.children.length
|
||||
while (low < high) {
|
||||
const middle = (low + high) >>> 1
|
||||
if ((box.children[middle] as HTMLElement).offsetTop > edge) high = middle
|
||||
else low = middle + 1
|
||||
}
|
||||
if (low && !status.current.has(low)) return
|
||||
}
|
||||
position = Math.min(bottom, position + speed * elapsed / 1000)
|
||||
box.scrollTop = Math.round(position)
|
||||
} else {
|
||||
bottomReached ??= now
|
||||
if (now - bottomReached >= pause * 1000) {
|
||||
position = 0
|
||||
box.scrollTop = 0
|
||||
nextMove = now + pause * 1000
|
||||
bottomReached = null
|
||||
}
|
||||
}
|
||||
}
|
||||
frame = requestAnimationFrame(tick)
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [ref, enabled, speed, pause, identity, status])
|
||||
}
|
||||
|
||||
function Html({ item }: { item: WidgetOf['html'] }) {
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const html = useMemo(() => DOMPurify.sanitize(item.html, {
|
||||
ALLOWED_TAGS: ['p', 'div', 'span', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'section', 'article', 'aside',
|
||||
'ul', 'ol', 'li', 'b', 'strong', 'i', 'em', 'img', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
||||
'hr', 'blockquote', 'mark', 'sub', 'sup', 'pre', 'code', 'figure', 'figcaption', 'dl', 'dt', 'dd'],
|
||||
ALLOWED_ATTR: ['class', 'style', 'src', 'alt', 'width', 'height', 'colspan', 'rowspan', 'scope'],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
}), [item.html])
|
||||
useAutoScroll(box, item.scroll, item.html)
|
||||
return <div ref={box} className="player-html-scroll"><div className="player-html" dangerouslySetInnerHTML={{ __html: html }} /></div>
|
||||
}
|
||||
|
||||
function ImageWithRetry({ src, alt, className, onReady, onFailure, retries = 2 }: {
|
||||
src: string; alt: string; className?: string; onReady?: () => void; onFailure?: () => void; retries?: number
|
||||
}) {
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||
useEffect(() => () => clearTimeout(timer.current), [src])
|
||||
if (failed) return <div className="player-media-error"><ImageOff size={20} /> Datei nicht verfügbar</div>
|
||||
return <img className={className} src={attempt ? `${src}?retry=${attempt}` : src} alt={alt} decoding="async" draggable={false}
|
||||
onLoad={onReady} onError={() => {
|
||||
if (attempt < retries) timer.current = setTimeout(() => setAttempt(attempt + 1), 2200)
|
||||
else {
|
||||
setFailed(true)
|
||||
onFailure?.()
|
||||
timer.current = setTimeout(() => { setAttempt(attempt + 1); setFailed(false) }, 20_000)
|
||||
}
|
||||
}} />
|
||||
}
|
||||
|
||||
type MediaUrl = (id: string, item: string) => string
|
||||
|
||||
function Gallery({ item, assets, url }: { item: WidgetOf['gallery']; assets: Map<string, Media>; url: MediaUrl }) {
|
||||
const [index, setIndex] = useState(0)
|
||||
const [settled, setSettled] = useState(-1)
|
||||
const [visible, setVisible] = useState(-1)
|
||||
const ids = item.assetIds
|
||||
useEffect(() => {
|
||||
if (ids.length < 2 || settled !== index) return
|
||||
const timer = setTimeout(() => setIndex(value => value + 1), item.seconds * 1000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [index, ids.length, item.seconds, settled])
|
||||
const frames = visible >= 0 && visible !== index ? [visible, index] : [index]
|
||||
return <div className="player-gallery">
|
||||
{frames.map(frame => {
|
||||
const current = frame === index
|
||||
const id = ids[frame % ids.length]
|
||||
return <div className={`gallery-frame${frame === visible || visible < 0 ? '' : ' gallery-incoming'}`} key={frame}>
|
||||
<ImageWithRetry src={url(id, 'image')} alt={assets.get(id)?.name ?? 'Galeriebild'} className={`gallery-${item.fit}`}
|
||||
onReady={current ? () => { setVisible(frame); setSettled(frame) } : undefined}
|
||||
onFailure={current ? () => setSettled(frame) : undefined} />
|
||||
</div>
|
||||
})}
|
||||
{ids.length > 1 && <div className="gallery-counter">{Math.max(0, visible) % ids.length + 1} / {ids.length}</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
function useDimensions(ref: RefObject<HTMLDivElement | null>) {
|
||||
const [size, setSize] = useState({ width: 0, height: 0 })
|
||||
useEffect(() => {
|
||||
const element = ref.current
|
||||
if (!element) return
|
||||
const observer = new ResizeObserver(([entry]) => setSize({ width: entry.contentRect.width, height: entry.contentRect.height }))
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [ref])
|
||||
return size
|
||||
}
|
||||
|
||||
function rasterSize(width: number, height: number, ratio: number) {
|
||||
const density = Math.min(devicePixelRatio || 1, 1.25)
|
||||
const need = Math.max(width, height || width / ratio) * density
|
||||
return need <= 800 ? 800 : need <= 1600 ? 1600 : 2400
|
||||
}
|
||||
|
||||
function PdfSlides({ item, asset, url }: { item: WidgetOf['pdf']; asset: Media; url: MediaUrl }) {
|
||||
const pages = asset.metadata.pages!
|
||||
const [page, setPage] = useState(0)
|
||||
const [ready, setReady] = useState(-1)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const { width, height } = useDimensions(ref)
|
||||
const current = page % pages.length
|
||||
const active = item.mode === 'pages' && pages.length > 1
|
||||
const src = (index: number) => {
|
||||
const ratio = pages[index]
|
||||
const pageWidth = Math.min(Math.max(0, width - 16), Math.max(0, height - 16) * ratio)
|
||||
return url(asset.id, `page-${index + 1}-${rasterSize(pageWidth, pageWidth / ratio, ratio)}`)
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!active || ready !== page) return
|
||||
const timer = setTimeout(() => setPage(value => value + 1), item.seconds * 1000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [active, item.seconds, page, ready])
|
||||
return <div ref={ref} className="pdf-slides">
|
||||
{width > 0 && <ImageWithRetry key={`${page}:${src(current)}`} src={src(current)} alt={`Seite ${current + 1}`}
|
||||
onReady={() => setReady(page)} onFailure={() => setReady(page)} />}
|
||||
{active && <span className="gallery-counter">{current + 1} / {pages.length}</span>}
|
||||
</div>
|
||||
}
|
||||
|
||||
function PdfScroll({ item, asset, url }: { item: WidgetOf['pdf']; asset: Media; url: MediaUrl }) {
|
||||
const pages = asset.metadata.pages!
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const status = useRef(new Set<number>())
|
||||
const { width, height } = useDimensions(box)
|
||||
const [nearby, setNearby] = useState(() => new Set([0]))
|
||||
useAutoScroll(box, item.scroll, asset.id, status)
|
||||
useEffect(() => {
|
||||
const root = box.current
|
||||
if (!root || width === 0 || height === 0) return
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
setNearby(previous => {
|
||||
const next = new Set(previous)
|
||||
for (const entry of entries) {
|
||||
const index = Number((entry.target as HTMLElement).dataset.pdfPage) - 1
|
||||
if (entry.isIntersecting) next.add(index)
|
||||
else if (index > 0) { next.delete(index); status.current.delete(index + 1) }
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, { root, rootMargin: `${Math.max(250, Math.ceil(height * 0.75))}px 0px` })
|
||||
root.querySelectorAll('[data-pdf-page]').forEach(page => observer.observe(page))
|
||||
return () => observer.disconnect()
|
||||
}, [height, width])
|
||||
return <div className="pdf-scroll" ref={box} tabIndex={item.scroll.enabled ? undefined : 0} aria-label={asset.name}>
|
||||
{width > 0 && pages.map((ratio, index) => {
|
||||
const pageWidth = Math.min(Math.max(0, width - 16), 1400)
|
||||
const src = url(asset.id, `page-${index + 1}-${rasterSize(pageWidth, pageWidth / ratio, ratio)}`)
|
||||
const done = () => status.current.add(index + 1)
|
||||
return <div className="pdf-sheet" key={index} data-pdf-page={index + 1} style={{ aspectRatio: ratio }}>
|
||||
{nearby.has(index) && <ImageWithRetry key={src} src={src} alt={`Seite ${index + 1}`} onReady={done} onFailure={done} />}
|
||||
</div>
|
||||
})}
|
||||
</div>
|
||||
}
|
||||
|
||||
function WidgetView({ item, assets, url, zone }: { item: Widget; assets: Map<string, Media>; url: MediaUrl; zone: string }) {
|
||||
let content
|
||||
if (item.type === 'html') content = <Html item={item} />
|
||||
else if (item.type === 'clock') content = <div className="player-clock-widget"><Clock zone={zone} seconds={item.seconds} date={item.date} /></div>
|
||||
else if (item.type === 'gallery' && item.assetIds.length) content = <Gallery key={item.assetIds.join()} item={item} assets={assets} url={url} />
|
||||
else if (item.type === 'pdf') {
|
||||
const asset = assets.get(item.assetId)
|
||||
if (asset?.metadata.pages?.length) content = item.mode === 'scroll'
|
||||
? <PdfScroll key={asset.id} item={item} asset={asset} url={url} />
|
||||
: <PdfSlides key={asset.id + item.mode} item={item} asset={asset} url={url} />
|
||||
}
|
||||
return <Card className={`player-tile player-tile-${item.type}`}>
|
||||
{item.showTitle && <h2 className="player-tile-title">{item.title}</h2>}
|
||||
<div className="player-tile-body">{content ?? <div className="player-media-error"><FileText size={20} />Keine Datei ausgewählt</div>}</div>
|
||||
</Card>
|
||||
}
|
||||
|
||||
export default function Player({ board, assets, url, preview = false }: {
|
||||
board: Board; assets: Media[]; url: MediaUrl; preview?: boolean
|
||||
}) {
|
||||
const now = useSchedule(board.widgets)
|
||||
const indexed = useMemo(() => new Map(assets.map(asset => [asset.id, asset])), [assets])
|
||||
const widgets = board.widgets.filter(item => (!item.from || Date.parse(item.from) <= now) && (!item.until || Date.parse(item.until) > now))
|
||||
const columns = board.layout === 'grid' ? Math.min(2, widgets.length) : Math.min(widgets.length, 2)
|
||||
const style = {
|
||||
'--widget-columns': Math.max(columns, 1),
|
||||
'--widget-rows': board.layout === 'grid' ? Math.max(1, Math.ceil(widgets.length / 2)) : board.layout === 'focus' && widgets.length > 2 ? 2 : 1,
|
||||
} as CSSProperties
|
||||
return <div className={`player theme-${board.theme}${preview ? ' player-preview' : ''}`}>
|
||||
{board.showHeader && <header>
|
||||
<div className="player-brand"><div className="player-symbol"><MonitorPlay /></div><div><strong>{board.name || 'Neuer Bildschirm'}</strong>{board.location && <small>{board.location}</small>}</div></div>
|
||||
{board.showClock && <Clock zone={board.timeZone} date />}
|
||||
</header>}
|
||||
<main className={`player-grid layout-${board.layout}`} style={style}>
|
||||
{widgets.length ? widgets.map(item => <WidgetView key={item.id} item={item} assets={indexed} url={url} zone={board.timeZone} />)
|
||||
: <div className="player-empty"><Monitor /><span>Derzeit sind keine Inhalte geplant.</span></div>}
|
||||
</main>
|
||||
</div>
|
||||
}
|
||||
59
src/styles.css
Normal file
59
src/styles.css
Normal file
@ -0,0 +1,59 @@
|
||||
@import "tailwindcss";
|
||||
@import "@fontsource-variable/inter/index.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--font-sans: "Inter Variable", Inter, system-ui, -apple-system, sans-serif;
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--background: #10131a;
|
||||
--foreground: #f0f3f8;
|
||||
--card: #171c25;
|
||||
--card-foreground: #f0f3f8;
|
||||
--primary: #75e1d1;
|
||||
--primary-foreground: #102923;
|
||||
--secondary: #262d3a;
|
||||
--secondary-foreground: #e0eaf0;
|
||||
--muted: #202632;
|
||||
--muted-foreground: #9ca9bd;
|
||||
--accent: #222b39;
|
||||
--accent-foreground: #f1f7fa;
|
||||
--destructive: #bf465e;
|
||||
--border: #2a3241;
|
||||
--input: #323d50;
|
||||
--ring: #75e1d1;
|
||||
--radius: .65rem;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* { @apply border-border; }
|
||||
body { @apply bg-background font-sans text-foreground antialiased; margin: 0; }
|
||||
button:not(:disabled), select, summary { cursor: pointer; }
|
||||
button:focus-visible, a:focus-visible, select:focus-visible, summary:focus-visible { outline: 2px solid var(--ring); outline-offset: 3px; }
|
||||
}
|
||||
|
||||
.center-state { min-height: 100dvh; display: grid; place-content: center; justify-items: center; gap: 14px; text-align: center; padding: 24px; color: var(--muted-foreground); }
|
||||
.display-state { align-items: center; padding: 32px; }
|
||||
1
src/vite-env.d.ts
vendored
Normal file
1
src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
15
tsconfig.json
Normal file
15
tsconfig.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
11
vite.config.ts
Normal file
11
vite.config.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
import tailwind from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwind()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
|
||||
server: { proxy: { '/api': 'http://127.0.0.1:8080' } },
|
||||
build: { target: 'chrome111' },
|
||||
})
|
||||
Loading…
Reference in New Issue
Block a user