From 5a9bc389136dbb969a4eb1adbee641f0519f6ae0 Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 13:55:53 -0500 Subject: [PATCH 1/9] docs(admin): plan event hosts panel --- docs/plans/300-event-hosts.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 docs/plans/300-event-hosts.md diff --git a/docs/plans/300-event-hosts.md b/docs/plans/300-event-hosts.md new file mode 100644 index 0000000..e15a701 --- /dev/null +++ b/docs/plans/300-event-hosts.md @@ -0,0 +1,18 @@ +# Event hosts panel + +## Remaining work + +Issues #299 and #300 already have resources, related events, topics, partners, and guest-side event links. This change completes the joined host read and the event-side speakers and hosts editor. + +## Design + +- Read `event_hosts` with its team or guest relation and map each valid row to a display-ready host card. +- Save the desired host list as one ordered operation: remove rows that are no longer wanted, then upsert the remaining rows with their current positions. +- Add the first event-extra panel for speakers and hosts. It supports an accessible grouped picker, draft-only add/remove/reorder controls, and a single save action. +- Keep guest links in sync after saves; team hosts remain visibly marked as not yet published on the site. + +## Files and tests + +- Update the host types, data functions, query hooks, event extras, guide, and add `EventHostsPanel`. +- Extend data tests for joined mapping and whole-list saves; extend event extras tests for keyboard reordering, picker choices, saving, and host visibility notes. +- Verify the admin lint, test, and build commands, plus the site build. Resource reordering will be checked but is outside this change if unsupported. From a174c314d7982929a787dc086191191cb3eaf284 Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 14:03:25 -0500 Subject: [PATCH 2/9] feat(admin): add event hosts panel --- .../src/components/events/EventExtras.tsx | 2 + .../src/components/events/EventHostsPanel.tsx | 40 +++ apps/admin/src/hooks/useEventHosts.ts | 62 +---- apps/admin/src/lib/data/event-hosts.ts | 211 ++++------------ apps/admin/src/types/event-host.ts | 43 +--- apps/admin/tests/lib/data/event-hosts.test.ts | 229 +++--------------- docs/admin-guide.md | 4 + 7 files changed, 148 insertions(+), 443 deletions(-) create mode 100644 apps/admin/src/components/events/EventHostsPanel.tsx diff --git a/apps/admin/src/components/events/EventExtras.tsx b/apps/admin/src/components/events/EventExtras.tsx index b0028c1..cd3d0d4 100644 --- a/apps/admin/src/components/events/EventExtras.tsx +++ b/apps/admin/src/components/events/EventExtras.tsx @@ -3,6 +3,7 @@ * last time. Each panel saves by itself, so it is only shown once the event exists. */ import type { Event } from '../../types/event'; +import { EventHostsPanel } from './EventHostsPanel'; import { EventLastTimePanel } from './EventLastTimePanel'; import { EventPartnersPanel } from './EventPartnersPanel'; import { EventResourcesPanel } from './EventResourcesPanel'; @@ -14,6 +15,7 @@ export function EventExtras({ event }: { event: Event }) {

On the event's page

+ diff --git a/apps/admin/src/components/events/EventHostsPanel.tsx b/apps/admin/src/components/events/EventHostsPanel.tsx new file mode 100644 index 0000000..0d520ee --- /dev/null +++ b/apps/admin/src/components/events/EventHostsPanel.tsx @@ -0,0 +1,40 @@ +/** Ordered speaker and host editor for an existing event. */ +import { ArrowDown, ArrowUp, X } from 'lucide-react'; +import { useState } from 'react'; +import { Link } from 'react-router'; +import { useEventHosts, useSaveHosts } from '../../hooks/useEventHosts'; +import { useGuests } from '../../hooks/useGuests'; +import { useTeam } from '../../hooks/useTeam'; +import { PATHS } from '../../paths'; +import type { HostCard, HostFields } from '../../types/event-host'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { SearchField } from '../ui/SearchField'; +import { Tag } from '../ui/Tag'; +import { ExtraPanel } from './ExtraPanel'; +import { PanelSaveBar } from './PanelSaveBar'; + +export function EventHostsPanel({ eventId }: { eventId: string }) { + const hosts = useEventHosts(eventId); const save = useSaveHosts(eventId); const guests = useGuests(); const team = useTeam(); + return + {(saved) => } + ; +} +type Person = { id: string; name: string; pictureUrl: string | null; title?: string | null; role?: string | null; isPublic?: boolean }; +function HostsEditor({ saved, save, guests, team }: { saved: readonly HostCard[]; save: ReturnType; guests: readonly Person[]; team: readonly Person[] }) { + const [rows, setRows] = useState(saved); const [changed, setChanged] = useState(false); const [query, setQuery] = useState(''); + const ids = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); const term = query.trim().toLocaleLowerCase(); + const visibleGuests = guests.filter((person) => !ids.has(`guest:${person.id}`) && person.name.toLocaleLowerCase().includes(term)); + const visibleTeam = team.filter((person) => !ids.has(`team:${person.id}`) && person.name.toLocaleLowerCase().includes(term)); + function change(next: readonly HostCard[]) { setRows(next); setChanged(true); } + function move(index: number, by: -1 | 1) { const next = [...rows]; const [row] = next.splice(index, 1); if (row) next.splice(index + by, 0, row); change(next); } + function add(kind: 'team' | 'guest', person: Person) { change([...rows, { id: crypto.randomUUID(), eventId: '', sortOrder: rows.length, kind, personId: person.id, name: person.name, subtitle: kind === 'team' ? person.role ?? null : person.title ?? null, pictureUrl: person.pictureUrl, company: null, isPublic: kind === 'team' ? person.isPublic === true : true }]); setQuery(''); } + const fields = (): readonly HostFields[] => rows.map((row) => row.kind === 'team' ? { kind: 'team', teamId: row.personId } : { kind: 'guest', guestId: row.personId }); + return <> + {rows.length === 0 ?

No speakers or hosts yet. Add guests here, or from their guest page.

:
    {rows.map((host, index) => change(rows.filter((row) => row.id !== host.id))} />)}
} +
add('guest', person)} /> add('team', person)} />

Add a new guest

