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
10 changed files with 352 additions and 156 deletions

View file

@ -146,6 +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, 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

@ -2,7 +2,7 @@
import type { BlockType, ContentBlock } from '$lib/types'; import type { BlockType, ContentBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults'; import { blockLabels } from '$lib/admin/blockDefaults';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte'; import ImagePicker from './ImagePicker.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte'; import ColorField from './ColorField.svelte';
import ShopBlockEditor from './ShopBlockEditor.svelte'; import ShopBlockEditor from './ShopBlockEditor.svelte';
@ -94,7 +94,7 @@
</div> </div>
{:else if block.type === 'image_text'} {:else if block.type === 'image_text'}
<div class="space-y-4"> <div class="space-y-4">
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} /> <ImagePicker url={block.data.url} alt={block.data.alt} onChange={(image) => updateData({ url: image.url, alt: image.alt })} />
<SegmentedControl label="Image position" options={['left', 'right']} value={block.data.imagePosition === 'right' ? 'right' : 'left'} onChange={(v) => updateData({ imagePosition: v })} /> <SegmentedControl label="Image position" options={['left', 'right']} value={block.data.imagePosition === 'right' ? 'right' : 'left'} onChange={(v) => updateData({ imagePosition: v })} />
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> <RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
</div> </div>
@ -199,7 +199,7 @@
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button> <button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div> </div>
{#if block.data.style !== 'numbered'} {#if block.data.style !== 'numbered'}
<ImageUploader url={card.imageUrl} alt={card.imageAlt} onChange={(image) => updateArray('items', i, { imageUrl: image.url, imageAlt: image.alt })} /> <ImagePicker url={card.imageUrl} alt={card.imageAlt} onChange={(image) => updateArray('items', i, { imageUrl: image.url, imageAlt: image.alt })} />
{/if} {/if}
<div class="grid gap-x-3 md:grid-cols-2"> <div class="grid gap-x-3 md:grid-cols-2">
{@render field('Title', card.title || '', (title) => updateArray('items', i, { title }))} {@render field('Title', card.title || '', (title) => updateArray('items', i, { title }))}
@ -255,7 +255,7 @@
{#if block.data._background?.type === 'color'} {#if block.data._background?.type === 'color'}
<ColorField label="Color" value={block.data._background?.color || ''} fallback="#66755d" placeholder="#66755d" onChange={(color) => updateBackground({ color })} /> <ColorField label="Color" value={block.data._background?.color || ''} fallback="#66755d" placeholder="#66755d" onChange={(color) => updateBackground({ color })} />
{:else if block.data._background?.type === 'image'} {:else if block.data._background?.type === 'image'}
<ImageUploader url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateBackground({ imageUrl: image.url, imageAlt: image.alt })} /> <ImagePicker url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateBackground({ imageUrl: image.url, imageAlt: image.alt })} />
<SegmentedControl label="Attachment" options={['scroll', 'fixed']} value={block.data._background?.attachment || 'scroll'} onChange={(attachment) => updateBackground({ attachment })} /> <SegmentedControl label="Attachment" options={['scroll', 'fixed']} value={block.data._background?.attachment || 'scroll'} onChange={(attachment) => updateBackground({ attachment })} />
<SegmentedControl <SegmentedControl
label="Overlay" label="Overlay"

View file

@ -2,7 +2,7 @@
import type { EmailBlock, EmailBlockType } from '$lib/types'; import type { EmailBlock, EmailBlockType } from '$lib/types';
import { emailBlockLabels } from '$lib/admin/emailBlockDefaults'; import { emailBlockLabels } from '$lib/admin/emailBlockDefaults';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte'; import ImagePicker from './ImagePicker.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte'; import ColorField from './ColorField.svelte';
@ -36,7 +36,7 @@
<p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p> <p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p>
{:else if block.type === 'image'} {:else if block.type === 'image'}
<div class="space-y-4"> <div class="space-y-4">
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} /> <ImagePicker url={block.data.url} alt={block.data.alt} onChange={(image) => updateData({ url: image.url, alt: image.alt })} />
<SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} /> <SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} />
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} /> <SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} />
<label class="fieldset"> <label class="fieldset">

View file

