Mediathek: zentrale Bildverwaltung mit Verwendungsnachweis und Bildauswahl
- Tabellen media und media_usages, Modelle Media/MediaUsage - App\Media\MediaLibrary (store/register/replace/delete/rebuild) und Registry App\Media\MediaUsages (Quellen: Seiten, Neuigkeiten inkl. künftiger content-Spalte, Termine, Startseiten-Kacheln), ImagePaths-Extraktor - Alle Uploads landen in der Mediathek (Seiten-Editor direkt, übrige über Beobachter beim Speichern); Daten-Migration und media:rebuild übernehmen bestehende Bilder - Recht media.manage, Zugang media.use für alle Redaktionsbereiche - /redaktion/mediathek (Suche, Filter, Upload mit Fortschritt, Details, Eingebunden in, Ersetzen, Löschen mit Warnung, Mehrfachauswahl), Abschnitt in der Redaktion und Menüpunkt im Admin-Bereich - MediaPicker (Hochladen/Mediathek) im Pagebuilder: Bildfelder und Galerie (Mehrfachauswahl), editor.pickMedia im provide-API - Bild-URLs mit ?v=Änderungszeit, null bei fehlender Datei; Modelle löschen geteilte Bilder nicht mehr selbst Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
3b72b5327e
commit
694ccf6ae0
46 changed files with 3101 additions and 89 deletions
|
|
@ -10,6 +10,7 @@ import {
|
|||
Heading2,
|
||||
Heading3,
|
||||
ImagePlus,
|
||||
Images,
|
||||
Italic,
|
||||
Link as LinkIcon,
|
||||
List,
|
||||
|
|
@ -25,13 +26,16 @@ import {
|
|||
|
||||
/**
|
||||
* Formatierter Text (TipTap). Liefert HTML – bereinigt wird auf dem Server
|
||||
* (App\Support\RichText::sanitize). Bilder nur, wenn uploadImage übergeben wird.
|
||||
* (App\Support\RichText::sanitize). Bilder nur, wenn uploadImage übergeben wird;
|
||||
* mit pickImage (z. B. editor.pickMedia der Bildauswahl) zusätzlich „Aus der Mediathek“.
|
||||
*/
|
||||
const props = defineProps({
|
||||
modelValue: { type: String, default: '' },
|
||||
placeholder: { type: String, default: '' },
|
||||
headings: { type: Array, default: () => [2, 3] },
|
||||
uploadImage: { type: Function, default: null },
|
||||
/** ({ multiple }) => Promise<[{ url, alt }] | null> */
|
||||
pickImage: { type: Function, default: null },
|
||||
minHeight: { type: String, default: '' },
|
||||
bordered: { type: Boolean, default: false },
|
||||
});
|
||||
|
|
@ -110,6 +114,16 @@ async function insertImage(event) {
|
|||
}
|
||||
}
|
||||
|
||||
async function pickImages() {
|
||||
const items = await props.pickImage({ multiple: true });
|
||||
|
||||
if (!items?.length) return;
|
||||
|
||||
const chain = editor.value.chain().focus();
|
||||
items.forEach((item) => chain.setImage({ src: item.url, alt: item.alt ?? '' }));
|
||||
chain.run();
|
||||
}
|
||||
|
||||
const buttonClass = (active) => [
|
||||
'grid size-8 place-items-center rounded-md transition-colors disabled:opacity-40',
|
||||
active ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground',
|
||||
|
|
@ -144,6 +158,7 @@ const buttonClass = (active) => [
|
|||
</button>
|
||||
<input ref="fileInput" type="file" accept="image/jpeg,image/png,image/webp,image/gif" class="hidden" @change="insertImage" />
|
||||
</template>
|
||||
<button v-if="pickImage" type="button" :class="buttonClass(false)" title="Bild aus der Mediathek" @click="pickImages"><Images class="size-4" /></button>
|
||||
<span class="mx-1 h-5 w-px bg-border" />
|
||||
<button type="button" :class="buttonClass(false)" title="Rückgängig" :disabled="!editor.can().undo()" @click="editor.chain().focus().undo().run()"><Undo2 class="size-4" /></button>
|
||||
<button type="button" :class="buttonClass(false)" title="Wiederholen" :disabled="!editor.can().redo()" @click="editor.chain().focus().redo().run()"><Redo2 class="size-4" /></button>
|
||||
|
|
|
|||
37
resources/js/components/editorial/EditorialMedia.vue
Normal file
37
resources/js/components/editorial/EditorialMedia.vue
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { ImageOff, Images } from '@lucide/vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
|
||||
/**
|
||||
* „Redaktion → Mediathek“: die neuesten Bilder und ein Weg zum Aufräumen.
|
||||
*/
|
||||
defineProps({
|
||||
total: { type: Number, default: 0 },
|
||||
unused: { type: Number, default: null },
|
||||
recent: { type: Array, default: () => [] },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Mediathek" action-label="Mediathek öffnen" action-href="/redaktion/mediathek">
|
||||
<p class="-mt-1 mb-3 text-[13px] text-muted-foreground">
|
||||
{{ total.toLocaleString('de-DE') }} {{ total === 1 ? 'Bild' : 'Bilder' }}
|
||||
<template v-if="unused">
|
||||
· <Link href="/redaktion/mediathek?status=unbenutzt" class="font-medium text-brand-text hover:underline">{{ unused }} nicht verwendet</Link>
|
||||
</template>
|
||||
</p>
|
||||
<ul v-if="recent.length" class="grid grid-cols-4 gap-2">
|
||||
<li v-for="item in recent" :key="item.id">
|
||||
<Link :href="`/redaktion/mediathek?q=${encodeURIComponent(item.name)}`" class="block overflow-hidden rounded-md border bg-muted hover:border-brand-300" :title="item.alt || item.name">
|
||||
<img v-if="item.thumb_url" :src="item.thumb_url" :alt="item.alt" loading="lazy" class="aspect-[4/3] w-full object-cover" />
|
||||
<span v-else class="grid aspect-[4/3] place-items-center text-muted-foreground"><ImageOff class="size-5" :stroke-width="1.5" /></span>
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="grid place-items-center rounded-md border border-dashed py-8 text-center text-[13px] text-muted-foreground">
|
||||
<Images class="mb-2 size-6" :stroke-width="1.5" />
|
||||
Noch keine Bilder hochgeladen.
|
||||
</div>
|
||||
</Panel>
|
||||
</template>
|
||||
218
resources/js/components/media/MediaDetails.vue
Normal file
218
resources/js/components/media/MediaDetails.vue
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Copy, Download, ImageOff, LoaderCircle, RefreshCw, Trash2, TriangleAlert } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { formatDate } from '@/lib/format';
|
||||
import { ACCEPT, formatBytes, mediaApi, mimeLabel } from './api';
|
||||
import MediaUsageList from './MediaUsageList.vue';
|
||||
|
||||
/**
|
||||
* Details eines Bilds: Vorschau, Angaben, Alternativtext/Bildunterschrift/
|
||||
* Schlagwörter, „Eingebunden in“ und – mit „Mediathek verwalten“ – Ersetzen und Löschen.
|
||||
*/
|
||||
const props = defineProps({
|
||||
id: { type: Number, required: true },
|
||||
canManage: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['updated', 'deleted']);
|
||||
|
||||
const item = ref(null);
|
||||
const usages = ref([]);
|
||||
const loading = ref(true);
|
||||
const form = ref({ alt: '', caption: '', tags: '' });
|
||||
const saving = ref(false);
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const data = await mediaApi.show(props.id);
|
||||
item.value = data.media;
|
||||
usages.value = data.usages;
|
||||
resetForm();
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
form.value = { alt: item.value.alt ?? '', caption: item.value.caption ?? '', tags: (item.value.tags ?? []).join(', ') };
|
||||
}
|
||||
|
||||
watch(() => props.id, load, { immediate: true });
|
||||
|
||||
const tags = computed(() => form.value.tags.split(',').map((tag) => tag.trim()).filter(Boolean));
|
||||
const dirty = computed(() => item.value && (form.value.alt !== (item.value.alt ?? '') || form.value.caption !== (item.value.caption ?? '') || tags.value.join('|') !== (item.value.tags ?? []).join('|')));
|
||||
|
||||
async function save() {
|
||||
saving.value = true;
|
||||
|
||||
try {
|
||||
const data = await mediaApi.update(item.value.id, { alt: form.value.alt, caption: form.value.caption, tags: tags.value });
|
||||
item.value = data.media;
|
||||
resetForm();
|
||||
emit('updated', data.media);
|
||||
toast.success('Gespeichert.');
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyUrl() {
|
||||
const url = new URL(item.value.url, window.location.origin).toString();
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
toast.success('Adresse kopiert.');
|
||||
} catch {
|
||||
window.prompt('Adresse des Bilds:', url);
|
||||
}
|
||||
}
|
||||
|
||||
// Ersetzen
|
||||
const replaceInput = ref(null);
|
||||
const replacing = ref(null);
|
||||
|
||||
async function replace(event) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
|
||||
if (!file) return;
|
||||
|
||||
replacing.value = 0;
|
||||
|
||||
try {
|
||||
const updated = await mediaApi.replace(item.value.id, file, (progress) => (replacing.value = progress));
|
||||
item.value = updated;
|
||||
emit('updated', updated);
|
||||
toast.success(usages.value.length ? 'Bild ersetzt – alle Einbindungen zeigen jetzt das neue Bild.' : 'Bild ersetzt.');
|
||||
} catch (error) {
|
||||
toast.error(error.fieldErrors?.image ?? error.message);
|
||||
} finally {
|
||||
replacing.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Löschen
|
||||
const confirmDelete = ref(false);
|
||||
const deleting = ref(false);
|
||||
|
||||
async function destroy() {
|
||||
deleting.value = true;
|
||||
|
||||
try {
|
||||
await mediaApi.remove(item.value.id);
|
||||
confirmDelete.value = false;
|
||||
emit('deleted', item.value.id);
|
||||
toast.success('Bild gelöscht.');
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
deleting.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="loading && !item" class="grid place-items-center py-24 text-muted-foreground"><LoaderCircle class="size-6 animate-spin" /></div>
|
||||
|
||||
<div v-else-if="item" class="grid gap-5">
|
||||
<div class="relative grid min-h-48 place-items-center overflow-hidden rounded-lg border bg-[repeating-conic-gradient(var(--muted)_0_25%,transparent_0_50%)] bg-[length:16px_16px]">
|
||||
<img v-if="item.url" :src="item.url" :alt="item.alt" class="max-h-[46vh] w-auto max-w-full object-contain" />
|
||||
<div v-else class="grid justify-items-center gap-2 py-12 text-sm text-muted-foreground"><ImageOff class="size-8" :stroke-width="1.5" /> Die Datei fehlt.</div>
|
||||
<div v-if="replacing !== null" class="absolute inset-0 grid place-items-center bg-card/80 text-sm font-medium">
|
||||
<span class="inline-flex items-center gap-2"><LoaderCircle class="size-4 animate-spin" /> Wird ersetzt … {{ Math.round(replacing * 100) }} %</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 class="text-base font-semibold break-all">{{ item.name }}</h2>
|
||||
<dl class="mt-2 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[13px]">
|
||||
<dt class="text-muted-foreground">Abmessungen</dt>
|
||||
<dd>{{ item.width && item.height ? `${item.width} × ${item.height} Pixel` : '–' }}</dd>
|
||||
<dt class="text-muted-foreground">Größe, Format</dt>
|
||||
<dd>{{ formatBytes(item.size) }} · {{ mimeLabel(item.mime) }}</dd>
|
||||
<dt class="text-muted-foreground">Hochgeladen</dt>
|
||||
<dd>{{ item.created_at ? formatDate(item.created_at) : '–' }}<template v-if="item.uploader"> von {{ item.uploader.name }}</template></dd>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="!item.url" @click="copyUrl"><Copy /> Adresse kopieren</Button>
|
||||
<Button variant="outline" size="sm" as-child :disabled="!item.url">
|
||||
<a :href="mediaApi.downloadUrl(item.id)"><Download /> Original</a>
|
||||
</Button>
|
||||
<template v-if="canManage">
|
||||
<Button variant="outline" size="sm" :disabled="replacing !== null" @click="replaceInput?.click()"><RefreshCw /> Ersetzen</Button>
|
||||
<Button variant="outline" size="sm" class="text-destructive hover:text-destructive" @click="confirmDelete = true"><Trash2 /> Löschen</Button>
|
||||
<input ref="replaceInput" type="file" :accept="ACCEPT" class="hidden" @change="replace" />
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<form class="grid gap-3 rounded-lg border bg-card p-4" @submit.prevent="save">
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Alternativtext</span>
|
||||
<Input v-model="form.alt" maxlength="300" placeholder="Was ist auf dem Bild zu sehen?" />
|
||||
<span class="text-xs text-muted-foreground">Beschreibt das Bild für Screenreader. Wird beim Einfügen vorgeschlagen.</span>
|
||||
</label>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Bildunterschrift</span>
|
||||
<Textarea v-model="form.caption" maxlength="500" rows="2" />
|
||||
</label>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Schlagwörter</span>
|
||||
<Input v-model="form.tags" placeholder="z. B. Sommerfest, Team, Standort Nord" />
|
||||
<span class="text-xs text-muted-foreground">Mit Komma trennen. Helfen beim Wiederfinden.</span>
|
||||
</label>
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button v-if="dirty" type="button" variant="ghost" size="sm" @click="resetForm">Verwerfen</Button>
|
||||
<Button type="submit" size="sm" :disabled="!dirty || saving"><LoaderCircle v-if="saving" class="animate-spin" /> Speichern</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Eingebunden in <span class="font-normal text-muted-foreground">({{ usages.length }})</span></h3>
|
||||
<MediaUsageList v-if="usages.length" :usages="usages" />
|
||||
<p v-else class="rounded-md border border-dashed px-3 py-3 text-[13px] text-muted-foreground">Nirgends eingebunden.</p>
|
||||
</section>
|
||||
|
||||
<AlertDialog v-model:open="confirmDelete">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Bild löschen?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
„{{ item.name }}“ wird endgültig gelöscht.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div v-if="usages.length" class="grid gap-2">
|
||||
<p class="flex items-start gap-2 rounded-md bg-amber-50 px-3 py-2 text-[13px] text-amber-900 dark:bg-amber-950/50 dark:text-amber-100">
|
||||
<TriangleAlert class="mt-0.5 size-4 shrink-0" />
|
||||
Das Bild ist noch an {{ usages.length }} {{ usages.length === 1 ? 'Stelle' : 'Stellen' }} eingebunden. Dort erscheint danach ein Platzhalter.
|
||||
</p>
|
||||
<div class="max-h-48 overflow-y-auto"><MediaUsageList :usages="usages" /></div>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||
<Button variant="destructive" :disabled="deleting" @click="destroy"><LoaderCircle v-if="deleting" class="animate-spin" /> Endgültig löschen</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</template>
|
||||
310
resources/js/components/media/MediaPicker.vue
Normal file
310
resources/js/components/media/MediaPicker.vue
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
<script setup>
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { ExternalLink, ImageOff, Images, LoaderCircle, Search, SearchX, Upload, X } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
|
||||
import { formatBytes, mediaApi, toSelection } from './api';
|
||||
import MediaTile from './MediaTile.vue';
|
||||
import MediaUploadZone from './MediaUploadZone.vue';
|
||||
import MediaUsageList from './MediaUsageList.vue';
|
||||
import { useMediaList } from './useMediaList';
|
||||
|
||||
/**
|
||||
* Bildauswahl für Editoren: „Hochladen“ (Ziehen & Ablegen, mehrere, Strg+V)
|
||||
* und „Mediathek“ (Suche, zuletzt verwendet, schon hier verwendet,
|
||||
* Mehrfachauswahl für Galerien, Alternativtext direkt bearbeiten).
|
||||
*
|
||||
* Liefert über „select“ eine Liste von { id, path, url, alt, caption, width, height }.
|
||||
* Bequemer über useMediaPicker() + MediaPickerHost (siehe dort).
|
||||
*/
|
||||
const props = defineProps({
|
||||
open: { type: Boolean, default: false },
|
||||
multiple: { type: Boolean, default: false },
|
||||
/** Pfade, die im bearbeiteten Inhalt schon vorkommen (Filter „Hier verwendet“) */
|
||||
contextPaths: { type: Array, default: () => [] },
|
||||
contextLabel: { type: String, default: 'Hier verwendet' },
|
||||
/** Eigenes Hochladen, z. B. in das Verzeichnis der Seite: (file, onProgress) => Promise<Eintrag | { media }> */
|
||||
upload: { type: Function, default: null },
|
||||
title: { type: String, default: '' },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['update:open', 'select']);
|
||||
|
||||
const tab = ref('library');
|
||||
const view = ref('all');
|
||||
const query = ref('');
|
||||
|
||||
const filters = computed(() => ({
|
||||
q: query.value,
|
||||
sortierung: view.value === 'recent' ? 'verwendet' : 'neu',
|
||||
status: view.value === 'unused' ? 'unbenutzt' : view.value === 'recent' ? 'verwendet' : '',
|
||||
pfade: view.value === 'here' ? props.contextPaths.slice(0, 500) : undefined,
|
||||
}));
|
||||
|
||||
const { items, total, loading, nextPage, load, observe, replaceItem, prepend } = useMediaList(filters);
|
||||
const sentinel = ref(null);
|
||||
const scroller = ref(null);
|
||||
const selection = ref([]);
|
||||
const activeId = ref(null);
|
||||
const here = computed(() => new Set(props.contextPaths));
|
||||
|
||||
const active = computed(() => items.value.find((item) => item.id === activeId.value) ?? selection.value.find((item) => item.id === activeId.value) ?? null);
|
||||
|
||||
watch(() => props.open, async (open) => {
|
||||
if (!open) return;
|
||||
|
||||
selection.value = [];
|
||||
activeId.value = null;
|
||||
query.value = '';
|
||||
view.value = 'all';
|
||||
tab.value = 'library';
|
||||
await load(true);
|
||||
await nextTick();
|
||||
observe(sentinel.value, scroller.value);
|
||||
}, { immediate: true });
|
||||
|
||||
watch(tab, async (value) => {
|
||||
if (value === 'library') {
|
||||
await nextTick();
|
||||
observe(sentinel.value, scroller.value);
|
||||
}
|
||||
});
|
||||
|
||||
const isSelected = (item) => selection.value.some((s) => s.id === item.id);
|
||||
|
||||
function toggle(item) {
|
||||
if (item.missing) return;
|
||||
|
||||
activeId.value = item.id;
|
||||
|
||||
if (!props.multiple) {
|
||||
selection.value = [item];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
selection.value = isSelected(item) ? selection.value.filter((s) => s.id !== item.id) : [...selection.value, item];
|
||||
}
|
||||
|
||||
function onOpen(item, event) {
|
||||
// Doppelklick in der Einzelauswahl übernimmt sofort.
|
||||
if (!props.multiple && event?.detail === 2 && !item.missing) {
|
||||
selection.value = [item];
|
||||
confirm();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
toggle(item);
|
||||
}
|
||||
|
||||
// Hochladen
|
||||
async function uploadFile(file, onProgress) {
|
||||
const result = props.upload ? await props.upload(file, onProgress) : await mediaApi.upload(file, onProgress);
|
||||
|
||||
return result?.media ?? result;
|
||||
}
|
||||
|
||||
function uploaded(list) {
|
||||
const fresh = list.map((item) => ({ ...item, usage_count: item.usage_count ?? 0 }));
|
||||
view.value = 'all';
|
||||
prepend(fresh);
|
||||
selection.value = props.multiple ? [...selection.value, ...fresh.filter((f) => !isSelected(f))] : [fresh[fresh.length - 1]];
|
||||
activeId.value = fresh[fresh.length - 1].id;
|
||||
tab.value = 'library';
|
||||
}
|
||||
|
||||
// Alternativtext direkt bearbeiten
|
||||
const altDraft = ref('');
|
||||
const altSaving = ref(false);
|
||||
const usages = ref(null);
|
||||
|
||||
watch(active, (item, previous) => {
|
||||
if (item?.id !== previous?.id) {
|
||||
altDraft.value = item?.alt ?? '';
|
||||
usages.value = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function saveAlt() {
|
||||
const item = active.value;
|
||||
|
||||
if (!item || altDraft.value.trim() === (item.alt ?? '')) return;
|
||||
|
||||
altSaving.value = true;
|
||||
|
||||
try {
|
||||
const data = await mediaApi.update(item.id, { alt: altDraft.value.trim() });
|
||||
replaceItem(data.media);
|
||||
selection.value = selection.value.map((s) => (s.id === item.id ? { ...s, alt: data.media.alt } : s));
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
altSaving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function showUsages() {
|
||||
try {
|
||||
usages.value = (await mediaApi.show(active.value.id)).usages;
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
await saveAlt();
|
||||
emit('select', selection.value.map((item) => toSelection(items.value.find((i) => i.id === item.id) ?? item)));
|
||||
emit('update:open', false);
|
||||
}
|
||||
|
||||
const views = computed(() => [
|
||||
{ key: 'all', label: 'Alle' },
|
||||
{ key: 'recent', label: 'Zuletzt verwendet' },
|
||||
...(props.contextPaths.length ? [{ key: 'here', label: props.contextLabel }] : []),
|
||||
{ key: 'unused', label: 'Nicht verwendet' },
|
||||
]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="(value) => emit('update:open', value)">
|
||||
<DialogContent class="flex h-[min(88vh,820px)] max-w-6xl flex-col gap-0 overflow-hidden p-0 sm:max-w-6xl">
|
||||
<header class="flex flex-wrap items-center gap-x-6 gap-y-2 border-b px-5 pt-4 pr-12">
|
||||
<div class="pb-3">
|
||||
<DialogTitle class="text-base">{{ title || (multiple ? 'Bilder auswählen' : 'Bild auswählen') }}</DialogTitle>
|
||||
<DialogDescription class="text-[13px]">
|
||||
{{ multiple ? 'Mehrere Bilder anklicken – die Reihenfolge der Auswahl bleibt erhalten.' : 'Ein Bild anklicken, mit Doppelklick direkt übernehmen.' }}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<nav class="-mb-px flex gap-1 self-end" role="tablist">
|
||||
<button
|
||||
v-for="entry in [{ key: 'upload', label: 'Hochladen', icon: Upload }, { key: 'library', label: 'Mediathek', icon: Images }]"
|
||||
:key="entry.key"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="tab === entry.key"
|
||||
class="inline-flex items-center gap-1.5 border-b-2 px-3 pb-2.5 text-sm font-medium transition-colors"
|
||||
:class="tab === entry.key ? 'border-brand text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'"
|
||||
@click="tab = entry.key"
|
||||
>
|
||||
<component :is="entry.icon" class="size-4" /> {{ entry.label }}
|
||||
</button>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div v-show="tab === 'upload'" class="min-h-0 flex-1 overflow-y-auto p-5">
|
||||
<MediaUploadZone v-if="open" :upload="uploadFile" :paste="tab === 'upload'" @done="uploaded" />
|
||||
<p class="mt-4 text-[13px] text-muted-foreground">Hochgeladene Bilder landen in der Mediathek und sind danach ausgewählt. Große Fotos werden automatisch verkleinert.</p>
|
||||
</div>
|
||||
|
||||
<div v-show="tab === 'library'" class="flex min-h-0 flex-1">
|
||||
<div class="flex min-w-0 flex-1 flex-col">
|
||||
<div class="flex flex-wrap items-center gap-2 border-b px-4 py-2.5">
|
||||
<label class="relative min-w-48 flex-1">
|
||||
<span class="sr-only">Suchen</span>
|
||||
<Search class="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
v-model="query"
|
||||
type="search"
|
||||
placeholder="Suchen: Name, Alternativtext, Schlagwort …"
|
||||
class="h-8 w-full rounded-md border border-input bg-card pr-3 pl-8 text-sm placeholder:text-muted-foreground focus-visible:border-brand-400 focus-visible:ring-3 focus-visible:ring-ring/30 focus-visible:outline-none"
|
||||
/>
|
||||
</label>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<button
|
||||
v-for="entry in views"
|
||||
:key="entry.key"
|
||||
type="button"
|
||||
class="h-8 rounded-md px-2.5 text-[13px] font-medium transition-colors"
|
||||
:class="view === entry.key ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground'"
|
||||
:aria-pressed="view === entry.key"
|
||||
@click="view = entry.key"
|
||||
>
|
||||
{{ entry.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="scroller" class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<ul v-if="items.length" class="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
<MediaTile :item="item" :selected="isSelected(item)" :checkable="multiple" :here="here.has(item.path)" @open="onOpen" @toggle="toggle" />
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else-if="!loading" class="grid place-items-center px-6 py-16 text-center">
|
||||
<component :is="query || view !== 'all' ? SearchX : Images" class="size-8 text-muted-foreground" :stroke-width="1.5" />
|
||||
<p class="mt-3 text-sm font-medium">{{ query || view !== 'all' ? 'Keine Bilder gefunden' : 'Die Mediathek ist noch leer' }}</p>
|
||||
<Button variant="outline" size="sm" class="mt-3" @click="tab = 'upload'"><Upload /> Bilder hochladen</Button>
|
||||
</div>
|
||||
<div ref="sentinel" class="grid h-12 place-items-center">
|
||||
<LoaderCircle v-if="loading" class="size-5 animate-spin text-muted-foreground" />
|
||||
<Button v-else-if="nextPage && items.length" variant="ghost" size="sm" @click="load()">Weitere laden</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside class="hidden w-72 shrink-0 overflow-y-auto border-l bg-muted/30 p-4 md:block">
|
||||
<div v-if="active" class="grid gap-3">
|
||||
<div class="grid place-items-center overflow-hidden rounded-md border bg-card">
|
||||
<img v-if="active.thumb_url || active.url" :src="active.url || active.thumb_url" :alt="active.alt" class="max-h-44 w-auto object-contain" />
|
||||
<ImageOff v-else class="my-10 size-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div class="text-[13px]">
|
||||
<p class="font-medium break-all">{{ active.name }}</p>
|
||||
<p class="text-muted-foreground">
|
||||
<template v-if="active.width">{{ active.width }} × {{ active.height }} · </template>{{ formatBytes(active.size) }}
|
||||
</p>
|
||||
</div>
|
||||
<label class="grid gap-1">
|
||||
<span class="flex items-center justify-between text-[13px] font-medium">
|
||||
Alternativtext
|
||||
<LoaderCircle v-if="altSaving" class="size-3.5 animate-spin text-muted-foreground" />
|
||||
</span>
|
||||
<textarea
|
||||
v-model="altDraft"
|
||||
rows="3"
|
||||
maxlength="300"
|
||||
placeholder="Was ist auf dem Bild zu sehen?"
|
||||
class="w-full resize-none rounded-md border border-input bg-card px-2.5 py-1.5 text-[13px] focus-visible:border-brand-400 focus-visible:ring-3 focus-visible:ring-ring/30 focus-visible:outline-none"
|
||||
@blur="saveAlt"
|
||||
/>
|
||||
<span class="text-[11px] text-muted-foreground">Wird in der Mediathek gespeichert und beim Einfügen übernommen.</span>
|
||||
</label>
|
||||
<div class="text-[13px]">
|
||||
<p v-if="here.has(active.path)" class="mb-1 font-medium text-brand-text">{{ contextLabel }}</p>
|
||||
<p v-if="!active.usage_count" class="text-muted-foreground">Noch nirgends verwendet.</p>
|
||||
<template v-else>
|
||||
<button v-if="!usages" type="button" class="font-medium text-brand-text hover:underline" @click="showUsages">
|
||||
In {{ active.usage_count }} {{ active.usage_count === 1 ? 'Inhalt' : 'Inhalten' }} verwendet
|
||||
</button>
|
||||
<MediaUsageList v-else :usages="usages" />
|
||||
</template>
|
||||
</div>
|
||||
<a :href="`/redaktion/mediathek?q=${encodeURIComponent(active.name)}`" target="_blank" class="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:underline">
|
||||
In der Mediathek öffnen <ExternalLink class="size-3" />
|
||||
</a>
|
||||
</div>
|
||||
<p v-else class="text-[13px] text-muted-foreground">Bild anklicken, um Details zu sehen und den Alternativtext zu ergänzen.</p>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<footer class="flex flex-wrap items-center gap-3 border-t bg-card px-5 py-3">
|
||||
<div class="flex min-w-0 flex-1 items-center gap-2">
|
||||
<template v-if="selection.length">
|
||||
<div class="flex -space-x-2">
|
||||
<img v-for="item in selection.slice(-5)" :key="item.id" :src="item.thumb_url" alt="" class="size-8 rounded border-2 border-card object-cover" />
|
||||
</div>
|
||||
<span class="text-[13px] font-medium">{{ selection.length === 1 ? '1 Bild ausgewählt' : `${selection.length} Bilder ausgewählt` }}</span>
|
||||
<button v-if="multiple" type="button" class="inline-flex items-center gap-0.5 text-xs text-muted-foreground hover:text-foreground" @click="selection = []"><X class="size-3" /> Auswahl leeren</button>
|
||||
</template>
|
||||
<span v-else-if="total !== null && tab === 'library'" class="text-[13px] text-muted-foreground">{{ total.toLocaleString('de-DE') }} {{ total === 1 ? 'Bild' : 'Bilder' }}</span>
|
||||
</div>
|
||||
<Button variant="outline" @click="emit('update:open', false)">Abbrechen</Button>
|
||||
<Button :disabled="!selection.length" @click="confirm">
|
||||
{{ multiple && selection.length > 1 ? `${selection.length} Bilder übernehmen` : 'Übernehmen' }}
|
||||
</Button>
|
||||
</footer>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
23
resources/js/components/media/MediaPickerHost.vue
Normal file
23
resources/js/components/media/MediaPickerHost.vue
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
<script setup>
|
||||
import MediaPicker from './MediaPicker.vue';
|
||||
|
||||
/**
|
||||
* Bindet eine Bildauswahl aus useMediaPicker() ein (einmal je Editor).
|
||||
*/
|
||||
defineProps({
|
||||
picker: { type: Object, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MediaPicker
|
||||
:open="picker.state.open"
|
||||
:multiple="picker.state.multiple"
|
||||
:title="picker.state.title"
|
||||
:context-paths="picker.state.contextPaths"
|
||||
:context-label="picker.state.contextLabel"
|
||||
:upload="picker.state.upload"
|
||||
@select="(items) => picker.finish(items)"
|
||||
@update:open="(value) => !value && picker.finish(null)"
|
||||
/>
|
||||
</template>
|
||||
55
resources/js/components/media/MediaTile.vue
Normal file
55
resources/js/components/media/MediaTile.vue
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<script setup>
|
||||
import { Check, ImageOff, Link2 } from '@lucide/vue';
|
||||
|
||||
/**
|
||||
* Vorschaubild in Mediathek und Bildauswahl.
|
||||
*/
|
||||
defineProps({
|
||||
item: { type: Object, required: true },
|
||||
selected: { type: Boolean, default: false },
|
||||
/** Auswahlkästchen immer zeigen (Mehrfachauswahl) */
|
||||
checkable: { type: Boolean, default: false },
|
||||
/** Hinweis „hier schon verwendet“ */
|
||||
here: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['open', 'toggle']);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="group relative overflow-hidden rounded-md border bg-muted transition-shadow"
|
||||
:class="selected ? 'border-brand-500 ring-2 ring-brand-400' : 'hover:border-brand-300'"
|
||||
>
|
||||
<button type="button" class="block w-full focus-visible:outline-none" :title="item.name" @click="emit('open', item, $event)">
|
||||
<img v-if="item.thumb_url" :src="item.thumb_url" :alt="item.alt" loading="lazy" class="aspect-[4/3] w-full object-cover" />
|
||||
<span v-else class="grid aspect-[4/3] w-full place-items-center text-muted-foreground">
|
||||
<span class="grid justify-items-center gap-1 text-xs"><ImageOff class="size-6" :stroke-width="1.5" /> Datei fehlt</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="absolute top-1.5 left-1.5 grid size-6 place-items-center rounded border shadow-sm transition-opacity focus-visible:opacity-100"
|
||||
:class="[selected ? 'border-brand-600 bg-brand text-brand-foreground opacity-100' : 'border-white/80 bg-black/25 text-transparent opacity-0 group-hover:opacity-100', checkable && 'opacity-100']"
|
||||
:aria-pressed="selected"
|
||||
:aria-label="selected ? 'Auswahl aufheben' : 'Auswählen'"
|
||||
@click.stop="emit('toggle', item)"
|
||||
>
|
||||
<Check class="size-4" />
|
||||
</button>
|
||||
|
||||
<span v-if="here" class="absolute top-1.5 right-1.5 rounded bg-card/95 px-1.5 py-0.5 text-[11px] font-medium text-brand-text shadow-sm">Hier verwendet</span>
|
||||
<span
|
||||
v-else-if="item.usage_count === 0"
|
||||
class="absolute top-1.5 right-1.5 rounded bg-card/95 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground shadow-sm"
|
||||
>Nicht verwendet</span>
|
||||
|
||||
<div class="pointer-events-none flex items-center gap-1 border-t bg-card px-2 py-1.5 text-xs">
|
||||
<span class="min-w-0 flex-1 truncate" :class="item.alt ? '' : 'text-muted-foreground'">{{ item.alt || item.name }}</span>
|
||||
<span v-if="item.usage_count" class="inline-flex shrink-0 items-center gap-0.5 text-muted-foreground" :title="`In ${item.usage_count} ${item.usage_count === 1 ? 'Inhalt' : 'Inhalten'} verwendet`">
|
||||
<Link2 class="size-3" />{{ item.usage_count }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
150
resources/js/components/media/MediaUploadZone.vue
Normal file
150
resources/js/components/media/MediaUploadZone.vue
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { CircleAlert, CircleCheck, ClipboardPaste, ImageUp, LoaderCircle, X } from '@lucide/vue';
|
||||
import { ACCEPT, mediaApi } from './api';
|
||||
|
||||
/**
|
||||
* Bilder hochladen: Ziehen & Ablegen, Dateiauswahl (mehrere) und Einfügen aus
|
||||
* der Zwischenablage (Strg+V). Zeigt je Datei den Fortschritt.
|
||||
*/
|
||||
const props = defineProps({
|
||||
/** (file, onProgress) => Promise<Eintrag der Mediathek> */
|
||||
upload: { type: Function, default: null },
|
||||
multiple: { type: Boolean, default: true },
|
||||
/** Strg+V im ganzen Fenster annehmen, solange sichtbar */
|
||||
paste: { type: Boolean, default: true },
|
||||
compact: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const emit = defineEmits(['uploaded', 'done']);
|
||||
|
||||
const MAX_BYTES = 15 * 1024 * 1024;
|
||||
const TYPES = ACCEPT.split(',');
|
||||
|
||||
const input = ref(null);
|
||||
const dragging = ref(false);
|
||||
const queue = ref([]);
|
||||
let counter = 0;
|
||||
let dragDepth = 0;
|
||||
|
||||
async function handle(files) {
|
||||
const list = [...files].filter(Boolean);
|
||||
|
||||
if (!list.length) return;
|
||||
|
||||
const chosen = props.multiple ? list : list.slice(0, 1);
|
||||
const uploaded = [];
|
||||
|
||||
// Nacheinander hochladen – schont Server mit wenig Arbeitsspeicher.
|
||||
for (const file of chosen) {
|
||||
const entry = { id: ++counter, name: file.name || 'Bild aus der Zwischenablage', progress: 0, status: 'uploading', error: '' };
|
||||
queue.value = [entry, ...queue.value].slice(0, 30);
|
||||
const item = queue.value.find((e) => e.id === entry.id);
|
||||
|
||||
if (!TYPES.includes(file.type)) {
|
||||
Object.assign(item, { status: 'error', error: 'Nur JPG, PNG, WebP oder GIF.' });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (file.size > MAX_BYTES) {
|
||||
Object.assign(item, { status: 'error', error: 'Größer als 15 MB.' });
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await (props.upload ?? mediaApi.upload)(file, (progress) => (item.progress = progress));
|
||||
Object.assign(item, { status: 'done', progress: 1 });
|
||||
uploaded.push(result);
|
||||
emit('uploaded', result);
|
||||
} catch (error) {
|
||||
Object.assign(item, { status: 'error', error: error.fieldErrors?.image ?? error.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (uploaded.length) emit('done', uploaded);
|
||||
}
|
||||
|
||||
function onDrop(event) {
|
||||
dragging.value = false;
|
||||
dragDepth = 0;
|
||||
handle(event.dataTransfer?.files ?? []);
|
||||
}
|
||||
|
||||
function onDragEnter() {
|
||||
dragDepth++;
|
||||
dragging.value = true;
|
||||
}
|
||||
|
||||
function onDragLeave() {
|
||||
dragDepth = Math.max(0, dragDepth - 1);
|
||||
dragging.value = dragDepth > 0;
|
||||
}
|
||||
|
||||
function onPaste(event) {
|
||||
const files = [...(event.clipboardData?.items ?? [])].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile());
|
||||
|
||||
if (files.length) {
|
||||
event.preventDefault();
|
||||
handle(files);
|
||||
}
|
||||
}
|
||||
|
||||
function onChange(event) {
|
||||
handle(event.target.files ?? []);
|
||||
event.target.value = '';
|
||||
}
|
||||
|
||||
onMounted(() => props.paste && document.addEventListener('paste', onPaste));
|
||||
onBeforeUnmount(() => document.removeEventListener('paste', onPaste));
|
||||
|
||||
defineExpose({ open: () => input.value?.click(), handle });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-3">
|
||||
<div
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="grid cursor-pointer place-items-center rounded-lg border-2 border-dashed text-center transition-colors focus-visible:ring-3 focus-visible:ring-ring/30 focus-visible:outline-none"
|
||||
:class="[dragging ? 'border-brand-400 bg-brand-soft/60' : 'border-border bg-muted/40 hover:border-brand-300 hover:bg-muted/70', compact ? 'px-4 py-6' : 'px-6 py-12']"
|
||||
@click="input?.click()"
|
||||
@keydown.enter.prevent="input?.click()"
|
||||
@keydown.space.prevent="input?.click()"
|
||||
@dragenter.prevent="onDragEnter"
|
||||
@dragover.prevent
|
||||
@dragleave.prevent="onDragLeave"
|
||||
@drop.prevent="onDrop"
|
||||
>
|
||||
<ImageUp class="text-muted-foreground" :class="compact ? 'size-7' : 'size-9'" :stroke-width="1.5" />
|
||||
<p class="mt-3 text-sm font-medium">
|
||||
{{ dragging ? 'Loslassen zum Hochladen' : multiple ? 'Bilder hierher ziehen oder klicken' : 'Bild hierher ziehen oder klicken' }}
|
||||
</p>
|
||||
<p class="mt-1 text-[13px] text-muted-foreground">JPG, PNG, WebP oder GIF, bis 15 MB{{ multiple ? ' – mehrere auf einmal möglich' : '' }}</p>
|
||||
<p v-if="paste" class="mt-2 inline-flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<ClipboardPaste class="size-3.5" /> Oder ein kopiertes Bild mit <kbd class="rounded border bg-card px-1 font-sans text-[11px]">Strg</kbd>+<kbd class="rounded border bg-card px-1 font-sans text-[11px]">V</kbd> einfügen
|
||||
</p>
|
||||
<input ref="input" type="file" :accept="ACCEPT" :multiple="multiple" class="hidden" @change="onChange" />
|
||||
</div>
|
||||
|
||||
<ul v-if="queue.length" class="grid gap-1.5" aria-live="polite">
|
||||
<li v-for="entry in queue" :key="entry.id" class="flex items-center gap-2.5 rounded-md border bg-card px-3 py-2 text-[13px]">
|
||||
<LoaderCircle v-if="entry.status === 'uploading'" class="size-4 shrink-0 animate-spin text-muted-foreground" />
|
||||
<CircleCheck v-else-if="entry.status === 'done'" class="size-4 shrink-0 text-emerald-600" />
|
||||
<CircleAlert v-else class="size-4 shrink-0 text-destructive" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-baseline justify-between gap-2">
|
||||
<span class="truncate font-medium">{{ entry.name }}</span>
|
||||
<span v-if="entry.status === 'uploading'" class="shrink-0 text-xs text-muted-foreground tabular-nums">{{ Math.round(entry.progress * 100) }} %</span>
|
||||
</div>
|
||||
<div v-if="entry.status === 'uploading'" class="mt-1 h-1 overflow-hidden rounded-full bg-muted">
|
||||
<div class="h-full rounded-full bg-brand transition-[width]" :style="{ width: `${Math.max(4, entry.progress * 100)}%` }" />
|
||||
</div>
|
||||
<p v-else-if="entry.status === 'error'" class="text-xs text-destructive">{{ entry.error }}</p>
|
||||
</div>
|
||||
<button v-if="entry.status !== 'uploading'" type="button" class="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent" title="Aus der Liste entfernen" @click="queue = queue.filter((e) => e.id !== entry.id)">
|
||||
<X class="size-3.5" />
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
25
resources/js/components/media/MediaUsageList.vue
Normal file
25
resources/js/components/media/MediaUsageList.vue
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<script setup>
|
||||
import { ExternalLink } from '@lucide/vue';
|
||||
|
||||
/**
|
||||
* „Eingebunden in“: Stellen, an denen ein Bild verwendet wird – mit Direktlink.
|
||||
*/
|
||||
defineProps({
|
||||
usages: { type: Array, required: true },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="divide-y rounded-md border bg-card">
|
||||
<li v-for="usage in usages" :key="usage.id" class="flex items-start gap-3 px-3 py-2">
|
||||
<div class="min-w-0 flex-1">
|
||||
<component :is="usage.url ? 'a' : 'span'" :href="usage.url || undefined" class="group inline-flex max-w-full items-center gap-1 text-[13px] font-medium" :class="usage.url && 'hover:underline'">
|
||||
<span class="truncate">{{ usage.label || 'Ohne Titel' }}</span>
|
||||
<ExternalLink v-if="usage.url" class="size-3 shrink-0 text-muted-foreground" />
|
||||
</component>
|
||||
<p class="text-xs text-muted-foreground">{{ usage.type_label }} · {{ usage.context }}</p>
|
||||
</div>
|
||||
<span v-if="usage.draft" class="mt-0.5 shrink-0 rounded bg-muted px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground">Entwurf</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
126
resources/js/components/media/api.js
Normal file
126
resources/js/components/media/api.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { http, HttpError } from '@/lib/http';
|
||||
|
||||
/**
|
||||
* Schnittstelle der Mediathek (App\Http\Controllers\MediaController).
|
||||
* Einträge: { id, path, url, thumb_url, name, alt, caption, tags, width, height, size, mime, missing, uploader, usage_count, created_at }
|
||||
*/
|
||||
export const BASE = '/redaktion/mediathek';
|
||||
|
||||
function xsrfToken() {
|
||||
const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/);
|
||||
|
||||
return match ? decodeURIComponent(match[1]) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei mit Fortschrittsanzeige hochladen (fetch kennt keinen Upload-Fortschritt).
|
||||
*
|
||||
* @returns {Promise<object>} JSON-Antwort
|
||||
*/
|
||||
export function uploadWithProgress(url, file, { field = 'image', onProgress } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = new FormData();
|
||||
body.append(field, file);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', url);
|
||||
xhr.setRequestHeader('Accept', 'application/json');
|
||||
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
|
||||
xhr.setRequestHeader('X-XSRF-TOKEN', xsrfToken());
|
||||
xhr.withCredentials = true;
|
||||
|
||||
xhr.upload.onprogress = (event) => event.lengthComputable && onProgress?.(event.loaded / event.total);
|
||||
xhr.onerror = () => reject(new HttpError(0, { message: 'Keine Verbindung. Bitte erneut versuchen.' }));
|
||||
xhr.onload = () => {
|
||||
let data = null;
|
||||
|
||||
try {
|
||||
data = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(data);
|
||||
} else {
|
||||
if (xhr.status === 413) data = { message: 'Die Datei ist zu groß.' };
|
||||
reject(new HttpError(xhr.status, data));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.send(body);
|
||||
});
|
||||
}
|
||||
|
||||
function query(params) {
|
||||
const search = new URLSearchParams();
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => search.append(`${key}[]`, item));
|
||||
} else if (value !== null && value !== undefined && value !== '' && value !== false) {
|
||||
search.append(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
const string = search.toString();
|
||||
|
||||
return string ? `?${string}` : '';
|
||||
}
|
||||
|
||||
export const mediaApi = {
|
||||
list: (params = {}) => http.get(`${BASE}/liste${query(params)}`),
|
||||
show: (id) => http.get(`${BASE}/${id}`),
|
||||
update: (id, data) => http.put(`${BASE}/${id}`, data),
|
||||
remove: (id) => http.delete(`${BASE}/${id}`),
|
||||
bulkRemove: (ids, onlyUnused = false) => http.post(`${BASE}/loeschen`, { ids, only_unused: onlyUnused }),
|
||||
rebuild: () => http.post(`${BASE}/neu-einlesen`),
|
||||
/** @returns {Promise<object>} Eintrag der Mediathek */
|
||||
upload: (file, onProgress) => uploadWithProgress(BASE, file, { onProgress }).then((data) => data.media),
|
||||
replace: (id, file, onProgress) => uploadWithProgress(`${BASE}/${id}/ersetzen`, file, { onProgress }).then((data) => data.media),
|
||||
downloadUrl: (id) => `${BASE}/${id}/original`,
|
||||
};
|
||||
|
||||
/** Auswahl, wie sie Editoren zurückbekommen. */
|
||||
export const toSelection = (item) => ({ id: item.id, path: item.path, url: item.url, alt: item.alt ?? '', caption: item.caption ?? '', width: item.width, height: item.height });
|
||||
|
||||
const PATH_PATTERN = /^[A-Za-z0-9_-][A-Za-z0-9/_.-]*\.(webp|jpe?g|png|gif)$/i;
|
||||
|
||||
/**
|
||||
* Bildpfade in beliebigen Daten (Pagebuilder-JSON, HTML mit src="/uploads/…") –
|
||||
* für den Filter „Hier verwendet“ der Bildauswahl.
|
||||
*
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function collectImagePaths(value, found = new Set()) {
|
||||
if (typeof value === 'string') {
|
||||
if (PATH_PATTERN.test(value) && !value.includes('..')) {
|
||||
found.add(value);
|
||||
} else if (value.includes('<img')) {
|
||||
for (const match of value.matchAll(/src=["'][^"']*?\/uploads\/([^"'?#]+)/gi)) {
|
||||
const path = decodeURIComponent(match[1]);
|
||||
|
||||
if (PATH_PATTERN.test(path)) found.add(path);
|
||||
}
|
||||
}
|
||||
} else if (Array.isArray(value)) {
|
||||
value.forEach((entry) => collectImagePaths(entry, found));
|
||||
} else if (value && typeof value === 'object') {
|
||||
Object.values(value).forEach((entry) => collectImagePaths(entry, found));
|
||||
}
|
||||
|
||||
return [...found];
|
||||
}
|
||||
|
||||
export const ACCEPT ='image/jpeg,image/png,image/webp,image/gif';
|
||||
|
||||
export function formatBytes(bytes) {
|
||||
if (!bytes) return '–';
|
||||
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1).replace('.', ',')} MB`;
|
||||
|
||||
return `${Math.max(1, Math.round(bytes / 1024))} KB`;
|
||||
}
|
||||
|
||||
export function mimeLabel(mime) {
|
||||
return { 'image/webp': 'WebP', 'image/jpeg': 'JPEG', 'image/png': 'PNG', 'image/gif': 'GIF' }[mime] ?? (mime || '–');
|
||||
}
|
||||
82
resources/js/components/media/useMediaList.js
Normal file
82
resources/js/components/media/useMediaList.js
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { mediaApi } from './api';
|
||||
|
||||
/**
|
||||
* Seitenweise geladene Liste der Mediathek mit Filtern (Suche verzögert).
|
||||
*
|
||||
* @param {import('vue').Ref<object>} filters z. B. { q, von, zeitraum, status, in, sortierung, pfade }
|
||||
*/
|
||||
export function useMediaList(filters) {
|
||||
const items = ref([]);
|
||||
const total = ref(null);
|
||||
const loading = ref(false);
|
||||
const nextPage = ref(1);
|
||||
let generation = 0;
|
||||
|
||||
async function load(reset = false) {
|
||||
if (reset) {
|
||||
generation++;
|
||||
nextPage.value = 1;
|
||||
}
|
||||
|
||||
if (!nextPage.value || (loading.value && !reset)) return;
|
||||
|
||||
const current = generation;
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const data = await mediaApi.list({ ...filters.value, page: nextPage.value });
|
||||
|
||||
if (current !== generation) return;
|
||||
|
||||
items.value = nextPage.value === 1 ? data.items : [...items.value, ...data.items.filter((item) => !items.value.some((i) => i.id === item.id))];
|
||||
nextPage.value = data.next_page;
|
||||
|
||||
if (data.total !== null) total.value = data.total;
|
||||
} catch (error) {
|
||||
if (current === generation) toast.error(error.message);
|
||||
} finally {
|
||||
if (current === generation) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const reload = () => load(true);
|
||||
const debouncedReload = useDebounceFn(reload, 250);
|
||||
|
||||
watch(() => filters.value.q, debouncedReload);
|
||||
watch(() => JSON.stringify({ ...filters.value, q: null }), reload);
|
||||
|
||||
/** Nachladen, sobald das Element sichtbar wird (Endlos-Scrollen). */
|
||||
let observer;
|
||||
|
||||
function observe(element, root = null) {
|
||||
observer?.disconnect();
|
||||
|
||||
if (!element) return;
|
||||
|
||||
observer = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && nextPage.value && load(), { root, rootMargin: '400px' });
|
||||
observer.observe(element);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => observer?.disconnect());
|
||||
|
||||
function replaceItem(updated) {
|
||||
items.value = items.value.map((item) => (item.id === updated.id ? { ...item, ...updated, usage_count: updated.usage_count ?? item.usage_count } : item));
|
||||
}
|
||||
|
||||
function removeItems(ids) {
|
||||
items.value = items.value.filter((item) => !ids.includes(item.id));
|
||||
|
||||
if (total.value !== null) total.value = Math.max(0, total.value - ids.length);
|
||||
}
|
||||
|
||||
function prepend(newItems) {
|
||||
items.value = [...newItems, ...items.value.filter((item) => !newItems.some((n) => n.id === item.id))];
|
||||
|
||||
if (total.value !== null) total.value += newItems.length;
|
||||
}
|
||||
|
||||
return { items, total, loading, nextPage, load, reload, observe, replaceItem, removeItems, prepend };
|
||||
}
|
||||
51
resources/js/components/media/useMediaPicker.js
Normal file
51
resources/js/components/media/useMediaPicker.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { reactive } from 'vue';
|
||||
|
||||
/**
|
||||
* Bildauswahl als Promise – für Editoren (Pagebuilder, Neuigkeiten …):
|
||||
*
|
||||
* const picker = useMediaPicker({ upload: (file, onProgress) => …, contextPaths: () => [...] });
|
||||
* const items = await picker.pick({ multiple: true }); // null bei Abbruch
|
||||
* // items: [{ id, path, url, alt, caption, width, height }]
|
||||
*
|
||||
* Im Template einmal <MediaPickerHost :picker="picker" /> einbinden.
|
||||
*
|
||||
* @param {{ upload?: Function, contextPaths?: () => string[], contextLabel?: string }} defaults
|
||||
*/
|
||||
export function useMediaPicker(defaults = {}) {
|
||||
const state = reactive({
|
||||
open: false,
|
||||
multiple: false,
|
||||
title: '',
|
||||
contextPaths: [],
|
||||
contextLabel: defaults.contextLabel ?? 'Hier verwendet',
|
||||
upload: defaults.upload ?? null,
|
||||
resolve: null,
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {{ multiple?: boolean, title?: string, contextPaths?: string[] }} options
|
||||
* @returns {Promise<Array<{id: number, path: string, url: string, alt: string, caption: string, width: number, height: number}> | null>}
|
||||
*/
|
||||
function pick(options = {}) {
|
||||
state.resolve?.(null);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
Object.assign(state, {
|
||||
multiple: !!options.multiple,
|
||||
title: options.title ?? '',
|
||||
contextPaths: options.contextPaths ?? defaults.contextPaths?.() ?? [],
|
||||
resolve,
|
||||
open: true,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function finish(items) {
|
||||
const resolve = state.resolve;
|
||||
state.resolve = null;
|
||||
state.open = false;
|
||||
resolve?.(items);
|
||||
}
|
||||
|
||||
return { state, pick, finish };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue