Ansprechpartner: komfortable, wiederverwendbare Auswahl

- Auswahlfeld mit Suche, Foto und Funktion; echte Checkboxen (Tastatur,
  Screenreader) und Ansage beim Hinzufügen/Entfernen
- Reihenfolge der gewählten Personen änderbar
- Neue Person direkt aus dem Feld anlegen und hinzufügen
- Personenseite zeigt „Verwendet in“ (Seiten und Meldungen)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-30 16:01:20 +00:00
parent 7da1a10af2
commit ded828ddef
7 changed files with 224 additions and 46 deletions

View file

@ -2,51 +2,179 @@
import { untrack } from 'svelte';
import X from '@lucide/svelte/icons/x';
import Plus from '@lucide/svelte/icons/plus';
import Search from '@lucide/svelte/icons/search';
import ChevronUp from '@lucide/svelte/icons/chevron-up';
import ChevronDown from '@lucide/svelte/icons/chevron-down';
import UserPlus from '@lucide/svelte/icons/user-plus';
import Check from '@lucide/svelte/icons/check';
import { toasts } from './toast.svelte';
import type { ContactCard } from '$lib/types';
type Option = { id: number; name: string; role: string };
let { name, options, value = [] }: { name: string; options: Option[]; value?: number[] } = $props();
/**
* Ansprechpartner auswählen – einmal unter „Ansprechpartner“ angelegt,
* überall wiederverwendbar. Neue Personen lassen sich direkt hier anlegen.
*/
let { name, options, value = [] }: { name: string; options: ContactCard[]; value?: number[] } = $props();
let all = $state<ContactCard[]>(untrack(() => [...options]));
let selected = $state<number[]>(untrack(() => value));
let adding = $state('');
let open = $state(false);
let q = $state('');
let creating = $state(false);
let draft = $state({ name: '', role: '', email: '', phone: '' });
let saving = $state(false);
let announce = $state('');
const byId = $derived(new Map(options.map((o) => [o.id, o])));
const available = $derived(options.filter((o) => !selected.includes(o.id)));
const uid = $props.id();
const byId = $derived(new Map(all.map((o) => [o.id, o])));
const filtered = $derived(
all.filter((o) => [o.name, o.role, o.location].join(' ').toLowerCase().includes(q.trim().toLowerCase()))
);
function toggle(id: number, on: boolean) {
selected = on ? [...selected, id] : selected.filter((x) => x !== id);
announce = `${byId.get(id)?.name} ${on ? 'hinzugefügt' : 'entfernt'}`;
}
function move(i: number, d: number) {
const next = [...selected];
[next[i], next[i + d]] = [next[i + d], next[i]];
selected = next;
announce = `${byId.get(next[i + d])?.name} auf Position ${i + d + 1} verschoben`;
}
async function create() {
if (!draft.name.trim()) return;
saving = true;
const res = await fetch('/admin/api/ansprechpartner', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(draft)
});
saving = false;
if (!res.ok) {
toasts.show((await res.json().catch(() => null))?.message ?? 'Anlegen fehlgeschlagen.', 'error');
return;
}
const contact: ContactCard = await res.json();
all = [...all, contact].sort((a, b) => a.name.localeCompare(b.name, 'de'));
selected = [...selected, contact.id];
draft = { name: '', role: '', email: '', phone: '' };
creating = false;
toasts.show(`${contact.name} angelegt und hinzugefügt`);
}
const initialsOf = (n: string) =>
n
.split(/\s+/)
.map((w) => w[0])
.slice(0, 2)
.join('');
</script>
<div>
<span class="label">Ansprechpartner</span>
<fieldset>
<legend class="label">Ansprechpartner</legend>
<input type="hidden" {name} value={JSON.stringify(selected)} />
<p class="sr-only" aria-live="polite">{announce}</p>
{#if selected.length}
<ul class="flex flex-wrap gap-2 mb-2">
{#each selected as id (id)}
<ol class="space-y-2 mb-3">
{#each selected as id, i (id)}
{@const c = byId.get(id)}
{#if c}
<li class="inline-flex items-center gap-2 rounded-full bg-brand-soft text-brand-ink pl-3 pr-1 py-1 text-sm font-semibold">
{c.name}
<button type="button" class="grid place-items-center size-6 rounded-full hover:bg-white/60" aria-label="{c.name} entfernen" onclick={() => (selected = selected.filter((x) => x !== id))}><X class="size-3.5" /></button>
<li class="flex items-center gap-3 rounded-xl border border-line bg-surface px-2.5 py-2">
{#if c.photo}
<img src={c.photo.thumb} alt="" class="size-9 rounded-full object-cover shrink-0" />
{:else}
<span class="grid place-items-center size-9 rounded-full bg-surface-2 text-brand-ink text-xs font-bold shrink-0" aria-hidden="true">{initialsOf(c.name)}</span>
{/if}
<span class="flex-1 min-w-0 leading-tight">
<span class="block font-semibold text-sm truncate">{c.name}</span>
{#if c.role || c.location}<span class="block text-xs text-ink-3 truncate">{[c.role, c.location].filter(Boolean).join(' · ')}</span>{/if}
</span>
{#if selected.length > 1}
<span class="flex">
<button type="button" class="grid place-items-center size-7 rounded-lg text-ink-3 hover:bg-surface-2 disabled:opacity-30" disabled={i === 0} aria-label="{c.name} nach oben" onclick={() => move(i, -1)}><ChevronUp class="size-4" /></button>
<button type="button" class="grid place-items-center size-7 rounded-lg text-ink-3 hover:bg-surface-2 disabled:opacity-30" disabled={i === selected.length - 1} aria-label="{c.name} nach unten" onclick={() => move(i, 1)}><ChevronDown class="size-4" /></button>
</span>
{/if}
<button type="button" class="grid place-items-center size-7 rounded-lg text-ink-3 hover:bg-surface-2 hover:text-danger" aria-label="{c.name} entfernen" onclick={() => toggle(id, false)}><X class="size-4" /></button>
</li>
{/if}
{/each}
</ul>
</ol>
{/if}
{#if available.length}
<div class="flex gap-2">
<select bind:value={adding} class="field min-h-10 py-1.5" aria-label="Ansprechpartner hinzufügen">
<option value="">Ansprechpartner hinzufügen …</option>
{#each available as o (o.id)}<option value={String(o.id)}>{o.name}{o.role ? ` – ${o.role}` : ''}</option>{/each}
</select>
<button
type="button"
class="btn btn-soft btn-sm btn-icon shrink-0 self-center"
aria-label="Hinzufügen"
disabled={!adding}
onclick={() => {
selected = [...selected, Number(adding)];
adding = '';
}}><Plus class="size-4" /></button
>
<button type="button" class="btn btn-soft btn-sm" aria-expanded={open} aria-controls="{uid}-panel" onclick={() => (open = !open)}>
<Plus class="size-4" />{open ? 'Auswahl schließen' : 'Ansprechpartner wählen'}
</button>
{#if open}
<div id="{uid}-panel" class="mt-3 rounded-2xl border border-line bg-surface-2/50 p-3 space-y-3">
{#if all.length > 5}
<label class="relative block">
<span class="sr-only">Ansprechpartner suchen</span>
<Search class="size-4 text-ink-3 absolute left-3 top-1/2 -translate-y-1/2" />
<input bind:value={q} type="search" class="field min-h-10 py-1.5 pl-9 text-sm" placeholder="Name, Aufgabe oder Standort" />
</label>
{/if}
{#if filtered.length}
<ul class="max-h-64 overflow-y-auto space-y-1 pr-1" aria-label="Verfügbare Ansprechpartner">
{#each filtered as c (c.id)}
{@const on = selected.includes(c.id)}
<li>
<label class="flex items-center gap-3 rounded-xl px-2 py-1.5 cursor-pointer hover:bg-surface {on ? 'bg-surface' : ''}">
<input type="checkbox" class="sr-only peer" checked={on} onchange={(e) => toggle(c.id, e.currentTarget.checked)} />
<span class="grid place-items-center size-5 rounded-md border-2 shrink-0 peer-focus-visible:ring-2 peer-focus-visible:ring-accent {on ? 'bg-brand border-brand text-on-brand' : 'border-line bg-surface'}" aria-hidden="true">
{#if on}<Check class="size-3.5" strokeWidth={3} />{/if}
</span>
{#if c.photo}
<img src={c.photo.thumb} alt="" class="size-8 rounded-full object-cover shrink-0" />
{:else}
<span class="grid place-items-center size-8 rounded-full bg-surface text-brand-ink text-[0.7rem] font-bold shrink-0" aria-hidden="true">{initialsOf(c.name)}</span>
{/if}
<span class="min-w-0 leading-tight">
<span class="block text-sm font-semibold truncate">{c.name}</span>
{#if c.role}<span class="block text-xs text-ink-3 truncate">{c.role}</span>{/if}
</span>
</label>
</li>
{/each}
</ul>
{:else}
<p class="text-sm text-ink-3 px-1">{all.length ? 'Niemand gefunden.' : 'Noch keine Ansprechpartner angelegt.'}</p>
{/if}
{#if creating}
<div class="rounded-xl bg-surface border border-line p-3 space-y-3" role="group" aria-label="Neue Person anlegen">
<div class="grid sm:grid-cols-2 gap-3">
<div>
<label class="label" for="{uid}-name">Name</label>
<input id="{uid}-name" bind:value={draft.name} class="field min-h-10 py-1.5 text-sm" />
</div>
<div>
<label class="label" for="{uid}-role">Aufgabe / Funktion</label>
<input id="{uid}-role" bind:value={draft.role} class="field min-h-10 py-1.5 text-sm" />
</div>
<div>
<label class="label" for="{uid}-email">E-Mail</label>
<input id="{uid}-email" type="email" bind:value={draft.email} class="field min-h-10 py-1.5 text-sm" />
</div>
<div>
<label class="label" for="{uid}-phone">Telefon</label>
<input id="{uid}-phone" type="tel" bind:value={draft.phone} class="field min-h-10 py-1.5 text-sm" />
</div>
</div>
<p class="hint !mt-0">Foto und Standort kannst du später unter „Ansprechpartner“ ergänzen.</p>
<div class="flex gap-2">
<button type="button" class="btn btn-primary btn-sm" disabled={!draft.name.trim() || saving} onclick={create}>Anlegen & hinzufügen</button>
<button type="button" class="btn btn-ghost btn-sm" onclick={() => (creating = false)}>Abbrechen</button>
</div>
</div>
{:else}
<button type="button" class="btn btn-ghost btn-sm" onclick={() => (creating = true)}><UserPlus class="size-4" />Neue Person anlegen</button>
{/if}
</div>
{:else if !options.length}
<p class="hint">Lege zuerst unter „Ansprechpartner“ Personen an.</p>
{/if}
</div>
</fieldset>

View file

@ -50,6 +50,12 @@ export function contactsByIds(ids: number[]): ContactCard[] {
}));
}
/** Alle Ansprechpartner für Auswahlfelder in der Redaktion (inkl. nicht gelisteter) */
export function contactOptions() {
const rows = db.select({ id: contacts.id }).from(contacts).orderBy(asc(contacts.name)).all();
return contactsByIds(rows.map((r) => r.id));
}
export function listedContacts(): ContactCard[] {
const rows = db
.select({ id: contacts.id })

View file

@ -7,13 +7,22 @@ import { fields, parseId } from '$lib/server/forms';
import { nextSortOrder } from '$lib/server/sorting';
import type { MediaItem } from '$lib/types';
/** Wo wird diese Person angezeigt? */
function usage(id: number) {
const hit = (ids: number[]) => ids.includes(id);
return [
...db.select({ id: pages.id, title: pages.title, contactIds: pages.contactIds }).from(pages).all().filter((p) => hit(p.contactIds)).map((p) => ({ href: `/admin/seiten/${p.id}`, title: p.title, kind: 'Seite' })),
...db.select({ id: posts.id, title: posts.title, contactIds: posts.contactIds }).from(posts).all().filter((p) => hit(p.contactIds)).map((p) => ({ href: `/admin/meldungen/${p.id}`, title: p.title, kind: 'Meldung' }))
];
}
export const load = ({ params }) => {
const id = parseId(params.id);
if (id === 'new')
return { isNew: true, contact: { id: 0, name: '', role: '', location: '', email: '', phone: '', listed: true, photo: null as MediaItem | null } };
return { isNew: true, usage: [] as ReturnType<typeof usage>, contact: { id: 0, name: '', role: '', location: '', email: '', phone: '', listed: true, photo: null as MediaItem | null } };
const c = db.select().from(contacts).where(eq(contacts.id, id)).get();
if (!c) error(404);
return { isNew: false, contact: { ...c, photo: getMedia(c.photoId) } };
return { isNew: false, usage: usage(c.id), contact: { ...c, photo: getMedia(c.photoId) } };
};
export const actions = {

View file

@ -42,6 +42,24 @@
<ImageField name="photoId" value={c.photo} label="Foto" aspect="aspect-square" />
<Switch name="listed" checked={c.listed} label="Im Verzeichnis zeigen" hint="Unter „Ansprechpartner“ in der App" />
</Panel>
{#if !data.isNew}
<Panel title="Verwendet in" description="Hier erscheint die Person. Änderungen gelten überall.">
{#if data.usage.length}
<ul class="space-y-1.5 -mt-2">
{#each data.usage as u (u.href)}
<li>
<a href={u.href} class="flex items-baseline gap-2 text-sm hover:text-brand-ink">
<span class="text-xs font-bold uppercase tracking-wider text-ink-3 w-16 shrink-0">{u.kind}</span>
<span class="font-semibold">{u.title}</span>
</a>
</li>
{/each}
</ul>
{:else}
<p class="text-sm text-ink-3 -mt-2">Noch bei keiner Seite oder Meldung eingetragen.</p>
{/if}
</Panel>
{/if}
{/snippet}
</EditForm>
{/key}

View file

@ -1,8 +1,8 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { asc, eq } from 'drizzle-orm';
import { eq } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { contacts, posts } from '$lib/server/db/schema';
import { attachmentsOf, getMedia, mediaByIds } from '$lib/server/content';
import { posts } from '$lib/server/db/schema';
import { attachmentsOf, contactOptions as listContactOptions, getMedia, mediaByIds } from '$lib/server/content';
import { fields, parseId, uniqueSlug } from '$lib/server/forms';
import { cleanHtml } from '$lib/server/sanitize';
import { fromLocalInput, toLocalInput } from '$lib/dates';
@ -10,11 +10,7 @@ import type { MediaItem } from '$lib/types';
export const load = ({ params }) => {
const id = parseId(params.id);
const contactOptions = db
.select({ id: contacts.id, name: contacts.name, role: contacts.role })
.from(contacts)
.orderBy(asc(contacts.name))
.all();
const contactOptions = listContactOptions();
if (id === 'new') {
return {

View file

@ -1,8 +1,8 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { asc, eq, isNull } from 'drizzle-orm';
import { eq, isNull } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { contacts, pages } from '$lib/server/db/schema';
import { attachmentsOf, getMedia } from '$lib/server/content';
import { pages } from '$lib/server/db/schema';
import { attachmentsOf, contactOptions as listContactOptions, getMedia } from '$lib/server/content';
import { fields, parseId, uniqueSlug } from '$lib/server/forms';
import { cleanHtml } from '$lib/server/sanitize';
import { descendantsOf, pageTree } from '$lib/server/pageTree';
@ -13,7 +13,7 @@ import type { MediaItem } from '$lib/types';
export const load = ({ params, url }) => {
const id = parseId(params.id);
const contactOptions = db.select({ id: contacts.id, name: contacts.name, role: contacts.role }).from(contacts).orderBy(asc(contacts.name)).all();
const contactOptions = listContactOptions();
const excluded = id === 'new' ? new Set<number>() : descendantsOf(id);
const parentOptions = pageTree()
.filter((r) => !excluded.has(r.id))

View file

@ -0,0 +1,21 @@
import { error, json } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { contacts } from '$lib/server/db/schema';
import { contactsByIds } from '$lib/server/content';
import { nextSortOrder } from '$lib/server/sorting';
/** Ansprechpartner direkt aus einem Auswahlfeld heraus anlegen */
export const POST = async ({ request }) => {
const body = await request.json().catch(() => null);
const str = (v: unknown, max = 200) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
const name = str(body?.name);
const email = str(body?.email);
if (!name) error(400, 'Bitte gib einen Namen ein.');
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) error(400, 'Die E-Mail-Adresse sieht nicht richtig aus.');
const created = db
.insert(contacts)
.values({ name, role: str(body?.role), location: str(body?.location), email, phone: str(body?.phone, 50), sortOrder: nextSortOrder(contacts) })
.returning({ id: contacts.id })
.get();
return json(contactsByIds([created.id])[0]);
};