+ save.mutate(fields(), { onSuccess: () => setChanged(false) })} /> + ; +} +function PickerGroup({ title, people, onPick }: { title: string; people: readonly Person[]; onPick: (person: Person) => void }) { return

{title}

{people.length === 0 ?

No people found.

:
    {people.map((person) =>
  • )}
}
; } +function HostRow({ host, index, total, onMove, onRemove }: { host: HostCard; index: number; total: number; onMove: (index: number, by: -1 | 1) => void; onRemove: () => void }) { return
  • {host.name}

    {host.subtitle &&

    {host.subtitle}

    }{host.kind === 'team' &&

    Not shown on the site yet{!host.isPublic && '; hidden from the site'}.

    }
    {host.kind === 'guest' && host.company && {host.company.logoUrl ? : }}{host.kind === 'team' ? 'Team' : 'Guest'}
  • ; } +function Face({ host }: { host: HostCard }) { return host.pictureUrl ? : ; } diff --git a/apps/admin/src/hooks/useEventHosts.ts b/apps/admin/src/hooks/useEventHosts.ts index 6ccab58..ef38a11 100644 --- a/apps/admin/src/hooks/useEventHosts.ts +++ b/apps/admin/src/hooks/useEventHosts.ts @@ -1,56 +1,10 @@ -/** Event hosts loaded and cached by TanStack Query, and the changes that refresh them. */ +/** Event hosts loaded and saved as an ordered list. */ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { addGuestHost, addTeamHost, deleteHost, getHost, listHosts, reorderHosts, updateHost } from '../lib/data/event-hosts'; -import type { EventHost, HostFields } from '../types/event-host'; - -// Every hosts query for an event starts with this key. +import { listHosts, saveHosts } from '../lib/data/event-hosts'; +import type { HostFields } from '../types/event-host'; +import { GUESTS_KEY } from './useGuests'; const makeHostsKey = (eventId: string) => ['hosts', eventId] as const; - -export function useEventHosts(eventId: string) { - return useQuery({ queryKey: makeHostsKey(eventId), queryFn: () => listHosts(eventId) }); -} - -/** One host for editing; `data` is null when there is no such host. */ -export function useEventHost(id: string) { - return useQuery({ queryKey: ['host', id], queryFn: () => getHost(id) }); -} - -/** Refreshes hosts for an event once a change has been saved. */ -function useRefreshHosts(eventId: string) { - const queryClient = useQueryClient(); - return () => queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }); -} - -export function useAddTeamHost(eventId: string) { - const refresh = useRefreshHosts(eventId); - return useMutation({ - mutationFn: (teamId: string) => addTeamHost(eventId, teamId), - onSuccess: refresh, - }); -} - -export function useAddGuestHost(eventId: string) { - const refresh = useRefreshHosts(eventId); - return useMutation({ - mutationFn: (guestId: string) => addGuestHost(eventId, guestId), - onSuccess: refresh, - }); -} - -export function useUpdateHost(host: EventHost) { - const refresh = useRefreshHosts(host.eventId); - return useMutation({ - mutationFn: (fields: HostFields) => updateHost(host, fields), - onSuccess: refresh, - }); -} - -export function useDeleteHost(host: EventHost) { - const refresh = useRefreshHosts(host.eventId); - return useMutation({ mutationFn: () => deleteHost(host), onSuccess: refresh }); -} - -export function useReorderHosts(eventId: string) { - const refresh = useRefreshHosts(eventId); - return useMutation({ mutationFn: (hosts: readonly EventHost[]) => reorderHosts(hosts), onSuccess: refresh }); -} +/** Loads display-ready hosts for one event. */ +export function useEventHosts(eventId: string) { return useQuery({ queryKey: makeHostsKey(eventId), queryFn: () => listHosts(eventId) }); } +/** Saves hosts and refreshes guest speaker links too. */ +export function useSaveHosts(eventId: string) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (people: readonly HostFields[]) => saveHosts(eventId, people), onSuccess: async () => { await Promise.all([queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }), queryClient.invalidateQueries({ queryKey: GUESTS_KEY })]); } }); } diff --git a/apps/admin/src/lib/data/event-hosts.ts b/apps/admin/src/lib/data/event-hosts.ts index cd13eed..3aeb6a2 100644 --- a/apps/admin/src/lib/data/event-hosts.ts +++ b/apps/admin/src/lib/data/event-hosts.ts @@ -1,188 +1,77 @@ -/** - * Reading, adding, changing, and deleting event hosts in Supabase v2. Rows are checked and turned into - * `EventHost`s here, once, so pages get typed data. Each host is either a team member or a guest, never both. - */ +/** Reading and saving event hosts in Supabase v2. */ import { z } from 'zod'; import type { Database } from '../../types/database.types'; -import { type EventHost, type HostFields, EventHostSchema, type SpeakerLink } from '../../types/event-host'; +import { type HostCard, HostCardSchema, type HostFields, type SpeakerLink } from '../../types/event-host'; import { UnavailableError } from '../server/errors'; +import { BUCKETS, publicUrl } from '../server/storage'; import { getSupabase } from '../server/supabase'; -type HostRow = Database['v2']['Tables']['event_hosts']['Row']; type HostInsert = Database['v2']['Tables']['event_hosts']['Insert']; -type HostUpdate = Database['v2']['Tables']['event_hosts']['Update']; - -const COLUMNS = 'id, event_id, team_id, guest_id, sort_order'; - +const COLUMNS = 'id, event_id, team_id, guest_id, sort_order, team(id, name, role, picture_path, is_public), guests(id, name, title, picture_path, companies(name, colour, logo_path))'; const v2 = () => getSupabase().schema('v2'); - -/** - * All hosts for an event, in sort order. Empty when there are none. A row that doesn't fit `EventHost` is left out - * and logged, so one bad row can't hide every other host. - * @throws UnavailableError when Supabase cannot be reached or refuses the read. - */ -export async function listHosts(eventId: string): Promise { +const HostRowSchema = z.object({ + id: z.uuid(), event_id: z.uuid(), team_id: z.uuid().nullable(), guest_id: z.uuid().nullable(), sort_order: z.number().int().nonnegative(), + team: z.object({ id: z.uuid(), name: z.string(), role: z.string().nullable(), picture_path: z.string().nullable(), is_public: z.boolean() }).nullable(), + guests: z.object({ id: z.uuid(), name: z.string(), title: z.string().nullable(), picture_path: z.string().nullable(), companies: z.object({ name: z.string(), colour: z.string(), logo_path: z.string().nullable() }).nullable() }).nullable(), +}); +/** Lists display-ready hosts for an event, in their saved order. */ +export async function listHosts(eventId: string): Promise { if (!z.uuid().safeParse(eventId).success) return []; - const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('event_id', eventId).order('sort_order') as any; + const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('event_id', eventId).order('sort_order'); if (error) throw new UnavailableError('Hosts could not be loaded.', { cause: error }); - return data.flatMap((row: any) => toEventHost(row) ?? []); -} - -/** - * One host by id, or null when there is no such host (including an id that isn't a valid id at all). - * @throws UnavailableError when Supabase cannot be reached, or the saved host has data the admin can't read. - */ -export async function getHost(id: string): Promise { - if (!z.uuid().safeParse(id).success) return null; - const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('id', id).maybeSingle() as any; - if (error) throw new UnavailableError('This host could not be loaded.', { cause: error }); - if (!data) return null; - const host = toEventHost(data); - if (!host) throw new UnavailableError("This host has saved data the admin can't read. It needs fixing in Supabase."); - return host; + return data.flatMap((row) => toHostCard(row)); } - -/** - * Adds a host (team member or guest) to an event. - * @throws UnavailableError when the row could not be saved. - */ -export async function addHost(eventId: string, fields: HostFields): Promise { +/** Saves the complete ordered host list, removing missing rows before upserts to respect unique person constraints. */ +export async function saveHosts(eventId: string, people: readonly HostFields[]): Promise { if (!z.uuid().safeParse(eventId).success) throw new UnavailableError('Invalid event id.'); - - const insert: HostInsert = { - event_id: eventId, - team_id: fields.kind === 'team' ? fields.teamId : null, - guest_id: fields.kind === 'guest' ? fields.guestId : null, - sort_order: 0, // Will be adjusted if needed - }; - - const { data, error } = await v2() - .from('event_hosts') - .select(COLUMNS) - .eq('event_id', eventId) - .order('sort_order', { ascending: false }) - .limit(1) as any; - if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); - - const nextSortOrder = data.length > 0 ? (data[0]?.sort_order ?? -1) + 1 : 0; - insert.sort_order = nextSortOrder; - - const { error: insertError } = await v2().from('event_hosts').insert(insert); - if (insertError) throw new UnavailableError("The host couldn't be added.", { cause: insertError }); -} - -/** - * Adds a team member as a host to an event. - * @throws UnavailableError when the row could not be saved. - */ -export async function addTeamHost(eventId: string, teamId: string): Promise { - return addHost(eventId, { kind: 'team', teamId }); -} - -/** - * Adds a guest as a host to an event. - * @throws UnavailableError when the row could not be saved. - */ -export async function addGuestHost(eventId: string, guestId: string): Promise { - return addHost(eventId, { kind: 'guest', guestId }); -} - -/** - * Updates a host (changing which team member or guest it refers to). - * @throws UnavailableError when it could not be saved (Supabase down, the host is gone, or the update was refused). - */ -export async function updateHost(host: EventHost, fields: HostFields): Promise { - const update: HostUpdate = { - team_id: fields.kind === 'team' ? fields.teamId : null, - guest_id: fields.kind === 'guest' ? fields.guestId : null, - }; - - const { data, error } = await v2().from('event_hosts').update(update).eq('id', host.id).select('id'); - if (error || data.length === 0) throw new UnavailableError("Your changes couldn't be saved.", { cause: error }); -} - -/** - * Deletes a host from an event. - * @throws UnavailableError when the host could not be deleted (Supabase down, or the delete was refused). - */ -export async function deleteHost(host: EventHost): Promise { - const { data, error } = await v2().from('event_hosts').delete().eq('id', host.id).select('id'); - if (error || data.length === 0) throw new UnavailableError("The host couldn't be deleted.", { cause: error }); -} - -/** - * Reorders hosts by sort_order. All sort orders must be valid, contiguous, and start from 0. - * @throws UnavailableError when the reorder could not be saved. - */ -export async function reorderHosts(hosts: readonly EventHost[]): Promise { - if (hosts.length === 0) return; - - for (let i = 0; i < hosts.length; i++) { - const { error } = await v2() - .from('event_hosts') - .update({ sort_order: i }) - .eq('id', hosts[i]!.id); - if (error) throw new UnavailableError("The hosts couldn't be reordered.", { cause: error }); + const { data: current, error: readError } = await v2().from('event_hosts').select('team_id, guest_id').eq('event_id', eventId); + const failure = "The event's hosts couldn't be saved."; + if (readError) throw new UnavailableError(failure, { cause: readError }); + const wanted = new Set(people.map((person) => `${person.kind}:${person.kind === 'team' ? person.teamId : person.guestId}`)); + for (const row of current) { + const kind = row.team_id ? 'team' : 'guest'; const personId = row.team_id ?? row.guest_id; + if (!personId || wanted.has(`${kind}:${personId}`)) continue; + const removal = v2().from('event_hosts').delete().eq('event_id', eventId); + const { error } = kind === 'team' ? await removal.eq('team_id', personId) : await removal.eq('guest_id', personId); + if (error) throw new UnavailableError(failure, { cause: error }); + } + const teams: HostInsert[] = people.flatMap((person, sort_order) => person.kind === 'team' ? [{ event_id: eventId, team_id: person.teamId, guest_id: null, sort_order }] : []); + const guests: HostInsert[] = people.flatMap((person, sort_order) => person.kind === 'guest' ? [{ event_id: eventId, team_id: null, guest_id: person.guestId, sort_order }] : []); + for (const [rows, conflict] of [[teams, 'event_id,team_id'], [guests, 'event_id,guest_id']] as const) { + if (rows.length === 0) continue; + const { error } = await v2().from('event_hosts').upsert(rows, { onConflict: conflict }); + if (error) throw new UnavailableError(failure, { cause: error }); } } - const SpeakerLinkRowSchema = z.object({ event_id: z.uuid(), guest_id: z.uuid() }); - -/** - * Which guest speaks at which event, for every guest host. Empty when no event has a guest yet. - * @throws UnavailableError when Supabase cannot be reached or refuses the read. - */ +/** Lists every guest-event speaker link for photo tagging. */ export async function listSpeakerLinks(): Promise { const { data, error } = await v2().from('event_hosts').select('event_id, guest_id').not('guest_id', 'is', null); if (error) throw new UnavailableError("Who speaks at which event couldn't be loaded.", { cause: error }); - return data.flatMap((row) => { - const parsed = SpeakerLinkRowSchema.safeParse(row); - return parsed.success ? [{ eventId: parsed.data.event_id, guestId: parsed.data.guest_id }] : []; - }); + return data.flatMap((row) => { const parsed = SpeakerLinkRowSchema.safeParse(row); return parsed.success ? [{ eventId: parsed.data.event_id, guestId: parsed.data.guest_id }] : []; }); } - -/** - * Sets the events a guest speaks at to `wanted`: adds them to the ones they aren't at yet and takes them off the - * rest. It reads where they speak now first, so running it again after a failure picks up where it stopped. - * @throws UnavailableError when any of it could not be saved. - */ +/** Adds and removes a guest's event links, appending newly added events after their existing hosts. */ export async function setGuestEvents(guestId: string, wanted: readonly string[]): Promise { const { data, error } = await v2().from('event_hosts').select('event_id').eq('guest_id', guestId); if (error) throw new UnavailableError("Their events couldn't be saved.", { cause: error }); const current = data.map((row) => row.event_id); - // One at a time: adding a host reads the event's last place in the running order to put them after it. for (const eventId of wanted.filter((id) => !current.includes(id))) await addGuestHost(eventId, guestId); - const leaving = current.filter((id) => !wanted.includes(id)); - if (leaving.length === 0) return; + const leaving = current.filter((id) => !wanted.includes(id)); if (leaving.length === 0) return; const removed = await v2().from('event_hosts').delete().eq('guest_id', guestId).in('event_id', leaving); if (removed.error) throw new UnavailableError("Their events couldn't all be saved.", { cause: removed.error }); } - -function toEventHost(row: HostRow): EventHost | null { - const baseData = { - id: row.id, - eventId: row.event_id, - sortOrder: row.sort_order, - }; - - if (row.team_id && !row.guest_id) { - const parsed = EventHostSchema.safeParse({ - ...baseData, - kind: 'team' as const, - teamId: row.team_id, - guestId: null, - }); - if (parsed.success) return parsed.data; - } else if (row.guest_id && !row.team_id) { - const parsed = EventHostSchema.safeParse({ - ...baseData, - kind: 'guest' as const, - teamId: null, - guestId: row.guest_id, - }); - if (parsed.success) return parsed.data; - } - - console.warn('event_hosts.row_skipped', { id: row.id, reason: 'invalid discriminator (must have exactly one of team_id or guest_id)' }); - return null; +async function addGuestHost(eventId: string, guestId: string): Promise { + const { data, error } = await v2().from('event_hosts').select('sort_order').eq('event_id', eventId).order('sort_order', { ascending: false }).limit(1); + if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); + const result = await v2().from('event_hosts').insert({ event_id: eventId, guest_id: guestId, team_id: null, sort_order: (data[0]?.sort_order ?? -1) + 1 }); + if (result.error) throw new UnavailableError("The host couldn't be added.", { cause: result.error }); +} +function toHostCard(row: unknown): HostCard[] { + const parsed = HostRowSchema.safeParse(row); + if (!parsed.success) { console.warn('event_hosts.row_skipped', { problems: parsed.error.issues.map((issue) => issue.path.join('.')) }); return []; } + const host = parsed.data; const base = { id: host.id, eventId: host.event_id, sortOrder: host.sort_order }; + if (host.team_id && !host.guest_id && host.team?.id === host.team_id) return parsedCard({ ...base, kind: 'team', personId: host.team.id, name: host.team.name, subtitle: host.team.role, pictureUrl: host.team.picture_path ? publicUrl(BUCKETS.team, host.team.picture_path) : null, company: null, isPublic: host.team.is_public }); + if (host.guest_id && !host.team_id && host.guests?.id === host.guest_id) { const company = host.guests.companies; return parsedCard({ ...base, kind: 'guest', personId: host.guests.id, name: host.guests.name, subtitle: host.guests.title, pictureUrl: host.guests.picture_path ? publicUrl(BUCKETS.guests, host.guests.picture_path) : null, company: company ? { name: company.name, colour: company.colour, logoUrl: company.logo_path ? publicUrl(BUCKETS.logos, company.logo_path) : null } : null, isPublic: true }); } + console.warn('event_hosts.row_skipped', { id: host.id, reason: 'missing joined host' }); return []; } +function parsedCard(value: unknown): HostCard[] { const parsed = HostCardSchema.safeParse(value); return parsed.success ? [parsed.data] : []; } diff --git a/apps/admin/src/types/event-host.ts b/apps/admin/src/types/event-host.ts index e5c8db0..aa8b591 100644 --- a/apps/admin/src/types/event-host.ts +++ b/apps/admin/src/types/event-host.ts @@ -1,37 +1,14 @@ -/** - * An event host as the admin works with it, matching the v2 `event_hosts` table. - * A discriminated union: either a team member (team_id set) or a guest (guest_id set), never both. - */ +/** Hosts on an event: a team member or a guest, plus the display details the event editor needs. */ import { z } from 'zod'; -const TeamHostSchema = z.object({ - id: z.uuid(), - eventId: z.uuid(), - kind: z.literal('team'), - teamId: z.uuid(), - guestId: z.null(), - sortOrder: z.number().int().nonnegative(), +export const HostCardSchema = z.object({ + id: z.uuid(), eventId: z.uuid(), sortOrder: z.number().int().nonnegative(), kind: z.enum(['team', 'guest']), + personId: z.uuid(), name: z.string().trim().min(1), subtitle: z.string().nullable(), pictureUrl: z.url().nullable(), + company: z.object({ name: z.string(), colour: z.string(), logoUrl: z.url().nullable() }).nullable(), isPublic: z.boolean(), }); -export type TeamHost = Readonly>; - -const GuestHostSchema = z.object({ - id: z.uuid(), - eventId: z.uuid(), - kind: z.literal('guest'), - teamId: z.null(), - guestId: z.uuid(), - sortOrder: z.number().int().nonnegative(), -}); -export type GuestHost = Readonly>; - -export const EventHostSchema = z.union([TeamHostSchema, GuestHostSchema]); -export type EventHost = Readonly>; - -/** What an exec fills in when adding a host. */ -export type HostFields = Readonly< - | { kind: 'team'; teamId: string } - | { kind: 'guest'; guestId: string } ->; - -/** A guest speaking at an event: one guest host row, without its place in the running order. */ +/** A host ready to show in the event editor. */ +export type HostCard = Readonly>; +/** What the event editor saves, in its intended order. */ +export type HostFields = Readonly<{ kind: 'team'; teamId: string } | { kind: 'guest'; guestId: string }>; +/** A guest speaking at an event, without their display details. */ export type SpeakerLink = Readonly<{ eventId: string; guestId: string }>; diff --git a/apps/admin/tests/lib/data/event-hosts.test.ts b/apps/admin/tests/lib/data/event-hosts.test.ts index d4824e0..921038b 100644 --- a/apps/admin/tests/lib/data/event-hosts.test.ts +++ b/apps/admin/tests/lib/data/event-hosts.test.ts @@ -1,217 +1,56 @@ import { UnavailableError } from '../../../src/lib/server/errors'; -import { - addGuestHost, - addTeamHost, - deleteHost, - getHost, - listHosts, - listSpeakerLinks, - reorderHosts, - setGuestEvents, - updateHost, -} from '../../../src/lib/data/event-hosts'; -import type { EventHost } from '../../../src/types/event-host'; -import { installV2Supabase } from '../server/supabase-v2-mock'; +import { listHosts, listSpeakerLinks, saveHosts, setGuestEvents } from '../../../src/lib/data/event-hosts'; +import { STORAGE_BASE, installV2Supabase } from '../server/supabase-v2-mock'; vi.mock('../../../src/lib/server/supabase'); - const EVENT_ID = '0b6f9c2e-7a41-4d5b-8e3c-2f1a9b8c7d6e'; -const HOST_ID = '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f'; const TEAM_ID = '2d8b1e4f-9c6a-4f7d-8e5b-0c1d2e3f4e5f'; const GUEST_ID = '3e9c2f5d-0d7b-4e8c-9f6d-1a2b3c4d5e6f'; - -const TEAM_HOST_ROW = { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0 }; -const GUEST_HOST_ROW = { id: HOST_ID, event_id: EVENT_ID, team_id: null, guest_id: GUEST_ID, sort_order: 0 }; - -const TEAM_HOST: EventHost = { - id: HOST_ID, - eventId: EVENT_ID, - kind: 'team' as const, - teamId: TEAM_ID, - guestId: null, - sortOrder: 0, -}; - -const GUEST_HOST: EventHost = { - id: HOST_ID, - eventId: EVENT_ID, - kind: 'guest' as const, - teamId: null, - guestId: GUEST_ID, - sortOrder: 0, -}; - -const SAVED = { data: [{ id: HOST_ID }], error: null }; -const FAILED = { data: null, error: { message: 'boom' } }; +const HOST_ID = '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f'; describe('listHosts', () => { - it('returns all hosts for an event', async () => { - const order = vi.fn().mockResolvedValue({ data: [TEAM_HOST_ROW], error: null }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order })) })) } }); - + it('maps joined team and guest rows to display cards', async () => { + const rows = [ + { id: HOST_ID, event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null, sort_order: 0, team: { id: TEAM_ID, name: 'Ada', role: 'President', picture_path: 'ada.png', is_public: false }, guests: null }, + { id: '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70', event_id: EVENT_ID, team_id: null, guest_id: GUEST_ID, sort_order: 1, team: null, guests: { id: GUEST_ID, name: 'Grace', title: 'Engineer', picture_path: 'grace.png', companies: { name: 'LCS', colour: '#111111', logo_path: 'logo.png' } } }, + ]; + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn().mockResolvedValue({ data: rows, error: null }) })) })) } }); const hosts = await listHosts(EVENT_ID); - expect(hosts).toHaveLength(1); - expect(hosts[0]?.kind).toBe('team'); - }); - - it('returns empty list for invalid event id', async () => { - expect(await listHosts('not-a-uuid')).toEqual([]); - }); -}); - -describe('getHost', () => { - it('returns a team host by id', async () => { - installV2Supabase({ - event_hosts: { - select: vi.fn(() => ({ - eq: vi.fn(() => ({ maybeSingle: vi.fn().mockResolvedValue({ data: TEAM_HOST_ROW, error: null }) })), - })), - }, - }); - - const host = await getHost(HOST_ID); - expect(host?.kind).toBe('team'); - expect(host?.teamId).toBe(TEAM_ID); + expect(hosts).toMatchObject([{ kind: 'team', name: 'Ada', isPublic: false, pictureUrl: `${STORAGE_BASE}/team-images/ada.png` }, { kind: 'guest', name: 'Grace', company: { logoUrl: `${STORAGE_BASE}/company-logos/logo.png` } }]); }); - - it('returns a guest host by id', async () => { - installV2Supabase({ - event_hosts: { - select: vi.fn(() => ({ - eq: vi.fn(() => ({ maybeSingle: vi.fn().mockResolvedValue({ data: GUEST_HOST_ROW, error: null }) })), - })), - }, - }); - - const host = await getHost(HOST_ID); - expect(host?.kind).toBe('guest'); - expect(host?.guestId).toBe(GUEST_ID); - }); -}); - -describe('addTeamHost', () => { - it('adds a team member as a host', async () => { - const insert = vi.fn().mockResolvedValue({ error: null }); - const select = vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) })); - installV2Supabase({ event_hosts: { insert, select } }); - - await addTeamHost(EVENT_ID, TEAM_ID); - - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: EVENT_ID, team_id: TEAM_ID, guest_id: null })); - }); -}); - -describe('addGuestHost', () => { - it('adds a guest as a host', async () => { - const insert = vi.fn().mockResolvedValue({ error: null }); - const select = vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) })); - installV2Supabase({ event_hosts: { insert, select } }); - - await addGuestHost(EVENT_ID, GUEST_ID); - - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: EVENT_ID, guest_id: GUEST_ID, team_id: null })); - }); -}); - -describe('updateHost', () => { - it('changes a team host to a guest host', async () => { - const update = vi.fn(() => ({ eq: vi.fn(() => ({ select: vi.fn().mockResolvedValue(SAVED) })) })); - installV2Supabase({ event_hosts: { update } }); - - await updateHost(TEAM_HOST, { kind: 'guest', guestId: GUEST_ID }); - - expect(update).toHaveBeenCalledWith(expect.objectContaining({ guest_id: GUEST_ID, team_id: null })); + it('skips an invalid joined row', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn(() => ({ order: vi.fn().mockResolvedValue({ data: [{ id: HOST_ID }], error: null }) })) })) } }); + expect(await listHosts(EVENT_ID)).toEqual([]); expect(warn).toHaveBeenCalled(); warn.mockRestore(); }); }); -describe('deleteHost', () => { - it('deletes a host', async () => { - const eq = vi.fn(() => ({ select: vi.fn().mockResolvedValue(SAVED) })); - installV2Supabase({ event_hosts: { delete: vi.fn(() => ({ eq })) } }); - - await deleteHost(TEAM_HOST); - - expect(eq).toHaveBeenCalledWith('id', HOST_ID); +describe('saveHosts', () => { + it('deletes missing rows before upserting ordered team and guest rows', async () => { + const remove = vi.fn().mockResolvedValue({ error: null }); const upsert = vi.fn().mockResolvedValue({ error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [{ team_id: '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70', guest_id: null }], error: null }) })), delete: vi.fn(() => ({ eq: vi.fn(() => ({ eq: remove })) })), upsert } }); + await saveHosts(EVENT_ID, [{ kind: 'guest', guestId: GUEST_ID }, { kind: 'team', teamId: TEAM_ID }]); + expect(remove).toHaveBeenCalledBefore(upsert); expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ guest_id: GUEST_ID, sort_order: 0 })]), { onConflict: 'event_id,guest_id' }); expect(upsert).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ team_id: TEAM_ID, sort_order: 1 })]), { onConflict: 'event_id,team_id' }); }); - - it('fails when delete fails', async () => { - installV2Supabase({ event_hosts: { delete: vi.fn(() => ({ eq: vi.fn(() => ({ select: vi.fn().mockResolvedValue(FAILED) })) })) } }); - - await expect(deleteHost(TEAM_HOST)).rejects.toBeInstanceOf(UnavailableError); + it('deletes every row for an empty list', async () => { + const remove = vi.fn().mockResolvedValue({ error: null }); + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [{ team_id: TEAM_ID, guest_id: null }], error: null }) })), delete: vi.fn(() => ({ eq: vi.fn(() => ({ eq: remove })) })) } }); + await saveHosts(EVENT_ID, []); expect(remove).toHaveBeenCalled(); }); -}); - -describe('reorderHosts', () => { - it('updates sort orders', async () => { - const hosts: EventHost[] = [ - { ...TEAM_HOST, sortOrder: 0 }, - { ...GUEST_HOST, id: '4f0d3g6h-1e8c-5f9d-0g7e-2b3c4d5e6f7g', sortOrder: 1 }, - ]; - const update = vi.fn(() => ({ eq: vi.fn(() => ({}) ) })); - installV2Supabase({ event_hosts: { update } }); - - await reorderHosts(hosts); - - expect(update).toHaveBeenCalledTimes(2); + it('reports failed saves as unavailable', async () => { + installV2Supabase({ event_hosts: { select: vi.fn(() => ({ eq: vi.fn().mockResolvedValue({ data: [], error: null }) })), upsert: vi.fn().mockResolvedValue({ error: { message: 'no' } }) } }); + await expect(saveHosts(EVENT_ID, [{ kind: 'team', teamId: TEAM_ID }])).rejects.toBeInstanceOf(UnavailableError); }); }); -describe('listSpeakerLinks', () => { - it('lists which guest speaks at which event', async () => { - const not = vi.fn().mockResolvedValue({ data: [{ event_id: EVENT_ID, guest_id: GUEST_ID }], error: null }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); - +describe('speaker links and guest events', () => { + it('lists guest speaker links', async () => { + const not = vi.fn().mockResolvedValue({ data: [{ event_id: EVENT_ID, guest_id: GUEST_ID }], error: null }); installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); expect(await listSpeakerLinks()).toEqual([{ eventId: EVENT_ID, guestId: GUEST_ID }]); - expect(not).toHaveBeenCalledWith('guest_id', 'is', null); }); - - it('reports a failed read as unavailable', async () => { - const not = vi.fn().mockResolvedValue({ data: null, error: { message: 'down' } }); - installV2Supabase({ event_hosts: { select: vi.fn(() => ({ not })) } }); - - await expect(listSpeakerLinks()).rejects.toBeInstanceOf(UnavailableError); - }); -}); - -describe('setGuestEvents', () => { - const OTHER_EVENT = '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70'; - const NEW_EVENT = '5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81'; - - /** An `event_hosts` table where the guest speaks at `current`, recording what is added and taken off. */ - function hostsTable(current: readonly string[], removeError: unknown = null) { - const insert = vi.fn().mockResolvedValue({ error: null }); - const takeOff = vi.fn().mockResolvedValue({ error: removeError }); - const select = vi.fn((columns: string) => - columns === 'event_id' - ? { eq: vi.fn().mockResolvedValue({ data: current.map((id) => ({ event_id: id })), error: null }) } - : { eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) }, - ); - installV2Supabase({ event_hosts: { select, insert, delete: vi.fn(() => ({ eq: vi.fn(() => ({ in: takeOff })) })) } }); - return { insert, takeOff }; - } - - it('adds the guest to new events and takes them off the ones no longer wanted', async () => { - const { insert, takeOff } = hostsTable([EVENT_ID, OTHER_EVENT]); - - await setGuestEvents(GUEST_ID, [EVENT_ID, NEW_EVENT]); - - expect(insert).toHaveBeenCalledTimes(1); - expect(insert).toHaveBeenCalledWith(expect.objectContaining({ event_id: NEW_EVENT, guest_id: GUEST_ID })); - expect(takeOff).toHaveBeenCalledWith('event_id', [OTHER_EVENT]); - }); - - it('changes nothing when the events are the same', async () => { - const { insert, takeOff } = hostsTable([EVENT_ID]); - - await setGuestEvents(GUEST_ID, [EVENT_ID]); - - expect(insert).not.toHaveBeenCalled(); - expect(takeOff).not.toHaveBeenCalled(); - }); - - it('reports a failed removal as unavailable', async () => { - hostsTable([EVENT_ID], { message: 'refused' }); - - await expect(setGuestEvents(GUEST_ID, [])).rejects.toThrow("Their events couldn't all be saved."); + it('adds and removes guest event links', async () => { + const OTHER = '4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70'; const NEW = '5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81'; const insert = vi.fn().mockResolvedValue({ error: null }); const takeOff = vi.fn().mockResolvedValue({ error: null }); + const select = vi.fn((columns: string) => columns === 'event_id' ? { eq: vi.fn().mockResolvedValue({ data: [{ event_id: OTHER }], error: null }) } : { eq: vi.fn(() => ({ order: vi.fn(() => ({ limit: vi.fn().mockResolvedValue({ data: [], error: null }) })) })) }); + installV2Supabase({ event_hosts: { select, insert, delete: vi.fn(() => ({ eq: vi.fn(() => ({ in: takeOff })) })) } }); await setGuestEvents(GUEST_ID, [NEW]); expect(insert).toHaveBeenCalled(); expect(takeOff).toHaveBeenCalledWith('event_id', [OTHER]); }); }); diff --git a/docs/admin-guide.md b/docs/admin-guide.md index c23bada..2096a2b 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -32,6 +32,10 @@ Notion) and sign in again; nothing you saved is lost. ## Events +### Speakers and hosts + +On an existing event, use **Speakers and hosts** to add guests or team members, put them in order, and save the whole list. Guests can also be linked to events from their guest page's **Speaks at** field. Only guest speakers appear on the public event page for now; team hosts are saved but marked as not shown there. + ### Post an event 1. On **Events**, press **New event**. From af2a45368d16b5730f0d0e0c9bfc50e8ac5ed8b1 Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 14:10:32 -0500 Subject: [PATCH 3/9] refactor(admin): clarify event hosts code --- .../src/components/events/EventHostsPanel.tsx | 150 +++++++++++++++--- apps/admin/src/hooks/useEventHosts.ts | 21 ++- apps/admin/src/lib/data/event-hosts.ts | 134 ++++++++++++---- apps/admin/src/types/event-host.ts | 26 ++- 4 files changed, 271 insertions(+), 60 deletions(-) diff --git a/apps/admin/src/components/events/EventHostsPanel.tsx b/apps/admin/src/components/events/EventHostsPanel.tsx index 0d520ee..e85519c 100644 --- a/apps/admin/src/components/events/EventHostsPanel.tsx +++ b/apps/admin/src/components/events/EventHostsPanel.tsx @@ -13,28 +13,134 @@ import { Tag } from '../ui/Tag'; import { ExtraPanel } from './ExtraPanel'; import { PanelSaveBar } from './PanelSaveBar'; +type Person = Readonly<{ + id: string; + name: string; + pictureUrl: string | null; + title?: string | null; + role?: string | null; + isPublic?: boolean; +}>; + +const ACTION_BUTTON = 'grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40'; + +/** Shows the event's saved hosts and an editor that keeps changes local until the exec presses Save. */ export function EventHostsPanel({ eventId }: { eventId: string }) { - const hosts = useEventHosts(eventId); const save = useSaveHosts(eventId); const guests = useGuests(); const team = useTeam(); - return - {(saved) => } - ; + const hosts = useEventHosts(eventId); + const save = useSaveHosts(eventId); + const guests = useGuests(); + const team = useTeam(); + + return ( + + {(saved) => ( + + )} + + ); +} + +type HostsEditorProps = Readonly<{ + saved: readonly HostCard[]; + save: ReturnType; + guests: readonly Person[]; + team: readonly Person[]; +}>; + +function HostsEditor({ saved, save, guests, team }: HostsEditorProps) { + const [rows, setRows] = useState(saved); + const [changed, setChanged] = useState(false); + const [query, setQuery] = useState(''); + const available = peopleToAdd(rows, guests, team, query); + + function change(next: readonly HostCard[]) { + setRows(next); + setChanged(true); + } + + function move(index: number, by: -1 | 1) { + const next = [...rows]; + const [row] = next.splice(index, 1); + if (row) next.splice(index + by, 0, row); + change(next); + } + + function add(kind: 'team' | 'guest', person: Person) { + change([...rows, newHostCard(kind, person, rows.length)]); + setQuery(''); + } + + return ( + <> + {rows.length === 0 ? ( +

    No speakers or hosts yet. Add guests here, or from their guest page.

    + ) : ( +
      + {rows.map((host, index) => ( + change(rows.filter((row) => row.id !== host.id))} + /> + ))} +
    + )} + + save.mutate(rows.map(toHostFields), { onSuccess: () => setChanged(false) })} + /> + + ); +} + +function HostPicker({ query, guests, team, onQueryChange, onPick }: Readonly<{ query: string; guests: readonly Person[]; team: readonly Person[]; onQueryChange: (query: string) => void; onPick: (kind: 'team' | 'guest', person: Person) => void }>) { + return ( +
    + + onPick('guest', person)} /> + onPick('team', person)} /> +

    + Add a new guest +

    +
    + ); } -type Person = { id: string; name: string; pictureUrl: string | null; title?: string | null; role?: string | null; isPublic?: boolean }; -function HostsEditor({ saved, save, guests, team }: { saved: readonly HostCard[]; save: ReturnType; guests: readonly Person[]; team: readonly Person[] }) { - const [rows, setRows] = useState(saved); const [changed, setChanged] = useState(false); const [query, setQuery] = useState(''); - const ids = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); const term = query.trim().toLocaleLowerCase(); - const visibleGuests = guests.filter((person) => !ids.has(`guest:${person.id}`) && person.name.toLocaleLowerCase().includes(term)); - const visibleTeam = team.filter((person) => !ids.has(`team:${person.id}`) && person.name.toLocaleLowerCase().includes(term)); - function change(next: readonly HostCard[]) { setRows(next); setChanged(true); } - function move(index: number, by: -1 | 1) { const next = [...rows]; const [row] = next.splice(index, 1); if (row) next.splice(index + by, 0, row); change(next); } - function add(kind: 'team' | 'guest', person: Person) { change([...rows, { id: crypto.randomUUID(), eventId: '', sortOrder: rows.length, kind, personId: person.id, name: person.name, subtitle: kind === 'team' ? person.role ?? null : person.title ?? null, pictureUrl: person.pictureUrl, company: null, isPublic: kind === 'team' ? person.isPublic === true : true }]); setQuery(''); } - const fields = (): readonly HostFields[] => rows.map((row) => row.kind === 'team' ? { kind: 'team', teamId: row.personId } : { kind: 'guest', guestId: row.personId }); - return <> - {rows.length === 0 ?

    No speakers or hosts yet. Add guests here, or from their guest page.

    :
      {rows.map((host, index) => change(rows.filter((row) => row.id !== host.id))} />)}
    } -
    add('guest', person)} /> add('team', person)} />

    Add a new guest

    - save.mutate(fields(), { onSuccess: () => setChanged(false) })} /> - ; + +function PickerGroup({ title, people, onPick }: Readonly<{ title: string; people: readonly Person[]; onPick: (person: Person) => void }>) { + return ( +
    +

    {title}

    + {people.length === 0 ?

    No people found.

    :
      {people.map((person) =>
    • )}
    } +
    + ); +} + +function HostRow({ host, index, total, onMove, onRemove }: Readonly<{ host: HostCard; index: number; total: number; onMove: (index: number, by: -1 | 1) => void; onRemove: () => void }>) { + return ( +
  • + +

    {host.name}

    {host.subtitle &&

    {host.subtitle}

    }{host.kind === 'team' &&

    Not shown on the site yet{!host.isPublic && '; hidden from the site'}.

    }
    + {host.kind === 'guest' && host.company && } + {host.kind === 'team' ? 'Team' : 'Guest'} +
    +
  • + ); } -function PickerGroup({ title, people, onPick }: { title: string; people: readonly Person[]; onPick: (person: Person) => void }) { return

    {title}

    {people.length === 0 ?

    No people found.

    :
      {people.map((person) =>
    • )}
    }
    ; } -function HostRow({ host, index, total, onMove, onRemove }: { host: HostCard; index: number; total: number; onMove: (index: number, by: -1 | 1) => void; onRemove: () => void }) { return
  • {host.name}

    {host.subtitle &&

    {host.subtitle}

    }{host.kind === 'team' &&

    Not shown on the site yet{!host.isPublic && '; hidden from the site'}.

    }
    {host.kind === 'guest' && host.company && {host.company.logoUrl ? : }}{host.kind === 'team' ? 'Team' : 'Guest'}
  • ; } -function Face({ host }: { host: HostCard }) { return host.pictureUrl ? : ; } + +function HostFace({ host }: { host: HostCard }) { return host.pictureUrl ? : ; } +function CompanyMark({ host }: { host: HostCard }) { const company = host.company!; return {company.logoUrl ? : }; } +function peopleToAdd(rows: readonly HostCard[], guests: readonly Person[], team: readonly Person[], query: string) { const added = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); const matches = (person: Person, kind: 'guest' | 'team') => !added.has(`${kind}:${person.id}`) && person.name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()); return { guests: guests.filter((person) => matches(person, 'guest')), team: team.filter((person) => matches(person, 'team')) }; } +function newHostCard(kind: 'team' | 'guest', person: Person, sortOrder: number): HostCard { return { id: crypto.randomUUID(), eventId: '', sortOrder, kind, personId: person.id, name: person.name, subtitle: kind === 'team' ? person.role ?? null : person.title ?? null, pictureUrl: person.pictureUrl, company: null, isPublic: kind === 'team' ? person.isPublic === true : true }; } +function toHostFields(host: HostCard): HostFields { return host.kind === 'team' ? { kind: 'team', teamId: host.personId } : { kind: 'guest', guestId: host.personId }; } diff --git a/apps/admin/src/hooks/useEventHosts.ts b/apps/admin/src/hooks/useEventHosts.ts index ef38a11..ff389b9 100644 --- a/apps/admin/src/hooks/useEventHosts.ts +++ b/apps/admin/src/hooks/useEventHosts.ts @@ -3,8 +3,23 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { listHosts, saveHosts } from '../lib/data/event-hosts'; import type { HostFields } from '../types/event-host'; import { GUESTS_KEY } from './useGuests'; + const makeHostsKey = (eventId: string) => ['hosts', eventId] as const; + /** Loads display-ready hosts for one event. */ -export function useEventHosts(eventId: string) { return useQuery({ queryKey: makeHostsKey(eventId), queryFn: () => listHosts(eventId) }); } -/** Saves hosts and refreshes guest speaker links too. */ -export function useSaveHosts(eventId: string) { const queryClient = useQueryClient(); return useMutation({ mutationFn: (people: readonly HostFields[]) => saveHosts(eventId, people), onSuccess: async () => { await Promise.all([queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }), queryClient.invalidateQueries({ queryKey: GUESTS_KEY })]); } }); } +export function useEventHosts(eventId: string) { + return useQuery({ queryKey: makeHostsKey(eventId), queryFn: () => listHosts(eventId) }); +} + +/** Saves hosts and refreshes guest event links, which power both the guest page and photo tagging. */ +export function useSaveHosts(eventId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (people: readonly HostFields[]) => saveHosts(eventId, people), + onSuccess: () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: makeHostsKey(eventId) }), + queryClient.invalidateQueries({ queryKey: GUESTS_KEY }), + ]), + }); +} diff --git a/apps/admin/src/lib/data/event-hosts.ts b/apps/admin/src/lib/data/event-hosts.ts index 3aeb6a2..51afd18 100644 --- a/apps/admin/src/lib/data/event-hosts.ts +++ b/apps/admin/src/lib/data/event-hosts.ts @@ -7,71 +7,145 @@ import { BUCKETS, publicUrl } from '../server/storage'; import { getSupabase } from '../server/supabase'; type HostInsert = Database['v2']['Tables']['event_hosts']['Insert']; -const COLUMNS = 'id, event_id, team_id, guest_id, sort_order, team(id, name, role, picture_path, is_public), guests(id, name, title, picture_path, companies(name, colour, logo_path))'; -const v2 = () => getSupabase().schema('v2'); + +const HOST_COLUMNS = ` + id, event_id, team_id, guest_id, sort_order, + team(id, name, role, picture_path, is_public), + guests(id, name, title, picture_path, companies(name, colour, logo_path)) +`; + const HostRowSchema = z.object({ - id: z.uuid(), event_id: z.uuid(), team_id: z.uuid().nullable(), guest_id: z.uuid().nullable(), sort_order: z.number().int().nonnegative(), - team: z.object({ id: z.uuid(), name: z.string(), role: z.string().nullable(), picture_path: z.string().nullable(), is_public: z.boolean() }).nullable(), - guests: z.object({ id: z.uuid(), name: z.string(), title: z.string().nullable(), picture_path: z.string().nullable(), companies: z.object({ name: z.string(), colour: z.string(), logo_path: z.string().nullable() }).nullable() }).nullable(), + id: z.uuid(), + event_id: z.uuid(), + team_id: z.uuid().nullable(), + guest_id: z.uuid().nullable(), + sort_order: z.number().int().nonnegative(), + team: z + .object({ id: z.uuid(), name: z.string(), role: z.string().nullable(), picture_path: z.string().nullable(), is_public: z.boolean() }) + .nullable(), + guests: z + .object({ + id: z.uuid(), + name: z.string(), + title: z.string().nullable(), + picture_path: z.string().nullable(), + companies: z.object({ name: z.string(), colour: z.string(), logo_path: z.string().nullable() }).nullable(), + }) + .nullable(), }); + +const SpeakerLinkRowSchema = z.object({ event_id: z.uuid(), guest_id: z.uuid() }); +const v2 = () => getSupabase().schema('v2'); + /** Lists display-ready hosts for an event, in their saved order. */ export async function listHosts(eventId: string): Promise { if (!z.uuid().safeParse(eventId).success) return []; - const { data, error } = await v2().from('event_hosts').select(COLUMNS).eq('event_id', eventId).order('sort_order'); + + const { data, error } = await v2().from('event_hosts').select(HOST_COLUMNS).eq('event_id', eventId).order('sort_order'); if (error) throw new UnavailableError('Hosts could not be loaded.', { cause: error }); - return data.flatMap((row) => toHostCard(row)); + + return data.flatMap(toHostCard); } -/** Saves the complete ordered host list, removing missing rows before upserts to respect unique person constraints. */ + +/** + * Saves the complete ordered host list. Removing absent people first makes a replacement safe when it would + * otherwise temporarily violate either unique `(event_id, person_id)` constraint. + */ export async function saveHosts(eventId: string, people: readonly HostFields[]): Promise { if (!z.uuid().safeParse(eventId).success) throw new UnavailableError('Invalid event id.'); - const { data: current, error: readError } = await v2().from('event_hosts').select('team_id, guest_id').eq('event_id', eventId); + const failure = "The event's hosts couldn't be saved."; + const { data: current, error: readError } = await v2().from('event_hosts').select('team_id, guest_id').eq('event_id', eventId); if (readError) throw new UnavailableError(failure, { cause: readError }); - const wanted = new Set(people.map((person) => `${person.kind}:${person.kind === 'team' ? person.teamId : person.guestId}`)); + + const wanted = new Set(people.map(hostKey)); for (const row of current) { - const kind = row.team_id ? 'team' : 'guest'; const personId = row.team_id ?? row.guest_id; - if (!personId || wanted.has(`${kind}:${personId}`)) continue; + const currentHost = row.team_id ? { kind: 'team' as const, personId: row.team_id } : { kind: 'guest' as const, personId: row.guest_id }; + if (!currentHost.personId || wanted.has(`${currentHost.kind}:${currentHost.personId}`)) continue; + const removal = v2().from('event_hosts').delete().eq('event_id', eventId); - const { error } = kind === 'team' ? await removal.eq('team_id', personId) : await removal.eq('guest_id', personId); - if (error) throw new UnavailableError(failure, { cause: error }); - } - const teams: HostInsert[] = people.flatMap((person, sort_order) => person.kind === 'team' ? [{ event_id: eventId, team_id: person.teamId, guest_id: null, sort_order }] : []); - const guests: HostInsert[] = people.flatMap((person, sort_order) => person.kind === 'guest' ? [{ event_id: eventId, team_id: null, guest_id: person.guestId, sort_order }] : []); - for (const [rows, conflict] of [[teams, 'event_id,team_id'], [guests, 'event_id,guest_id']] as const) { - if (rows.length === 0) continue; - const { error } = await v2().from('event_hosts').upsert(rows, { onConflict: conflict }); + const { error } = currentHost.kind === 'team' + ? await removal.eq('team_id', currentHost.personId) + : await removal.eq('guest_id', currentHost.personId); if (error) throw new UnavailableError(failure, { cause: error }); } + + await upsertHosts(eventId, people, 'team', failure); + await upsertHosts(eventId, people, 'guest', failure); } -const SpeakerLinkRowSchema = z.object({ event_id: z.uuid(), guest_id: z.uuid() }); + /** Lists every guest-event speaker link for photo tagging. */ export async function listSpeakerLinks(): Promise { const { data, error } = await v2().from('event_hosts').select('event_id, guest_id').not('guest_id', 'is', null); if (error) throw new UnavailableError("Who speaks at which event couldn't be loaded.", { cause: error }); - return data.flatMap((row) => { const parsed = SpeakerLinkRowSchema.safeParse(row); return parsed.success ? [{ eventId: parsed.data.event_id, guestId: parsed.data.guest_id }] : []; }); + + return data.flatMap((row) => { + const parsed = SpeakerLinkRowSchema.safeParse(row); + return parsed.success ? [{ eventId: parsed.data.event_id, guestId: parsed.data.guest_id }] : []; + }); } -/** Adds and removes a guest's event links, appending newly added events after their existing hosts. */ + +/** Adds and removes a guest's event links, appending new events after their existing hosts. */ export async function setGuestEvents(guestId: string, wanted: readonly string[]): Promise { const { data, error } = await v2().from('event_hosts').select('event_id').eq('guest_id', guestId); if (error) throw new UnavailableError("Their events couldn't be saved.", { cause: error }); + const current = data.map((row) => row.event_id); for (const eventId of wanted.filter((id) => !current.includes(id))) await addGuestHost(eventId, guestId); - const leaving = current.filter((id) => !wanted.includes(id)); if (leaving.length === 0) return; + + const leaving = current.filter((id) => !wanted.includes(id)); + if (leaving.length === 0) return; + const removed = await v2().from('event_hosts').delete().eq('guest_id', guestId).in('event_id', leaving); if (removed.error) throw new UnavailableError("Their events couldn't all be saved.", { cause: removed.error }); } + +async function upsertHosts(eventId: string, people: readonly HostFields[], kind: HostFields['kind'], failure: string): Promise { + const rows = people.flatMap((person, sortOrder): HostInsert[] => { + if (person.kind !== kind) return []; + return [{ event_id: eventId, team_id: kind === 'team' ? person.teamId : null, guest_id: kind === 'guest' ? person.guestId : null, sort_order: sortOrder }]; + }); + if (rows.length === 0) return; + + const conflict = kind === 'team' ? 'event_id,team_id' : 'event_id,guest_id'; + const { error } = await v2().from('event_hosts').upsert(rows, { onConflict: conflict }); + if (error) throw new UnavailableError(failure, { cause: error }); +} + async function addGuestHost(eventId: string, guestId: string): Promise { const { data, error } = await v2().from('event_hosts').select('sort_order').eq('event_id', eventId).order('sort_order', { ascending: false }).limit(1); if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); + const result = await v2().from('event_hosts').insert({ event_id: eventId, guest_id: guestId, team_id: null, sort_order: (data[0]?.sort_order ?? -1) + 1 }); if (result.error) throw new UnavailableError("The host couldn't be added.", { cause: result.error }); } + +function hostKey(person: HostFields): string { + return person.kind === 'team' ? `team:${person.teamId}` : `guest:${person.guestId}`; +} + function toHostCard(row: unknown): HostCard[] { const parsed = HostRowSchema.safeParse(row); - if (!parsed.success) { console.warn('event_hosts.row_skipped', { problems: parsed.error.issues.map((issue) => issue.path.join('.')) }); return []; } - const host = parsed.data; const base = { id: host.id, eventId: host.event_id, sortOrder: host.sort_order }; - if (host.team_id && !host.guest_id && host.team?.id === host.team_id) return parsedCard({ ...base, kind: 'team', personId: host.team.id, name: host.team.name, subtitle: host.team.role, pictureUrl: host.team.picture_path ? publicUrl(BUCKETS.team, host.team.picture_path) : null, company: null, isPublic: host.team.is_public }); - if (host.guest_id && !host.team_id && host.guests?.id === host.guest_id) { const company = host.guests.companies; return parsedCard({ ...base, kind: 'guest', personId: host.guests.id, name: host.guests.name, subtitle: host.guests.title, pictureUrl: host.guests.picture_path ? publicUrl(BUCKETS.guests, host.guests.picture_path) : null, company: company ? { name: company.name, colour: company.colour, logoUrl: company.logo_path ? publicUrl(BUCKETS.logos, company.logo_path) : null } : null, isPublic: true }); } - console.warn('event_hosts.row_skipped', { id: host.id, reason: 'missing joined host' }); return []; + if (!parsed.success) { + console.warn('event_hosts.row_skipped', { problems: parsed.error.issues.map((issue) => issue.path.join('.')) }); + return []; + } + + const host = parsed.data; + const base = { id: host.id, eventId: host.event_id, sortOrder: host.sort_order }; + if (host.team_id && !host.guest_id && host.team?.id === host.team_id) { + return parseHostCard({ ...base, kind: 'team', personId: host.team.id, name: host.team.name, subtitle: host.team.role, pictureUrl: host.team.picture_path ? publicUrl(BUCKETS.team, host.team.picture_path) : null, company: null, isPublic: host.team.is_public }); + } + if (host.guest_id && !host.team_id && host.guests?.id === host.guest_id) { + const company = host.guests.companies; + return parseHostCard({ ...base, kind: 'guest', personId: host.guests.id, name: host.guests.name, subtitle: host.guests.title, pictureUrl: host.guests.picture_path ? publicUrl(BUCKETS.guests, host.guests.picture_path) : null, company: company ? { name: company.name, colour: company.colour, logoUrl: company.logo_path ? publicUrl(BUCKETS.logos, company.logo_path) : null } : null, isPublic: true }); + } + + console.warn('event_hosts.row_skipped', { id: host.id, reason: 'missing joined host' }); + return []; +} + +function parseHostCard(value: unknown): HostCard[] { + const parsed = HostCardSchema.safeParse(value); + return parsed.success ? [parsed.data] : []; } -function parsedCard(value: unknown): HostCard[] { const parsed = HostCardSchema.safeParse(value); return parsed.success ? [parsed.data] : []; } diff --git a/apps/admin/src/types/event-host.ts b/apps/admin/src/types/event-host.ts index aa8b591..0ada8ca 100644 --- a/apps/admin/src/types/event-host.ts +++ b/apps/admin/src/types/event-host.ts @@ -1,14 +1,30 @@ -/** Hosts on an event: a team member or a guest, plus the display details the event editor needs. */ +/** The person and company details needed to draw a saved event host. */ import { z } from 'zod'; +const HostCompanySchema = z.object({ + name: z.string().trim().min(1), + colour: z.string(), + logoUrl: z.url().nullable(), +}); + export const HostCardSchema = z.object({ - id: z.uuid(), eventId: z.uuid(), sortOrder: z.number().int().nonnegative(), kind: z.enum(['team', 'guest']), - personId: z.uuid(), name: z.string().trim().min(1), subtitle: z.string().nullable(), pictureUrl: z.url().nullable(), - company: z.object({ name: z.string(), colour: z.string(), logoUrl: z.url().nullable() }).nullable(), isPublic: z.boolean(), + id: z.uuid(), + eventId: z.uuid(), + sortOrder: z.number().int().nonnegative(), + kind: z.enum(['team', 'guest']), + personId: z.uuid(), + name: z.string().trim().min(1), + subtitle: z.string().nullable(), + pictureUrl: z.url().nullable(), + company: HostCompanySchema.nullable(), + isPublic: z.boolean(), }); + /** A host ready to show in the event editor. */ export type HostCard = Readonly>; -/** What the event editor saves, in its intended order. */ + +/** One person in the order the editor wants to save. */ export type HostFields = Readonly<{ kind: 'team'; teamId: string } | { kind: 'guest'; guestId: string }>; + /** A guest speaking at an event, without their display details. */ export type SpeakerLink = Readonly<{ eventId: string; guestId: string }>; From 0bb0469dbcf46fc267a1790005315cd676845643 Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 14:17:50 -0500 Subject: [PATCH 4/9] fix(admin): narrow event host save rows --- apps/admin/src/lib/data/event-hosts.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/apps/admin/src/lib/data/event-hosts.ts b/apps/admin/src/lib/data/event-hosts.ts index 51afd18..10e203d 100644 --- a/apps/admin/src/lib/data/event-hosts.ts +++ b/apps/admin/src/lib/data/event-hosts.ts @@ -101,10 +101,7 @@ export async function setGuestEvents(guestId: string, wanted: readonly string[]) } async function upsertHosts(eventId: string, people: readonly HostFields[], kind: HostFields['kind'], failure: string): Promise { - const rows = people.flatMap((person, sortOrder): HostInsert[] => { - if (person.kind !== kind) return []; - return [{ event_id: eventId, team_id: kind === 'team' ? person.teamId : null, guest_id: kind === 'guest' ? person.guestId : null, sort_order: sortOrder }]; - }); + const rows = kind === 'team' ? teamRows(eventId, people) : guestRows(eventId, people); if (rows.length === 0) return; const conflict = kind === 'team' ? 'event_id,team_id' : 'event_id,guest_id'; @@ -112,6 +109,18 @@ async function upsertHosts(eventId: string, people: readonly HostFields[], kind: if (error) throw new UnavailableError(failure, { cause: error }); } +function teamRows(eventId: string, people: readonly HostFields[]): HostInsert[] { + return people.flatMap((person, sortOrder): HostInsert[] => + person.kind === 'team' ? [{ event_id: eventId, team_id: person.teamId, guest_id: null, sort_order: sortOrder }] : [], + ); +} + +function guestRows(eventId: string, people: readonly HostFields[]): HostInsert[] { + return people.flatMap((person, sortOrder): HostInsert[] => + person.kind === 'guest' ? [{ event_id: eventId, team_id: null, guest_id: person.guestId, sort_order: sortOrder }] : [], + ); +} + async function addGuestHost(eventId: string, guestId: string): Promise { const { data, error } = await v2().from('event_hosts').select('sort_order').eq('event_id', eventId).order('sort_order', { ascending: false }).limit(1); if (error) throw new UnavailableError("The host couldn't be added.", { cause: error }); From 534228862f31fdc31b79e216eec062746162df9b Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 14:27:15 -0500 Subject: [PATCH 5/9] docs(admin): plan hosts review fixes --- docs/plans/300-event-hosts.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/plans/300-event-hosts.md b/docs/plans/300-event-hosts.md index e15a701..04e60ed 100644 --- a/docs/plans/300-event-hosts.md +++ b/docs/plans/300-event-hosts.md @@ -16,3 +16,10 @@ Issues #299 and #300 already have resources, related events, topics, partners, a - Update the host types, data functions, query hooks, event extras, guide, and add `EventHostsPanel`. - Extend data tests for joined mapping and whole-list saves; extend event extras tests for keyboard reordering, picker choices, saving, and host visibility notes. - Verify the admin lint, test, and build commands, plus the site build. Resource reordering will be checked but is outside this change if unsupported. + +## Review fixes + +- Match the other extras panels' formatting, helper comments, and picker-state handling. +- Reuse the guest company mark and show a newly picked guest's company before saving. +- Only show picker results after a search, with distinct loading, failed, and empty states. +- Add event-page and data-layer coverage for host editing, ordering, failures, and incomplete joined rows. From 0285eed88a8aa1b60861ab30ea86087c7cd85b98 Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 14:33:24 -0500 Subject: [PATCH 6/9] refactor(admin): polish event hosts panel --- .../src/components/events/EventHostsPanel.tsx | 398 ++++++++++++++---- .../src/components/guests/CompanyMark.tsx | 7 +- apps/admin/tests/pages/EventExtras.test.tsx | 334 +++++++++++---- 3 files changed, 588 insertions(+), 151 deletions(-) diff --git a/apps/admin/src/components/events/EventHostsPanel.tsx b/apps/admin/src/components/events/EventHostsPanel.tsx index e85519c..34aa2ed 100644 --- a/apps/admin/src/components/events/EventHostsPanel.tsx +++ b/apps/admin/src/components/events/EventHostsPanel.tsx @@ -1,35 +1,34 @@ -/** Ordered speaker and host editor for an existing event. */ -import { ArrowDown, ArrowUp, X } from 'lucide-react'; -import { useState } from 'react'; -import { Link } from 'react-router'; -import { useEventHosts, useSaveHosts } from '../../hooks/useEventHosts'; -import { useGuests } from '../../hooks/useGuests'; -import { useTeam } from '../../hooks/useTeam'; -import { PATHS } from '../../paths'; -import type { HostCard, HostFields } from '../../types/event-host'; -import { FIELD_INPUT } from '../ui/field-styles'; -import { SearchField } from '../ui/SearchField'; -import { Tag } from '../ui/Tag'; -import { ExtraPanel } from './ExtraPanel'; -import { PanelSaveBar } from './PanelSaveBar'; +/** "Speakers and hosts" for an event, held locally until the exec saves. */ +import { ArrowDown, ArrowUp, X } from "lucide-react"; +import { useState } from "react"; +import { Link } from "react-router"; +import { type Choices, choicesFrom } from "../../hooks/choices"; +import { useCompanies } from "../../hooks/useCompanies"; +import { useEventHosts, useSaveHosts } from "../../hooks/useEventHosts"; +import { useGuests } from "../../hooks/useGuests"; +import { useTeam } from "../../hooks/useTeam"; +import { PATHS } from "../../paths"; +import type { Company } from "../../types/company"; +import type { Guest } from "../../types/guest"; +import type { HostCard, HostFields } from "../../types/event-host"; +import type { TeamMember } from "../../types/team"; +import { CompanyMark } from "../guests/CompanyMark"; +import { FIELD_INPUT } from "../ui/field-styles"; +import { SearchField } from "../ui/SearchField"; +import { Tag } from "../ui/Tag"; +import { ExtraPanel } from "./ExtraPanel"; +import { PanelSaveBar } from "./PanelSaveBar"; -type Person = Readonly<{ - id: string; - name: string; - pictureUrl: string | null; - title?: string | null; - role?: string | null; - isPublic?: boolean; -}>; +const ACTION_BUTTON = + "grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40"; -const ACTION_BUTTON = 'grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40'; - -/** Shows the event's saved hosts and an editor that keeps changes local until the exec presses Save. */ +/** Loads an event's hosts and the people who can be added to it. */ export function EventHostsPanel({ eventId }: { eventId: string }) { const hosts = useEventHosts(eventId); const save = useSaveHosts(eventId); - const guests = useGuests(); - const team = useTeam(); + const guests = choicesFrom(useGuests()); + const team = choicesFrom(useTeam()); + const companies = choicesFrom(useCompanies()); return ( {(saved) => ( - + )} ); } -type HostsEditorProps = Readonly<{ +type HostsEditorProps = { saved: readonly HostCard[]; save: ReturnType; - guests: readonly Person[]; - team: readonly Person[]; -}>; + guests: Choices; + team: Choices; + companies: Choices; +}; -function HostsEditor({ saved, save, guests, team }: HostsEditorProps) { +function HostsEditor({ + saved, + save, + guests, + team, + companies, +}: HostsEditorProps) { const [rows, setRows] = useState(saved); const [changed, setChanged] = useState(false); - const [query, setQuery] = useState(''); - const available = peopleToAdd(rows, guests, team, query); + const [query, setQuery] = useState(""); + const companyById = new Map( + (typeof companies === "string" ? [] : companies).map((company) => [ + company.id, + company, + ]), + ); function change(next: readonly HostCard[]) { setRows(next); setChanged(true); } - function move(index: number, by: -1 | 1) { const next = [...rows]; const [row] = next.splice(index, 1); if (row) next.splice(index + by, 0, row); change(next); } - - function add(kind: 'team' | 'guest', person: Person) { - change([...rows, newHostCard(kind, person, rows.length)]); - setQuery(''); + function addGuest(guest: Guest) { + change([ + ...rows, + guestHostCard(guest, companyById.get(guest.companyId ?? ""), rows.length), + ]); + setQuery(""); + } + function addTeamMember(member: TeamMember) { + change([...rows, teamHostCard(member, rows.length)]); + setQuery(""); } return ( <> - {rows.length === 0 ? ( -

    No speakers or hosts yet. Add guests here, or from their guest page.

    - ) : ( -
      - {rows.map((host, index) => ( - change(rows.filter((row) => row.id !== host.id))} - /> - ))} -
    - )} - + change(rows.filter((row) => row.id !== id))} + /> + save.mutate(rows.map(toHostFields), { onSuccess: () => setChanged(false) })} + onSave={() => + save.mutate(rows.map(toHostFields), { + onSuccess: () => setChanged(false), + }) + } /> ); } -function HostPicker({ query, guests, team, onQueryChange, onPick }: Readonly<{ query: string; guests: readonly Person[]; team: readonly Person[]; onQueryChange: (query: string) => void; onPick: (kind: 'team' | 'guest', person: Person) => void }>) { +function HostList({ + rows, + onMove, + onRemove, +}: { + rows: readonly HostCard[]; + onMove: (index: number, by: -1 | 1) => void; + onRemove: (id: string) => void; +}) { + if (rows.length === 0) + return ( +

    + No speakers or hosts yet. Add guests here, or from their guest page. +

    + ); + return ( +
      + {rows.map((host, index) => ( + onRemove(host.id)} + /> + ))} +
    + ); +} + +function HostPicker({ + query, + guests, + team, + rows, + onQueryChange, + onPickGuest, + onPickTeam, +}: { + query: string; + guests: Choices; + team: Choices; + rows: readonly HostCard[]; + onQueryChange: (query: string) => void; + onPickGuest: (guest: Guest) => void; + onPickTeam: (member: TeamMember) => void; +}) { + const added = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); return (
    - - onPick('guest', person)} /> - onPick('team', person)} /> + + +

    - Add a new guest + + Add a new guest +

    ); } -function PickerGroup({ title, people, onPick }: Readonly<{ title: string; people: readonly Person[]; onPick: (person: Person) => void }>) { +function PickerGroup({ + title, + query, + choices, + onPick, +}: { + title: string; + query: string; + choices: Choices; + onPick: (person: T) => void; +}) { + const message = pickerMessage(title, query, choices); return (

    {title}

    - {people.length === 0 ?

    No people found.

    :
      {people.map((person) =>
    • )}
    } + {message ? ( +

    {message}

    + ) : ( +
      + {(choices as readonly T[]).map((person) => ( +
    • + +
    • + ))} +
    + )}
    ); } -function HostRow({ host, index, total, onMove, onRemove }: Readonly<{ host: HostCard; index: number; total: number; onMove: (index: number, by: -1 | 1) => void; onRemove: () => void }>) { +function HostRow({ + host, + index, + total, + onMove, + onRemove, +}: { + host: HostCard; + index: number; + total: number; + onMove: (index: number, by: -1 | 1) => void; + onRemove: () => void; +}) { return (
  • -

    {host.name}

    {host.subtitle &&

    {host.subtitle}

    }{host.kind === 'team' &&

    Not shown on the site yet{!host.isPublic && '; hidden from the site'}.

    }
    - {host.kind === 'guest' && host.company && } - {host.kind === 'team' ? 'Team' : 'Guest'} -
    +
    +

    {host.name}

    + {host.subtitle && ( +

    {host.subtitle}

    + )} + {host.kind === "team" && ( +

    + Not shown on the site yet + {!host.isPublic && "; hidden from the site"}. +

    + )} +
    + {host.kind === "guest" && } + {host.kind === "team" ? "Team" : "Guest"} +
    + + + +
  • ); } -function HostFace({ host }: { host: HostCard }) { return host.pictureUrl ? : ; } -function CompanyMark({ host }: { host: HostCard }) { const company = host.company!; return {company.logoUrl ? : }; } -function peopleToAdd(rows: readonly HostCard[], guests: readonly Person[], team: readonly Person[], query: string) { const added = new Set(rows.map((row) => `${row.kind}:${row.personId}`)); const matches = (person: Person, kind: 'guest' | 'team') => !added.has(`${kind}:${person.id}`) && person.name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()); return { guests: guests.filter((person) => matches(person, 'guest')), team: team.filter((person) => matches(person, 'team')) }; } -function newHostCard(kind: 'team' | 'guest', person: Person, sortOrder: number): HostCard { return { id: crypto.randomUUID(), eventId: '', sortOrder, kind, personId: person.id, name: person.name, subtitle: kind === 'team' ? person.role ?? null : person.title ?? null, pictureUrl: person.pictureUrl, company: null, isPublic: kind === 'team' ? person.isPublic === true : true }; } -function toHostFields(host: HostCard): HostFields { return host.kind === 'team' ? { kind: 'team', teamId: host.personId } : { kind: 'guest', guestId: host.personId }; } +/** Their photo, or one initial so a missing photo does not leave a blank gap. */ +function HostFace({ host }: { host: HostCard }) { + return host.pictureUrl ? ( + + ) : ( + + ); +} +/** Removes saved people from a searched list, without presenting a full directory first. */ +function choicesToAdd( + choices: Choices, + kind: "guest" | "team", + added: ReadonlySet, + query: string, +): Choices { + if (typeof choices === "string" || !query.trim()) return choices; + const term = query.trim().toLocaleLowerCase(); + return choices.filter( + (person) => + !added.has(`${kind}:${person.id}`) && + person.name.toLocaleLowerCase().includes(term), + ); +} +function pickerMessage( + title: string, + query: string, + choices: Choices, +): string | null { + if (!query.trim()) return "Start typing to search."; + if (choices === "loading") return `Loading ${title.toLocaleLowerCase()}…`; + if (choices === "failed") return `${title} couldn't be loaded.`; + return choices.length === 0 ? `No ${title.toLocaleLowerCase()} found.` : null; +} +/** Builds a draft guest row with the company details it will have after the joined read reloads. */ +function guestHostCard( + guest: Guest, + company: Company | undefined, + sortOrder: number, +): HostCard { + return { + id: crypto.randomUUID(), + eventId: "", + sortOrder, + kind: "guest", + personId: guest.id, + name: guest.name, + subtitle: guest.title, + pictureUrl: guest.pictureUrl, + company: company + ? { name: company.name, colour: company.colour, logoUrl: company.logoUrl } + : null, + isPublic: true, + }; +} +/** Builds a draft team row. Team members are recorded for now, not rendered on the site. */ +function teamHostCard(member: TeamMember, sortOrder: number): HostCard { + return { + id: crypto.randomUUID(), + eventId: "", + sortOrder, + kind: "team", + personId: member.id, + name: member.name, + subtitle: member.role, + pictureUrl: member.pictureUrl, + company: null, + isPublic: member.isPublic, + }; +} +/** Turns display rows back into the small list the save function stores. */ +function toHostFields(host: HostCard): HostFields { + return host.kind === "team" + ? { kind: "team", teamId: host.personId } + : { kind: "guest", guestId: host.personId }; +} diff --git a/apps/admin/src/components/guests/CompanyMark.tsx b/apps/admin/src/components/guests/CompanyMark.tsx index 219e986..146e2de 100644 --- a/apps/admin/src/components/guests/CompanyMark.tsx +++ b/apps/admin/src/components/guests/CompanyMark.tsx @@ -2,9 +2,12 @@ * A company's name beside a dot in its own brand colour, or "No company" when there isn't one. The colour is * the company's data from Supabase, so it is set inline rather than from a token. */ -import type { CompanyBadge } from '../../types/company'; +import type { CompanyBadge } from "../../types/company"; -export function CompanyMark({ company }: { company: CompanyBadge | null }) { +/** The company fields this small mark needs, whether it comes from the guest book or another list. */ +type MarkCompany = Pick; + +export function CompanyMark({ company }: { company: MarkCompany | null }) { if (!company) return No company; return ( diff --git a/apps/admin/tests/pages/EventExtras.test.tsx b/apps/admin/tests/pages/EventExtras.test.tsx index 54f0ec7..96e06a0 100644 --- a/apps/admin/tests/pages/EventExtras.test.tsx +++ b/apps/admin/tests/pages/EventExtras.test.tsx @@ -1,30 +1,77 @@ -import { screen, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { listBuildings } from '../../src/lib/data/buildings'; -import { listCompanies } from '../../src/lib/data/companies'; -import { addLinkDocument, listDocuments } from '../../src/lib/data/event-documents'; -import { listPartners, savePartners } from '../../src/lib/data/event-partners'; -import { listRelated, saveRelated } from '../../src/lib/data/event-related'; -import { listTopics, saveTopics } from '../../src/lib/data/event-topics'; -import { getEvent, listEvents } from '../../src/lib/data/events'; -import { UnavailableError } from '../../src/lib/server/errors'; -import { sampleEvent } from '../fixtures/events'; -import { mockAccess, SAM_ADMIN } from '../mocks/auth'; -import { renderApp } from '../renderApp'; - -vi.mock('../../src/lib/auth/auth'); -vi.mock('../../src/lib/data/events'); -vi.mock('../../src/lib/data/buildings'); -vi.mock('../../src/lib/data/event-topics'); -vi.mock('../../src/lib/data/event-partners'); -vi.mock('../../src/lib/data/companies'); -vi.mock('../../src/lib/data/event-documents'); -vi.mock('../../src/lib/data/event-related'); - -const FINAL_REVIEW = sampleEvent({ id: '0b6f9c2e-7a41-4d5b-8e3c-2f1a9b8c7d6e', title: 'CP312 Final Review', date: '2026-12-05', category: 'review' }); -const MIDTERM_REVIEW = sampleEvent({ id: '1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f', title: 'CP312 Midterm Review', date: '2026-10-15', category: 'review' }); -const LWICS = { id: '2d8b1e4f-9c6a-4f7d-8e5b-0c1d2e3f4a5b', name: 'LWICS', colour: '#ff9fc4', logoPath: null, logoUrl: null, cardLogoPath: null, cardLogoUrl: null }; -const TOPIC_ID = '3e9c2f5a-0d7b-4a8e-9f6c-1d2e3f4a5b6c'; +import { screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { listBuildings } from "../../src/lib/data/buildings"; +import { listCompanies } from "../../src/lib/data/companies"; +import { + addLinkDocument, + listDocuments, +} from "../../src/lib/data/event-documents"; +import { listPartners, savePartners } from "../../src/lib/data/event-partners"; +import { listRelated, saveRelated } from "../../src/lib/data/event-related"; +import { listTopics, saveTopics } from "../../src/lib/data/event-topics"; +import { listHosts, saveHosts } from "../../src/lib/data/event-hosts"; +import { listGuests } from "../../src/lib/data/guests"; +import { listTeam } from "../../src/lib/data/team"; +import { getEvent, listEvents } from "../../src/lib/data/events"; +import { UnavailableError } from "../../src/lib/server/errors"; +import { sampleEvent } from "../fixtures/events"; +import { mockAccess, SAM_ADMIN } from "../mocks/auth"; +import { renderApp } from "../renderApp"; + +vi.mock("../../src/lib/auth/auth"); +vi.mock("../../src/lib/data/events"); +vi.mock("../../src/lib/data/buildings"); +vi.mock("../../src/lib/data/event-topics"); +vi.mock("../../src/lib/data/event-partners"); +vi.mock("../../src/lib/data/companies"); +vi.mock("../../src/lib/data/event-documents"); +vi.mock("../../src/lib/data/event-related"); +vi.mock("../../src/lib/data/event-hosts"); +vi.mock("../../src/lib/data/guests"); +vi.mock("../../src/lib/data/team"); + +const FINAL_REVIEW = sampleEvent({ + id: "0b6f9c2e-7a41-4d5b-8e3c-2f1a9b8c7d6e", + title: "CP312 Final Review", + date: "2026-12-05", + category: "review", +}); +const MIDTERM_REVIEW = sampleEvent({ + id: "1c7a0d3f-8b52-4e6c-9f4d-3a2b1c0d9e8f", + title: "CP312 Midterm Review", + date: "2026-10-15", + category: "review", +}); +const LWICS = { + id: "2d8b1e4f-9c6a-4f7d-8e5b-0c1d2e3f4a5b", + name: "LWICS", + colour: "#ff9fc4", + logoPath: null, + logoUrl: null, + cardLogoPath: null, + cardLogoUrl: null, +}; +const TOPIC_ID = "3e9c2f5a-0d7b-4a8e-9f6c-1d2e3f4a5b6c"; +const GUEST = { + id: "4f0d3a6e-1e8c-4f9d-8a7e-2b3c4d5e6f70", + name: "Grace Hopper", + title: "Engineer", + companyId: LWICS.id, + picturePath: null, + pictureUrl: null, + linkUrl: null, +}; +const MEMBER = { + id: "5a1e4b7f-2f9d-4a0e-9b8f-3c4d5e6f7a81", + name: "Ada Lovelace", + role: "President", + department: "Engineering" as const, + isPublic: false, + photoPath: null, + pictureUrl: null, + githubUrl: null, + linkedinUrl: null, +}; beforeEach(() => { mockAccess(SAM_ADMIN); @@ -40,104 +87,243 @@ beforeEach(() => { vi.mocked(savePartners).mockResolvedValue(); vi.mocked(saveRelated).mockResolvedValue(); vi.mocked(addLinkDocument).mockResolvedValue(); + vi.mocked(listHosts).mockResolvedValue([]); + vi.mocked(saveHosts).mockResolvedValue(); + vi.mocked(listGuests).mockResolvedValue([GUEST]); + vi.mocked(listTeam).mockResolvedValue([MEMBER]); }); /** One of the panels under the form, once its list has loaded. */ async function panel(name: string) { - const section = await screen.findByRole('region', { name }); - await within(section).findByRole('button', { name: /^Save|Add resource/ }); + const section = await screen.findByRole("region", { name }); + await within(section).findByRole("button", { name: /^Save|Add resource/ }); return within(section); } describe("what they'll cover", () => { - it('adds a topic with an icon picked by search, and saves the list', async () => { - vi.mocked(listTopics).mockResolvedValue([{ id: TOPIC_ID, eventId: FINAL_REVIEW.id, text: 'Past exam walkthrough', icon: null, sortOrder: 0 }]); + it("adds a topic with an icon picked by search, and saves the list", async () => { + vi.mocked(listTopics).mockResolvedValue([ + { + id: TOPIC_ID, + eventId: FINAL_REVIEW.id, + text: "Past exam walkthrough", + icon: null, + sortOrder: 0, + }, + ]); renderApp(`/events/${FINAL_REVIEW.id}`); const topics = await panel("What they'll cover"); - await userEvent.click(topics.getByRole('button', { name: 'Add a topic' })); - await userEvent.type(topics.getByLabelText('Topic 2'), 'Study tips'); - await userEvent.click(topics.getByRole('button', { name: 'Change the icon of topic 2' })); - await userEvent.type(screen.getByLabelText('Search icons'), 'rocket'); - await userEvent.click(screen.getByRole('button', { name: 'rocket' })); - await userEvent.click(topics.getByRole('button', { name: 'Move topic 2 up' })); - await userEvent.click(topics.getByRole('button', { name: 'Save topics' })); + await userEvent.click(topics.getByRole("button", { name: "Add a topic" })); + await userEvent.type(topics.getByLabelText("Topic 2"), "Study tips"); + await userEvent.click( + topics.getByRole("button", { name: "Change the icon of topic 2" }), + ); + await userEvent.type(screen.getByLabelText("Search icons"), "rocket"); + await userEvent.click(screen.getByRole("button", { name: "rocket" })); + await userEvent.click( + topics.getByRole("button", { name: "Move topic 2 up" }), + ); + await userEvent.click(topics.getByRole("button", { name: "Save topics" })); expect(saveTopics).toHaveBeenCalledWith(FINAL_REVIEW.id, [ - { id: null, text: 'Study tips', icon: 'rocket' }, - { id: TOPIC_ID, text: 'Past exam walkthrough', icon: null }, + { id: null, text: "Study tips", icon: "rocket" }, + { id: TOPIC_ID, text: "Past exam walkthrough", icon: null }, ]); - expect(await topics.findByText('Saved.')).toBeInTheDocument(); + expect(await topics.findByText("Saved.")).toBeInTheDocument(); }); it("won't save a topic with no words", async () => { renderApp(`/events/${FINAL_REVIEW.id}`); const topics = await panel("What they'll cover"); - await userEvent.click(topics.getByRole('button', { name: 'Add a topic' })); - await userEvent.click(topics.getByRole('button', { name: 'Save topics' })); + await userEvent.click(topics.getByRole("button", { name: "Add a topic" })); + await userEvent.click(topics.getByRole("button", { name: "Save topics" })); - expect(topics.getByText('Write what the topic is.')).toBeInTheDocument(); + expect(topics.getByText("Write what the topic is.")).toBeInTheDocument(); expect(saveTopics).not.toHaveBeenCalled(); }); - it('says the topics could not be loaded instead of showing none', async () => { - vi.mocked(listTopics).mockRejectedValue(new UnavailableError("The event's topics could not be loaded.")); + it("says the topics could not be loaded instead of showing none", async () => { + vi.mocked(listTopics).mockRejectedValue( + new UnavailableError("The event's topics could not be loaded."), + ); renderApp(`/events/${FINAL_REVIEW.id}`); - const topics = within(await screen.findByRole('region', { name: "What they'll cover" })); - expect(await topics.findByRole('alert')).toHaveTextContent("The event's topics could not be loaded."); + const topics = within( + await screen.findByRole("region", { name: "What they'll cover" }), + ); + expect(await topics.findByRole("alert")).toHaveTextContent( + "The event's topics could not be loaded.", + ); expect(topics.queryByText(/No topics yet/)).not.toBeInTheDocument(); }); }); -describe('in collaboration with', () => { - it('adds a partner from Companies and saves the list', async () => { +describe("in collaboration with", () => { + it("adds a partner from Companies and saves the list", async () => { renderApp(`/events/${FINAL_REVIEW.id}`); - const partners = await panel('In collaboration with'); - const option = await partners.findByRole('option', { name: 'LWICS' }); - await userEvent.selectOptions(partners.getByLabelText('Add a partner'), option); - expect(partners.getByRole('button', { name: 'Remove LWICS' })).toBeInTheDocument(); - await userEvent.click(partners.getByRole('button', { name: 'Save partners' })); + const partners = await panel("In collaboration with"); + const option = await partners.findByRole("option", { name: "LWICS" }); + await userEvent.selectOptions( + partners.getByLabelText("Add a partner"), + option, + ); + expect( + partners.getByRole("button", { name: "Remove LWICS" }), + ).toBeInTheDocument(); + await userEvent.click( + partners.getByRole("button", { name: "Save partners" }), + ); expect(savePartners).toHaveBeenCalledWith(FINAL_REVIEW.id, [LWICS.id]); }); }); -describe('resources', () => { - it('adds a link with its kind', async () => { +describe("speakers and hosts", () => { + it("lists, adds, reorders, removes and saves hosts", async () => { + vi.mocked(listHosts).mockResolvedValue([ + { + id: "6b2f5c8a-3d1e-4f0a-9b7c-2d3e4f5a6b7c", + eventId: FINAL_REVIEW.id, + sortOrder: 0, + kind: "team", + personId: MEMBER.id, + name: MEMBER.name, + subtitle: MEMBER.role, + pictureUrl: null, + company: null, + isPublic: false, + }, + { + id: "7c3e6d9b-4f2a-4b1c-8d9e-3f4a5b6c7d8e", + eventId: FINAL_REVIEW.id, + sortOrder: 1, + kind: "guest", + personId: GUEST.id, + name: GUEST.name, + subtitle: GUEST.title, + pictureUrl: null, + company: { name: LWICS.name, colour: LWICS.colour, logoUrl: null }, + isPublic: true, + }, + ]); renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel("Speakers and hosts"); - const resources = await panel('Resources'); - await userEvent.type(resources.getByLabelText('Resource name'), 'Practice final'); - await userEvent.selectOptions(resources.getByLabelText('Kind'), 'Practice exam'); - await userEvent.type(resources.getByLabelText('Link'), 'https://drive.google.com/file/abc'); - await userEvent.click(resources.getByRole('button', { name: 'Add resource' })); + expect( + hosts + .getByText("Ada Lovelace") + .compareDocumentPosition(hosts.getByText("Grace Hopper")) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(hosts.getByText(/hidden from the site/)).toBeInTheDocument(); + await userEvent.type( + hosts.getByLabelText("Add a speaker or host"), + "grace", + ); + expect( + hosts.queryByRole("button", { name: "Grace Hopper" }), + ).not.toBeInTheDocument(); + await userEvent.clear(hosts.getByLabelText("Add a speaker or host")); + await userEvent.type(hosts.getByLabelText("Add a speaker or host"), "ada"); + expect( + hosts.queryByRole("button", { name: "Ada Lovelace" }), + ).not.toBeInTheDocument(); + await userEvent.click( + hosts.getByRole("button", { name: "Move Grace Hopper up" }), + ); + await userEvent.click( + hosts.getByRole("button", { name: "Remove Ada Lovelace" }), + ); + await userEvent.click( + hosts.getByRole("button", { name: "Save speakers and hosts" }), + ); - expect(addLinkDocument).toHaveBeenCalledWith(FINAL_REVIEW.id, { title: 'Practice final', kind: 'practice_exam' }, 'https://drive.google.com/file/abc'); + expect(saveHosts).toHaveBeenCalledWith(FINAL_REVIEW.id, [ + { kind: "guest", guestId: GUEST.id }, + ]); + }); + + it("explains loading, failed and empty picker choices", async () => { + vi.mocked(listGuests).mockRejectedValue( + new UnavailableError("Guests couldn't be loaded."), + ); + vi.mocked(listTeam).mockResolvedValue([]); + renderApp(`/events/${FINAL_REVIEW.id}`); + const hosts = await panel("Speakers and hosts"); + await userEvent.type(hosts.getByLabelText("Add a speaker or host"), "a"); + expect( + await hosts.findByText("Guests couldn't be loaded."), + ).toBeInTheDocument(); + expect(hosts.getByText("No team members found.")).toBeInTheDocument(); + }); +}); + +describe("resources", () => { + it("adds a link with its kind", async () => { + renderApp(`/events/${FINAL_REVIEW.id}`); + + const resources = await panel("Resources"); + await userEvent.type( + resources.getByLabelText("Resource name"), + "Practice final", + ); + await userEvent.selectOptions( + resources.getByLabelText("Kind"), + "Practice exam", + ); + await userEvent.type( + resources.getByLabelText("Link"), + "https://drive.google.com/file/abc", + ); + await userEvent.click( + resources.getByRole("button", { name: "Add resource" }), + ); + + expect(addLinkDocument).toHaveBeenCalledWith( + FINAL_REVIEW.id, + { title: "Practice final", kind: "practice_exam" }, + "https://drive.google.com/file/abc", + ); }); it("refuses a file that isn't a PDF or a deck", async () => { renderApp(`/events/${FINAL_REVIEW.id}`); - const resources = await panel('Resources'); - await userEvent.click(resources.getByRole('radio', { name: 'A file' })); - await userEvent.upload(resources.getByLabelText('File'), new File(['x'], 'notes.zip', { type: 'application/zip' }), { applyAccept: false }); + const resources = await panel("Resources"); + await userEvent.click(resources.getByRole("radio", { name: "A file" })); + await userEvent.upload( + resources.getByLabelText("File"), + new File(["x"], "notes.zip", { type: "application/zip" }), + { applyAccept: false }, + ); - expect(resources.getByLabelText('File')).toHaveAccessibleDescription(/isn't a PDF or a PowerPoint deck/); + expect(resources.getByLabelText("File")).toHaveAccessibleDescription( + /isn't a PDF or a PowerPoint deck/, + ); }); }); -describe('last time', () => { - it('links the event to an earlier one', async () => { +describe("last time", () => { + it("links the event to an earlier one", async () => { renderApp(`/events/${FINAL_REVIEW.id}`); - const lastTime = await panel('Last time'); - const option = await lastTime.findByRole('option', { name: 'CP312 Midterm Review · Oct 15, 2026' }); - await userEvent.selectOptions(lastTime.getByLabelText('Follows on from'), option); - await userEvent.click(lastTime.getByRole('button', { name: 'Save last time' })); + const lastTime = await panel("Last time"); + const option = await lastTime.findByRole("option", { + name: "CP312 Midterm Review · Oct 15, 2026", + }); + await userEvent.selectOptions( + lastTime.getByLabelText("Follows on from"), + option, + ); + await userEvent.click( + lastTime.getByRole("button", { name: "Save last time" }), + ); - expect(saveRelated).toHaveBeenCalledWith(FINAL_REVIEW.id, [MIDTERM_REVIEW.id]); + expect(saveRelated).toHaveBeenCalledWith(FINAL_REVIEW.id, [ + MIDTERM_REVIEW.id, + ]); }); }); From 3317d59d6b533fe15c663040302a12ba03b00c0d Mon Sep 17 00:00:00 2001 From: Flapjacck Date: Mon, 30 Nov 2026 15:14:41 -0500 Subject: [PATCH 7/9] style(admin): restore event host panel conventions --- .../src/components/events/EventHostsPanel.tsx | 93 ++++++++++--------- .../src/components/guests/CompanyMark.tsx | 4 +- 2 files changed, 52 insertions(+), 45 deletions(-) diff --git a/apps/admin/src/components/events/EventHostsPanel.tsx b/apps/admin/src/components/events/EventHostsPanel.tsx index 34aa2ed..677cb6f 100644 --- a/apps/admin/src/components/events/EventHostsPanel.tsx +++ b/apps/admin/src/components/events/EventHostsPanel.tsx @@ -1,26 +1,26 @@ -/** "Speakers and hosts" for an event, held locally until the exec saves. */ -import { ArrowDown, ArrowUp, X } from "lucide-react"; -import { useState } from "react"; -import { Link } from "react-router"; -import { type Choices, choicesFrom } from "../../hooks/choices"; -import { useCompanies } from "../../hooks/useCompanies"; -import { useEventHosts, useSaveHosts } from "../../hooks/useEventHosts"; -import { useGuests } from "../../hooks/useGuests"; -import { useTeam } from "../../hooks/useTeam"; -import { PATHS } from "../../paths"; -import type { Company } from "../../types/company"; -import type { Guest } from "../../types/guest"; -import type { HostCard, HostFields } from "../../types/event-host"; -import type { TeamMember } from "../../types/team"; -import { CompanyMark } from "../guests/CompanyMark"; -import { FIELD_INPUT } from "../ui/field-styles"; -import { SearchField } from "../ui/SearchField"; -import { Tag } from "../ui/Tag"; -import { ExtraPanel } from "./ExtraPanel"; -import { PanelSaveBar } from "./PanelSaveBar"; +/** 'Speakers and hosts' for an event, held locally until the exec saves. */ +import { ArrowDown, ArrowUp, X } from 'lucide-react'; +import { useState } from 'react'; +import { Link } from 'react-router'; +import { type Choices, choicesFrom } from '../../hooks/choices'; +import { useCompanies } from '../../hooks/useCompanies'; +import { useEventHosts, useSaveHosts } from '../../hooks/useEventHosts'; +import { useGuests } from '../../hooks/useGuests'; +import { useTeam } from '../../hooks/useTeam'; +import { PATHS } from '../../paths'; +import type { Company } from '../../types/company'; +import type { Guest } from '../../types/guest'; +import type { HostCard, HostFields } from '../../types/event-host'; +import type { TeamMember } from '../../types/team'; +import { CompanyMark } from '../guests/CompanyMark'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { SearchField } from '../ui/SearchField'; +import { Tag } from '../ui/Tag'; +import { ExtraPanel } from './ExtraPanel'; +import { PanelSaveBar } from './PanelSaveBar'; const ACTION_BUTTON = - "grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40"; + 'grid size-10 place-items-center rounded-full transition-colors hover:bg-slate disabled:opacity-40'; /** Loads an event's hosts and the people who can be added to it. */ export function EventHostsPanel({ eventId }: { eventId: string }) { @@ -67,9 +67,9 @@ function HostsEditor({ }: HostsEditorProps) { const [rows, setRows] = useState(saved); const [changed, setChanged] = useState(false); - const [query, setQuery] = useState(""); + const [query, setQuery] = useState(''); const companyById = new Map( - (typeof companies === "string" ? [] : companies).map((company) => [ + (typeof companies === 'string' ? [] : companies).map((company) => [ company.id, company, ]), @@ -88,13 +88,13 @@ function HostsEditor({ function addGuest(guest: Guest) { change([ ...rows, - guestHostCard(guest, companyById.get(guest.companyId ?? ""), rows.length), + guestHostCard(guest, companyById.get(guest.companyId ?? ''), rows.length), ]); - setQuery(""); + setQuery(''); } function addTeamMember(member: TeamMember) { change([...rows, teamHostCard(member, rows.length)]); - setQuery(""); + setQuery(''); } return ( @@ -222,6 +222,7 @@ function PickerGroup({ onPick: (person: T) => void; }) { const message = pickerMessage(title, query, choices); + const people = typeof choices === 'string' ? null : choices; return (

    {title}

    @@ -229,7 +230,7 @@ function PickerGroup({

    {message}

    ) : (
      - {(choices as readonly T[]).map((person) => ( + {people?.map((person) => (
    - {host.kind === "guest" && } - {host.kind === "team" ? "Team" : "Guest"} + {host.kind === 'guest' && } + {host.kind === 'team' ? 'Team' : 'Guest'}