Seiten: Bausteine und Vorlagen (0.22.0)
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 5m0s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 5m0s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m50s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m33s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 6m11s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 6m46s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m24s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 5m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m17s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 07:48:02 +00:00
parent 8817727283
commit 2166a7e11a
129 changed files with 1381 additions and 267 deletions

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Wiederverwendbare Blöcke („Bausteine“, überall gleich) und Seitenvorlagen (Kopie beim Anlegen).
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('content_snippets', function (Blueprint $table) {
$table->id();
$table->string('kind', 10); // block | template
$table->string('name', 120);
$table->string('description', 300)->nullable();
$table->json('content');
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->index(['kind', 'name']);
});
}
public function down(): void
{
Schema::dropIfExists('content_snippets');
}
};

View file

@ -0,0 +1,32 @@
<script setup>
import { computed, inject, provide } from 'vue';
import { Component, PencilLine, TriangleAlert } from '@lucide/vue';
import BlockList from '@/pagebuilder/BlockList.vue';
/**
* Baustein: zeigt den gemeinsamen Inhalt. Im Editor nur als Vorschau mit Rahmen –
* bearbeitet wird der Baustein an einer Stelle (Redaktion → Bausteine & Vorlagen).
*/
const props = defineProps({ block: { type: Object, required: true } });
const editing = inject('pagebuilder:editing', computed(() => false));
// Inhalt des Bausteins ist hier nicht bearbeitbar – auch nicht in verschachtelten Blöcken
provide('pagebuilder:list', BlockList);
provide('pagebuilder:editing', computed(() => false));
const content = computed(() => ({ blocks: props.block.props?.blocks ?? [] }));
</script>
<template>
<div v-if="editing" class="rounded-md border border-dashed border-brand-300 p-3">
<div class="mb-3 flex flex-wrap items-center gap-2 text-xs">
<span class="inline-flex items-center gap-1.5 rounded bg-brand-soft px-2 py-0.5 font-medium text-brand-soft-foreground"><Component class="size-3.5" /> Baustein{{ block.props?.name ? `: ${block.props.name}` : '' }}</span>
<a v-if="block.props?.edit_url" :href="block.props.edit_url" target="_blank" class="inline-flex items-center gap-1 text-brand-text hover:underline" @click.stop><PencilLine class="size-3" /> Baustein bearbeiten</a>
</div>
<p v-if="!block.data.snippet" class="text-sm text-muted-foreground">Bitte rechts einen Baustein auswählen.</p>
<p v-else-if="block.props?.missing" class="flex items-center gap-2 text-sm text-amber-700 dark:text-amber-400"><TriangleAlert class="size-4" /> Dieser Baustein wurde gelöscht und wird nicht angezeigt.</p>
<div v-else class="pointer-events-none"><BlockList :item="content" /></div>
</div>
<BlockList v-else-if="content.blocks.length" :item="content" />
</template>

View file

