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
|
|
@ -31,10 +31,13 @@ class Editorial
|
|||
unset($this->sections[$key]);
|
||||
}
|
||||
|
||||
public function visibleFor(User $user): bool
|
||||
/**
|
||||
* @param string|null $except diesen Abschnitt nicht mitprüfen (verhindert Zirkelschlüsse, z. B. „media“)
|
||||
*/
|
||||
public function visibleFor(User $user, ?string $except = null): bool
|
||||
{
|
||||
foreach ($this->sections as $section) {
|
||||
if (($section['visible'])($user)) {
|
||||
foreach ($this->sections as $key => $section) {
|
||||
if ($key !== $except && ($section['visible'])($user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
232
app/Http/Controllers/MediaController.php
Normal file
232
app/Http/Controllers/MediaController.php
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\Media;
|
||||
use App\Models\MediaUsage;
|
||||
use App\Models\User;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\File;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* Mediathek im Portal (Redaktion) und JSON-Schnittstelle der Bildauswahl.
|
||||
* Benutzen und Hochladen: „media.use“, Ersetzen und Löschen: „media.manage“.
|
||||
*/
|
||||
class MediaController extends Controller
|
||||
{
|
||||
public const PER_PAGE = 48;
|
||||
|
||||
public function __construct(private readonly MediaLibrary $library, private readonly MediaUsages $usages) {}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return Inertia::render('Media/Index', [
|
||||
'filters' => (object) $request->only(['q', 'von', 'zeitraum', 'status', 'in']),
|
||||
'uploaders' => User::query()->whereIn('id', Media::query()->whereNotNull('uploaded_by')->distinct()->select('uploaded_by'))
|
||||
->orderBy('last_name')->orderBy('first_name')->get()->map(fn (User $user) => ['value' => (string) $user->id, 'label' => $user->name])->values(),
|
||||
'sources' => collect($this->usages->labels())->map(fn (string $label, string $type) => ['value' => $type, 'label' => $label])->values(),
|
||||
'canManage' => $request->user()->can('media.manage'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function list(Request $request): JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'von' => ['nullable', 'integer'],
|
||||
'zeitraum' => ['nullable', Rule::in(['7', '30', '365'])],
|
||||
'status' => ['nullable', Rule::in(['unbenutzt', 'verwendet'])],
|
||||
'in' => ['nullable', 'string', 'max:60'],
|
||||
'sortierung' => ['nullable', Rule::in(['neu', 'verwendet', 'name'])],
|
||||
'pfade' => ['nullable', 'array', 'max:500'],
|
||||
'pfade.*' => ['string', 'max:255'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
]);
|
||||
|
||||
$query = Media::query()->with('uploader:id,name')->withCount('usages');
|
||||
$this->applyFilters($query, $filters);
|
||||
|
||||
$page = $query->simplePaginate(self::PER_PAGE);
|
||||
|
||||
return response()->json([
|
||||
'items' => $page->getCollection()->map(fn (Media $media) => $media->toLibraryArray())->values(),
|
||||
'next_page' => $page->hasMorePages() ? $page->currentPage() + 1 : null,
|
||||
'total' => $page->currentPage() === 1 ? $this->countFor($filters) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
|
||||
|
||||
$media = $this->library->store($request->file('image'), MediaLibrary::DIRECTORY, $request->user());
|
||||
$media->load('uploader:id,name')->loadCount('usages');
|
||||
|
||||
return response()->json(['media' => $media->toLibraryArray()], 201);
|
||||
}
|
||||
|
||||
public function show(Media $media): JsonResponse
|
||||
{
|
||||
$media->load('uploader:id,name')->loadCount('usages');
|
||||
$labels = $this->usages->labels();
|
||||
|
||||
return response()->json([
|
||||
'media' => $media->toLibraryArray(),
|
||||
'usages' => $media->usages()->orderBy('draft')->orderBy('source_type')->orderBy('label')->get()->map(fn (MediaUsage $usage) => [
|
||||
'id' => $usage->id,
|
||||
'type' => $usage->source_type,
|
||||
'type_label' => $labels[$usage->source_type] ?? $usage->source_type,
|
||||
'context' => $usage->context,
|
||||
'label' => $usage->label,
|
||||
'url' => $usage->url,
|
||||
'draft' => $usage->draft,
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Media $media): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'alt' => ['nullable', 'string', 'max:300'],
|
||||
'caption' => ['nullable', 'string', 'max:500'],
|
||||
'tags' => ['nullable', 'array', 'max:20'],
|
||||
'tags.*' => ['string', 'max:40'],
|
||||
]);
|
||||
|
||||
$tags = isset($data['tags']) ? array_values(array_unique(array_filter(array_map(fn ($tag) => trim((string) $tag), $data['tags'])))) : ($media->tags ?? []);
|
||||
|
||||
$media->forceFill([
|
||||
'alt' => array_key_exists('alt', $data) ? (trim((string) $data['alt']) ?: null) : $media->alt,
|
||||
'caption' => array_key_exists('caption', $data) ? (trim((string) $data['caption']) ?: null) : $media->caption,
|
||||
'tags' => $tags ?: null,
|
||||
]);
|
||||
|
||||
// Nur Metadaten: updated_at nicht anfassen, sonst ändern sich alle Bildadressen („?v=“).
|
||||
Media::withoutTimestamps(fn () => $media->save());
|
||||
|
||||
return response()->json(['media' => $media->loadCount('usages')->load('uploader:id,name')->toLibraryArray()]);
|
||||
}
|
||||
|
||||
public function replace(Request $request, Media $media): JsonResponse
|
||||
{
|
||||
Gate::authorize('media.manage');
|
||||
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
|
||||
|
||||
$this->library->replace($media, $request->file('image'));
|
||||
Audit::log('media.replaced', ['media' => $media->id, 'path' => $media->path]);
|
||||
|
||||
return response()->json(['media' => $media->loadCount('usages')->load('uploader:id,name')->toLibraryArray()]);
|
||||
}
|
||||
|
||||
public function destroy(Media $media): JsonResponse
|
||||
{
|
||||
Gate::authorize('media.manage');
|
||||
|
||||
$usages = $media->usages()->count();
|
||||
$this->library->delete($media);
|
||||
Audit::log('media.deleted', ['media' => $media->id, 'path' => $media->path, 'usages' => $usages]);
|
||||
|
||||
return response()->json(['deleted' => 1]);
|
||||
}
|
||||
|
||||
public function bulkDestroy(Request $request): JsonResponse
|
||||
{
|
||||
Gate::authorize('media.manage');
|
||||
$data = $request->validate([
|
||||
'ids' => ['required', 'array', 'max:500'],
|
||||
'ids.*' => ['integer'],
|
||||
'only_unused' => ['boolean'],
|
||||
]);
|
||||
|
||||
$deleted = 0;
|
||||
|
||||
Media::query()->whereIn('id', $data['ids'])
|
||||
->when($data['only_unused'] ?? false, fn (Builder $q) => $q->doesntHave('usages'))
|
||||
->get()->each(function (Media $media) use (&$deleted) {
|
||||
$this->library->delete($media);
|
||||
$deleted++;
|
||||
});
|
||||
|
||||
Audit::log('media.bulk_deleted', ['count' => $deleted]);
|
||||
|
||||
return response()->json(['deleted' => $deleted]);
|
||||
}
|
||||
|
||||
public function download(Media $media): StreamedResponse
|
||||
{
|
||||
$disk = Storage::disk($media->disk ?: MediaLibrary::DISK);
|
||||
abort_unless($disk->exists($media->path), 404);
|
||||
|
||||
$extension = pathinfo($media->path, PATHINFO_EXTENSION);
|
||||
$name = pathinfo($media->displayName(), PATHINFO_FILENAME) ?: 'bild';
|
||||
|
||||
return $disk->download($media->path, $name.'.'.$extension);
|
||||
}
|
||||
|
||||
public function rebuild(): JsonResponse
|
||||
{
|
||||
Gate::authorize('media.manage');
|
||||
|
||||
$result = $this->library->rebuild();
|
||||
Audit::log('media.rebuilt', $result);
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Media> $query
|
||||
* @param array<string, mixed> $filters
|
||||
*/
|
||||
private function applyFilters(Builder $query, array $filters, bool $sort = true): void
|
||||
{
|
||||
if ($term = trim((string) ($filters['q'] ?? ''))) {
|
||||
$like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $term).'%';
|
||||
$query->where(fn (Builder $q) => $q
|
||||
->where('original_name', 'like', $like)
|
||||
->orWhere('alt', 'like', $like)
|
||||
->orWhere('caption', 'like', $like)
|
||||
->orWhere('tags', 'like', $like)
|
||||
->orWhere('path', 'like', $like));
|
||||
}
|
||||
|
||||
$query->when($filters['von'] ?? null, fn (Builder $q, $id) => $q->where('uploaded_by', $id))
|
||||
->when($filters['zeitraum'] ?? null, fn (Builder $q, $days) => $q->where('created_at', '>=', now()->subDays((int) $days)))
|
||||
->when(($filters['status'] ?? null) === 'unbenutzt', fn (Builder $q) => $q->doesntHave('usages'))
|
||||
->when(($filters['status'] ?? null) === 'verwendet', fn (Builder $q) => $q->has('usages'))
|
||||
->when($filters['in'] ?? null, fn (Builder $q, $type) => $q->whereHas('usages', fn (Builder $u) => $u->where('source_type', $type)))
|
||||
->when(array_key_exists('pfade', $filters), fn (Builder $q) => $q->whereIn('path', $filters['pfade'] ?: ['']));
|
||||
|
||||
if (! $sort) {
|
||||
return;
|
||||
}
|
||||
|
||||
match ($filters['sortierung'] ?? 'neu') {
|
||||
// Zuletzt verwendet: jüngste Einbindung zuerst (wird bei jedem Speichern der Quelle neu erfasst)
|
||||
'verwendet' => $query->orderByDesc(MediaUsage::query()->selectRaw('MAX(created_at)')->whereColumn('media_usages.media_id', 'media.id'))->orderByDesc('id'),
|
||||
'name' => $query->orderBy('original_name')->orderBy('id'),
|
||||
default => $query->orderByDesc('id'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $filters
|
||||
*/
|
||||
private function countFor(array $filters): int
|
||||
{
|
||||
$query = Media::query();
|
||||
$this->applyFilters($query, $filters, false);
|
||||
|
||||
return $query->count();
|
||||
}
|
||||
}
|
||||
29
app/Media/EditorialMedia.php
Normal file
29
app/Media/EditorialMedia.php
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Media;
|
||||
|
||||
use App\Models\Media;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* „Redaktion → Mediathek“: Überblick mit den neuesten Bildern.
|
||||
*/
|
||||
final class EditorialMedia
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function props(User $user): array
|
||||
{
|
||||
return [
|
||||
'total' => Media::query()->count(),
|
||||
'unused' => $user->can('media.manage') ? Media::query()->doesntHave('usages')->count() : null,
|
||||
'recent' => Media::query()->latest('id')->limit(8)->get()->map(fn (Media $media) => [
|
||||
'id' => $media->id,
|
||||
'name' => $media->displayName(),
|
||||
'alt' => $media->alt ?? '',
|
||||
'thumb_url' => $media->url('thumb'),
|
||||
])->all(),
|
||||
];
|
||||
}
|
||||
}
|
||||
148
app/Media/ImagePaths.php
Normal file
148
app/Media/ImagePaths.php
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
<?php
|
||||
|
||||
namespace App\Media;
|
||||
|
||||
use App\Pagebuilder\Blocks;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Findet Bildpfade im Speicher „uploads“ in Inhalten: in Pagebuilder-JSON
|
||||
* (jeder String, der wie ein Upload-Pfad aussieht) und in HTML
|
||||
* (src="/uploads/…"). Grundlage für „Eingebunden in“ der Mediathek.
|
||||
*/
|
||||
final class ImagePaths
|
||||
{
|
||||
/** Bezeichnung der Stelle je Blockart. */
|
||||
public const BLOCK_CONTEXTS = [
|
||||
'image' => 'Bild-Block',
|
||||
'gallery' => 'Galerie',
|
||||
'hero' => 'Hero',
|
||||
'text' => 'Im Text',
|
||||
];
|
||||
|
||||
public const HTML_CONTEXT = 'Im Text';
|
||||
|
||||
/**
|
||||
* Sieht der Wert wie ein Bildpfad im Upload-Speicher aus (relativ, ohne „..“)?
|
||||
*/
|
||||
public static function isCandidate(mixed $value): bool
|
||||
{
|
||||
return is_string($value)
|
||||
&& strlen($value) <= 255
|
||||
&& preg_match('#^[A-Za-z0-9_-][A-Za-z0-9/_.\-]*\.(webp|jpe?g|png|gif)$#i', $value) === 1
|
||||
&& ! str_contains($value, '..')
|
||||
&& ! str_contains($value, '//');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfade aus src-Attributen, die auf den Upload-Speicher zeigen.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function fromHtml(?string $html): array
|
||||
{
|
||||
if (! $html || ! str_contains($html, '<img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
preg_match_all('/\ssrc\s*=\s*(["\'])(.*?)\1/i', $html, $matches);
|
||||
$paths = [];
|
||||
|
||||
foreach ($matches[2] as $src) {
|
||||
if ($path = self::fromUrl(html_entity_decode($src))) {
|
||||
$paths[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
// Anhänge des Filament-Editors: <img data-id="news/inline/…">
|
||||
preg_match_all('/\sdata-id\s*=\s*(["\'])(.*?)\1/i', $html, $ids);
|
||||
|
||||
foreach ($ids[2] as $id) {
|
||||
if (self::isCandidate($id = html_entity_decode($id))) {
|
||||
$paths[] = $id;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($paths));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad im Upload-Speicher zu einer Adresse („/uploads/news/a.webp?v=1“), sonst null.
|
||||
*/
|
||||
public static function fromUrl(string $url): ?string
|
||||
{
|
||||
$parts = parse_url(trim($url));
|
||||
|
||||
if ($parts === false || ! isset($parts['path'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($parts['host'])) {
|
||||
$ownHost = parse_url((string) Storage::disk('uploads')->url(''), PHP_URL_HOST);
|
||||
|
||||
if ($ownHost && strcasecmp($parts['host'], $ownHost) !== 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$position = strpos($parts['path'], '/uploads/');
|
||||
|
||||
if ($position === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = rawurldecode(substr($parts['path'], $position + strlen('/uploads/')));
|
||||
|
||||
return self::isCandidate($path) ? $path : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Bildpfade eines Pagebuilder-Inhalts, gruppiert nach Stelle
|
||||
* („Bild-Block“, „Galerie“, „Hero“, „Im Text“ oder die Blockbezeichnung).
|
||||
*
|
||||
* @param array<mixed>|null $content
|
||||
* @return array<string, list<string>> Stelle => Pfade
|
||||
*/
|
||||
public static function fromContent(?array $content): array
|
||||
{
|
||||
$result = [];
|
||||
$blocks = app(Blocks::class);
|
||||
|
||||
$walkBlocks = function (mixed $list, int $depth) use (&$walkBlocks, &$result, $blocks): void {
|
||||
if (! is_array($list) || $depth > 10) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($list as $block) {
|
||||
if (! is_array($block)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = (string) ($block['type'] ?? '');
|
||||
$context = self::BLOCK_CONTEXTS[$type] ?? ($blocks->get($type)?->label ?? 'Inhalt');
|
||||
|
||||
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
|
||||
|
||||
array_walk_recursive($data, function ($value) use (&$result, $context) {
|
||||
if (self::isCandidate($value)) {
|
||||
$result[$context][] = $value;
|
||||
} elseif (is_string($value) && str_contains($value, '<')) {
|
||||
foreach (self::fromHtml($value) as $path) {
|
||||
$result[self::HTML_CONTEXT][] = $path;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
foreach ((array) ($block['items'] ?? []) as $item) {
|
||||
$walkBlocks(is_array($item) ? ($item['blocks'] ?? []) : [], $depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (is_array($content)) {
|
||||
$walkBlocks($content['blocks'] ?? [], 1);
|
||||
}
|
||||
|
||||
return array_map(fn (array $paths) => array_values(array_unique($paths)), $result);
|
||||
}
|
||||
}
|
||||
189
app/Media/MediaLibrary.php
Normal file
189
app/Media/MediaLibrary.php
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
<?php
|
||||
|
||||
namespace App\Media;
|
||||
|
||||
use App\Models\Media;
|
||||
use App\Models\User;
|
||||
use App\Support\Images;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Mediathek: jedes hochgeladene Bild wird hier als App\Models\Media erfasst.
|
||||
* Inhalte speichern weiterhin den Pfad im Speicher „uploads“ – deshalb
|
||||
* ersetzt replace() die Datei am selben Pfad, und jede Einbindung zeigt sofort
|
||||
* das neue Bild.
|
||||
*/
|
||||
class MediaLibrary
|
||||
{
|
||||
public const DISK = 'uploads';
|
||||
|
||||
/** Verzeichnis für Uploads direkt in der Mediathek bzw. über die Bildauswahl. */
|
||||
public const DIRECTORY = 'mediathek';
|
||||
|
||||
public function __construct(private readonly Images $images) {}
|
||||
|
||||
/**
|
||||
* Vorhandene Datei erfassen (idempotent über den Pfad).
|
||||
*
|
||||
* @param array{original_name?: string|null, alt?: string|null, caption?: string|null, tags?: list<string>|null, created_at?: mixed} $meta
|
||||
*/
|
||||
public function register(string $path, array $meta = [], ?User $user = null): Media
|
||||
{
|
||||
$existing = Media::query()->where('path', $path)->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
...$this->fileInfo($path),
|
||||
'disk' => self::DISK,
|
||||
'path' => $path,
|
||||
'original_name' => isset($meta['original_name']) ? Str::limit((string) $meta['original_name'], 250, '') : null,
|
||||
'alt' => $meta['alt'] ?? null,
|
||||
'caption' => $meta['caption'] ?? null,
|
||||
'tags' => $meta['tags'] ?? null,
|
||||
'uploaded_by' => $user?->id,
|
||||
];
|
||||
|
||||
try {
|
||||
$media = new Media($attributes);
|
||||
|
||||
if (isset($meta['created_at'])) {
|
||||
$media->created_at = Carbon::parse($meta['created_at']);
|
||||
}
|
||||
|
||||
$media->save();
|
||||
|
||||
return $media;
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
// Gleichzeitig von einer anderen Anfrage erfasst.
|
||||
return Media::query()->where('path', $path)->firstOrFail();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfade auf Mediathek-IDs abbilden; vorhandene, noch unbekannte Bilddateien
|
||||
* werden dabei erfasst (z. B. aus Admin-Formularen oder älteren Versionen).
|
||||
*
|
||||
* @param list<string> $paths
|
||||
* @return array<string, int> Pfad => Media-ID
|
||||
*/
|
||||
public function ensureRegistered(array $paths): array
|
||||
{
|
||||
$paths = array_values(array_filter(array_unique($paths), fn ($path) => ImagePaths::isCandidate($path)));
|
||||
|
||||
if ($paths === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$known = Media::query()->whereIn('path', $paths)->pluck('id', 'path')->all();
|
||||
$disk = Storage::disk(self::DISK);
|
||||
$user = Auth::user();
|
||||
|
||||
foreach (array_diff($paths, array_keys($known)) as $path) {
|
||||
if (! $disk->exists($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$modified = @filemtime($disk->path($path));
|
||||
$known[$path] = $this->register($path, ['created_at' => $modified ? Carbon::createFromTimestamp($modified) : null], $user instanceof User ? $user : null)->id;
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
return $known;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload speichern (höchstens 2000 px breit, WebP; GIFs unverändert) und erfassen.
|
||||
*/
|
||||
public function store(UploadedFile $file, string $directory = self::DIRECTORY, ?User $user = null, array $meta = []): Media
|
||||
{
|
||||
$name = $file->getClientOriginalName();
|
||||
$path = $this->images->storeContentImage($file, trim($directory, '/'));
|
||||
|
||||
// Vorschaubild für Mediathek und Bildauswahl
|
||||
$this->images->createVariants($path, ['thumb']);
|
||||
|
||||
return $this->register($path, ['original_name' => $name, ...$meta], $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei austauschen – Pfad, Alternativtext und alle Einbindungen bleiben.
|
||||
*/
|
||||
public function replace(Media $media, UploadedFile $file): Media
|
||||
{
|
||||
$name = $file->getClientOriginalName();
|
||||
$this->images->overwrite($media->path, $file);
|
||||
|
||||
if (! Storage::disk(self::DISK)->exists($this->images->variantPath($media->path, 'thumb'))) {
|
||||
$this->images->createVariants($media->path, ['thumb']);
|
||||
}
|
||||
|
||||
$media->forceFill([...$this->fileInfo($media->path), 'original_name' => Str::limit($name, 250, ''), 'updated_at' => now()])->save();
|
||||
|
||||
return $media;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bild samt Varianten löschen. Einbindungen zeigen danach ihren Platzhalter.
|
||||
*/
|
||||
public function delete(Media $media): void
|
||||
{
|
||||
$this->images->deleteWithVariants($media->path);
|
||||
$media->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei über ihren Pfad entfernen – mit Eintrag in der Mediathek, falls vorhanden.
|
||||
*/
|
||||
public function deletePath(string $path): void
|
||||
{
|
||||
$media = Media::query()->where('path', $path)->first();
|
||||
$media ? $this->delete($media) : $this->images->deleteWithVariants($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bereits verwendete Bilder übernehmen und alle Verwendungen neu erfassen.
|
||||
*
|
||||
* @return array{sources: int, media: int}
|
||||
*/
|
||||
public function rebuild(): array
|
||||
{
|
||||
@set_time_limit(0);
|
||||
|
||||
$sources = app(MediaUsages::class)->rebuild();
|
||||
|
||||
return ['sources' => $sources, 'media' => Media::query()->count()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{mime: string|null, size: int|null, width: int|null, height: int|null}
|
||||
*/
|
||||
private function fileInfo(string $path): array
|
||||
{
|
||||
$disk = Storage::disk(self::DISK);
|
||||
|
||||
if (! $disk->exists($path)) {
|
||||
return ['mime' => null, 'size' => null, 'width' => null, 'height' => null];
|
||||
}
|
||||
|
||||
$size = @getimagesize($disk->path($path));
|
||||
|
||||
return [
|
||||
'mime' => $size['mime'] ?? ($disk->mimeType($path) ?: null),
|
||||
'size' => $disk->size($path),
|
||||
'width' => $size[0] ?? null,
|
||||
'height' => $size[1] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
198
app/Media/MediaUsages.php
Normal file
198
app/Media/MediaUsages.php
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
<?php
|
||||
|
||||
namespace App\Media;
|
||||
|
||||
use App\Models\MediaUsage;
|
||||
use Illuminate\Contracts\Events\Dispatcher;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Registry „Wo ist das Bild eingebunden?“. Kern und Plugins melden ihre
|
||||
* Quellen an (Seiten, Neuigkeiten, Termine …):
|
||||
*
|
||||
* $usages->add('news', 'Neuigkeiten',
|
||||
* scan: fn (NewsPost $post) => [
|
||||
* ['context' => 'Titelbild', 'label' => $post->title, 'url' => '/…', 'draft' => false, 'paths' => [$post->cover_path]],
|
||||
* ],
|
||||
* all: fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each)),
|
||||
* );
|
||||
* $usages->watch('news', NewsPost::class, ['cover_path', 'body_html']);
|
||||
*
|
||||
* scan() liefert je Stelle Pfade im Speicher „uploads“ (ImagePaths hilft beim
|
||||
* Auslesen von Pagebuilder-JSON und HTML). Unbekannte, aber vorhandene
|
||||
* Bilddateien werden dabei automatisch in die Mediathek übernommen – so landen
|
||||
* auch Uploads aus Formularen, die die Mediathek nicht kennen, dort.
|
||||
*/
|
||||
class MediaUsages
|
||||
{
|
||||
/** @var array<string, array{label: string, scan: callable, all: callable|null}> */
|
||||
private array $sources = [];
|
||||
|
||||
private bool $ready = false;
|
||||
|
||||
public function __construct(private readonly Dispatcher $events) {}
|
||||
|
||||
/**
|
||||
* @param callable(Model): list<array{context: string, label: string, url?: string|null, draft?: bool, paths: list<string|null>, source_id?: int}> $scan
|
||||
* @param (callable(callable(Model): void): void)|null $all ruft $each für jede Quelle auf (für „Neu einlesen“)
|
||||
*/
|
||||
public function add(string $type, string $label, callable $scan, ?callable $all = null): void
|
||||
{
|
||||
$this->sources[$type] = ['label' => $label, 'scan' => $scan, 'all' => $all];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verwendungen bei jedem Speichern/Löschen des Modells aktualisieren.
|
||||
*
|
||||
* @param class-string<Model> $model
|
||||
* @param list<string> $columns nur neu berechnen, wenn sich eine dieser Spalten ändert (leer = immer)
|
||||
*/
|
||||
public function watch(string $type, string $model, array $columns = []): void
|
||||
{
|
||||
$this->events->listen("eloquent.saved: {$model}", function (Model $record) use ($type, $columns) {
|
||||
if ($columns === [] || $record->wasRecentlyCreated || $record->wasChanged($columns)) {
|
||||
$this->sync($type, $record);
|
||||
}
|
||||
});
|
||||
|
||||
$this->events->listen("eloquent.deleted: {$model}", fn (Model $record) => $this->forget($type, (int) $record->getKey()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Typ => Bezeichnung (z. B. „pages“ => „Seiten“)
|
||||
*/
|
||||
public function labels(): array
|
||||
{
|
||||
return array_map(fn (array $source) => $source['label'], $this->sources);
|
||||
}
|
||||
|
||||
public function has(string $type): bool
|
||||
{
|
||||
return isset($this->sources[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verwendungen einer Quelle neu erfassen. Fehler werden nur protokolliert –
|
||||
* Speichern von Inhalten darf nie an der Mediathek scheitern.
|
||||
*/
|
||||
public function sync(string $type, Model $record): void
|
||||
{
|
||||
if (! isset($this->sources[$type]) || ! $this->tablesReady()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$entries = ($this->sources[$type]['scan'])($record);
|
||||
$paths = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
foreach ($entry['paths'] ?? [] as $path) {
|
||||
if (is_string($path) && $path !== '') {
|
||||
$paths[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$ids = app(MediaLibrary::class)->ensureRegistered(array_values(array_unique($paths)));
|
||||
$rows = [];
|
||||
$now = now();
|
||||
|
||||
// Nicht-Entwürfe zuerst, damit dieselbe Stelle nicht doppelt als Entwurf erscheint.
|
||||
usort($entries, fn (array $a, array $b) => (int) ($a['draft'] ?? false) <=> (int) ($b['draft'] ?? false));
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
foreach (array_unique(array_filter((array) ($entry['paths'] ?? []), 'is_string')) as $path) {
|
||||
if (! isset($ids[$path])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sourceId = (int) ($entry['source_id'] ?? $record->getKey());
|
||||
$key = $ids[$path].'|'.$sourceId.'|'.$entry['context'];
|
||||
|
||||
if (isset($rows[$key])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[$key] = [
|
||||
'media_id' => $ids[$path],
|
||||
'source_type' => $type,
|
||||
'source_id' => $sourceId,
|
||||
'context' => mb_substr((string) $entry['context'], 0, 80),
|
||||
'label' => mb_substr((string) ($entry['label'] ?? ''), 0, 250),
|
||||
'url' => isset($entry['url']) ? mb_substr((string) $entry['url'], 0, 1000) : null,
|
||||
'draft' => (bool) ($entry['draft'] ?? false),
|
||||
'created_at' => $now,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($type, $record, $rows) {
|
||||
MediaUsage::query()->where('source_type', $type)->where('source_id', $record->getKey())->delete();
|
||||
|
||||
foreach (array_chunk(array_values($rows), 200) as $chunk) {
|
||||
MediaUsage::query()->insert($chunk);
|
||||
}
|
||||
});
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
public function forget(string $type, int $id): void
|
||||
{
|
||||
if (! $this->tablesReady()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
MediaUsage::query()->where('source_type', $type)->where('source_id', $id)->delete();
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Verwendungen neu erfassen (dabei referenzierte Dateien übernehmen).
|
||||
*
|
||||
* @return int Anzahl der durchsuchten Quellen
|
||||
*/
|
||||
public function rebuild(): int
|
||||
{
|
||||
if (! $this->tablesReady()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
|
||||
// Verwendungen von Quellen, die es nicht mehr gibt (z. B. Plugin entfernt), fallen weg.
|
||||
MediaUsage::query()->whereNotIn('source_type', array_keys($this->sources) ?: [''])->delete();
|
||||
|
||||
foreach ($this->sources as $type => $source) {
|
||||
if (! $source['all']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
MediaUsage::query()->where('source_type', $type)->delete();
|
||||
|
||||
($source['all'])(function (Model $record) use ($type, &$count) {
|
||||
$this->sync($type, $record);
|
||||
$count++;
|
||||
});
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
private function tablesReady(): bool
|
||||
{
|
||||
// Nur „ja“ merken: Während eines Updates entstehen die Tabellen erst mittendrin.
|
||||
return $this->ready = $this->ready || Schema::hasTable('media_usages');
|
||||
}
|
||||
}
|
||||
|
|
@ -3,12 +3,12 @@
|
|||
namespace App\Models;
|
||||
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Support\Images;
|
||||
use App\Support\Permissions\Audiences;
|
||||
use App\Support\RichText;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Eigene Kachel auf der Startseite („Administration → Portal → Startseite“).
|
||||
|
|
@ -46,7 +46,7 @@ class DashboardTile extends Model
|
|||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (DashboardTile $tile) => $tile->image_path && Storage::disk('uploads')->delete($tile->image_path));
|
||||
// Das Bild bleibt in der Mediathek (evtl. auch anderswo eingebunden) – aufräumen lässt es sich dort.
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
|
|
@ -82,7 +82,7 @@ class DashboardTile extends Model
|
|||
'tile' => [
|
||||
'type' => $this->type,
|
||||
'title' => $this->title,
|
||||
'image_url' => $this->image_path ? Storage::disk('uploads')->url($this->image_path) : null,
|
||||
'image_url' => app(Images::class)->url($this->image_path, null),
|
||||
'url' => $this->url,
|
||||
'new_tab' => $this->new_tab,
|
||||
'alt' => $this->alt ?: '',
|
||||
|
|
|
|||
98
app/Models/Media.php
Normal file
98
app/Models/Media.php
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Images;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Ein Bild der Mediathek. Eingebunden wird es überall über seinen Pfad im
|
||||
* Speicher „uploads“ – Inhalte speichern weiterhin den Pfad, nicht die ID.
|
||||
*/
|
||||
#[Fillable(['disk', 'path', 'original_name', 'mime', 'size', 'width', 'height', 'alt', 'caption', 'tags', 'uploaded_by'])]
|
||||
class Media extends Model
|
||||
{
|
||||
protected $table = 'media';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'tags' => 'array',
|
||||
'size' => 'integer',
|
||||
'width' => 'integer',
|
||||
'height' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function uploader(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'uploaded_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<MediaUsage, $this>
|
||||
*/
|
||||
public function usages(): HasMany
|
||||
{
|
||||
return $this->hasMany(MediaUsage::class);
|
||||
}
|
||||
|
||||
public function fileExists(): bool
|
||||
{
|
||||
return Storage::disk($this->disk ?: 'uploads')->exists($this->path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse des Bilds – null, wenn die Datei fehlt.
|
||||
*
|
||||
* @param string|null $variant „thumb“, „large“ oder null für das Original
|
||||
*/
|
||||
public function url(?string $variant = null): ?string
|
||||
{
|
||||
// „?v=“ folgt dem Änderungszeitpunkt der Datei (Ersetzen setzt ihn weiter) – so
|
||||
// haben Mediathek, Seiten und Beiträge dieselbe Adresse und teilen sich den Cache.
|
||||
return app(Images::class)->url($this->path, $variant);
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return $this->original_name ?: basename($this->path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Für Mediathek und Bildauswahl.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toLibraryArray(): array
|
||||
{
|
||||
$url = $this->url();
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'path' => $this->path,
|
||||
'url' => $url,
|
||||
'thumb_url' => $url ? $this->url('thumb') : null,
|
||||
'name' => $this->displayName(),
|
||||
'alt' => $this->alt ?? '',
|
||||
'caption' => $this->caption ?? '',
|
||||
'tags' => $this->tags ?? [],
|
||||
'mime' => $this->mime,
|
||||
'size' => $this->size,
|
||||
'width' => $this->width,
|
||||
'height' => $this->height,
|
||||
'missing' => $url === null,
|
||||
'uploader' => $this->relationLoaded('uploader') && $this->uploader ? ['id' => $this->uploader->id, 'name' => $this->uploader->name] : null,
|
||||
'usage_count' => $this->usages_count ?? null,
|
||||
'created_at' => $this->created_at?->toIso8601String(),
|
||||
'updated_at' => $this->updated_at?->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
34
app/Models/MediaUsage.php
Normal file
34
app/Models/MediaUsage.php
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* „Eingebunden in“: eine Stelle, an der ein Bild der Mediathek verwendet wird.
|
||||
* Wird von App\Media\MediaUsages bei jedem Speichern der Quelle neu berechnet.
|
||||
*/
|
||||
#[Fillable(['media_id', 'source_type', 'source_id', 'context', 'label', 'url', 'draft', 'created_at'])]
|
||||
class MediaUsage extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'draft' => 'boolean',
|
||||
'source_id' => 'integer',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Media, $this>
|
||||
*/
|
||||
public function media(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Media::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ namespace App\Pagebuilder;
|
|||
use App\Http\Resources\PersonResource;
|
||||
use App\Models\User;
|
||||
use App\Plugins\Hooks;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use App\Support\Images;
|
||||
|
||||
/**
|
||||
* Registry der Pagebuilder-Blöcke. Der Kern bringt Layout- und Inhaltsblöcke
|
||||
|
|
@ -66,9 +66,13 @@ class Blocks
|
|||
return array_values(array_map(fn (BlockType $type) => $type->toArray(), $this->all()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse eines Bilds – null, wenn die Datei fehlt (z. B. in der Mediathek
|
||||
* gelöscht): Der Block zeigt dann seinen Platzhalter.
|
||||
*/
|
||||
public static function imageUrl(?string $path): ?string
|
||||
{
|
||||
return $path ? Storage::disk('uploads')->url($path) : null;
|
||||
return app(Images::class)->url($path, null);
|
||||
}
|
||||
|
||||
private function registerLayout(): void
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace App\Pagebuilder;
|
||||
|
||||
use App\Media\ImagePaths;
|
||||
use App\Models\User;
|
||||
use App\Plugins\PluginAccess;
|
||||
use App\Support\Permissions\Audiences;
|
||||
|
|
@ -138,7 +139,7 @@ class Content
|
|||
$texts = [];
|
||||
|
||||
array_walk_recursive($block['data'], function ($value) use (&$texts) {
|
||||
if (is_string($value) && ! str_starts_with($value, 'pagebuilder/')) {
|
||||
if (is_string($value) && ! ImagePaths::isCandidate($value)) {
|
||||
$texts[] = strip_tags($value);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace App\Pagebuilder;
|
||||
|
||||
use App\Media\ImagePaths;
|
||||
use App\Support\Icons;
|
||||
use App\Support\RichText;
|
||||
use Closure;
|
||||
|
|
@ -62,7 +63,7 @@ final class Field
|
|||
return new self($name, 'url', $label, ['default' => $default]);
|
||||
}
|
||||
|
||||
/** Hochgeladenes Bild (Pfad im Upload-Speicher). */
|
||||
/** Hochgeladenes Bild bzw. Bild aus der Mediathek (Pfad im Upload-Speicher). */
|
||||
public static function image(string $name, string $label): self
|
||||
{
|
||||
return new self($name, 'image', $label, ['default' => null]);
|
||||
|
|
@ -140,7 +141,7 @@ final class Field
|
|||
'toggle' => (bool) $value,
|
||||
'number' => max($this->options['min'], min($this->options['max'], is_numeric($value) ? (int) $value : $this->options['default'])),
|
||||
'url' => self::safeUrl($value),
|
||||
'image' => is_string($value) && preg_match('#^pagebuilder/[A-Za-z0-9/_.-]+$#', $value) && ! str_contains($value, '..') ? $value : null,
|
||||
'image' => ImagePaths::isCandidate($value) ? $value : null,
|
||||
'people', 'ids' => array_values(array_slice(array_unique(array_filter(array_map('intval', is_array($value) ? $value : []))), 0, $this->options['max'])),
|
||||
'table' => $this->sanitizeTable($value),
|
||||
'icon' => Icons::has($value) ? $value : $this->options['default'],
|
||||
|
|
|
|||
|
|
@ -7,6 +7,11 @@ use App\Dashboard\Widgets;
|
|||
use App\Editorial\Editorial;
|
||||
use App\Identity\Entra\EntraDriver;
|
||||
use App\Identity\IdentityDrivers;
|
||||
use App\Media\EditorialMedia;
|
||||
use App\Media\ImagePaths;
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\DashboardTile;
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
|
|
@ -69,6 +74,8 @@ class AppServiceProvider extends ServiceProvider
|
|||
return $drivers;
|
||||
});
|
||||
$this->app->singleton(Editorial::class);
|
||||
$this->app->singleton(MediaUsages::class);
|
||||
$this->app->singleton(MediaLibrary::class);
|
||||
$this->app->singleton(BackgroundTasks::class);
|
||||
$this->app->singleton(InstalledVersion::class);
|
||||
$this->app->singleton(UpdateProgress::class);
|
||||
|
|
@ -79,9 +86,11 @@ class AppServiceProvider extends ServiceProvider
|
|||
{
|
||||
CoreWidgets::register($this->app->make(Widgets::class));
|
||||
|
||||
$this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder'], sort: 85,
|
||||
$this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder', 'media.*'], sort: 85,
|
||||
visible: fn (User $user) => $this->app->make(Editorial::class)->visibleFor($user));
|
||||
|
||||
$this->registerMedia();
|
||||
|
||||
// N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance).
|
||||
Model::preventLazyLoading(! $this->app->isProduction());
|
||||
|
||||
|
|
@ -115,4 +124,30 @@ class AppServiceProvider extends ServiceProvider
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mediathek: Zugang für alle, die in der Redaktion arbeiten, Abschnitt in der
|
||||
* Redaktion und die Startseiten-Kacheln als Quelle für „Eingebunden in“.
|
||||
*/
|
||||
private function registerMedia(): void
|
||||
{
|
||||
$editorial = $this->app->make(Editorial::class);
|
||||
|
||||
// Bildauswahl und Hochladen: wer irgendwo in der Redaktion arbeitet (Seiten, Beiträge …) oder die Mediathek verwaltet.
|
||||
Gate::define('media.use', fn (User $user) => $user->can('media.manage') || $editorial->visibleFor($user, except: 'media'));
|
||||
|
||||
// Abschnitt nur neben anderen Redaktionsbereichen – sonst erschiene „Redaktion“ ohne Inhalte.
|
||||
$editorial->add('media', 'Mediathek', 'core::EditorialMedia', 90,
|
||||
fn (User $user) => $editorial->visibleFor($user, except: 'media'),
|
||||
fn (User $user) => EditorialMedia::props($user));
|
||||
|
||||
$usages = $this->app->make(MediaUsages::class);
|
||||
$usages->add('dashboard_tiles', 'Startseiten-Kacheln',
|
||||
fn (DashboardTile $tile) => [
|
||||
['context' => 'Kachelbild', 'label' => $tile->name ?: (string) $tile->title, 'url' => '/admin/kacheln', 'draft' => $tile->is_active === false, 'paths' => [$tile->image_path]],
|
||||
['context' => ImagePaths::HTML_CONTEXT, 'label' => $tile->name ?: (string) $tile->title, 'url' => '/admin/kacheln', 'draft' => $tile->is_active === false, 'paths' => ImagePaths::fromHtml($tile->body_html)],
|
||||
],
|
||||
fn (callable $each) => DashboardTile::query()->chunkById(100, fn ($tiles) => $tiles->each($each)));
|
||||
$usages->watch('dashboard_tiles', DashboardTile::class, ['image_path', 'body_html', 'name', 'title', 'is_active']);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,6 +57,13 @@ class AdminPanelProvider extends PanelProvider
|
|||
->url(fn () => Feedback::getUrl()),
|
||||
])
|
||||
->navigationItems([
|
||||
// Die Mediathek lebt im Portal (Redaktion) – hier nur der Weg dorthin.
|
||||
NavigationItem::make('Mediathek')
|
||||
->url('/redaktion/mediathek')
|
||||
->icon(Heroicon::OutlinedPhoto)
|
||||
->group('Inhalte')
|
||||
->sort(90)
|
||||
->visible(fn () => auth()->user()?->can('media.use') ?? false),
|
||||
NavigationItem::make('Zum Portal')
|
||||
->url('/')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ class Abilities
|
|||
$this->define('updates.manage', 'Aktualisierungen, Lizenz und Systemzustand', 'System');
|
||||
$this->define('mail.manage', 'E-Mail-Versand einrichten', 'System');
|
||||
$this->define('feedback.send', 'Rückmeldungen an den Hersteller senden', 'System');
|
||||
$this->define('media.manage', 'Mediathek verwalten: ersetzen, löschen, aufräumen', 'Mediathek');
|
||||
}
|
||||
|
||||
public function define(string $ability, string $label, string $group, ?string $resource = null): void
|
||||
|
|
|
|||
|
|
@ -2,13 +2,13 @@
|
|||
|
||||
namespace App\Support\Demo;
|
||||
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Models\DashboardTile;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Content;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Images;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\Client\Pool;
|
||||
|
|
@ -170,7 +170,7 @@ class DemoContent
|
|||
}
|
||||
|
||||
$files = 0;
|
||||
$images = app(Images::class);
|
||||
$library = app(MediaLibrary::class);
|
||||
|
||||
foreach ((array) ($state['files'] ?? []) as $file) {
|
||||
try {
|
||||
|
|
@ -180,7 +180,8 @@ class DemoContent
|
|||
$files++;
|
||||
}
|
||||
|
||||
! empty($file['image']) ? $images->deleteWithVariants((string) $file['path']) : $disk->delete((string) $file['path']);
|
||||
// Bilder samt Eintrag in der Mediathek entfernen
|
||||
! empty($file['image']) ? $library->deletePath((string) $file['path']) : $disk->delete((string) $file['path']);
|
||||
} catch (Throwable) {
|
||||
$warnings[] = "Datei {$file['path']} konnte nicht gelöscht werden.";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,9 @@ use Illuminate\Http\UploadedFile;
|
|||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Intervention\Image\Drivers\Gd\Driver;
|
||||
use Intervention\Image\Encoders\GifEncoder;
|
||||
use Intervention\Image\Encoders\JpegEncoder;
|
||||
use Intervention\Image\Encoders\PngEncoder;
|
||||
use Intervention\Image\Encoders\WebpEncoder;
|
||||
use Intervention\Image\ImageManager;
|
||||
use Throwable;
|
||||
|
|
@ -23,7 +26,10 @@ class Images
|
|||
|
||||
private const VARIANTS_LARGEST_FIRST = ['large', 'thumb'];
|
||||
|
||||
public function createVariants(string $path): void
|
||||
/**
|
||||
* @param list<string>|null $only nur diese Varianten (z. B. ['thumb'] für die Mediathek)
|
||||
*/
|
||||
public function createVariants(string $path, ?array $only = null): void
|
||||
{
|
||||
$disk = Storage::disk('uploads');
|
||||
|
||||
|
|
@ -39,6 +45,10 @@ class Images
|
|||
$image = ImageManager::usingDriver(Driver::class)->decodePath($disk->path($path));
|
||||
|
||||
foreach (self::VARIANTS_LARGEST_FIRST as $variant) {
|
||||
if ($only !== null && ! in_array($variant, $only, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$width, $height] = self::VARIANTS[$variant];
|
||||
$image->coverDown($width, $height);
|
||||
$disk->put($this->variantPath($path, $variant), $image->encode(new WebpEncoder(quality: 82))->toString());
|
||||
|
|
@ -48,12 +58,6 @@ class Images
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bild für Inhalte (Pagebuilder, Beiträge): Seitenverhältnis bleibt, höchstens
|
||||
* 2000 Pixel breit, als WebP. GIFs bleiben unverändert (Animationen).
|
||||
*
|
||||
* @return string Pfad im Speicher „uploads“
|
||||
*/
|
||||
/**
|
||||
* Führt $callback mit dem Pfad einer lokalen Kopie des Uploads aus.
|
||||
*
|
||||
|
|
@ -83,6 +87,12 @@ class Images
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bild für Inhalte (Pagebuilder, Beiträge): Seitenverhältnis bleibt, höchstens
|
||||
* 2000 Pixel breit, als WebP. GIFs bleiben unverändert (Animationen).
|
||||
*
|
||||
* @return string Pfad im Speicher „uploads“
|
||||
*/
|
||||
public function storeContentImage(UploadedFile $file, string $directory): string
|
||||
{
|
||||
$disk = Storage::disk('uploads');
|
||||
|
|
@ -104,6 +114,50 @@ class Images
|
|||
return $name.'.webp';
|
||||
}
|
||||
|
||||
/**
|
||||
* Datei an Ort und Stelle austauschen (Mediathek „Ersetzen“): Der Pfad bleibt,
|
||||
* damit jede Einbindung automatisch das neue Bild zeigt. Das Format folgt der
|
||||
* Dateiendung des bestehenden Pfads; vorhandene Varianten werden neu erzeugt.
|
||||
*/
|
||||
public function overwrite(string $path, UploadedFile $file): void
|
||||
{
|
||||
$disk = Storage::disk('uploads');
|
||||
$previous = (int) @filemtime($disk->path($path));
|
||||
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
||||
$variants = array_values(array_filter(array_keys(self::VARIANTS), fn (string $variant) => $disk->exists($this->variantPath($path, $variant))));
|
||||
|
||||
if ($extension === 'gif' && $file->getMimeType() === 'image/gif') {
|
||||
self::withLocalCopy($file, fn (string $local) => $disk->put($path, (string) file_get_contents($local)));
|
||||
} else {
|
||||
self::withLocalCopy($file, function (string $local) use ($disk, $path, $extension) {
|
||||
self::raiseMemoryLimitFor($local);
|
||||
$image = ImageManager::usingDriver(Driver::class)->decodePath($local);
|
||||
$image->scaleDown(width: 2000);
|
||||
$encoded = match ($extension) {
|
||||
'jpg', 'jpeg' => $image->encode(new JpegEncoder(quality: 85)),
|
||||
'png' => $image->encode(new PngEncoder),
|
||||
'gif' => $image->encode(new GifEncoder),
|
||||
default => $image->encode(new WebpEncoder(quality: 84)),
|
||||
};
|
||||
$disk->put($path, $encoded->toString());
|
||||
});
|
||||
}
|
||||
|
||||
if ($variants !== []) {
|
||||
$this->createVariants($path, $variants);
|
||||
}
|
||||
|
||||
// Der Änderungszeitpunkt steckt in „?v=“ der Adressen (siehe url()): muss sich
|
||||
// auch beim Ersetzen in derselben Sekunde ändern, damit Browser neu laden.
|
||||
$modified = max(time(), $previous + 1);
|
||||
|
||||
foreach ([$path, ...array_map(fn (string $variant) => $this->variantPath($path, $variant), $variants)] as $file) {
|
||||
@touch($disk->path($file), $modified);
|
||||
}
|
||||
|
||||
clearstatcache();
|
||||
}
|
||||
|
||||
public function deleteWithVariants(?string $path): void
|
||||
{
|
||||
if (! $path) {
|
||||
|
|
@ -118,16 +172,30 @@ class Images
|
|||
}
|
||||
}
|
||||
|
||||
public function url(?string $path, string $variant = 'large'): ?string
|
||||
/**
|
||||
* Öffentliche Adresse – null, wenn die Datei fehlt (z. B. in der Mediathek
|
||||
* gelöscht): Komponenten zeigen dann ihren Platzhalter statt eines kaputten Bilds.
|
||||
* „?v=“ ändert sich beim Ersetzen, damit Browser trotz langem Cache das neue Bild laden.
|
||||
*
|
||||
* @param string|null $variant null = Original
|
||||
*/
|
||||
public function url(?string $path, ?string $variant = 'large'): ?string
|
||||
{
|
||||
if (! $path) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$disk = Storage::disk('uploads');
|
||||
$variantPath = $this->variantPath($path, $variant);
|
||||
$variantPath = $variant ? $this->variantPath($path, $variant) : null;
|
||||
$file = $variantPath && $disk->exists($variantPath) ? $variantPath : $path;
|
||||
|
||||
return $disk->url($disk->exists($variantPath) ? $variantPath : $path);
|
||||
if ($file === $path && ! $disk->exists($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$modified = @filemtime($disk->path($file));
|
||||
|
||||
return $disk->url($file).($modified ? '?v='.$modified : '');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -170,7 +238,7 @@ class Images
|
|||
};
|
||||
}
|
||||
|
||||
private function variantPath(string $path, string $variant): string
|
||||
public function variantPath(string $path, string $variant): string
|
||||
{
|
||||
return preg_replace('/\.[^.\/]+$/', '', $path)."-{$variant}.webp";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Mediathek: alle hochgeladenen Bilder und wo sie eingebunden sind.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('media', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('disk', 40)->default('uploads');
|
||||
$table->string('path')->unique();
|
||||
$table->string('original_name')->nullable();
|
||||
$table->string('mime', 100)->nullable();
|
||||
$table->unsignedBigInteger('size')->nullable();
|
||||
$table->unsignedInteger('width')->nullable();
|
||||
$table->unsignedInteger('height')->nullable();
|
||||
$table->string('alt', 300)->nullable();
|
||||
$table->string('caption', 500)->nullable();
|
||||
$table->json('tags')->nullable();
|
||||
$table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('created_at');
|
||||
});
|
||||
|
||||
Schema::create('media_usages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('media_id')->constrained('media')->cascadeOnDelete();
|
||||
$table->string('source_type', 60);
|
||||
$table->unsignedBigInteger('source_id');
|
||||
$table->string('context', 80);
|
||||
$table->string('label')->nullable();
|
||||
$table->string('url', 1000)->nullable();
|
||||
$table->boolean('draft')->default(false);
|
||||
$table->timestamp('created_at')->nullable();
|
||||
|
||||
$table->index(['source_type', 'source_id']);
|
||||
$table->index(['media_id', 'created_at']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('media_usages');
|
||||
Schema::dropIfExists('media');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
use App\Media\MediaLibrary;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Bestehende Installationen: bereits verwendete Bilder in die Mediathek
|
||||
* übernehmen und die Verwendungen erfassen. Fehler brechen das Update nicht
|
||||
* ab – „php artisan media:rebuild“ bzw. „Neu einlesen“ in der Mediathek holt es nach.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
try {
|
||||
app(MediaLibrary::class)->rebuild();
|
||||
} catch (Throwable $e) {
|
||||
Log::warning('Mediathek konnte nicht eingelesen werden: '.$e->getMessage(), ['exception' => $e]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void {}
|
||||
};
|
||||
|
|
@ -3,6 +3,8 @@
|
|||
namespace Inhaus\Plugins\Events;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Media\ImagePaths;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
|
|
@ -26,6 +28,14 @@ class EventsPlugin extends Plugin
|
|||
$this->app->make(Abilities::class)->define('events.manage', 'Termine verwalten', 'Termine');
|
||||
Gate::policy(Event::class, EventPolicy::class);
|
||||
|
||||
// Mediathek „Eingebunden in“
|
||||
$usages = $this->app->make(MediaUsages::class);
|
||||
$usages->add('events', 'Termine', fn (Event $event) => [
|
||||
['context' => 'Titelbild', 'label' => $event->title, 'url' => route('events.show', $event, false), 'draft' => $event->is_published === false, 'paths' => [$event->image_path]],
|
||||
['context' => ImagePaths::HTML_CONTEXT, 'label' => $event->title, 'url' => route('events.show', $event, false), 'draft' => $event->is_published === false, 'paths' => ImagePaths::fromHtml($event->description_html)],
|
||||
], fn (callable $each) => Event::query()->chunkById(100, fn ($events) => $events->each($each)));
|
||||
$usages->watch('events', Event::class, ['image_path', 'description_html', 'title', 'is_published']);
|
||||
|
||||
$this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [
|
||||
'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(),
|
||||
], label: 'Termine', mobileSort: 30);
|
||||
|
|
|
|||
|
|
@ -34,24 +34,17 @@ class Event extends Model
|
|||
}
|
||||
});
|
||||
|
||||
// Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen.
|
||||
// Bildvarianten erzeugen. Alte Bilder bleiben in der Mediathek (sie können
|
||||
// auch anderswo eingebunden sein) und lassen sich dort als „nicht verwendet“ aufräumen.
|
||||
static::saved(function (Event $event): void {
|
||||
if (! $event->wasRecentlyCreated && ! $event->wasChanged('image_path')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = $event->wasRecentlyCreated ? null : $event->getOriginal('image_path');
|
||||
|
||||
if ($previous && $previous !== $event->image_path) {
|
||||
app(Images::class)->deleteWithVariants($previous);
|
||||
}
|
||||
|
||||
if ($event->image_path) {
|
||||
app(Images::class)->createVariants($event->image_path);
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (Event $event) => app(Images::class)->deleteWithVariants($event->image_path));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
|
|
|
|||
|
|
@ -54,24 +54,17 @@ class NewsPost extends Model
|
|||
}
|
||||
});
|
||||
|
||||
// Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen.
|
||||
// Bildvarianten erzeugen. Alte Bilder bleiben in der Mediathek (sie können
|
||||
// auch anderswo eingebunden sein) und lassen sich dort als „nicht verwendet“ aufräumen.
|
||||
static::saved(function (NewsPost $post): void {
|
||||
if (! $post->wasRecentlyCreated && ! $post->wasChanged('cover_path')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = $post->wasRecentlyCreated ? null : $post->getOriginal('cover_path');
|
||||
|
||||
if ($previous && $previous !== $post->cover_path) {
|
||||
app(Images::class)->deleteWithVariants($previous);
|
||||
}
|
||||
|
||||
if ($post->cover_path) {
|
||||
app(Images::class)->createVariants($post->cover_path);
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (NewsPost $post) => app(Images::class)->deleteWithVariants($post->cover_path));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ namespace Inhaus\Plugins\News;
|
|||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Editorial\Editorial;
|
||||
use App\Media\ImagePaths;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
|
|
@ -15,6 +17,7 @@ use App\Support\Navigation;
|
|||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
|
@ -39,6 +42,7 @@ class NewsPlugin extends Plugin
|
|||
Gate::policy(NewsPost::class, NewsPostPolicy::class);
|
||||
|
||||
$this->registerWidgets($this->app->make(Widgets::class));
|
||||
$this->registerMediaUsages($this->app->make(MediaUsages::class));
|
||||
|
||||
$this->app->make(Editorial::class)->add(
|
||||
'news',
|
||||
|
|
@ -69,6 +73,41 @@ class NewsPlugin extends Plugin
|
|||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mediathek „Eingebunden in“: Titelbild, Bilder im Text und – sobald Beiträge
|
||||
* mit dem Pagebuilder geschrieben werden – Bilder in der Spalte „content“.
|
||||
*/
|
||||
private function registerMediaUsages(MediaUsages $usages): void
|
||||
{
|
||||
$usages->add('news', 'Neuigkeiten', function (NewsPost $post) {
|
||||
$base = ['label' => $post->title, 'url' => route('news.editor.edit', $post, false), 'draft' => $post->status !== NewsPost::PUBLISHED];
|
||||
$entries = [
|
||||
[...$base, 'context' => 'Titelbild', 'paths' => [$post->cover_path]],
|
||||
[...$base, 'context' => ImagePaths::HTML_CONTEXT, 'paths' => [...ImagePaths::fromHtml($post->body_html), ...ImagePaths::fromHtml($post->body)]],
|
||||
];
|
||||
|
||||
if (self::hasContentColumn()) {
|
||||
$content = $post->getAttribute('content');
|
||||
$content = is_string($content) ? json_decode($content, true) : $content;
|
||||
|
||||
foreach (ImagePaths::fromContent(is_array($content) ? $content : null) as $context => $paths) {
|
||||
$entries[] = [...$base, 'context' => $context, 'paths' => $paths];
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}, fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each)));
|
||||
|
||||
$usages->watch('news', NewsPost::class);
|
||||
}
|
||||
|
||||
private static function hasContentColumn(): bool
|
||||
{
|
||||
static $has;
|
||||
|
||||
return $has ??= Schema::hasColumn('news_posts', 'content');
|
||||
}
|
||||
|
||||
private function registerWidgets(Widgets $widgets): void
|
||||
{
|
||||
// Slider: hervorgehobene Beiträge mit Bild, sonst die neuesten mit Bild.
|
||||
|
|
|
|||
|
|
@ -37,6 +37,9 @@ 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 MediaPickerHost from '@/components/media/MediaPickerHost.vue';
|
||||
import { collectImagePaths, uploadWithProgress } from '@/components/media/api';
|
||||
import { useMediaPicker } from '@/components/media/useMediaPicker';
|
||||
import { formatTime } from '@/lib/format';
|
||||
import PublishDialog from '../components/PublishDialog.vue';
|
||||
import RevisionsDialog from '../components/RevisionsDialog.vue';
|
||||
|
|
@ -133,14 +136,18 @@ function containsActive(item) {
|
|||
return candidates.some((block) => block.items?.includes(item) || locate(item.blocks, block.id));
|
||||
}
|
||||
|
||||
// ——— Hochladen ———
|
||||
async function uploadImage(file) {
|
||||
const body = new FormData();
|
||||
body.append('image', file);
|
||||
|
||||
return http.post(`${base}/bilder`, body);
|
||||
// ——— Hochladen und Mediathek ———
|
||||
// Bilder landen im Verzeichnis der Seite und zugleich in der Mediathek.
|
||||
async function uploadImage(file, onProgress) {
|
||||
return uploadWithProgress(`${base}/bilder`, file, { onProgress });
|
||||
}
|
||||
|
||||
const mediaPicker = useMediaPicker({
|
||||
upload: uploadImage,
|
||||
contextLabel: 'Auf dieser Seite',
|
||||
contextPaths: () => collectImagePaths(working.content),
|
||||
});
|
||||
|
||||
async function uploadFile(file) {
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
|
|
@ -170,6 +177,8 @@ provide('pagebuilder:editor', {
|
|||
containsActive,
|
||||
uploadImage,
|
||||
uploadFile,
|
||||
// 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}`,
|
||||
});
|
||||
provide('pagebuilder:list', EditorBlockList);
|
||||
|
|
@ -632,5 +641,6 @@ const canvasWidth = computed(() => devices.find((d) => d.key === device.value).w
|
|||
<NewPageDialog v-model:open="dialogs.newPage" :parent-id="page.id" :parent-title="page.title" @before-create="save" />
|
||||
</div>
|
||||
|
||||
<MediaPickerHost :picker="mediaPicker" />
|
||||
<Toaster position="bottom-left" />
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -3,13 +3,13 @@
|
|||
namespace Inhaus\Plugins\Pages\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Notifications\PortalNotification;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\Content;
|
||||
use App\Support\Audit;
|
||||
use App\Support\Images;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
|
@ -312,14 +312,15 @@ class PageEditorController extends Controller
|
|||
return response()->json(['ok' => true]);
|
||||
}
|
||||
|
||||
public function uploadImage(Request $request, Page $page, Images $images): JsonResponse
|
||||
public function uploadImage(Request $request, Page $page, MediaLibrary $library): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $page);
|
||||
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
|
||||
|
||||
$path = $images->storeContentImage($request->file('image'), 'pagebuilder/pages/'.$page->id);
|
||||
// Landet zugleich in der Mediathek.
|
||||
$media = $library->store($request->file('image'), 'pagebuilder/pages/'.$page->id, $request->user());
|
||||
|
||||
return response()->json(['path' => $path, 'url' => Blocks::imageUrl($path)]);
|
||||
return response()->json(['path' => $media->path, 'url' => Blocks::imageUrl($media->path), 'media' => $media->toLibraryArray()]);
|
||||
}
|
||||
|
||||
public function uploadFile(Request $request, Page $page): JsonResponse
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
namespace Inhaus\Plugins\Pages;
|
||||
|
||||
use App\Editorial\Editorial;
|
||||
use App\Media\ImagePaths;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
|
|
@ -88,6 +90,7 @@ class PagesPlugin extends Plugin
|
|||
);
|
||||
|
||||
$this->registerBlocks($this->app->make(Blocks::class));
|
||||
$this->registerMediaUsages($this->app->make(MediaUsages::class));
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
|
|
@ -98,6 +101,33 @@ class PagesPlugin extends Plugin
|
|||
})->everyMinute()->name('pages-scheduled')->withoutOverlapping(5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mediathek „Eingebunden in“: veröffentlichter Inhalt, Entwurf und geplanter Stand.
|
||||
*/
|
||||
private function registerMediaUsages(MediaUsages $usages): void
|
||||
{
|
||||
$usages->add('pages', 'Seiten', function (Page $page) {
|
||||
$entries = [];
|
||||
$url = route('pages.editor', $page, false);
|
||||
|
||||
foreach (['content' => false, 'scheduled_content' => true, 'draft' => true] as $column => $draft) {
|
||||
$title = match ($column) {
|
||||
'draft' => $page->draft_title ?? $page->title,
|
||||
'scheduled_content' => $page->scheduled_title ?? $page->title,
|
||||
default => $page->title,
|
||||
};
|
||||
|
||||
foreach (ImagePaths::fromContent($page->{$column}) as $context => $paths) {
|
||||
$entries[] = ['context' => $context, 'label' => $title, 'url' => $url, 'draft' => $draft, 'paths' => $paths];
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}, 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']);
|
||||
}
|
||||
|
||||
private function registerBlocks(Blocks $blocks): void
|
||||
{
|
||||
$blocks->add(BlockType::make('downloads', 'Downloads', 'file-down', 'media', 'pages::Downloads')
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
|
@ -20,6 +20,14 @@ watch(() => props.block.data.layout, () => {
|
|||
if (props.block.type === 'columns') syncColumns(props.block);
|
||||
});
|
||||
|
||||
// Bild aus der Mediathek: Alternativtext und Bildunterschrift übernehmen, wenn noch leer.
|
||||
function fillFromMedia(item) {
|
||||
const data = props.block.data;
|
||||
|
||||
if ('alt' in data && !data.alt && item.alt) data.alt = item.alt;
|
||||
if ('caption' in data && !data.caption && item.caption) data.caption = item.caption;
|
||||
}
|
||||
|
||||
function addItem() {
|
||||
props.block.items.push({ id: uid(), title: `${type.value.container.label} ${props.block.items.length + 1}`, blocks: [] });
|
||||
}
|
||||
|
|
@ -79,6 +87,7 @@ const ruleGroups = computed(() => [
|
|||
:key="`${block.id}-${field.name}`"
|
||||
v-model="block.data[field.name]"
|
||||
:field="field"
|
||||
@image-picked="fillFromMedia"
|
||||
/>
|
||||
|
||||
<section v-if="type.container && type.container.max > 1 && type.key !== 'columns'" class="grid gap-2">
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup>
|
||||
import { computed, inject, ref, watch } from 'vue';
|
||||
import { ArrowDown, ArrowUp, FileDown, ImagePlus, LoaderCircle, Plus, Search, Trash2, Upload, X } from '@lucide/vue';
|
||||
import { ArrowDown, ArrowUp, FileDown, ImagePlus, Images, LoaderCircle, Plus, Search, Trash2, Upload, X } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
|
@ -23,16 +23,14 @@ const props = defineProps({
|
|||
|
||||
const model = defineModel({ default: null });
|
||||
const editor = inject('pagebuilder:editor');
|
||||
const emit = defineEmits(['image-uploaded']);
|
||||
const emit = defineEmits(['image-uploaded', 'image-picked']);
|
||||
|
||||
// Bild
|
||||
// Bild: hochladen (auch per Ziehen & Ablegen) oder aus der Mediathek wählen (editor.pickMedia)
|
||||
const uploading = ref(false);
|
||||
const imageInput = ref(null);
|
||||
const dropping = ref(false);
|
||||
|
||||
async function uploadImage(event) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
|
||||
async function uploadImageFile(file) {
|
||||
if (!file) return;
|
||||
|
||||
uploading.value = true;
|
||||
|
|
@ -48,6 +46,57 @@ async function uploadImage(event) {
|
|||
}
|
||||
}
|
||||
|
||||
function uploadImage(event) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = '';
|
||||
uploadImageFile(file);
|
||||
}
|
||||
|
||||
function dropImage(event) {
|
||||
dropping.value = false;
|
||||
const file = [...(event.dataTransfer?.files ?? [])].find((f) => f.type.startsWith('image/'));
|
||||
uploadImageFile(file);
|
||||
}
|
||||
|
||||
async function pickImage() {
|
||||
const items = await editor.pickMedia({ multiple: false });
|
||||
|
||||
if (items?.length) {
|
||||
model.value = items[0].path;
|
||||
emit('image-picked', items[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// Galerie & Co.: Wiederholer mit Bildfeld – mehrere Bilder auf einmal aus der Mediathek
|
||||
const repeaterImageField = computed(() => (props.field.type === 'repeater' ? props.field.fields.find((sub) => sub.type === 'image') : null));
|
||||
|
||||
async function pickRepeaterImages() {
|
||||
const items = await editor.pickMedia({ multiple: true, title: `${props.field.label} aus der Mediathek hinzufügen` });
|
||||
|
||||
if (!items?.length) return;
|
||||
|
||||
const free = Math.max(0, props.field.max - (model.value ?? []).length);
|
||||
const added = items.slice(0, free).map((item) => {
|
||||
const entry = newRepeaterItem();
|
||||
entry[repeaterImageField.value.name] = item.path;
|
||||
|
||||
if ('alt' in entry) entry.alt = item.alt ?? '';
|
||||
if ('caption' in entry) entry.caption = item.caption ?? '';
|
||||
|
||||
return entry;
|
||||
});
|
||||
|
||||
model.value = [...(model.value ?? []), ...added];
|
||||
|
||||
if (items.length > free) toast.warning(`Nur ${free} von ${items.length} Bildern übernommen – höchstens ${props.field.max} möglich.`);
|
||||
}
|
||||
|
||||
/** Alternativtext/Bildunterschrift aus der Mediathek übernehmen, wenn im Eintrag noch leer. */
|
||||
function fillFromMedia(entry, item) {
|
||||
if ('alt' in entry && !entry.alt && item.alt) entry.alt = item.alt;
|
||||
if ('caption' in entry && !entry.caption && item.caption) entry.caption = item.caption;
|
||||
}
|
||||
|
||||
// Personen
|
||||
const peopleQuery = ref('');
|
||||
const peopleResults = ref([]);
|
||||
|
|
@ -96,9 +145,12 @@ function removeItem(index) {
|
|||
model.value = model.value.filter((_, i) => i !== index);
|
||||
}
|
||||
|
||||
function newRepeaterItem() {
|
||||
return Object.fromEntries(props.field.fields.map((sub) => [sub.name, structuredClone(sub.default ?? (sub.type === 'toggle' ? false : sub.type === 'repeater' ? [] : ''))]));
|
||||
}
|
||||
|
||||
function addRepeaterItem() {
|
||||
const item = Object.fromEntries(props.field.fields.map((sub) => [sub.name, structuredClone(sub.default ?? (sub.type === 'toggle' ? false : sub.type === 'repeater' ? [] : ''))]));
|
||||
model.value = [...(model.value ?? []), item];
|
||||
model.value = [...(model.value ?? []), newRepeaterItem()];
|
||||
}
|
||||
|
||||
// Tabelle
|
||||
|
|
@ -205,23 +257,42 @@ watch(iconQuery, (query) => query.trim() && loadIconSet());
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="field.type === 'image'" class="grid gap-2">
|
||||
<div
|
||||
v-else-if="field.type === 'image'"
|
||||
class="grid gap-2 rounded-md"
|
||||
:class="dropping && 'ring-2 ring-brand-400 ring-offset-2 ring-offset-card'"
|
||||
@dragover.prevent="dropping = true"
|
||||
@dragleave="dropping = false"
|
||||
@drop.prevent="dropImage"
|
||||
>
|
||||
<div v-if="model" class="relative overflow-hidden rounded-md border bg-muted">
|
||||
<img :src="editor.imageUrl(model)" alt="" class="aspect-video w-full object-cover" />
|
||||
<button type="button" class="absolute top-1.5 right-1.5 grid size-7 place-items-center rounded-md bg-card/90 shadow-sm hover:bg-card" title="Bild entfernen" @click="model = null">
|
||||
<X class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 items-center justify-center gap-2 rounded-md border border-dashed text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
:disabled="uploading"
|
||||
@click="imageInput?.click()"
|
||||
>
|
||||
<LoaderCircle v-if="uploading" class="size-4 animate-spin" />
|
||||
<ImagePlus v-else class="size-4" />
|
||||
{{ model ? 'Anderes Bild wählen' : 'Bild hochladen' }}
|
||||
</button>
|
||||
<div class="grid gap-2" :class="editor.pickMedia ? 'grid-cols-2' : ''">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 items-center justify-center gap-1.5 rounded-md border border-dashed px-2 text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
:disabled="uploading"
|
||||
:title="'Bild hochladen – oder eine Datei hierher ziehen'"
|
||||
@click="imageInput?.click()"
|
||||
>
|
||||
<LoaderCircle v-if="uploading" class="size-4 animate-spin" />
|
||||
<ImagePlus v-else class="size-4" />
|
||||
{{ editor.pickMedia ? 'Hochladen' : model ? 'Anderes Bild wählen' : 'Bild hochladen' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="editor.pickMedia"
|
||||
type="button"
|
||||
class="flex h-9 items-center justify-center gap-1.5 rounded-md border px-2 text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
:disabled="uploading"
|
||||
@click="pickImage"
|
||||
>
|
||||
<Images class="size-4" /> Aus Mediathek
|
||||
</button>
|
||||
</div>
|
||||
<input ref="imageInput" type="file" accept="image/jpeg,image/png,image/webp,image/gif" class="hidden" @change="uploadImage" />
|
||||
</div>
|
||||
|
||||
|
|
@ -287,17 +358,33 @@ watch(iconQuery, (query) => query.trim() && loadIconSet());
|
|||
<button type="button" class="grid size-6 place-items-center rounded text-destructive hover:bg-destructive/10" title="Entfernen" @click.prevent="removeItem(index)"><Trash2 class="size-3.5" /></button>
|
||||
</summary>
|
||||
<div class="grid gap-3 border-t px-3 py-3">
|
||||
<FieldInput v-for="sub in field.fields" :id="`${id}-${index}-${sub.name}`" :key="sub.name" v-model="entry[sub.name]" :field="sub" />
|
||||
<FieldInput
|
||||
v-for="sub in field.fields"
|
||||
:id="`${id}-${index}-${sub.name}`"
|
||||
:key="sub.name"
|
||||
v-model="entry[sub.name]"
|
||||
:field="sub"
|
||||
@image-picked="(item) => fillFromMedia(entry, item)"
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
<button
|
||||
v-if="(model ?? []).length < field.max"
|
||||
type="button"
|
||||
class="flex h-8 items-center justify-center gap-1.5 rounded-md border border-dashed text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
@click="addRepeaterItem"
|
||||
>
|
||||
<Plus class="size-3.5" /> {{ field.itemLabel }} hinzufügen
|
||||
</button>
|
||||
<div v-if="(model ?? []).length < field.max" class="grid gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 items-center justify-center gap-1.5 rounded-md border border-dashed px-2 text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
@click="addRepeaterItem"
|
||||
>
|
||||
<Plus class="size-3.5" /> {{ field.itemLabel }} hinzufügen
|
||||
</button>
|
||||
<button
|
||||
v-if="repeaterImageField && editor.pickMedia"
|
||||
type="button"
|
||||
class="flex h-8 items-center justify-center gap-1.5 rounded-md border px-2 text-[13px] font-medium text-muted-foreground hover:border-brand-300 hover:text-foreground"
|
||||
@click="pickRepeaterImages"
|
||||
>
|
||||
<Images class="size-3.5" /> Mehrere aus der Mediathek hinzufügen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="field.type === 'ids' && field.kind === 'page-file'" class="grid gap-2">
|
||||
|
|
|
|||
|
|
@ -17,6 +17,11 @@ for (const [path, loader] of Object.entries(loaders)) {
|
|||
const [, slug] = path.match(/plugins-core\/([^/]+)\//);
|
||||
components[`${slug}::${path.split('/').pop().replace('.vue', '')}`] = defineAsyncComponent(loader);
|
||||
}
|
||||
|
||||
// Abschnitte des Kerns („core::Name“ aus resources/js/components/editorial), z. B. die Mediathek.
|
||||
for (const [path, loader] of Object.entries(import.meta.glob('../../components/editorial/*.vue'))) {
|
||||
components[`core::${path.split('/').pop().replace('.vue', '')}`] = defineAsyncComponent(loader);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
|
|||
281
resources/js/pages/Media/Index.vue
Normal file
281
resources/js/pages/Media/Index.vue
Normal file
|
|
@ -0,0 +1,281 @@
|
|||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { EllipsisVertical, ImagePlus, Images, LoaderCircle, RotateCw, Search, SearchX, Trash2, TriangleAlert, X } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import PageHeader from '@/components/PageHeader.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import MediaDetails from '@/components/media/MediaDetails.vue';
|
||||
import MediaTile from '@/components/media/MediaTile.vue';
|
||||
import MediaUploadZone from '@/components/media/MediaUploadZone.vue';
|
||||
import { mediaApi } from '@/components/media/api';
|
||||
import { useMediaList } from '@/components/media/useMediaList';
|
||||
|
||||
/**
|
||||
* Mediathek: alle Bilder des Portals – suchen, filtern, hochladen, Details
|
||||
* bearbeiten, sehen wo sie eingebunden sind, ersetzen und aufräumen.
|
||||
*/
|
||||
const props = defineProps({
|
||||
filters: { type: Object, default: () => ({}) },
|
||||
uploaders: { type: Array, default: () => [] },
|
||||
sources: { type: Array, default: () => [] },
|
||||
canManage: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
const filters = ref({
|
||||
q: props.filters.q ?? '',
|
||||
von: props.filters.von ?? '',
|
||||
zeitraum: props.filters.zeitraum ?? '',
|
||||
status: props.filters.status ?? '',
|
||||
in: props.filters.in ?? '',
|
||||
sortierung: 'neu',
|
||||
});
|
||||
|
||||
const { items, total, loading, nextPage, load, observe, replaceItem, removeItems, prepend } = useMediaList(filters);
|
||||
const sentinel = ref(null);
|
||||
|
||||
onMounted(() => {
|
||||
load(true);
|
||||
observe(sentinel.value);
|
||||
});
|
||||
|
||||
// Filter in der Adresse merken (Zurück-Taste, Link teilen)
|
||||
watch(filters, (value) => {
|
||||
const query = new URLSearchParams(Object.entries(value).filter(([key, v]) => v && key !== 'sortierung'));
|
||||
window.history.replaceState(window.history.state, '', `${window.location.pathname}${query.toString() ? `?${query}` : ''}`);
|
||||
}, { deep: true });
|
||||
|
||||
const filtered = computed(() => ['q', 'von', 'zeitraum', 'status', 'in'].some((key) => filters.value[key]));
|
||||
|
||||
function resetFilters() {
|
||||
Object.assign(filters.value, { q: '', von: '', zeitraum: '', status: '', in: '' });
|
||||
}
|
||||
|
||||
// Hochladen
|
||||
const showUpload = ref(false);
|
||||
|
||||
function uploaded(list) {
|
||||
prepend(list.map((item) => ({ ...item, usage_count: item.usage_count ?? 0 })));
|
||||
toast.success(list.length === 1 ? 'Bild hochgeladen.' : `${list.length} Bilder hochgeladen.`);
|
||||
}
|
||||
|
||||
// Details
|
||||
const openId = ref(null);
|
||||
const detailsOpen = computed({ get: () => openId.value !== null, set: (value) => !value && (openId.value = null) });
|
||||
|
||||
function onDeleted(id) {
|
||||
removeItems([id]);
|
||||
openId.value = null;
|
||||
}
|
||||
|
||||
// Auswahl
|
||||
const selected = ref(new Set());
|
||||
const selectedItems = computed(() => items.value.filter((item) => selected.value.has(item.id)));
|
||||
const selectedUsed = computed(() => selectedItems.value.filter((item) => item.usage_count > 0));
|
||||
|
||||
function toggle(item) {
|
||||
const next = new Set(selected.value);
|
||||
next.has(item.id) ? next.delete(item.id) : next.add(item.id);
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
function open(item, event) {
|
||||
// Bei laufender Auswahl (oder mit Strg/Umschalt) wählt ein Klick aus, statt Details zu öffnen.
|
||||
if (selected.value.size || event?.ctrlKey || event?.metaKey || event?.shiftKey) {
|
||||
toggle(item);
|
||||
} else {
|
||||
openId.value = item.id;
|
||||
}
|
||||
}
|
||||
|
||||
const confirmBulk = ref(false);
|
||||
const bulkDeleting = ref(false);
|
||||
|
||||
async function bulkDelete(onlyUnused) {
|
||||
bulkDeleting.value = true;
|
||||
const ids = (onlyUnused ? selectedItems.value.filter((item) => !item.usage_count) : selectedItems.value).map((item) => item.id);
|
||||
|
||||
try {
|
||||
const result = await mediaApi.bulkRemove(ids, onlyUnused);
|
||||
removeItems(ids);
|
||||
selected.value = new Set();
|
||||
confirmBulk.value = false;
|
||||
toast.success(result.deleted === 1 ? '1 Bild gelöscht.' : `${result.deleted} Bilder gelöscht.`);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
bulkDeleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const rebuilding = ref(false);
|
||||
|
||||
async function rebuild() {
|
||||
rebuilding.value = true;
|
||||
|
||||
try {
|
||||
const result = await mediaApi.rebuild();
|
||||
toast.success(`Neu eingelesen: ${result.sources} Inhalte durchsucht.`);
|
||||
load(true);
|
||||
} catch (error) {
|
||||
toast.error(error.message);
|
||||
} finally {
|
||||
rebuilding.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const selectClass = 'h-9 rounded-md border border-input bg-card px-2.5 text-sm focus-visible:border-brand-400 focus-visible:ring-3 focus-visible:ring-ring/30 focus-visible:outline-none';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout title="Mediathek">
|
||||
<PageHeader title="Mediathek" :breadcrumbs="[{ label: 'Redaktion', href: '/redaktion' }]">
|
||||
<template #description>
|
||||
<template v-if="total !== null">{{ total.toLocaleString('de-DE') }} {{ total === 1 ? 'Bild' : 'Bilder' }}{{ filtered ? ' gefunden' : '' }} · </template>
|
||||
Alle Bilder aus Seiten, Neuigkeiten, Terminen und Kacheln an einem Ort.
|
||||
</template>
|
||||
<template #actions>
|
||||
<Button @click="showUpload = !showUpload"><ImagePlus /> Hochladen</Button>
|
||||
<DropdownMenu v-if="canManage">
|
||||
<DropdownMenuTrigger as-child>
|
||||
<Button variant="outline" size="icon" aria-label="Weitere Aktionen"><EllipsisVertical /></Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" class="w-64">
|
||||
<DropdownMenuItem :disabled="rebuilding" @select="rebuild">
|
||||
<RotateCw :class="rebuilding && 'animate-spin'" /> Verwendungen neu einlesen
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem @select="filters.status = 'unbenutzt'"><Trash2 /> Nicht verwendete Bilder anzeigen</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<section v-if="showUpload" class="mb-5 rounded-lg border bg-card p-4">
|
||||
<div class="mb-3 flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold">Bilder hochladen</h2>
|
||||
<button type="button" class="grid size-7 place-items-center rounded-md text-muted-foreground hover:bg-accent" aria-label="Schließen" @click="showUpload = false"><X class="size-4" /></button>
|
||||
</div>
|
||||
<MediaUploadZone compact @done="uploaded" />
|
||||
</section>
|
||||
|
||||
<div class="mb-4 flex flex-wrap items-center gap-2 rounded-lg border bg-card p-2.5">
|
||||
<label class="relative min-w-56 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="filters.q"
|
||||
type="search"
|
||||
placeholder="Dateiname, Alternativtext, Bildunterschrift, Schlagwort …"
|
||||
class="h-9 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>
|
||||
<select v-model="filters.status" :class="selectClass" aria-label="Verwendung">
|
||||
<option value="">Verwendet und unbenutzt</option>
|
||||
<option value="verwendet">Verwendet</option>
|
||||
<option value="unbenutzt">Nicht verwendet</option>
|
||||
</select>
|
||||
<select v-if="sources.length" v-model="filters.in" :class="selectClass" aria-label="Verwendet in">
|
||||
<option value="">Verwendet in: überall</option>
|
||||
<option v-for="source in sources" :key="source.value" :value="source.value">Verwendet in: {{ source.label }}</option>
|
||||
</select>
|
||||
<select v-model="filters.zeitraum" :class="selectClass" aria-label="Zeitraum">
|
||||
<option value="">Jederzeit hochgeladen</option>
|
||||
<option value="7">Letzte 7 Tage</option>
|
||||
<option value="30">Letzte 30 Tage</option>
|
||||
<option value="365">Letztes Jahr</option>
|
||||
</select>
|
||||
<select v-if="uploaders.length" v-model="filters.von" :class="selectClass" aria-label="Hochgeladen von">
|
||||
<option value="">Von allen</option>
|
||||
<option v-for="person in uploaders" :key="person.value" :value="person.value">{{ person.label }}</option>
|
||||
</select>
|
||||
<select v-model="filters.sortierung" :class="selectClass" aria-label="Sortierung">
|
||||
<option value="neu">Neueste zuerst</option>
|
||||
<option value="verwendet">Zuletzt verwendet</option>
|
||||
<option value="name">Nach Name</option>
|
||||
</select>
|
||||
<Button v-if="filtered" variant="ghost" size="sm" @click="resetFilters"><X /> Filter zurücksetzen</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="selected.size" class="sticky top-16 z-20 mb-4 flex flex-wrap items-center gap-2 rounded-lg border border-brand-200 bg-brand-soft px-3 py-2 text-sm text-brand-soft-foreground shadow-sm">
|
||||
<span class="font-medium">{{ selected.size }} ausgewählt</span>
|
||||
<span v-if="selectedUsed.length" class="text-[13px]">· davon {{ selectedUsed.length }} verwendet</span>
|
||||
<span class="flex-1" />
|
||||
<Button variant="ghost" size="sm" @click="selected = new Set()">Auswahl aufheben</Button>
|
||||
<Button v-if="canManage" variant="destructive" size="sm" @click="confirmBulk = true"><Trash2 /> Löschen</Button>
|
||||
</div>
|
||||
|
||||
<ul v-if="items.length" class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 2xl:grid-cols-6">
|
||||
<li v-for="item in items" :key="item.id">
|
||||
<MediaTile :item="item" :selected="selected.has(item.id)" :checkable="selected.size > 0" @open="open" @toggle="toggle" />
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div v-else-if="!loading" class="grid place-items-center rounded-lg border border-dashed bg-card px-6 py-16 text-center">
|
||||
<component :is="filtered ? SearchX : Images" class="size-8 text-muted-foreground" :stroke-width="1.5" />
|
||||
<p class="mt-3 font-medium">{{ filtered ? 'Keine Bilder gefunden' : 'Noch keine Bilder' }}</p>
|
||||
<p class="mt-1 max-w-sm text-sm text-muted-foreground">
|
||||
{{ filtered ? 'Versuchen Sie einen anderen Suchbegriff oder andere Filter.' : 'Laden Sie Bilder hoch – oder fügen Sie sie direkt in Seiten und Beiträge ein, sie landen automatisch hier.' }}
|
||||
</p>
|
||||
<Button v-if="!filtered" class="mt-4" @click="showUpload = true"><ImagePlus /> Bilder hochladen</Button>
|
||||
</div>
|
||||
|
||||
<div ref="sentinel" class="grid h-16 place-items-center">
|
||||
<LoaderCircle v-if="loading" class="size-5 animate-spin text-muted-foreground" />
|
||||
<Button v-else-if="nextPage && items.length" variant="outline" size="sm" @click="load()">Weitere laden</Button>
|
||||
</div>
|
||||
|
||||
<Sheet v-model:open="detailsOpen">
|
||||
<SheetContent class="w-full overflow-y-auto sm:max-w-xl">
|
||||
<SheetHeader class="px-5 pt-5 pb-0">
|
||||
<SheetTitle>Bilddetails</SheetTitle>
|
||||
<SheetDescription class="sr-only">Angaben, Verwendung und Aktionen für das Bild</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div class="px-5 pb-6">
|
||||
<MediaDetails v-if="openId" :id="openId" :can-manage="canManage" @updated="replaceItem" @deleted="onDeleted" />
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<AlertDialog v-model:open="confirmBulk">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{{ selected.size === 1 ? 'Bild löschen?' : `${selected.size} Bilder löschen?` }}</AlertDialogTitle>
|
||||
<AlertDialogDescription>Gelöschte Bilder lassen sich nicht wiederherstellen.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div v-if="selectedUsed.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" />
|
||||
{{ selectedUsed.length }} der ausgewählten Bilder {{ selectedUsed.length === 1 ? 'ist' : 'sind' }} noch eingebunden. Dort erscheint nach dem Löschen ein Platzhalter.
|
||||
</p>
|
||||
<ul class="max-h-40 overflow-y-auto rounded-md border text-[13px]">
|
||||
<li v-for="item in selectedUsed" :key="item.id" class="flex items-center gap-2 border-b px-2 py-1.5 last:border-0">
|
||||
<img v-if="item.thumb_url" :src="item.thumb_url" alt="" class="size-8 rounded object-cover" />
|
||||
<span class="min-w-0 flex-1 truncate">{{ item.alt || item.name }}</span>
|
||||
<button type="button" class="shrink-0 text-xs font-medium text-brand-text hover:underline" @click="confirmBulk = false; openId = item.id">{{ item.usage_count }}× verwendet</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<AlertDialogFooter class="flex-wrap gap-2">
|
||||
<AlertDialogCancel>Abbrechen</AlertDialogCancel>
|
||||
<Button v-if="selectedUsed.length && selectedUsed.length < selected.size" variant="outline" :disabled="bulkDeleting" @click="bulkDelete(true)">
|
||||
Nur nicht verwendete ({{ selected.size - selectedUsed.length }})
|
||||
</Button>
|
||||
<Button variant="destructive" :disabled="bulkDeleting" @click="bulkDelete(false)">
|
||||
<LoaderCircle v-if="bulkDeleting" class="animate-spin" /> {{ selectedUsed.length ? 'Trotzdem alle löschen' : 'Löschen' }}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
|
@ -1,10 +1,18 @@
|
|||
<?php
|
||||
|
||||
use App\Identity\Entra\EntraDirectorySync;
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Support\BackgroundTasks;
|
||||
use App\Support\Feedback\FeedbackOutbox;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Schedule;
|
||||
|
||||
// Mediathek: verwendete Bilder übernehmen und „Eingebunden in“ neu erfassen.
|
||||
Artisan::command('media:rebuild', function (MediaLibrary $library) {
|
||||
$result = $library->rebuild();
|
||||
$this->info("{$result['sources']} Inhalte durchsucht, {$result['media']} Bilder in der Mediathek.");
|
||||
})->purpose('Mediathek: verwendete Bilder übernehmen und Verwendungen neu erfassen');
|
||||
|
||||
/*
|
||||
| Geplante Aufgaben. Ausgelöst per Cron, Web-Cron oder Pseudo-Cron (App\Support\BackgroundTasks).
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ use App\Http\Controllers\CronController;
|
|||
use App\Http\Controllers\DashboardController;
|
||||
use App\Http\Controllers\EditorialController;
|
||||
use App\Http\Controllers\InstallController;
|
||||
use App\Http\Controllers\MediaController;
|
||||
use App\Http\Controllers\NotificationController;
|
||||
use App\Http\Controllers\OrganigramController;
|
||||
use App\Http\Controllers\PeopleController;
|
||||
|
|
@ -52,6 +53,20 @@ Route::middleware('auth')->group(function () {
|
|||
|
||||
Route::get('/redaktion', EditorialController::class)->name('editorial');
|
||||
|
||||
// Mediathek und Bildauswahl der Editoren
|
||||
Route::prefix('redaktion/mediathek')->name('media.')->middleware('can:media.use')->controller(MediaController::class)->group(function () {
|
||||
Route::get('/', 'index')->name('index');
|
||||
Route::get('/liste', 'list')->name('list');
|
||||
Route::post('/', 'store')->name('store')->middleware('throttle:120,1');
|
||||
Route::post('/loeschen', 'bulkDestroy')->name('bulk-destroy');
|
||||
Route::post('/neu-einlesen', 'rebuild')->name('rebuild')->middleware('throttle:5,1');
|
||||
Route::get('/{media}', 'show')->name('show')->whereNumber('media');
|
||||
Route::put('/{media}', 'update')->name('update')->whereNumber('media');
|
||||
Route::post('/{media}/ersetzen', 'replace')->name('replace')->whereNumber('media');
|
||||
Route::delete('/{media}', 'destroy')->name('destroy')->whereNumber('media');
|
||||
Route::get('/{media}/original', 'download')->name('download')->whereNumber('media');
|
||||
});
|
||||
|
||||
Route::get('/personen', [PeopleController::class, 'index'])->name('people.index');
|
||||
Route::get('/suche', [SearchController::class, 'index'])->name('search');
|
||||
Route::get('/suche/live', [SearchController::class, 'live'])->name('search.live');
|
||||
|
|
|
|||
307
tests/Feature/Media/MediaLibraryTest.php
Normal file
307
tests/Feature/Media/MediaLibraryTest.php
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
<?php
|
||||
|
||||
namespace Tests\Feature\Media;
|
||||
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Models\DashboardTile;
|
||||
use App\Models\Media;
|
||||
use App\Models\MediaUsage;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Content;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Inhaus\Plugins\Events\Models\Event;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Inhaus\Plugins\Pages\Models\Page;
|
||||
use Tests\TestCase;
|
||||
|
||||
class MediaLibraryTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $admin;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Storage::fake('uploads');
|
||||
Storage::fake('local');
|
||||
$this->admin = User::factory()->admin()->create();
|
||||
}
|
||||
|
||||
private function pageEditor(Page $page): User
|
||||
{
|
||||
$role = Role::query()->create(['name' => 'MAV']);
|
||||
$role->grants()->create(['ability' => 'pages.edit', 'resource_type' => 'page', 'resource_id' => $page->id, 'include_children' => true]);
|
||||
|
||||
return User::factory()->withRoles([$role])->create();
|
||||
}
|
||||
|
||||
private function putImage(string $path, int $width = 800, int $height = 600): string
|
||||
{
|
||||
Storage::disk('uploads')->put($path, UploadedFile::fake()->image(basename($path), $width, $height)->getContent());
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
private function imageBlock(string $path, string $id = 'blk00001'): array
|
||||
{
|
||||
return ['id' => $id, 'type' => 'image', 'data' => ['path' => $path, 'alt' => 'Foto']];
|
||||
}
|
||||
|
||||
public function test_page_editor_upload_lands_in_library_and_usage_is_tracked(): void
|
||||
{
|
||||
$page = Page::query()->create(['title' => 'Arbeitsschutz']);
|
||||
|
||||
$result = $this->actingAs($this->admin)->post('/redaktion/seiten/'.$page->id.'/bilder', ['image' => UploadedFile::fake()->image('Baustelle.jpg', 1200, 800)])
|
||||
->assertOk()->json();
|
||||
|
||||
$media = Media::query()->sole();
|
||||
$this->assertSame($result['path'], $media->path);
|
||||
$this->assertSame('Baustelle.jpg', $media->original_name);
|
||||
$this->assertSame($this->admin->id, $media->uploaded_by);
|
||||
$this->assertSame(1200, $media->width);
|
||||
$this->assertSame($media->id, $result['media']['id']);
|
||||
Storage::disk('uploads')->assertExists($media->path);
|
||||
|
||||
// Entwurf: als Entwurf erfasst
|
||||
$this->putJson('/redaktion/seiten/'.$page->id.'/entwurf', ['title' => 'Arbeitsschutz', 'content' => ['blocks' => [$this->imageBlock($media->path)]]])->assertOk();
|
||||
$usage = MediaUsage::query()->sole();
|
||||
$this->assertSame('pages', $usage->source_type);
|
||||
$this->assertSame($page->id, $usage->source_id);
|
||||
$this->assertSame('Bild-Block', $usage->context);
|
||||
$this->assertTrue($usage->draft);
|
||||
$this->assertSame('/redaktion/seiten/'.$page->id, $usage->url);
|
||||
|
||||
// Veröffentlicht: nicht mehr Entwurf
|
||||
$this->postJson('/redaktion/seiten/'.$page->id.'/veroeffentlichen', ['title' => 'Arbeitsschutz', 'content' => ['blocks' => [$this->imageBlock($media->path)]]])->assertOk();
|
||||
$this->assertFalse(MediaUsage::query()->sole()->draft);
|
||||
|
||||
// Bild entfernt: keine Verwendung mehr
|
||||
$page->fresh()->publish('Arbeitsschutz', ['blocks' => []], $this->admin);
|
||||
$this->assertSame(0, MediaUsage::query()->count());
|
||||
}
|
||||
|
||||
public function test_gallery_hero_and_inline_images_are_found_with_context(): void
|
||||
{
|
||||
$a = $this->putImage('pagebuilder/pages/1/a.webp');
|
||||
$b = $this->putImage('mediathek/2026/10/b.webp');
|
||||
$c = $this->putImage('news/inline/c.webp');
|
||||
|
||||
$content = app(Content::class)->sanitize(['blocks' => [
|
||||
['id' => 'gal00001', 'type' => 'gallery', 'data' => ['images' => [['path' => $a], ['path' => $b]]]],
|
||||
['id' => 'sec00001', 'type' => 'section', 'data' => [], 'items' => [['blocks' => [
|
||||
['id' => 'txt00001', 'type' => 'text', 'data' => ['html' => '<p>Hallo <img src="/uploads/'.$c.'?v=1" alt=""></p>']],
|
||||
['id' => 'her00001', 'type' => 'hero', 'data' => ['path' => $a, 'title' => 'Willkommen']],
|
||||
]]]],
|
||||
]]);
|
||||
|
||||
$page = Page::query()->create(['title' => 'Team']);
|
||||
$page->publish('Team', $content, $this->admin);
|
||||
|
||||
$contexts = MediaUsage::query()->with('media')->get()->map(fn (MediaUsage $u) => $u->media->path.'|'.$u->context)->all();
|
||||
$this->assertEqualsCanonicalizing([$a.'|Galerie', $a.'|Hero', $b.'|Galerie', $c.'|Im Text'], $contexts);
|
||||
$this->assertSame(3, Media::query()->count());
|
||||
|
||||
$page->delete();
|
||||
$this->assertSame(0, MediaUsage::query()->count());
|
||||
}
|
||||
|
||||
public function test_news_cover_and_inline_images_are_tracked(): void
|
||||
{
|
||||
$cover = $this->putImage('news/cover.jpg', 1600, 900);
|
||||
$inline = $this->putImage('news/inline/2026/10/bild.webp');
|
||||
|
||||
$post = NewsPost::factory()->create([
|
||||
'title' => 'Sommerfest',
|
||||
'cover_path' => $cover,
|
||||
'body' => '<p>Text</p><img src="http://localhost/uploads/'.$inline.'" alt="">',
|
||||
]);
|
||||
|
||||
$usages = MediaUsage::query()->where('source_type', 'news')->with('media')->get()->keyBy('context');
|
||||
$this->assertSame($cover, $usages['Titelbild']->media->path);
|
||||
$this->assertSame($inline, $usages['Im Text']->media->path);
|
||||
$this->assertSame('Sommerfest', $usages['Titelbild']->label);
|
||||
$this->assertSame(route('news.editor.edit', $post, false), $usages['Titelbild']->url);
|
||||
|
||||
// Titelbild entfernen: Datei bleibt in der Mediathek, Verwendung fällt weg.
|
||||
$post->update(['cover_path' => null]);
|
||||
$this->assertSame(['Im Text'], MediaUsage::query()->where('source_type', 'news')->pluck('context')->all());
|
||||
Storage::disk('uploads')->assertExists($cover);
|
||||
}
|
||||
|
||||
public function test_events_and_dashboard_tiles_are_tracked(): void
|
||||
{
|
||||
$image = $this->putImage('events/fest.jpg');
|
||||
$tileImage = $this->putImage('dashboard/banner.png');
|
||||
|
||||
Event::factory()->create(['title' => 'Betriebsfest', 'image_path' => $image]);
|
||||
DashboardTile::query()->create(['name' => 'Banner', 'type' => 'image', 'image_path' => $tileImage, 'is_active' => true]);
|
||||
|
||||
$this->assertSame(['dashboard_tiles', 'events'], MediaUsage::query()->orderBy('source_type')->pluck('source_type')->all());
|
||||
// Standardwerte der Datenbank (veröffentlicht/aktiv) gelten nicht als Entwurf.
|
||||
$this->assertSame(0, MediaUsage::query()->where('draft', true)->count());
|
||||
}
|
||||
|
||||
public function test_replace_keeps_path_and_changes_url_version(): void
|
||||
{
|
||||
$media = app(MediaLibrary::class)->store(UploadedFile::fake()->image('alt.jpg', 800, 600), 'mediathek', $this->admin);
|
||||
$path = $media->path;
|
||||
$oldUrl = $media->url();
|
||||
$this->assertStringContainsString('?v=', $oldUrl);
|
||||
|
||||
$this->actingAs($this->admin)->post('/redaktion/mediathek/'.$media->id.'/ersetzen', ['image' => UploadedFile::fake()->image('neu.png', 400, 300)])
|
||||
->assertOk()
|
||||
->assertJsonPath('media.path', $path)
|
||||
->assertJsonPath('media.width', 400);
|
||||
|
||||
$media->refresh();
|
||||
$this->assertSame($path, $media->path);
|
||||
$this->assertSame(300, $media->height);
|
||||
$this->assertSame('neu.png', $media->original_name);
|
||||
$this->assertNotSame($oldUrl, $media->url());
|
||||
Storage::disk('uploads')->assertExists($path);
|
||||
Storage::disk('uploads')->assertExists(preg_replace('/\.webp$/', '', $path).'-thumb.webp');
|
||||
}
|
||||
|
||||
public function test_delete_removes_files_and_usages_and_blocks_show_placeholder(): void
|
||||
{
|
||||
$path = $this->putImage('pagebuilder/pages/1/foto.webp');
|
||||
$page = Page::query()->create(['title' => 'Team']);
|
||||
$page->publish('Team', app(Content::class)->sanitize(['blocks' => [$this->imageBlock($path)]]), $this->admin);
|
||||
$media = Media::query()->sole();
|
||||
$this->assertSame(1, $media->usages()->count());
|
||||
|
||||
$this->actingAs($this->admin)->getJson('/redaktion/mediathek/'.$media->id)->assertOk()
|
||||
->assertJsonPath('usages.0.context', 'Bild-Block')
|
||||
->assertJsonPath('usages.0.label', 'Team')
|
||||
->assertJsonPath('usages.0.type_label', 'Seiten');
|
||||
|
||||
$this->deleteJson('/redaktion/mediathek/'.$media->id)->assertOk();
|
||||
|
||||
$this->assertSame(0, Media::query()->count());
|
||||
$this->assertSame(0, MediaUsage::query()->count());
|
||||
Storage::disk('uploads')->assertMissing($path);
|
||||
|
||||
// Die Seite zeigt den Platzhalter statt eines kaputten Bilds.
|
||||
$this->get('/seiten/team')->assertOk()->assertInertia(fn (Assert $p) => $p->where('content.blocks.0.props.url', null));
|
||||
}
|
||||
|
||||
public function test_bulk_delete_only_unused(): void
|
||||
{
|
||||
$library = app(MediaLibrary::class);
|
||||
$used = $library->register($this->putImage('mediathek/a.webp'));
|
||||
$unused = $library->register($this->putImage('mediathek/b.webp'));
|
||||
$page = Page::query()->create(['title' => 'Team']);
|
||||
$page->publish('Team', app(Content::class)->sanitize(['blocks' => [$this->imageBlock($used->path)]]), $this->admin);
|
||||
|
||||
$this->actingAs($this->admin)->postJson('/redaktion/mediathek/loeschen', ['ids' => [$used->id, $unused->id], 'only_unused' => true])
|
||||
->assertOk()->assertJsonPath('deleted', 1);
|
||||
|
||||
$this->assertModelExists($used);
|
||||
$this->assertModelMissing($unused);
|
||||
}
|
||||
|
||||
public function test_listing_filters_and_search(): void
|
||||
{
|
||||
$library = app(MediaLibrary::class);
|
||||
$used = $library->register($this->putImage('mediathek/sommerfest.webp'), ['original_name' => 'Sommerfest.jpg'], $this->admin);
|
||||
$other = $library->register($this->putImage('mediathek/buero.webp'), ['original_name' => 'Büro.jpg', 'alt' => 'Großraumbüro']);
|
||||
$page = Page::query()->create(['title' => 'Team']);
|
||||
$page->publish('Team', app(Content::class)->sanitize(['blocks' => [$this->imageBlock($used->path)]]), $this->admin);
|
||||
|
||||
$this->actingAs($this->admin);
|
||||
$this->getJson('/redaktion/mediathek/liste')->assertOk()->assertJsonCount(2, 'items')->assertJsonPath('total', 2)->assertJsonPath('items.0.id', $other->id);
|
||||
$this->getJson('/redaktion/mediathek/liste?q=raumbü')->assertJsonCount(1, 'items')->assertJsonPath('items.0.id', $other->id);
|
||||
$this->getJson('/redaktion/mediathek/liste?status=unbenutzt')->assertJsonCount(1, 'items')->assertJsonPath('items.0.id', $other->id);
|
||||
$this->getJson('/redaktion/mediathek/liste?in=pages')->assertJsonCount(1, 'items')->assertJsonPath('items.0.id', $used->id)->assertJsonPath('items.0.usage_count', 1);
|
||||
$this->getJson('/redaktion/mediathek/liste?von='.$this->admin->id)->assertJsonCount(1, 'items');
|
||||
$this->getJson('/redaktion/mediathek/liste?'.http_build_query(['pfade' => [$used->path]]))->assertJsonCount(1, 'items');
|
||||
$this->getJson('/redaktion/mediathek/liste?sortierung=verwendet')->assertJsonPath('items.0.id', $used->id);
|
||||
|
||||
$this->putJson('/redaktion/mediathek/'.$other->id, ['alt' => 'Büro mit Pflanzen', 'caption' => 'Verwaltung', 'tags' => ['Büro', ' Verwaltung ', 'Büro']])
|
||||
->assertOk()->assertJsonPath('media.alt', 'Büro mit Pflanzen')->assertJsonPath('media.tags', ['Büro', 'Verwaltung']);
|
||||
$this->getJson('/redaktion/mediathek/liste?q=Verwaltung')->assertJsonCount(1, 'items');
|
||||
|
||||
$this->get('/redaktion/mediathek')->assertOk()->assertInertia(fn (Assert $p) => $p
|
||||
->component('Media/Index')
|
||||
->where('canManage', true)
|
||||
->has('sources'));
|
||||
}
|
||||
|
||||
public function test_permissions(): void
|
||||
{
|
||||
$media = app(MediaLibrary::class)->register($this->putImage('mediathek/a.webp'));
|
||||
$employee = User::factory()->create();
|
||||
|
||||
$this->actingAs($employee)->get('/redaktion/mediathek')->assertForbidden();
|
||||
$this->getJson('/redaktion/mediathek/liste')->assertForbidden();
|
||||
$this->post('/redaktion/mediathek', ['image' => UploadedFile::fake()->image('x.jpg')])->assertForbidden();
|
||||
|
||||
// Wer Seiten bearbeitet, darf die Mediathek benutzen und hochladen – aber nicht löschen oder ersetzen.
|
||||
$editor = $this->pageEditor(Page::query()->create(['title' => 'MAV']));
|
||||
$this->actingAs($editor)->get('/redaktion/mediathek')->assertOk()->assertInertia(fn (Assert $p) => $p->where('canManage', false));
|
||||
$this->getJson('/redaktion/mediathek/liste')->assertOk();
|
||||
$this->post('/redaktion/mediathek', ['image' => UploadedFile::fake()->image('x.jpg', 300, 200)], ['Accept' => 'application/json'])->assertCreated()
|
||||
->assertJsonPath('media.uploader.id', $editor->id);
|
||||
$this->putJson('/redaktion/mediathek/'.$media->id, ['alt' => 'Beschreibung'])->assertOk();
|
||||
$this->deleteJson('/redaktion/mediathek/'.$media->id)->assertForbidden();
|
||||
$this->post('/redaktion/mediathek/'.$media->id.'/ersetzen', ['image' => UploadedFile::fake()->image('y.jpg')], ['Accept' => 'application/json'])->assertForbidden();
|
||||
$this->postJson('/redaktion/mediathek/loeschen', ['ids' => [$media->id]])->assertForbidden();
|
||||
|
||||
// „Mediathek verwalten“ allein reicht für alles.
|
||||
$role = Role::query()->create(['name' => 'Medien']);
|
||||
$role->grants()->create(['ability' => 'media.manage']);
|
||||
$manager = User::factory()->withRoles([$role])->create();
|
||||
$this->actingAs($manager)->deleteJson('/redaktion/mediathek/'.$media->id)->assertOk();
|
||||
}
|
||||
|
||||
public function test_rebuild_command_imports_referenced_files(): void
|
||||
{
|
||||
$cover = $this->putImage('news/alt-cover.jpg', 1600, 900);
|
||||
$orphan = $this->putImage('news/verwaist.jpg');
|
||||
$pageImage = $this->putImage('pagebuilder/pages/9/bild.webp');
|
||||
$category = NewsCategory::factory()->create();
|
||||
|
||||
// Wie aus einer älteren Version: Inhalte ohne Mediathek-Einträge.
|
||||
NewsPost::factory()->create(['category_id' => $category->id, 'cover_path' => $cover, 'published_at' => now()->subDay()]);
|
||||
$page = Page::query()->create(['title' => 'Team']);
|
||||
$page->publish('Team', app(Content::class)->sanitize(['blocks' => [$this->imageBlock($pageImage)]]), $this->admin);
|
||||
MediaUsage::query()->delete();
|
||||
Media::query()->delete();
|
||||
|
||||
$this->artisan('media:rebuild')->assertSuccessful();
|
||||
|
||||
$this->assertEqualsCanonicalizing([$cover, $pageImage], Media::query()->pluck('path')->all());
|
||||
$this->assertSame(2, MediaUsage::query()->count());
|
||||
$this->assertNull(Media::query()->where('path', $orphan)->first());
|
||||
$this->assertFalse(MediaUsage::query()->where('source_type', 'news')->sole()->draft);
|
||||
}
|
||||
|
||||
public function test_missing_file_resolves_to_null_url(): void
|
||||
{
|
||||
$media = app(MediaLibrary::class)->register($this->putImage('mediathek/weg.webp'));
|
||||
Storage::disk('uploads')->delete($media->path);
|
||||
|
||||
$this->assertNull($media->url());
|
||||
$this->assertTrue($media->toLibraryArray()['missing']);
|
||||
}
|
||||
|
||||
public function test_image_field_accepts_library_paths_but_not_traversal(): void
|
||||
{
|
||||
$content = app(Content::class)->sanitize(['blocks' => [
|
||||
$this->imageBlock('mediathek/2026/10/a.webp', 'blk00001'),
|
||||
$this->imageBlock('../.env', 'blk00002'),
|
||||
$this->imageBlock('news/x.php', 'blk00003'),
|
||||
]]);
|
||||
|
||||
$this->assertSame('mediathek/2026/10/a.webp', $content['blocks'][0]['data']['path']);
|
||||
$this->assertNull($content['blocks'][1]['data']['path']);
|
||||
$this->assertNull($content['blocks'][2]['data']['path']);
|
||||
}
|
||||
}
|
||||
|
|
@ -250,7 +250,7 @@ class PagesTest extends TestCase
|
|||
|
||||
$props = $this->postJson('/redaktion/seiten/'.$page->id.'/vorschau', ['blocks' => [['id' => 'img00001', 'type' => 'image', 'data' => ['path' => $result['path']]]]])
|
||||
->assertOk()->json('props.img00001');
|
||||
$this->assertStringEndsWith($result['path'], $props['url']);
|
||||
$this->assertStringContainsString($result['path'].'?v=', $props['url']);
|
||||
}
|
||||
|
||||
public function test_top_level_pages_can_appear_in_the_main_navigation(): void
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace Tests\Feature\Plugins;
|
||||
|
||||
use App\Models\Media;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
|
|
@ -96,7 +97,7 @@ class NewsTest extends TestCase
|
|||
$this->assertSame(3, $post->reading_minutes);
|
||||
}
|
||||
|
||||
public function test_cover_variants_are_created_and_removed(): void
|
||||
public function test_cover_variants_are_created_and_image_stays_in_the_library(): void
|
||||
{
|
||||
Storage::fake('uploads');
|
||||
Storage::disk('uploads')->put('news/cover.jpg', UploadedFile::fake()->image('cover.jpg', 2000, 1200)->getContent());
|
||||
|
|
@ -105,12 +106,17 @@ class NewsTest extends TestCase
|
|||
|
||||
Storage::disk('uploads')->assertExists('news/cover-thumb.webp');
|
||||
Storage::disk('uploads')->assertExists('news/cover-large.webp');
|
||||
$this->assertStringEndsWith('news/cover-thumb.webp', $post->coverUrl('thumb'));
|
||||
$this->assertStringContainsString('news/cover-thumb.webp?v=', $post->coverUrl('thumb'));
|
||||
|
||||
// Das Bild kann auch anderswo eingebunden sein – es bleibt in der Mediathek, nur die Verwendung fällt weg.
|
||||
$post->delete();
|
||||
|
||||
Storage::disk('uploads')->assertMissing('news/cover.jpg');
|
||||
Storage::disk('uploads')->assertMissing('news/cover-thumb.webp');
|
||||
Storage::disk('uploads')->assertExists('news/cover.jpg');
|
||||
$this->assertSame(0, Media::query()->where('path', 'news/cover.jpg')->sole()->usages()->count());
|
||||
|
||||
// Fehlt die Datei, gibt es keine Adresse (Platzhalter statt kaputtem Bild).
|
||||
Storage::disk('uploads')->delete(['news/cover.jpg', 'news/cover-thumb.webp', 'news/cover-large.webp']);
|
||||
$this->assertNull($post->coverUrl('thumb'));
|
||||
}
|
||||
|
||||
public function test_large_photos_fit_into_shared_hosting_memory_limit(): void
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue