Admin: one image picker everywhere, with paste, drag-and-drop and a library #12

Merged
reudy merged 4 commits from unified-image-picker into main 2026-10-26 18:01:18 +01:00
4 changed files with 190 additions and 55 deletions
Showing only changes of commit 650c95fb78 - Show all commits

View file

@ -146,7 +146,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- Section card: `rounded-box bg-base-100 p-5 shadow` with an `h2.text-2xl.font-bold` title (see Site design / globals). - Section card: `rounded-box bg-base-100 p-5 shadow` with an `h2.text-2xl.font-bold` title (see Site design / globals).
- Form field: `<label class="fieldset"><span class="fieldset-legend">Label</span><input class="input w-full" /></label>`; hints in `<span class="label">`. - Form field: `<label class="fieldset"><span class="fieldset-legend">Label</span><input class="input w-full" /></label>`; hints in `<span class="label">`.
- Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker. - Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker.
- Images: always `$lib/admin/editors/ImagePicker.svelte` (choose, drag in or paste an image; address and alt text). It uploads to `media` through `/api/upload`; `withUrl={false}` + `altHint=""` + the `id` from `onChange` where a field stores a media relation (Services & products). Store only `url`/`alt` from `onChange` elsewhere. - Images: always `$lib/admin/editors/ImagePicker.svelte` (choose, drag in or paste an image, or pick an uploaded one from the library: `MediaLibrary.svelte`, `/api/media`; address and alt text). It uploads to `media` through `/api/upload`; `withUrl={false}` + `altHint=""` + the `id` from `onChange` where a field stores a media relation (Services & products). Store only `url`/`alt` from `onChange` elsewhere.
- Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel). - Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel).
- Server actions wrap PocketBase writes in `attempt()` from `$lib/server/actions` so failures show as an error banner, not a 500. - Server actions wrap PocketBase writes in `attempt()` from `$lib/server/actions` so failures show as an error banner, not a 500.
- Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`. - Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`.

View file

@ -1,13 +1,16 @@
<script lang="ts"> <script lang="ts">
import { onMount, type Snippet } from 'svelte'; import { onMount, type Snippet } from 'svelte';
import { altFromFileName, uploadMedia } from '$lib/pb'; import { altFromFileName, uploadMedia } from '$lib/pb';
import MediaLibrary from './MediaLibrary.svelte';
type ImageValue = { url: string; alt: string; id?: string }; type ImageValue = { url: string; alt: string; id?: string };
/** /**
* The one image field of the admin: choose a file, drag one in or paste one (Ctrl+V while the * The one image field of the admin: choose a file, drag one in, paste one (Ctrl+V while the
* picker has focus, or the Paste button), and edit the address and alt text. * picker has focus, or the Paste button) or pick an uploaded one from the library, and edit
* `id` is the media record of a new upload ('' after Remove or a typed address; left out when * the address and alt text. Firefox and Safari show their own small "Paste" confirmation for
* the Paste button (a page can't read the clipboard unasked); Ctrl+V needs none.
* `id` is the media record of a new upload or library pick ('' after Remove or a typed address; left out when
* only the alt text changed), for fields that store a relation instead of an address * only the alt text changed), for fields that store a relation instead of an address
* (Services & products). Callers that store an address take `url` and `alt` only. * (Services & products). Callers that store an address take `url` and `alt` only.
*/ */
@ -15,7 +18,7 @@
url = '', url = '',
alt = '', alt = '',
withUrl = true, withUrl = true,
altHint = 'Describes the image for people who can’t see it, and for search engines', altHint = 'What the image shows, for people who can’t see it',
uploading = $bindable(false), uploading = $bindable(false),
children, children,
onChange = (value: ImageValue) => {} onChange = (value: ImageValue) => {}
@ -24,7 +27,7 @@
alt?: string; alt?: string;
/** Show the Image URL field (off where an uploaded media record is required). */ /** Show the Image URL field (off where an uploaded media record is required). */
withUrl?: boolean; withUrl?: boolean;
/** Hint under Alt text; '' hides the Alt text field (where the alt text comes from elsewhere). */ /** Placeholder of Alt text; '' hides the Alt text field (where the alt text comes from elsewhere). */
altHint?: string; altHint?: string;
/** True while a file uploads (bind it to hold off a form's Save). */ /** True while a file uploads (bind it to hold off a form's Save). */
uploading?: boolean; uploading?: boolean;
@ -40,6 +43,7 @@
let dragging = $state(false); let dragging = $state(false);
let error = $state(''); let error = $state('');
let canReadClipboard = $state(false); let canReadClipboard = $state(false);
let libraryOpen = $state(false);
let fileInput = $state<HTMLInputElement>(); let fileInput = $state<HTMLInputElement>();
let altInput = $state<HTMLInputElement>(); let altInput = $state<HTMLInputElement>();
@ -113,6 +117,12 @@
} }
} }
// An image from the library; like an upload, a hand-written alt text is kept.
function pick(media: { id: string; url: string; alt: string }) {
error = '';
onChange({ url: media.url, alt: alt || media.alt, id: media.id });
}
function remove() { function remove() {
error = ''; error = '';
onChange({ url: '', alt: '', id: '' }); onChange({ url: '', alt: '', id: '' });
@ -122,71 +132,68 @@
<!-- Paste is caught here, from whichever button or field inside has focus. --> <!-- Paste is caught here, from whichever button or field inside has focus. -->
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="@container" onpaste={onPaste}> <div class="@container" onpaste={onPaste}>
<div class="grid gap-x-5 gap-y-3 @md:grid-cols-[13rem_minmax(0,1fr)] @md:items-start"> <div class="grid gap-x-5 gap-y-3 @md:grid-cols-[11rem_minmax(0,1fr)] @md:items-center">
<div class="space-y-2"> <div class="group relative">
<div class="group relative"> <button
<button type="button"
type="button" class="relative flex h-40 w-full flex-col items-center justify-center overflow-hidden rounded-box p-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary {dragging ? 'border-2 border-dashed border-primary bg-primary/10' : url ? 'border border-base-300 bg-base-200' : 'border-2 border-dashed border-base-300 hover:border-primary'}"
class="relative flex h-40 w-full flex-col items-center justify-center overflow-hidden rounded-box p-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary {dragging ? 'border-2 border-dashed border-primary bg-primary/10' : url ? 'border border-base-300 bg-base-200' : 'border-2 border-dashed border-base-300 hover:border-primary'}" aria-label={url ? 'Replace image: choose a file, drop one here, or paste one' : 'Add image: choose a file, drop one here, or paste one'}
aria-label={url ? 'Replace image: choose a file, drop one here, or paste one' : 'Add image: choose a file, drop one here, or paste one'} aria-busy={uploading}
aria-busy={uploading} onclick={() => uploading || fileInput?.click()}
onclick={() => uploading || fileInput?.click()} ondragenter={(e) => { e.preventDefault(); dragging = true; }}
ondragenter={(e) => { e.preventDefault(); dragging = true; }} ondragover={(e) => e.preventDefault()}
ondragover={(e) => e.preventDefault()} ondragleave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) dragging = false; }}
ondragleave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) dragging = false; }} ondrop={onDrop}
ondrop={onDrop} >
> {#if uploading}
{#if uploading} <span class="loading loading-spinner loading-lg text-primary"></span>
<span class="loading loading-spinner loading-lg text-primary"></span> <span class="mt-2 text-sm text-base-content/60">Uploading…</span>
<span class="mt-2 text-sm text-base-content/60">Uploading…</span> {:else if url && !dragging}
{:else if url && !dragging} <img class="max-h-full max-w-full rounded object-contain" src={url} alt="" />
<img class="max-h-full max-w-full rounded object-contain" src={url} alt="" /> <span class="absolute inset-0 flex items-center justify-center bg-black/55 p-4 text-center text-sm font-medium text-white opacity-0 transition-opacity group-hover:opacity-100 group-has-[:focus-visible]:opacity-100">Click, drop or paste to replace</span>
<span class="absolute inset-0 flex items-center justify-center bg-black/55 p-4 text-center text-sm font-medium text-white opacity-0 transition-opacity group-hover:opacity-100 group-has-[:focus-visible]:opacity-100">Click, drop or paste to replace</span> {:else}
{:else} <svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909M3.75 21h16.5A1.5 1.5 0 0 0 21.75 19.5V4.5A1.5 1.5 0 0 0 20.25 3H3.75A1.5 1.5 0 0 0 2.25 4.5v15A1.5 1.5 0 0 0 3.75 21Zm10.5-11.25h.008v.008h-.008V9.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909M3.75 21h16.5A1.5 1.5 0 0 0 21.75 19.5V4.5A1.5 1.5 0 0 0 20.25 3H3.75A1.5 1.5 0 0 0 2.25 4.5v15A1.5 1.5 0 0 0 3.75 21Zm10.5-11.25h.008v.008h-.008V9.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" /> </svg>
</svg> <span class="text-center text-sm font-medium text-base-content/70">{dragging ? 'Drop to upload' : 'Click, drop or paste an image'}</span>
<span class="text-center text-sm font-medium text-base-content/70">{dragging ? 'Drop to upload' : 'Click, drop or paste an image'}</span> <span class="text-xs text-base-content/40">JPG, PNG, WebP, GIF, SVG</span>
<span class="text-xs text-base-content/40">JPG, PNG, WebP, GIF, SVG</span> {/if}
{/if} </button>
{#if url && !uploading}
<button class="btn btn-circle btn-sm absolute top-2 right-2 border-base-300 bg-base-100 text-error shadow-sm" type="button" aria-label="Remove image" title="Remove image" onclick={remove}>
<svg class="size-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
</button> </button>
{#if url && !uploading} {/if}
<button class="btn btn-circle btn-sm absolute top-2 right-2 border-base-300 bg-base-100 text-error shadow-sm" type="button" aria-label="Remove image" title="Remove image" onclick={remove}>
<svg class="size-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
</button>
{/if}
</div>
<div class="flex gap-2">
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={() => fileInput?.click()}>{url ? 'Replace…' : 'Choose file…'}</button>
{#if canReadClipboard}
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={pasteFromButton} title="Upload the image you copied">Paste</button>
{/if}
</div>
</div> </div>
{#if withUrl || altHint} {#if withUrl || altHint}
<div class="min-w-0"> <div class="min-w-0 space-y-3">
{#if altHint} {#if altHint}
<label class="fieldset pt-0"> <label class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3">
<span class="fieldset-legend pt-0">Alt text</span> <span class="w-24 shrink-0 text-sm font-medium">Alt text</span>
<input class="input w-full" value={alt} bind:this={altInput} oninput={(e) => onChange({ url, alt: e.currentTarget.value })} /> <input class="input w-full" value={alt} placeholder={altHint} title={altHint} bind:this={altInput} oninput={(e) => onChange({ url, alt: e.currentTarget.value })} />
<span class="label whitespace-normal">{altHint}</span>
</label> </label>
{/if} {/if}
{#if withUrl} {#if withUrl}
<label class="fieldset {altHint ? '' : 'pt-0'}"> <label class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3">
<span class="fieldset-legend {altHint ? '' : 'pt-0'}">Image URL</span> <span class="w-24 shrink-0 text-sm font-medium">Image URL</span>
<input class="input input-sm w-full text-base-content/70" value={url} placeholder="https://…" oninput={(e) => onChange({ url: e.currentTarget.value, alt, id: '' })} /> <input class="input w-full text-base-content/70" value={url} placeholder="Filled in by an upload, or https://…" oninput={(e) => onChange({ url: e.currentTarget.value, alt, id: '' })} />
<span class="label whitespace-normal">Filled in by an upload, or the address of an image elsewhere</span>
</label> </label>
{/if} {/if}
</div> </div>
{:else} {:else}
<div class="space-y-2 text-sm text-base-content/60 @md:self-center"> <div class="space-y-2 text-sm text-base-content/60">
<p>Click the box to choose a file, drag an image onto it, or click it and press Ctrl+V to paste.</p> <p>Click the box to choose a file, drag an image onto it, or click it and press Ctrl+V to paste.</p>
{@render children?.()} {@render children?.()}
</div> </div>
{/if} {/if}
<div class="flex gap-2 @md:col-span-2">
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={() => (libraryOpen = true)}>Pick from library</button>
{#if canReadClipboard}
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={pasteFromButton} title="Upload the image you copied">Paste</button>
{/if}
</div>
</div> </div>
{#if error} {#if error}
@ -194,4 +201,5 @@
{/if} {/if}
<input class="hidden" type="file" accept={TYPES.join(',')} onchange={onFileChosen} bind:this={fileInput} /> <input class="hidden" type="file" accept={TYPES.join(',')} onchange={onFileChosen} bind:this={fileInput} />
<MediaLibrary bind:open={libraryOpen} onPick={pick} />
</div> </div>

View file

@ -0,0 +1,98 @@
<script lang="ts">
import { untrack } from 'svelte';
import Modal from '$lib/admin/Modal.svelte';
import { thumbUrl } from '$shared/pb';
type Media = { id: string; url: string; alt: string };
// The images already uploaded to `media`, to reuse one instead of uploading it again.
let { open = $bindable(false), onPick = (media: Media) => {} } = $props<{
open?: boolean;
onPick?: (media: Media) => void;
}>();
let items = $state<Media[]>([]);
let page = $state(0);
let totalPages = $state(0);
let query = $state('');
let loading = $state(false);
let error = $state('');
let searchTimer: ReturnType<typeof setTimeout> | undefined;
async function load(nextPage: number) {
loading = true;
error = '';
try {
const res = await fetch(`/api/media?page=${nextPage}&q=${encodeURIComponent(query)}`);
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.message || `Loading failed (${res.status})`);
const data = await res.json();
items = nextPage === 1 ? data.items : [...items, ...data.items];
page = data.page;
totalPages = data.totalPages;
} catch (e) {
error = e instanceof Error ? e.message : 'Loading failed';
} finally {
loading = false;
}
}
// Fresh list each time it opens, so new uploads show up.
$effect(() => {
if (open) untrack(() => {
query = '';
load(1);
});
});
function search(value: string) {
query = value;
clearTimeout(searchTimer);
searchTimer = setTimeout(() => load(1), 250);
}
function pick(media: Media) {
onPick(media);
open = false;
}
</script>
<Modal bind:open title="Pick an uploaded image" wide>
<input
class="input mb-4 w-full"
type="search"
placeholder="Search by alt text or file name"
aria-label="Search images"
value={query}
oninput={(e) => search(e.currentTarget.value)}
onkeydown={(e) => e.key === 'Enter' && e.preventDefault()}
/>
{#if error}
<div class="alert alert-error mb-4 text-sm" role="alert">{error}</div>
{/if}
{#if items.length}
<div class="grid max-h-[60vh] grid-cols-3 gap-3 overflow-y-auto p-1 sm:grid-cols-4">
{#each items as media (media.id)}
<button
type="button"
class="group overflow-hidden rounded-box border border-base-300 bg-base-200 text-left transition hover:border-primary focus-visible:outline-2 focus-visible:outline-primary"
title={media.alt || 'No alt text'}
onclick={() => pick(media)}
>
<img class="aspect-square w-full object-cover" src={thumbUrl(media.url)} alt="" loading="lazy" />
<span class="block truncate px-2 py-1 text-xs text-base-content/70 group-hover:text-base-content">{media.alt || '—'}</span>
</button>
{/each}
</div>
{#if page < totalPages}
<div class="mt-3 text-center">
<button class="btn btn-sm" type="button" disabled={loading} onclick={() => load(page + 1)}>{loading ? 'Loading…' : 'Show more'}</button>
</div>
{/if}
{:else if loading}
<div class="py-10 text-center"><span class="loading loading-spinner loading-lg text-primary"></span></div>
{:else if !error}
<p class="py-10 text-center text-base-content/60">{query ? 'No images match that search.' : 'No images have been uploaded yet.'}</p>
{/if}
</Modal>

View file

@ -0,0 +1,29 @@
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
const PER_PAGE = 24;
// Uploaded images for the image picker's library, newest first; `q` searches alt text and file name.
export const GET: RequestHandler = async ({ url, locals }) => {
const page = Math.max(1, Number(url.searchParams.get('page')) || 1);
const q = (url.searchParams.get('q') || '').trim();
try {
const list = await locals.pb.collection('media').getList(page, PER_PAGE, {
sort: '-created',
filter: q ? locals.pb.filter('alt ~ {:q} || file ~ {:q}', { q }) : ''
});
return json({
page: list.page,
totalPages: list.totalPages,
items: list.items.map((record) => ({
id: record.id,
alt: record.alt || '',
url: `${env.PUBLIC_POCKETBASE_URL}/api/files/${record.collectionId}/${record.id}/${record.file}`
}))
});
} catch (e) {
console.error('Media list error:', e);
throw error(500, 'Couldn’t load the uploaded images');
}
};