@ -4,6 +4,8 @@ import { useForm } from '@inertiajs/vue3';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import NativeSelect from '@/components/NativeSelect.vue';
import { http } from '@/lib/http';
const props = defineProps({
parentId: { type: Number, default: null },
@ -12,9 +14,21 @@ const props = defineProps({
const open = defineModel('open', { type: Boolean, default: false });
const emit = defineEmits(['before-create']);
const form = useForm({ title: '', parent_id: null });
const form = useForm({ title: '', parent_id: null, template_id: null });
const templates = ref([]);
watch(open, (value) => value && (form.reset(), form.clearErrors()));
watch(open, async (value) => {
if (!value) return;
form.reset();
form.clearErrors();
try {
templates.value = (await http.get('/redaktion/bausteine?kind=template')).snippets;
} catch {
templates.value = [];
}
});
async function create() {
emit('before-create');
@ -37,6 +51,10 @@ async function create() {
<Input v-model="form.title" maxlength="200" autofocus :aria-invalid="!!form.errors.title" />
<span v-if="form.errors.title" class="text-[13px] text-destructive">{{ form.errors.title }}</span>
</label>
<label v-if="templates.length" class="grid gap-1.5">
<span class="text-[13px] font-medium">Vorlage</span>
<NativeSelect v-model="form.template_id" :options="[{ value: null, label: 'Leere Seite' }, ...templates.map((t) => ({ value: t.id, label: t.description ? `${t.name} – ${t.description}` : t.name }))]" />
</label>
<DialogFooter>
<Button type="button" variant="outline" @click="open = false">Abbrechen</Button>
<Button type="submit" :disabled="form.processing || !form.title.trim()">Anlegen und bearbeiten</Button>

View file

@ -0,0 +1,75 @@
<script setup>
import { ref, watch } from 'vue';
import { LoaderCircle } from '@lucide/vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { http } from '@/lib/http';
/**
* Block als Baustein bzw. Seite als Vorlage speichern.
*/
const props = defineProps({
kind: { type: String, default: 'block' },
content: { type: Object, default: null },
suggestion: { type: String, default: '' },
});
const open = defineModel('open', { type: Boolean, default: false });
const emit = defineEmits(['saved']);
const name = ref('');
const description = ref('');
const saving = ref(false);
const error = ref('');
watch(open, (value) => {
if (!value) return;
name.value = props.suggestion;
description.value = '';
error.value = '';
});
async function save() {
saving.value = true;
error.value = '';
try {
const data = await http.post('/redaktion/bausteine', { kind: props.kind, name: name.value, description: description.value || null, content: props.content });
emit('saved', data.snippet);
open.value = false;
} catch (e) {
error.value = e.data?.errors?.name?.[0] ?? e.message;
} finally {
saving.value = false;
}
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ kind === 'block' ? 'Als Baustein speichern' : 'Als Vorlage speichern' }}</DialogTitle>
<DialogDescription v-if="kind === 'block'">Der Block wird zum Baustein und lässt sich auf anderen Seiten einsetzen. Änderungen am Baustein wirken dann überall.</DialogDescription>
<DialogDescription v-else>Der Inhalt dieser Seite steht beim Anlegen neuer Seiten als Vorlage zur Wahl.</DialogDescription>
</DialogHeader>
<form class="grid gap-3" @submit.prevent="save">
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Name</span>
<Input v-model="name" maxlength="120" autofocus :aria-invalid="!!error" />
</label>
<label class="grid gap-1.5">
<span class="text-[13px] font-medium">Beschreibung (optional)</span>
<Input v-model="description" maxlength="300" />
</label>
<p v-if="error" class="text-[13px] text-destructive">{{ error }}</p>
<DialogFooter>
<Button type="button" variant="outline" @click="open = false">Abbrechen</Button>
<Button type="submit" :disabled="saving || !name.trim()"><LoaderCircle v-if="saving" class="animate-spin" /> Speichern</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>

View file

@ -0,0 +1,94 @@
<script setup>
import { computed, ref } from 'vue';
import { Link, router } from '@inertiajs/vue3';
import { Component, FileStack, Plus, Trash2 } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import Panel from '@/components/Panel.vue';
import { http } from '@/lib/http';
import { formatRelative } from '@/lib/format';
/**
* „Redaktion → Bausteine & Vorlagen“.
*/
const props = defineProps({
snippets: { type: Array, required: true },
});
const tab = ref('block');
const list = computed(() => props.snippets.filter((s) => s.kind === tab.value));
const creating = ref(false);
const name = ref('');
const saving = ref(false);
async function create() {
saving.value = true;
try {
const data = await http.post('/redaktion/bausteine', { kind: tab.value, name: name.value, content: { blocks: [] } });
router.visit(data.edit_url);
} catch (error) {
toast.error(error.data?.errors?.name?.[0] ?? error.message);
saving.value = false;
}
}
function remove(snippet) {
const warning = snippet.usages.length ? `\n\nAchtung: Der Baustein ist auf ${snippet.usages.length} Seite(n) eingebunden und verschwindet dort.` : '';
if (window.confirm(`„${snippet.name}“ löschen?${warning}`)) {
router.delete(`/redaktion/bausteine/${snippet.id}`, { preserveScroll: true, onSuccess: () => toast.success('Gelöscht') });
}
}
</script>
<template>
<Panel title="Bausteine & Vorlagen">
<template #actions>
<Button size="sm" variant="outline" @click="(name = ''), (creating = true)"><Plus /> {{ tab === 'block' ? 'Neuer Baustein' : 'Neue Vorlage' }}</Button>
</template>
<div class="-mt-1 mb-3 inline-flex rounded-md border p-0.5 text-[13px]" role="tablist">
<button type="button" role="tab" :aria-selected="tab === 'block'" class="inline-flex items-center gap-1.5 rounded-sm px-3 py-1" :class="tab === 'block' ? 'bg-muted font-medium' : 'text-muted-foreground'" @click="tab = 'block'"><Component class="size-3.5" /> Bausteine</button>
<button type="button" role="tab" :aria-selected="tab === 'template'" class="inline-flex items-center gap-1.5 rounded-sm px-3 py-1" :class="tab === 'template' ? 'bg-muted font-medium' : 'text-muted-foreground'" @click="tab = 'template'"><FileStack class="size-3.5" /> Seitenvorlagen</button>
</div>
<p class="mb-3 text-[13px] text-muted-foreground">
<template v-if="tab === 'block'">Bausteine erscheinen auf vielen Seiten gleich, z. B. ein Kontaktkasten oder Öffnungszeiten. Eine Änderung wirkt überall.</template>
<template v-else>Vorlagen sind Ausgangspunkt für neue Seiten – beim Anlegen wird der Inhalt kopiert.</template>
</p>
<ul v-if="list.length" class="-mx-5 divide-y border-t">
<li v-for="snippet in list" :key="snippet.id" class="flex items-center gap-3 px-5 py-2.5">
<div class="min-w-0 flex-1">
<Link :href="snippet.edit_url" class="block truncate text-sm font-medium hover:underline">{{ snippet.name }}</Link>
<p class="truncate text-xs text-muted-foreground">
<template v-if="snippet.description">{{ snippet.description }} · </template>
{{ snippet.blocks }} {{ snippet.blocks === 1 ? 'Block' : 'Blöcke' }}
<template v-if="snippet.kind === 'block'"> · {{ snippet.usages.length ? `auf ${snippet.usages.length} ${snippet.usages.length === 1 ? 'Seite' : 'Seiten'}` : 'noch nicht eingebunden' }}</template>
<template v-if="snippet.updated_at"> · {{ formatRelative(snippet.updated_at) }}{{ snippet.editor ? ` von ${snippet.editor}` : '' }}</template>
</p>
</div>
<Button size="icon" variant="ghost" class="size-8 text-muted-foreground hover:text-destructive" :aria-label="`${snippet.name} löschen`" @click="remove(snippet)"><Trash2 /></Button>
</li>
</ul>
<p v-else class="text-sm text-muted-foreground">{{ tab === 'block' ? 'Noch keine Bausteine. Tipp: Im Seiteneditor lässt sich jeder Block „Als Baustein speichern“.' : 'Noch keine Vorlagen. Tipp: Im Seiteneditor unter ⋮ „Als Vorlage speichern“.' }}</p>
<Dialog v-model:open="creating">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ tab === 'block' ? 'Neuer Baustein' : 'Neue Seitenvorlage' }}</DialogTitle>
<DialogDescription>Danach öffnet sich der Editor.</DialogDescription>
</DialogHeader>
<form class="grid gap-4" @submit.prevent="create">
<Input v-model="name" maxlength="120" autofocus placeholder="Name, z. B. „Kontakt Personalabteilung“" aria-label="Name" />
<DialogFooter>
<Button type="button" variant="outline" @click="creating = false">Abbrechen</Button>
<Button type="submit" :disabled="saving || !name.trim()">Anlegen</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</Panel>
</template>

View file

@ -9,6 +9,7 @@ import {
EllipsisVertical,
Eye,
FilePlus2,
FileStack,
History,
LoaderCircle,
Lock,
@ -46,6 +47,7 @@ import RevisionsDialog from '../components/RevisionsDialog.vue';
import PageSettingsDialog from '../components/PageSettingsDialog.vue';
import ReviewDialog from '../components/ReviewDialog.vue';
import NewPageDialog from '../components/NewPageDialog.vue';
import SaveSnippetDialog from '../components/SaveSnippetDialog.vue';
const props = defineProps({
page: { type: Object, required: true },
@ -180,7 +182,54 @@ provide('pagebuilder:editor', {
// Bildauswahl „Aus der Mediathek“: ({ multiple?, title? }) => Promise<[{ id, path, url, alt, caption, width, height }] | null>
pickMedia: (options) => mediaPicker.pick(options),
imageUrl: (path) => `${props.uploadsUrl}/${path}`,
// „Als Baustein speichern“ in der Werkzeugleiste eines Blocks (nur wer Bausteine pflegen darf)
saveAsSnippet: props.page.can?.snippets ? (id) => openSnippetDialog('block', id) : null,
});
// ——— Bausteine und Vorlagen ———
const snippetDialog = reactive({ open: false, kind: 'block', blockId: null, content: null, suggestion: '' });
function openSnippetDialog(kind, blockId = null) {
const block = blockId ? locate(working.content.blocks, blockId)?.block : null;
Object.assign(snippetDialog, {
open: true,
kind,
blockId,
content: block ? { blocks: [clone(block)] } : clone(working.content),
suggestion: block ? snippetName(block) : working.title,
});
}
// Vorschlag: Überschrift bzw. Anfang des Textes, sonst die Blockart
function snippetName(block) {
const text = [block.data?.title, block.data?.text, block.data?.html, block.data?.content]
.find((value) => typeof value === 'string' && value.replace(/<[^>]+>/g, '').trim());
const plain = text?.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() ?? '';
return plain ? (plain.length > 60 ? `${plain.slice(0, 57)} …` : plain) : types[block.type]?.label ?? '';
}
function snippetSaved(snippet) {
if (snippetDialog.kind === 'template') {
toast.success(`Vorlage „${snippet.name}“ gespeichert`);
return;
}
// Block durch den neuen Baustein ersetzen
const type = types['pages.snippet'];
const found = locate(working.content.blocks, snippetDialog.blockId);
if (!type || !found) return;
type.fields[0].choices = [...(type.fields[0].choices ?? []), { value: String(snippet.id), label: snippet.name }];
const block = createBlock(type);
block.data.snippet = String(snippet.id);
found.list.splice(found.index, 1, block);
select(block.id);
toast.success(`Baustein „${snippet.name}“ angelegt – er lässt sich jetzt auf anderen Seiten einsetzen`);
}
provide('pagebuilder:list', EditorBlockList);
provide('pagebuilder:types', types);
provide('pagebuilder:editing', computed(() => !readOnly.value));
@ -538,6 +587,7 @@ const canvasWidth = computed(() => devices.find((d) => d.key === device.value).w
<DropdownMenuItem @select="dialogs.revisions = true"><History /> Versionen</DropdownMenuItem>
<DropdownMenuItem v-if="page.can.configure" @select="dialogs.settings = true"><Settings2 /> Seiteneinstellungen</DropdownMenuItem>
<DropdownMenuItem v-if="page.can.create_child" @select="dialogs.newPage = true"><FilePlus2 /> Unterseite anlegen</DropdownMenuItem>
<DropdownMenuItem v-if="page.can.snippets" @select="openSnippetDialog('template')"><FileStack /> Als Vorlage speichern</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
v-if="page.has_draft && page.is_published && !readOnly"
@ -643,4 +693,5 @@ const canvasWidth = computed(() => devices.find((d) => d.key === device.value).w
<MediaPickerHost :picker="mediaPicker" />
<Toaster position="bottom-left" />
<SaveSnippetDialog v-model:open="snippetDialog.open" :kind="snippetDialog.kind" :content="snippetDialog.content" :suggestion="snippetDialog.suggestion" @saved="snippetSaved" />
</template>

View file

@ -0,0 +1,280 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, provide, reactive, ref, watch } from 'vue';
import { Head, Link } from '@inertiajs/vue3';
import { ArrowLeft, Component, FileStack, LoaderCircle, Plus, Save } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import { Toaster } from '@/components/ui/sonner';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import BlockPalette from '@/pagebuilder/editor/BlockPalette.vue';
import BlockSettings from '@/pagebuilder/editor/BlockSettings.vue';
import EditorBlockList from '@/pagebuilder/editor/EditorBlockList.vue';
import { clone, createBlock, duplicate as duplicateBlock, locate, walk } from '@/pagebuilder/editor/tree';
import { http } from '@/lib/http';
import { formatRelative } from '@/lib/format';
import MediaPickerHost from '@/components/media/MediaPickerHost.vue';
import { collectImagePaths, uploadWithProgress } from '@/components/media/api';
import { useMediaPicker } from '@/components/media/useMediaPicker';
/**
* Baustein bzw. Seitenvorlage bearbeiten – derselbe Pagebuilder wie bei Seiten,
* gespeichert wird ausdrücklich (Bausteine wirken sofort auf allen Seiten).
*/
const props = defineProps({
snippet: { type: Object, required: true },
kinds: { type: Object, required: true },
usages: { type: Array, default: () => [] },
blockTypes: { type: Array, required: true },
blockGroups: { type: Object, required: true },
audienceOptions: { type: Object, required: true },
uploadsUrl: { type: String, required: true },
});
const base = '/redaktion/bausteine';
const types = Object.fromEntries(props.blockTypes.map((type) => [type.key, type]));
const isBlock = props.snippet.kind === 'block';
const working = reactive({ name: props.snippet.name, description: props.snippet.description ?? '', content: clone(props.snippet.content) });
const selectedId = ref(null);
const hoveredId = ref(null);
const previews = reactive({});
const sidebarTab = ref('blocks');
const sheetOpen = ref(false);
const updatedAt = ref(props.snippet.updated_at);
const selected = computed(() => (selectedId.value ? locate(working.content.blocks, selectedId.value)?.block ?? null : null));
watch(selectedId, (id) => (sidebarTab.value = id ? 'block' : 'blocks'));
const select = (id) => (selectedId.value = id ?? null);
function insert(list, index, type) {
const block = createBlock(type);
list.splice(index, 0, block);
select(block.id);
}
function insertFromPalette(type) {
const found = selected.value ? locate(working.content.blocks, selected.value.id) : null;
found ? insert(found.list, found.index + 1, type) : insert(working.content.blocks, working.content.blocks.length, type);
sheetOpen.value = false;
}
function remove(id) {
const found = locate(working.content.blocks, id);
if (!found) return;
found.list.splice(found.index, 1);
if (selectedId.value === id) select(null);
}
function move(id, direction) {
const found = locate(working.content.blocks, id);
const target = found ? found.index + direction : -1;
if (found && target >= 0 && target < found.list.length) {
found.list.splice(target, 0, found.list.splice(found.index, 1)[0]);
}
}
function duplicate(id) {
const found = locate(working.content.blocks, id);
if (!found) return;
const copy = duplicateBlock(found.block);
found.list.splice(found.index + 1, 0, copy);
select(copy.id);
}
function containsActive(item) {
const candidates = [selected.value, hoveredId.value ? locate(working.content.blocks, hoveredId.value)?.block : null].filter(Boolean);
return candidates.some((block) => block.items?.includes(item) || locate(item.blocks, block.id));
}
const uploadImage = (file, onProgress) => uploadWithProgress(`${base}/bilder`, file, { onProgress });
const mediaPicker = useMediaPicker({ upload: uploadImage, contextLabel: isBlock ? 'In diesem Baustein' : 'In dieser Vorlage', contextPaths: () => collectImagePaths(working.content) });
provide('pagebuilder:editor', {
types,
groups: props.blockGroups,
selectedId,
hoveredId,
previews,
readOnly: ref(false),
files: ref([]),
peopleCache: reactive({}),
audienceOptions: props.audienceOptions,
select,
insert,
remove,
move,
duplicate,
containsActive,
uploadImage,
uploadFile: () => Promise.reject(new Error('Dateien zum Herunterladen gehören zu einer Seite – bitte dort hochladen.')),
pickMedia: (options) => mediaPicker.pick(options),
imageUrl: (path) => `${props.uploadsUrl}/${path}`,
saveAsSnippet: null,
});
provide('pagebuilder:list', EditorBlockList);
provide('pagebuilder:types', types);
provide('pagebuilder:editing', computed(() => true));
// Vorschau dynamischer Blöcke
const previewHashes = {};
let previewTimer;
function refreshPreviews() {
const changed = [];
walk(working.content.blocks, (block) => {
if (!types[block.type]?.dynamic) return;
const hash = JSON.stringify(block.data);
if (previewHashes[block.id] !== hash) {
previewHashes[block.id] = hash;
changed.push({ id: block.id, type: block.type, data: block.data });
}
});
if (changed.length) {
http.post(`${base}/vorschau`, { blocks: changed.slice(0, 100) }).then((data) => Object.assign(previews, data.props)).catch(() => {});
}
}
// Speichern
const saving = ref(false);
let lastSaved = JSON.stringify(working);
const dirty = ref(false);
watch(working, () => {
dirty.value = JSON.stringify(working) !== lastSaved;
clearTimeout(previewTimer);
previewTimer = setTimeout(refreshPreviews, 500);
}, { deep: true });
async function save() {
if (saving.value) return;
saving.value = true;
try {
const data = await http.put(`${base}/${props.snippet.id}`, { name: working.name, description: working.description || null, content: working.content });
lastSaved = JSON.stringify(working);
dirty.value = false;
updatedAt.value = data.updated_at;
toast.success(isBlock && props.usages.length ? `Gespeichert – gilt jetzt auf ${props.usages.length} ${props.usages.length === 1 ? 'Seite' : 'Seiten'}` : 'Gespeichert');
} catch (error) {
toast.error(error.data?.errors?.name?.[0] ?? error.message ?? 'Speichern fehlgeschlagen');
} finally {
saving.value = false;
}
}
function onKey(event) {
if ((event.ctrlKey || event.metaKey) && event.key === 's') {
event.preventDefault();
save();
}
}
const warnUnsaved = (event) => dirty.value && event.preventDefault();
onMounted(() => {
refreshPreviews();
window.addEventListener('keydown', onKey);
window.addEventListener('beforeunload', warnUnsaved);
});
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKey);
window.removeEventListener('beforeunload', warnUnsaved);
});
</script>
<template>
<Head :title="`${kinds[snippet.kind]}: ${working.name}`" />
<div class="flex h-dvh flex-col bg-background">
<header class="flex shrink-0 items-center gap-3 border-b bg-card px-3 py-2 sm:px-4">
<Link href="/redaktion" class="grid size-9 place-items-center rounded-md text-muted-foreground hover:bg-accent" aria-label="Zurück zur Redaktion"><ArrowLeft class="size-5" /></Link>
<span class="inline-flex shrink-0 items-center gap-1.5 rounded bg-brand-soft px-2 py-0.5 text-xs font-medium text-brand-soft-foreground">
<Component v-if="isBlock" class="size-3.5" /><FileStack v-else class="size-3.5" /> {{ kinds[snippet.kind] }}
</span>
<p class="hidden min-w-0 flex-1 truncate text-xs text-muted-foreground sm:block">
<template v-if="isBlock">{{ usages.length ? `Eingebunden auf: ${usages.map((u) => u.title).join(', ')}` : 'Noch auf keiner Seite eingebunden' }}</template>
<template v-else>Neue Seiten können mit diesem Inhalt starten.</template>
<template v-if="updatedAt"> · gespeichert {{ formatRelative(updatedAt) }}</template>
</p>
<span class="flex-1 sm:hidden" />
<Button variant="outline" size="icon" class="lg:hidden" aria-label="Block hinzufügen" @click="sheetOpen = true"><Plus /></Button>
<Button :disabled="saving || !working.name.trim()" @click="save">
<LoaderCircle v-if="saving" class="animate-spin" /><Save v-else /> Speichern<span v-if="dirty" class="size-1.5 rounded-full bg-current" aria-label="ungespeicherte Änderungen" />
</Button>
</header>
<div class="flex min-h-0 flex-1">
<main class="min-w-0 flex-1 overflow-y-auto" @click="select(null)">
<div class="mx-auto max-w-[1100px] px-4 py-8 sm:px-8">
<input
v-model="working.name"
class="w-full bg-transparent text-3xl font-semibold tracking-tight outline-none placeholder:text-muted-foreground/60"
:placeholder="isBlock ? 'Name des Bausteins' : 'Name der Vorlage'"
maxlength="120"
aria-label="Name"
@click.stop
/>
<input
v-model="working.description"
class="mt-1 mb-6 w-full bg-transparent text-sm text-muted-foreground outline-none placeholder:text-muted-foreground/60"
placeholder="Kurze Beschreibung (optional) – erscheint bei der Auswahl"
maxlength="300"
aria-label="Beschreibung"
@click.stop
/>
<div class="@container">
<EditorBlockList :item="working.content" root />
</div>
</div>
</main>
<aside class="hidden w-[340px] shrink-0 flex-col border-l bg-card lg:flex">
<div class="flex shrink-0 border-b px-2" role="tablist">
<button
v-for="tab in [{ key: 'blocks', label: 'Blöcke' }, { key: 'block', label: 'Ausgewählter Block' }]"
:key="tab.key"
type="button"
role="tab"
class="relative px-3 py-3 text-sm font-medium disabled:opacity-40"
:class="sidebarTab === tab.key ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'"
:aria-selected="sidebarTab === tab.key"
:disabled="tab.key === 'block' && !selected"
@click="sidebarTab = tab.key"
>
{{ tab.label }}
<span v-if="sidebarTab === tab.key" class="absolute inset-x-2 bottom-0 h-[3px] rounded-t-full bg-brand" />
</button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<BlockSettings v-if="sidebarTab === 'block' && selected" :key="selected.id" :block="selected" />
<BlockPalette v-else @pick="insertFromPalette" />
</div>
</aside>
</div>
<Sheet v-model:open="sheetOpen">
<SheetContent side="right" class="w-[340px] overflow-y-auto p-4">
<SheetHeader class="p-0"><SheetTitle>{{ selected ? 'Block bearbeiten' : 'Block hinzufügen' }}</SheetTitle></SheetHeader>
<BlockSettings v-if="selected" :key="selected.id" :block="selected" />
<BlockPalette v-else @pick="insertFromPalette" />
</SheetContent>
</Sheet>
</div>
<MediaPickerHost :picker="mediaPicker" />
<Toaster position="bottom-left" />
</template>

View file

@ -3,12 +3,24 @@
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Pages\Http\Controllers\PageController;
use Inhaus\Plugins\Pages\Http\Controllers\PageEditorController;
use Inhaus\Plugins\Pages\Http\Controllers\SnippetController;
Route::middleware('auth')->group(function () {
Route::get('/seiten', [PageController::class, 'index'])->name('pages.index');
Route::get('/seiten/{path}', [PageController::class, 'show'])->where('path', '[a-z0-9][a-z0-9\-/]*')->name('pages.show');
Route::get('/dateien/seiten/{file}/{name}', [PageController::class, 'file'])->name('pages.file');
// Bausteine und Vorlagen
Route::prefix('redaktion/bausteine')->name('snippets.')->controller(SnippetController::class)->group(function () {
Route::get('/', 'index')->name('index');
Route::post('/', 'store')->name('store');
Route::post('/bilder', 'uploadImage')->name('images');
Route::post('/vorschau', 'preview')->name('preview');
Route::get('/{snippet}', 'edit')->name('edit');
Route::put('/{snippet}', 'update')->name('update');
Route::delete('/{snippet}', 'destroy')->name('destroy');
});
Route::prefix('redaktion/seiten')->name('pages.')->controller(PageEditorController::class)->group(function () {
Route::post('/', 'store')->name('store');
Route::get('/{page}', 'edit')->name('editor');

View file

@ -23,6 +23,7 @@ use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Pages\Models\ContentSnippet;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\Models\PageFile;
use Inhaus\Plugins\Pages\Models\PageRevision;
@ -46,6 +47,7 @@ class PageEditorController extends Controller
$data = $request->validate([
'title' => ['required', 'string', 'max:200'],
'parent_id' => ['nullable', 'integer', Rule::exists('pages', 'id')],
'template_id' => ['nullable', 'integer', Rule::exists('content_snippets', 'id')->where('kind', ContentSnippet::TEMPLATE)],
]);
$parent = isset($data['parent_id']) ? Page::query()->findOrFail($data['parent_id']) : null;
@ -58,7 +60,13 @@ class PageEditorController extends Controller
'created_by' => $request->user()->id,
]);
Audit::log('page.created', ['page' => $page->id, 'title' => $page->title]);
// Vorlage: Inhalt als erster Entwurf (Kopie – spätere Änderungen an der Vorlage wirken nicht zurück)
if (isset($data['template_id'])) {
$template = ContentSnippet::query()->findOrFail($data['template_id']);
$page->forceFill(['draft' => $this->content->sanitize($template->content), 'draft_title' => $page->title, 'draft_updated_at' => now()])->save();
}
Audit::log('page.created', ['page' => $page->id, 'title' => $page->title, 'template' => $data['template_id'] ?? null]);
return to_route('pages.editor', $page);
}
@ -358,7 +366,7 @@ class PageEditorController extends Controller
foreach ($request->input('blocks') as $block) {
if (is_string($block['id'] ?? null)) {
$props[$block['id']] = $this->content->preview($block, $request->user(), ['page_id' => $page->id]);
$props[$block['id']] = $this->content->preview($block, $request->user(), ['page_id' => $page->id, 'editing' => true]);
}
}
@ -413,6 +421,7 @@ class PageEditorController extends Controller
'delete' => $user->can('delete', $page),
'create_child' => $user->can('create', [Page::class, $page]),
'navigation' => $page->parent_id === null && $user->can('pages.manage'),
'snippets' => $user->can('pages.manage'),
],
];
}
@ -422,7 +431,7 @@ class PageEditorController extends Controller
*
* @return array{role: list<array{value: string, label: string}>, department: list<string>, location: list<string>}
*/
private function audienceOptions(): array
public static function audienceOptions(): array
{
return Cache::remember('pagebuilder.audience-options', 300, fn () => [
'role' => Role::query()->orderBy('name')->get(['id', 'name'])->map(fn (Role $role) => ['value' => (string) $role->id, 'label' => $role->name])->all(),

View file

@ -0,0 +1,139 @@
<?php
namespace Inhaus\Plugins\Pages\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Media\MediaLibrary;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\Content;
use App\Support\Audit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Pages\Models\ContentSnippet;
use Inhaus\Plugins\Pages\Snippets;
/**
* Bausteine und Vorlagen („Redaktion → Bausteine & Vorlagen“). Pflegen darf, wer
* alle Seiten verwalten darf; Bausteine einsetzen darf jede Redaktion.
*/
class SnippetController extends Controller
{
public function __construct(private readonly Content $content) {}
/**
* Auswahl für Editor und „Neue Seite“.
*/
public function index(Request $request): JsonResponse
{
$request->validate(['kind' => ['nullable', Rule::in(array_keys(ContentSnippet::KINDS))]]);
return response()->json(['snippets' => ContentSnippet::query()
->when($request->query('kind'), fn ($q, $kind) => $q->where('kind', $kind))
->orderBy('name')
->get(['id', 'kind', 'name', 'description'])]);
}
public function store(Request $request): JsonResponse
{
$this->authorizeManage($request);
$data = $request->validate([
'kind' => ['required', Rule::in(array_keys(ContentSnippet::KINDS))],
'name' => ['required', 'string', 'max:120'],
'description' => ['nullable', 'string', 'max:300'],
'content' => ['present', 'array'],
], [], ['name' => 'Name']);
$snippet = ContentSnippet::query()->create([
...$data,
'content' => $this->content->sanitize($data['content']),
'created_by' => $request->user()->id,
'updated_by' => $request->user()->id,
]);
Audit::log('snippet.created', ['snippet' => $snippet->id, 'kind' => $snippet->kind, 'name' => $snippet->name]);
return response()->json(['snippet' => $snippet->only(['id', 'kind', 'name', 'description']), 'edit_url' => route('snippets.edit', $snippet)], 201);
}
public function edit(Request $request, ContentSnippet $snippet, Blocks $blocks, Snippets $snippets): Response
{
$this->authorizeManage($request);
return Inertia::render('pages::SnippetEditor', [
'snippet' => [
...$snippet->only(['id', 'kind', 'name', 'description']),
'content' => $snippet->content ?: Content::empty(),
'updated_at' => $snippet->updated_at?->toIso8601String(),
'editor' => $snippet->editor?->name,
],
'kinds' => ContentSnippet::KINDS,
'usages' => $snippet->kind === ContentSnippet::BLOCK ? ($snippets->usages()[$snippet->id] ?? []) : [],
// Ein Baustein darf sich nicht selbst enthalten
'blockTypes' => array_values(array_filter($blocks->forEditor(), fn (array $type) => $snippet->kind === ContentSnippet::TEMPLATE || $type['key'] !== Snippets::BLOCK_TYPE)),
'blockGroups' => Blocks::GROUPS,
'audienceOptions' => PageEditorController::audienceOptions(),
'uploadsUrl' => rtrim(Storage::disk('uploads')->url(''), '/'),
]);
}
public function update(Request $request, ContentSnippet $snippet): JsonResponse
{
$this->authorizeManage($request);
$data = $request->validate([
'name' => ['required', 'string', 'max:120'],
'description' => ['nullable', 'string', 'max:300'],
'content' => ['present', 'array'],
], [], ['name' => 'Name']);
$snippet->update([...$data, 'content' => $this->content->sanitize($data['content']), 'updated_by' => $request->user()->id]);
Audit::log('snippet.updated', ['snippet' => $snippet->id, 'name' => $snippet->name]);
return response()->json(['snippet' => $snippet->only(['id', 'name', 'description']), 'updated_at' => $snippet->updated_at?->toIso8601String()]);
}
public function destroy(Request $request, ContentSnippet $snippet): RedirectResponse
{
$this->authorizeManage($request);
$snippet->delete();
Audit::log('snippet.deleted', ['snippet' => $snippet->id, 'name' => $snippet->name]);
return back()->with('status', ContentSnippet::KINDS[$snippet->kind].' „'.$snippet->name.'“ gelöscht.');
}
public function uploadImage(Request $request, MediaLibrary $library): JsonResponse
{
$this->authorizeManage($request);
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
$media = $library->store($request->file('image'), 'pagebuilder/snippets', $request->user());
return response()->json(['path' => $media->path, 'url' => Blocks::imageUrl($media->path), 'media' => $media->toLibraryArray()]);
}
public function preview(Request $request): JsonResponse
{
$this->authorizeManage($request);
$request->validate(['blocks' => ['required', 'array', 'max:100'], 'blocks.*' => ['array']]);
$props = [];
foreach ($request->input('blocks') as $block) {
if (is_string($block['id'] ?? null)) {
$props[$block['id']] = $this->content->preview($block, $request->user(), ['editing' => true]);
}
}
return response()->json(['props' => (object) $props]);
}
private function authorizeManage(Request $request): void
{
abort_unless($request->user()->can('pages.manage'), 403);
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Inhaus\Plugins\Pages\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Baustein (kind = block): ein Inhalt, der auf vielen Seiten eingebunden wird –
* Änderungen wirken überall. Vorlage (kind = template): Ausgangsinhalt für neue Seiten.
*/
#[Fillable(['kind', 'name', 'description', 'content', 'created_by', 'updated_by'])]
class ContentSnippet extends Model
{
public const BLOCK = 'block';
public const TEMPLATE = 'template';
public const KINDS = [self::BLOCK => 'Baustein', self::TEMPLATE => 'Vorlage'];
protected function casts(): array
{
return ['content' => 'array'];
}
/**
* @return BelongsTo<User, $this>
*/
public function editor(): BelongsTo
{
return $this->belongsTo(User::class, 'updated_by');
}
}

View file

@ -16,6 +16,7 @@ use App\Support\Navigation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Pages\Models\ContentSnippet;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\Models\PageFile;
use Inhaus\Plugins\Pages\Policies\PagePolicy;
@ -89,6 +90,16 @@ class PagesPlugin extends Plugin
fn (User $user) => EditorialPages::props($user),
);
$this->app->make(Editorial::class)->add(
'pages.snippets',
'Bausteine & Vorlagen',
'pages::EditorialSnippets',
25,
fn (User $user) => $user->can('pages.manage'),
fn (User $user) => $this->snippetList(),
);
$this->app->singleton(Snippets::class);
$this->registerBlocks($this->app->make(Blocks::class));
$this->registerMediaUsages($this->app->make(MediaUsages::class));
}
@ -126,10 +137,51 @@ class PagesPlugin extends Plugin
}, fn (callable $each) => Page::query()->chunkById(50, fn ($pages) => $pages->each($each)));
$usages->watch('pages', Page::class, ['content', 'draft', 'scheduled_content', 'title', 'draft_title', 'scheduled_title']);
$usages->add('snippets', 'Bausteine & Vorlagen', function (ContentSnippet $snippet) {
$entries = [];
foreach (ImagePaths::fromContent($snippet->content) as $context => $paths) {
$entries[] = ['context' => $context, 'label' => ContentSnippet::KINDS[$snippet->kind].': '.$snippet->name, 'url' => route('snippets.edit', $snippet, false), 'draft' => false, 'paths' => $paths];
}
return $entries;
}, fn (callable $each) => ContentSnippet::query()->chunkById(50, fn ($snippets) => $snippets->each($each)));
$usages->watch('snippets', ContentSnippet::class, ['content', 'name']);
}
/**
* @return array<string, mixed>
*/
private function snippetList(): array
{
$usages = $this->app->make(Snippets::class)->usages();
return ['snippets' => ContentSnippet::query()->with('editor:id,name')->orderBy('kind')->orderBy('name')->get()->map(fn (ContentSnippet $snippet) => [
'id' => $snippet->id,
'kind' => $snippet->kind,
'name' => $snippet->name,
'description' => $snippet->description,
'blocks' => count($snippet->content['blocks'] ?? []),
'usages' => $usages[$snippet->id] ?? [],
'edit_url' => route('snippets.edit', $snippet),
'updated_at' => $snippet->updated_at?->toIso8601String(),
'editor' => $snippet->editor?->name,
])->all()];
}
private function registerBlocks(Blocks $blocks): void
{
// Baustein: gemeinsamer Inhalt, der auf vielen Seiten gleich erscheint
$blocks->add(BlockType::make(Snippets::BLOCK_TYPE, 'Baustein', 'component', 'layout', 'pages::Snippet')
->description('Wiederverwendbarer Inhalt – Änderungen am Baustein wirken auf allen Seiten.')
->fields([
Field::select('snippet', 'Baustein', fn () => ContentSnippet::query()->where('kind', ContentSnippet::BLOCK)->orderBy('name')->pluck('name', 'id')->all())
->help('Bausteine legen Sie unter Redaktion → Bausteine & Vorlagen an – oder direkt aus einem Block („Als Baustein speichern“).'),
])
->resolveUsing(fn (array $data, ?User $user, array $context) => $this->app->make(Snippets::class)->resolve($data, $user, $context)));
$blocks->add(BlockType::make('downloads', 'Downloads', 'file-down', 'media', 'pages::Downloads')
->description('Dateien zum Herunterladen – nur für Personen, die die Seite sehen dürfen.')
->fields([

View file

@ -0,0 +1,75 @@
<?php
namespace Inhaus\Plugins\Pages;
use App\Models\User;
use App\Pagebuilder\Content;
use Inhaus\Plugins\Pages\Models\ContentSnippet;
use Inhaus\Plugins\Pages\Models\Page;
/**
* Bausteine im Pagebuilder: Anzeige (mit Schutz vor Endlosschleifen) und Verwendungsnachweis.
*/
class Snippets
{
public const BLOCK_TYPE = 'pages.snippet';
/** @var list<int> gerade angezeigte Bausteine (verschachtelt) */
private array $stack = [];
/**
* Daten für den Block „Baustein“ – null blendet ihn aus.
*
* @param array<string, mixed> $data
* @return array<string, mixed>|null
*/
public function resolve(array $data, ?User $user, array $context): ?array
{
$id = (int) ($data['snippet'] ?? 0);
$snippet = $id ? ContentSnippet::query()->where('kind', ContentSnippet::BLOCK)->find($id) : null;
if (! $snippet || in_array($id, $this->stack, true) || count($this->stack) >= 3) {
// Im Editor einen Hinweis zeigen, auf der Seite nichts
return ($context['editing'] ?? false) ? ['missing' => true] : null;
}
$this->stack[] = $id;
try {
$blocks = app(Content::class)->render($snippet->content, $user, [...$context, 'snippet_id' => $id])['blocks'];
} finally {
array_pop($this->stack);
}
return [
'name' => $snippet->name,
'blocks' => $blocks,
'edit_url' => $user?->can('pages.manage') ? route('snippets.edit', $snippet) : null,
];
}
/**
* Seiten, die einen Baustein einbinden (veröffentlicht oder im Entwurf).
*
* @return array<int, list<array{id: int, title: string}>> Baustein => Seiten
*/
public function usages(): array
{
$content = app(Content::class);
$usages = [];
Page::query()->get(['id', 'title', 'content', 'draft'])->each(function (Page $page) use ($content, &$usages) {
$ids = [];
foreach ([$page->content, $page->draft] as $tree) {
array_push($ids, ...$content->collect($tree, fn (array $block) => ($block['type'] ?? null) === self::BLOCK_TYPE ? [(int) ($block['data']['snippet'] ?? 0)] : []));
}
foreach (array_unique(array_filter($ids)) as $id) {
$usages[$id][] = ['id' => $page->id, 'title' => $page->title];
}
});
return $usages;
}
}