@ -0,0 +1,205 @@
<script lang="ts">
import { onMount, type Snippet } from 'svelte';
import { altFromFileName, uploadMedia } from '$lib/pb';
import MediaLibrary from './MediaLibrary.svelte';
type ImageValue = { url: string; alt: string; id?: string };
/**
* 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) or pick an uploaded one from the library, and edit
* 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
* (Services & products). Callers that store an address take `url` and `alt` only.
*/
let {
url = '',
alt = '',
withUrl = true,
altHint = 'What the image shows, for people who can’t see it',
uploading = $bindable(false),
children,
onChange = (value: ImageValue) => {}
} = $props<{
url?: string;
alt?: string;
/** Show the Image URL field (off where an uploaded media record is required). */
withUrl?: boolean;
/** Placeholder of Alt text; '' hides the Alt text field (where the alt text comes from elsewhere). */
altHint?: string;
/** True while a file uploads (bind it to hold off a form's Save). */
uploading?: boolean;
/** Extra notes beside the box when there are no fields to show. */
children?: Snippet;
onChange?: (value: ImageValue) => void;
}>();
// What the media collection accepts (pb_schema.json → media.file).
const TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
const MAX_BYTES = 20 * 1024 * 1024;
let dragging = $state(false);
let error = $state('');
let canReadClipboard = $state(false);
let libraryOpen = $state(false);
let fileInput = $state<HTMLInputElement>();
let altInput = $state<HTMLInputElement>();
onMount(() => {
canReadClipboard = typeof navigator.clipboard?.read === 'function';
});
/** `pasted`: a clipboard image is called "image.png", so its name makes no alt text. */
async function upload(file: File, pasted = false) {
error = '';
if (!TYPES.includes(file.type)) {
error = 'That isn’t an image the site can use. Use a JPG, PNG, WebP, GIF or SVG.';
return;
}
if (file.size > MAX_BYTES) {
error = 'That image is larger than 20 MB. Make it smaller and try again.';
return;
}
uploading = true;
try {
// Keep a hand-written alt text; otherwise use the one made from the file name.
const newAlt = alt || (pasted ? '' : altFromFileName(file.name));
const result = await uploadMedia(file, newAlt);
onChange({ url: result.url, alt: newAlt, id: result.record.id });
if (pasted && !newAlt) altInput?.focus();
} catch (e) {
error = e instanceof Error ? e.message : 'Upload failed';
} finally {
uploading = false;
}
}
function pastedFile(blob: Blob) {
const extension = blob.type.split('/')[1]?.replace('svg+xml', 'svg') || 'png';
const stamp = new Date().toISOString().slice(0, 19).replace(/\D/g, '');
return new File([blob], `pasted-${stamp}.${extension}`, { type: blob.type });
}
function onFileChosen(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (file) upload(file);
}
function onDrop(event: DragEvent) {
event.preventDefault();
dragging = false;
const file = event.dataTransfer?.files?.[0];
if (file && !uploading) upload(file);
}
// Paste anywhere in the picker: an image is uploaded; text goes into the focused field as usual.
function onPaste(event: ClipboardEvent) {
const file = [...(event.clipboardData?.files || [])].find((f) => f.type.startsWith('image/'));
if (!file || uploading) return;
event.preventDefault();
upload(pastedFile(file), true);
}
async function pasteFromButton() {
error = '';
try {
for (const item of await navigator.clipboard.read()) {
const type = item.types.find((t) => t.startsWith('image/'));
if (type) return upload(pastedFile(await item.getType(type)), true);
}
error = 'There’s no image on the clipboard. Copy an image first (right-click it → Copy image).';
} catch {
error = 'The browser didn’t allow reading the clipboard. Click the image box and press Ctrl+V (⌘V on a Mac) instead.';
}
}
// 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() {
error = '';
onChange({ url: '', alt: '', id: '' });
}
</script>
<!-- Paste is caught here, from whichever button or field inside has focus. -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="@container" onpaste={onPaste}>
<div class="grid gap-x-5 gap-y-3 @md:grid-cols-[11rem_minmax(0,1fr)] @md:items-center">
<div class="group relative">
<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'}"
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}
onclick={() => uploading || fileInput?.click()}
ondragenter={(e) => { e.preventDefault(); dragging = true; }}
ondragover={(e) => e.preventDefault()}
ondragleave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) dragging = false; }}
ondrop={onDrop}
>
{#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span>
<span class="mt-2 text-sm text-base-content/60">Uploading…</span>
{:else if url && !dragging}
<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>
{: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">
<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>
<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>
{/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>
{/if}
</div>
{#if withUrl || altHint}
<div class="min-w-0">
{#if altHint}
<label class="fieldset pt-0">
<span class="fieldset-legend pt-0">Alt text</span>
<input class="input w-full" value={alt} placeholder={altHint} title={altHint} bind:this={altInput} oninput={(e) => onChange({ url, alt: e.currentTarget.value })} />
</label>
{/if}
{#if withUrl}
<label class="fieldset {altHint ? '' : 'pt-0'}">
<span class="fieldset-legend {altHint ? '' : 'pt-0'}">Image URL</span>
<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: '' })} />
</label>
{/if}
</div>
{:else}
<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>
{@render children?.()}
</div>
{/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>
{#if error}
<div class="alert alert-error mt-3 text-sm" role="alert">{error}</div>
{/if}
<input class="hidden" type="file" accept={TYPES.join(',')} onchange={onFileChosen} bind:this={fileInput} />
<MediaLibrary bind:open={libraryOpen} onPick={pick} />
</div>

View file

@ -1,107 +0,0 @@
<script lang="ts">
import { uploadMedia } from '$lib/pb';
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
url?: string;
alt?: string;
onChange?: (value: { url: string; alt: string }) => void;
}>();
let uploading = $state(false);
let error = $state('');
let fileInput = $state<HTMLInputElement>();
// Local state synced from props so reactivity works reliably in Svelte 5
let localUrl = $state(urlProp);
let localAlt = $state(altProp);
$effect(() => { localUrl = urlProp; });
$effect(() => { localAlt = altProp; });
function emitChange() {
onChange({ url: localUrl, alt: localAlt });
}
async function handleFile(event: Event) {
const file = (event.currentTarget as HTMLInputElement).files?.[0];
if (!file) return;
uploading = true;
error = '';
try {
const result = await uploadMedia(file);
localUrl = result.url;
// Keep a hand-written alt text; otherwise use the one derived from the filename.
if (!localAlt) localAlt = result.record?.alt || '';
emitChange();
} catch (e) {
error = e instanceof Error ? e.message : 'Upload failed';
console.error('Image upload error:', e);
} finally {
uploading = false;
}
}
function removeImage() {
localUrl = '';
localAlt = '';
emitChange();
if (fileInput) fileInput.value = '';
}
</script>
<div class="grid grid-cols-[1fr_1.5fr] gap-4">
<!-- Drop zone / upload area -->
<div
class="flex h-32 cursor-pointer flex-col items-center justify-center rounded-box border-2 border-dashed p-3 transition-colors hover:border-primary {localUrl ? 'border-success/40' : 'border-base-300'}"
role="button"
tabindex="0"
onclick={() => fileInput?.click()}
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
>
{#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-3 text-sm text-base-content/60">Uploading…</p>
{:else if localUrl}
<div class="relative w-full">
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
<button
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
type="button"
onclick={(e) => { e.stopPropagation(); removeImage(); }}
title="Remove image"
>✕</button>
</div>
{: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">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
</svg>
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
<p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
{/if}
</div>
{#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div>
{/if}
<input
class="hidden"
type="file"
accept="image/*"
onchange={handleFile}
disabled={uploading}
bind:this={fileInput}
/>
<!-- URL & Alt fields -->
<div>
<label class="fieldset pt-0">
<span class="fieldset-legend">Image URL</span>
<input class="input w-full" bind:value={localUrl} oninput={() => emitChange()} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Alt text</span>
<input class="input w-full" bind:value={localAlt} oninput={() => emitChange()} />
</label>
</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

@ -1,10 +1,11 @@
export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb'; export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb';
// App-specific: admin uploads go through the admin upload endpoint. // App-specific: admin uploads go through the admin upload endpoint.
export async function uploadMedia(file: File) { // Without an alt text, the media record gets one made from the file name.
export async function uploadMedia(file: File, alt = altFromFileName(file.name)) {
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); formData.append('alt', alt);
const res = await fetch('/api/upload', { method: 'POST', body: formData }); const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) { if (!res.ok) {
@ -13,3 +14,7 @@ export async function uploadMedia(file: File) {
} }
return res.json(); return res.json();
} }
export function altFromFileName(name: string) {
return name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ');
}

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');
}
};

View file

@ -2,7 +2,7 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { fly, slide } from 'svelte/transition'; import { fly, slide } from 'svelte/transition';
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte'; import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
import { PRIVACY_PAGE_SLUG } from '$lib/admin/privacyTemplate'; import { PRIVACY_PAGE_SLUG } from '$lib/admin/privacyTemplate';
import { shopLinks } from '$lib/types'; import { shopLinks } from '$lib/types';
import type { SubmitFunction } from '@sveltejs/kit'; import type { SubmitFunction } from '@sveltejs/kit';
@ -126,7 +126,7 @@
<input type="hidden" name="data" value={JSON.stringify(header)} /> <input type="hidden" name="data" value={JSON.stringify(header)} />
<h2 class="mb-4 text-2xl font-bold">Header</h2> <h2 class="mb-4 text-2xl font-bold">Header</h2>
<h3 class="mb-2 font-bold">Logo</h3> <h3 class="mb-2 font-bold">Logo</h3>
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} /> <ImagePicker url={header.logo?.url} alt={header.logo?.alt} altHint="Usually the business name" onChange={(image) => (header.logo = { url: image.url, alt: image.alt })} />
<h3 class="mt-6 mb-2 font-bold">Home page</h3> <h3 class="mt-6 mb-2 font-bold">Home page</h3>
<select class="select w-full" aria-label="Home page" bind:value={header.homePage}> <select class="select w-full" aria-label="Home page" bind:value={header.homePage}>
<option value="">— Select a page —</option> <option value="">— Select a page —</option>

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { uploadMedia } from '$lib/pb'; import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
@ -9,8 +9,6 @@
let items = $derived(data.items || []); let items = $derived(data.items || []);
let showEditor = $state(false); let showEditor = $state(false);
let uploading = $state(false); let uploading = $state(false);
let uploadError = $state('');
let fileInput: HTMLInputElement | undefined = $state();
type ItemDraft = { type ItemDraft = {
id: string; id: string;
@ -102,7 +100,6 @@
function createItem() { function createItem() {
draft = emptyDraft(); draft = emptyDraft();
uploadError = '';
showEditor = true; showEditor = true;
} }
@ -123,26 +120,8 @@
capacity: item.capacity == null ? '' : String(item.capacity), capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active active: item.active
}; };
uploadError = '';
showEditor = true; showEditor = true;
} }
async function onImageSelected(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
uploading = true;
uploadError = '';
try {
const result = await uploadMedia(file);
draft = { ...draft, image: result.record.id, imageUrl: result.url };
} catch (err) {
uploadError = err instanceof Error ? err.message : 'Upload failed.';
} finally {
uploading = false;
input.value = '';
}
}
</script> </script>
<svelte:head><title>Services & products | CMS</title></svelte:head> <svelte:head><title>Services & products | CMS</title></svelte:head>
@ -326,23 +305,9 @@
<div class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Image</span> <span class="fieldset-legend">Image</span>
<div class="flex items-center gap-4"> <ImagePicker url={draft.imageUrl} withUrl={false} altHint="" bind:uploading onChange={(image) => (draft = { ...draft, image: image.id ?? draft.image, imageUrl: image.url })}>
{#if draft.imageUrl} <p>The shop uses the name as the image’s alt text.</p>
<img class="size-20 rounded-box object-cover shadow" src={draft.imageUrl} alt="" /> </ImagePicker>
{:else}
<div class="grid size-20 place-items-center rounded-box border-2 border-dashed border-base-300 text-xs text-base-content/40">No image</div>
{/if}
<div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" disabled={uploading} onclick={() => fileInput?.click()}>
{#if uploading}<span class="loading loading-spinner loading-xs"></span> Uploading…{:else}{draft.imageUrl ? 'Replace image' : 'Upload image'}{/if}
</button>
{#if draft.image}
<button class="btn btn-ghost btn-sm text-error" type="button" onclick={() => (draft = { ...draft, image: '', imageUrl: '' })}>Remove</button>
{/if}
</div>
<input class="hidden" type="file" accept="image/*" bind:this={fileInput} onchange={onImageSelected} />
</div>
{#if uploadError}<span class="label text-error">{uploadError}</span>{/if}
</div> </div>
<label class="label mt-2 cursor-pointer gap-3 text-base-content"> <label class="label mt-2 cursor-pointer gap-3 text-base-content">