From e00690c471139c32576827b4b5a62777d12d55f0 Mon Sep 17 00:00:00 2001 From: b4sleal Date: Sun, 29 Nov 2026 22:15:11 -0500 Subject: [PATCH 1/6] chore(admin): add markdown-it for event descriptions --- apps/admin/package.json | 2 ++ apps/admin/pnpm-lock.yaml | 71 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/apps/admin/package.json b/apps/admin/package.json index 9a5c10b..e42c2f3 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -23,6 +23,7 @@ "browser-image-compression": "2.0.2", "diff": "9.0.0", "lucide-react": "1.75.0", + "markdown-it": "14.1.0", "motion": "^14.14.0", "papaparse": "5.7.0", "react": "^19.3.1", @@ -38,6 +39,7 @@ "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.12", + "@types/markdown-it": "14.1.2", "@types/node": "^24.19.2", "@types/papaparse": "5.5.2", "@types/react": "^19.3.0", diff --git a/apps/admin/pnpm-lock.yaml b/apps/admin/pnpm-lock.yaml index 3ef5b28..f8ae1b0 100644 --- a/apps/admin/pnpm-lock.yaml +++ b/apps/admin/pnpm-lock.yaml @@ -41,6 +41,9 @@ importers: lucide-react: specifier: 1.75.0 version: 1.75.0(@types/react@19.3.0)(react@19.3.1) + markdown-it: + specifier: 14.1.0 + version: 14.1.0 motion: specifier: ^14.14.0 version: 14.14.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -81,6 +84,9 @@ importers: '@testing-library/user-event': specifier: ^14.6.12 version: 14.6.12(@testing-library/dom@10.4.2) + '@types/markdown-it': + specifier: 14.1.2 + version: 14.1.2 '@types/node': specifier: ^24.19.2 version: 24.19.2 @@ -680,6 +686,15 @@ packages: '@types/estree@1.0.10': resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + '@types/linkify-it@5.0.0': + resolution: {integrity: sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==} + + '@types/markdown-it@14.1.2': + resolution: {integrity: sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==} + + '@types/mdurl@2.0.0': + resolution: {integrity: sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==} + '@types/node@24.19.2': resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==} @@ -852,6 +867,9 @@ packages: resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} engines: {node: '>=10'} + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + aria-query@5.3.0: resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} @@ -914,6 +932,10 @@ packages: resolution: {integrity: sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==} engines: {node: '>=10.13.0'} + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + entities@9.0.0: resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} engines: {node: '>=20.19.0'} @@ -1069,6 +1091,9 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} + linkify-it@5.0.2: + resolution: {integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==} + lru-cache@11.5.3: resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} engines: {node: 20 || >=22} @@ -1089,6 +1114,13 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + markdown-it@14.1.0: + resolution: {integrity: sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==} + hasBin: true + + mdurl@2.1.0: + resolution: {integrity: sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==} + min-indent@1.0.1: resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==} engines: {node: '>=4'} @@ -1162,6 +1194,10 @@ packages: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} + punycode.js@2.3.1: + resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} + engines: {node: '>=6'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -1290,6 +1326,9 @@ packages: engines: {node: '>=16.20.0'} hasBin: true + uc.micro@2.1.0: + resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} + undici-types@7.24.6: resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} @@ -1788,6 +1827,15 @@ snapshots: '@types/estree@1.0.10': {} + '@types/linkify-it@5.0.0': {} + + '@types/markdown-it@14.1.2': + dependencies: + '@types/linkify-it': 5.0.0 + '@types/mdurl': 2.0.0 + + '@types/mdurl@2.0.0': {} + '@types/node@24.19.2': dependencies: undici-types: 7.24.6 @@ -1884,6 +1932,8 @@ snapshots: ansi-styles@5.2.0: {} + argparse@2.0.1: {} + aria-query@5.3.0: dependencies: dequal: 2.0.3 @@ -1936,6 +1986,8 @@ snapshots: graceful-fs: 4.2.12 tapable: 2.3.4 + entities@4.5.0: {} + entities@9.0.0: {} es-module-lexer@2.3.2: {} @@ -2061,6 +2113,10 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 + linkify-it@5.0.2: + dependencies: + uc.micro: 2.1.0 + lru-cache@11.5.3: {} lucide-react@1.75.0(@types/react@19.3.0)(react@19.3.1): @@ -2075,6 +2131,17 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 + markdown-it@14.1.0: + dependencies: + argparse: 2.0.1 + entities: 4.5.0 + linkify-it: 5.0.2 + mdurl: 2.1.0 + punycode.js: 2.3.1 + uc.micro: 2.1.0 + + mdurl@2.1.0: {} + min-indent@1.0.1: {} motion-dom@14.14.0: @@ -2145,6 +2212,8 @@ snapshots: ansi-styles: 5.2.0 react-is: 17.0.2 + punycode.js@2.3.1: {} + punycode@2.3.1: {} react-dom@19.3.1(react@19.3.1): @@ -2277,6 +2346,8 @@ snapshots: '@typescript/typescript-win32-arm64': 7.0.2 '@typescript/typescript-win32-x64': 7.0.2 + uc.micro@2.1.0: {} + undici-types@7.24.6: {} undici@8.12.4: {} From 6a1044f22fcadebd0383cd80c057b01b763b110f Mon Sep 17 00:00:00 2001 From: b4sleal Date: Sun, 29 Nov 2026 22:15:12 -0500 Subject: [PATCH 2/6] feat(admin): save an event's related events as a list, and hooks for its topics and partners --- apps/admin/src/hooks/useEventPartners.ts | 17 ++++++++ apps/admin/src/hooks/useEventRelated.ts | 11 ++++- apps/admin/src/hooks/useEventTopics.ts | 18 +++++++++ apps/admin/src/lib/data/event-related.ts | 17 ++++++++ .../tests/lib/data/event-related.test.ts | 40 ++++++++++++++++++- 5 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 apps/admin/src/hooks/useEventPartners.ts create mode 100644 apps/admin/src/hooks/useEventTopics.ts diff --git a/apps/admin/src/hooks/useEventPartners.ts b/apps/admin/src/hooks/useEventPartners.ts new file mode 100644 index 0000000..2757cd7 --- /dev/null +++ b/apps/admin/src/hooks/useEventPartners.ts @@ -0,0 +1,17 @@ +/** The companies an event is run with, loaded and cached by TanStack Query, and saving the list. */ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { listPartners, savePartners } from '../lib/data/event-partners'; + +const makePartnersKey = (eventId: string) => ['partners', eventId] as const; + +export function useEventPartners(eventId: string) { + return useQuery({ queryKey: makePartnersKey(eventId), queryFn: () => listPartners(eventId) }); +} + +export function useSavePartners(eventId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (companyIds: readonly string[]) => savePartners(eventId, companyIds), + onSuccess: () => queryClient.invalidateQueries({ queryKey: makePartnersKey(eventId) }), + }); +} diff --git a/apps/admin/src/hooks/useEventRelated.ts b/apps/admin/src/hooks/useEventRelated.ts index f27862f..97b1ecc 100644 --- a/apps/admin/src/hooks/useEventRelated.ts +++ b/apps/admin/src/hooks/useEventRelated.ts @@ -1,6 +1,6 @@ /** Event relationships loaded and cached by TanStack Query, and the changes that refresh them. */ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { addRelated, deleteRelated, listRelated, reorderRelated } from '../lib/data/event-related'; +import { addRelated, deleteRelated, listRelated, reorderRelated, saveRelated } from '../lib/data/event-related'; import type { EventRelated } from '../types/event-related'; // Every related events query for an event starts with this key. @@ -32,6 +32,15 @@ export function useDeleteRelated(eventId: string) { }); } +/** Saves the whole list of events this one links to, in order. */ +export function useSaveRelated(eventId: string) { + const refresh = useRefreshRelated(eventId); + return useMutation({ + mutationFn: (relatedIds: readonly string[]) => saveRelated(eventId, relatedIds), + onSuccess: refresh, + }); +} + export function useReorderRelated(eventId: string) { const refresh = useRefreshRelated(eventId); return useMutation({ diff --git a/apps/admin/src/hooks/useEventTopics.ts b/apps/admin/src/hooks/useEventTopics.ts new file mode 100644 index 0000000..a207fbd --- /dev/null +++ b/apps/admin/src/hooks/useEventTopics.ts @@ -0,0 +1,18 @@ +/** An event's topics loaded and cached by TanStack Query, and saving the list. */ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { listTopics, saveTopics } from '../lib/data/event-topics'; +import type { TopicFields } from '../types/event-topic'; + +const makeTopicsKey = (eventId: string) => ['topics', eventId] as const; + +export function useEventTopics(eventId: string) { + return useQuery({ queryKey: makeTopicsKey(eventId), queryFn: () => listTopics(eventId) }); +} + +export function useSaveTopics(eventId: string) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (topics: readonly TopicFields[]) => saveTopics(eventId, topics), + onSuccess: () => queryClient.invalidateQueries({ queryKey: makeTopicsKey(eventId) }), + }); +} diff --git a/apps/admin/src/lib/data/event-related.ts b/apps/admin/src/lib/data/event-related.ts index a1814d6..0c56f32 100644 --- a/apps/admin/src/lib/data/event-related.ts +++ b/apps/admin/src/lib/data/event-related.ts @@ -91,6 +91,23 @@ export async function reorderRelated(related: readonly EventRelated[]): Promise< } } +/** + * Saves the events an event links to as the list given, in that order: the list is written first, then links + * taken out are removed, so a failure part way never loses a link. + * @throws UnavailableError when the links could not be saved. + */ +export async function saveRelated(eventId: string, relatedIds: readonly string[]): Promise { + const rows: RelatedInsert[] = relatedIds.map((relatedId, index) => ({ event_id: eventId, related_id: relatedId, sort_order: index })); + const failure = "The related events couldn't be saved."; + if (rows.length > 0) { + const { error } = await v2().from('event_related').upsert(rows, { onConflict: 'event_id,related_id' }); + if (error) throw new UnavailableError(failure, { cause: error }); + } + const removal = v2().from('event_related').delete().eq('event_id', eventId); + const { error } = relatedIds.length > 0 ? await removal.not('related_id', 'in', `(${relatedIds.join(',')})`) : await removal; + if (error) throw new UnavailableError(failure, { cause: error }); +} + function toEventRelated(row: RelatedRow): EventRelated | null { const parsed = EventRelatedSchema.safeParse({ eventId: row.event_id, diff --git a/apps/admin/tests/lib/data/event-related.test.ts b/apps/admin/tests/lib/data/event-related.test.ts index 1958488..aaa60ab 100644 --- a/apps/admin/tests/lib/data/event-related.test.ts +++ b/apps/admin/tests/lib/data/event-related.test.ts @@ -1,5 +1,5 @@ import { UnavailableError } from '../../../src/lib/server/errors'; -import { addRelated, deleteRelated, listRelated, reorderRelated } from '../../../src/lib/data/event-related'; +import { addRelated, deleteRelated, listRelated, reorderRelated, saveRelated } from '../../../src/lib/data/event-related'; import type { EventRelated } from '../../../src/types/event-related'; import { installV2Supabase } from '../server/supabase-v2-mock'; @@ -98,3 +98,41 @@ describe('reorderRelated', () => { // Should not throw }); }); + +describe('saveRelated', () => { + function saveTable(upsertError: unknown = null) { + const upsert = vi.fn().mockResolvedValue({ error: upsertError }); + const not = vi.fn().mockResolvedValue({ error: null }); + const eq = vi.fn(() => Object.assign(Promise.resolve({ error: null }), { not })); + return { table: { upsert, delete: vi.fn(() => ({ eq })) }, upsert, eq, not }; + } + + it('writes the links in order, then removes the others', async () => { + const { table, upsert, not } = saveTable(); + installV2Supabase({ event_related: table }); + + await saveRelated(EVENT_ID, [RELATED_ID]); + + expect(upsert).toHaveBeenCalledWith([GOOD_ROW], { onConflict: 'event_id,related_id' }); + expect(not).toHaveBeenCalledWith('related_id', 'in', `(${RELATED_ID})`); + }); + + it('removes every link when the list is empty', async () => { + const { table, upsert, eq, not } = saveTable(); + installV2Supabase({ event_related: table }); + + await saveRelated(EVENT_ID, []); + + expect(upsert).not.toHaveBeenCalled(); + expect(eq).toHaveBeenCalledWith('event_id', EVENT_ID); + expect(not).not.toHaveBeenCalled(); + }); + + it('stops before removing anything when the write fails', async () => { + const { table, eq } = saveTable({ message: 'refused' }); + installV2Supabase({ event_related: table }); + + await expect(saveRelated(EVENT_ID, [RELATED_ID])).rejects.toBeInstanceOf(UnavailableError); + expect(eq).not.toHaveBeenCalled(); + }); +}); From 77e1000a64d710056f391360f6748a75ba51e7a0 Mon Sep 17 00:00:00 2001 From: b4sleal Date: Sun, 29 Nov 2026 22:15:12 -0500 Subject: [PATCH 3/6] feat(admin): description Markdown, event colours, resource file checks and last-time choices --- apps/admin/src/lib/form/last-time.ts | 9 ++++ apps/admin/src/lib/form/resource-form.ts | 25 +++++++++ apps/admin/src/lib/ui/documents.ts | 29 ++++++++++ apps/admin/src/lib/ui/event-palette.ts | 43 +++++++++++++++ apps/admin/src/lib/ui/markdown.ts | 53 +++++++++++++++++++ apps/admin/tests/lib/form/last-time.test.ts | 13 +++++ apps/admin/tests/lib/ui/documents.test.ts | 29 ++++++++++ apps/admin/tests/lib/ui/event-palette.test.ts | 25 +++++++++ apps/admin/tests/lib/ui/markdown.test.ts | 44 +++++++++++++++ 9 files changed, 270 insertions(+) create mode 100644 apps/admin/src/lib/form/last-time.ts create mode 100644 apps/admin/src/lib/form/resource-form.ts create mode 100644 apps/admin/src/lib/ui/documents.ts create mode 100644 apps/admin/src/lib/ui/event-palette.ts create mode 100644 apps/admin/src/lib/ui/markdown.ts create mode 100644 apps/admin/tests/lib/form/last-time.test.ts create mode 100644 apps/admin/tests/lib/ui/documents.test.ts create mode 100644 apps/admin/tests/lib/ui/event-palette.test.ts create mode 100644 apps/admin/tests/lib/ui/markdown.test.ts diff --git a/apps/admin/src/lib/form/last-time.ts b/apps/admin/src/lib/form/last-time.ts new file mode 100644 index 0000000..d3f8fce --- /dev/null +++ b/apps/admin/src/lib/form/last-time.ts @@ -0,0 +1,9 @@ +/** Which events can be picked as an event's "last time", the earlier event its page links back to. */ +import type { Event } from '../../types/event'; + +/** The events before this one, of the same kind first (the last review before this review), newest first in each. */ +export function earlierEvents(event: Pick, events: readonly Event[]): readonly Event[] { + // Dates are YYYY-MM-DD, so comparing the text compares the days. + const newestFirst = events.filter((other) => other.id !== event.id && other.date < event.date).toSorted((a, b) => b.date.localeCompare(a.date)); + return [...newestFirst.filter((other) => other.category === event.category), ...newestFirst.filter((other) => other.category !== event.category)]; +} diff --git a/apps/admin/src/lib/form/resource-form.ts b/apps/admin/src/lib/form/resource-form.ts new file mode 100644 index 0000000..b8a5eb6 --- /dev/null +++ b/apps/admin/src/lib/form/resource-form.ts @@ -0,0 +1,25 @@ +/** + * The form for adding a resource to an event: a title, what kind of thing it is, and a link or a file. The file + * is checked on its own when it's chosen (`checkDocument`), like a picture, so only the link is checked here. + */ +import { z } from 'zod'; +import { DOCUMENT_KINDS, DocumentLinkSchema, EventDocumentSchema } from '../../types/event-document'; + +export const RESOURCE_SOURCES = ['link', 'file'] as const; +export type ResourceSource = (typeof RESOURCE_SOURCES)[number]; + +export const ResourceFormSchema = z + .object({ + title: EventDocumentSchema.shape.title, + kind: z.enum(DOCUMENT_KINDS), + source: z.enum(RESOURCE_SOURCES), + url: z.string(), + }) + .superRefine((values, context) => { + if (values.source === 'link' && !DocumentLinkSchema.safeParse(values.url.trim()).success) { + context.addIssue({ code: 'custom', path: ['url'], message: 'Paste the whole link, starting with https://.' }); + } + }); +export type ResourceFormValues = z.input; + +export const EMPTY_RESOURCE_FORM: ResourceFormValues = { title: '', kind: 'slides', source: 'link', url: '' }; diff --git a/apps/admin/src/lib/ui/documents.ts b/apps/admin/src/lib/ui/documents.ts new file mode 100644 index 0000000..1a97109 --- /dev/null +++ b/apps/admin/src/lib/ui/documents.ts @@ -0,0 +1,29 @@ +/** + * Which files an event's resources accept, checked once when a file is chosen: PDFs and PowerPoint decks, the + * same types and size the `event-media` bucket allows. + */ +import { type CheckedImage, fileSize } from './images'; + +const EXTENSIONS: ReadonlyMap = new Map([ + ['application/pdf', 'pdf'], + ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptx'], +]); +const MAX_MB = 20; + +/** For a file input's `accept`. */ +export const ACCEPTED_DOCUMENT_TYPES = [...EXTENSIONS.keys()].join(','); + +/** The rules in words, for a hint. */ +export const DOCUMENT_RULES = `PDF or PowerPoint (.pptx), up to ${MAX_MB} MB.`; + +export type DocumentCheck = { kind: 'accepted'; file: CheckedImage } | { kind: 'rejected'; reason: string }; + +/** Whether a chosen file can be added as a resource, with the reason in plain words when it can't. */ +export function checkDocument(file: File): DocumentCheck { + const extension = EXTENSIONS.get(file.type); + if (!extension) return { kind: 'rejected', reason: 'That file isn\'t a PDF or a PowerPoint deck. Choose a .pdf or .pptx.' }; + if (file.size > MAX_MB * 1024 * 1024) { + return { kind: 'rejected', reason: `That file is ${fileSize(file)}. Files can be up to ${MAX_MB} MB.` }; + } + return { kind: 'accepted', file: { file, extension } }; +} diff --git a/apps/admin/src/lib/ui/event-palette.ts b/apps/admin/src/lib/ui/event-palette.ts new file mode 100644 index 0000000..c751071 --- /dev/null +++ b/apps/admin/src/lib/ui/event-palette.ts @@ -0,0 +1,43 @@ +/** + * An event's two colours as its page shows them: the colours an exec picked, or the LCS default when they left + * them empty. The default is two LCS accents, so a change of brand colour reaches it through the tokens. + */ +import type { Accent } from './accents'; + +/** The colours of an event that has none of its own: LCS yellow, with pink beside it. */ +export const DEFAULT_PALETTE: Readonly<{ primary: Accent; secondary: Accent }> = { primary: 'yellow', secondary: 'pink' }; + +/** What each default colour is called, for the form's hints. */ +export const ACCENT_NAMES: Readonly> = { pink: 'pink', yellow: 'yellow', blue: 'blue', sky: 'light blue', orange: 'orange' }; + +const ACCENT_COLOUR: Readonly> = { + pink: 'var(--pink)', + yellow: 'var(--yellow)', + blue: 'var(--blue)', + sky: 'var(--light-blue)', + orange: 'var(--orange)', +}; + +/** Which text reads on an accent: white on the LCS blue, dark on the four light ones. */ +const ACCENT_INK: Readonly> = { pink: 'dark', yellow: 'dark', blue: 'light', sky: 'dark', orange: 'dark' }; + +export type TextOnColour = 'dark' | 'light'; + +/** One of an event's colours, ready for a `style`: the colour itself and which text reads on it. */ +export type PaletteColour = Readonly<{ colour: string; text: TextOnColour }>; + +/** The colour to show for a picked `#rrggbb`, or for the default accent when none is picked. */ +export function paletteColour(picked: string | null, fallback: Accent): PaletteColour { + return picked === null ? { colour: ACCENT_COLOUR[fallback], text: ACCENT_INK[fallback] } : { colour: picked, text: textOn(picked) }; +} + +/** + * Dark or white text on a `#rrggbb` colour, whichever has more contrast (WCAG relative luminance). Dark text + * wins from a luminance of about 0.18 up, which is where the two contrasts are equal. + */ +export function textOn(hex: string): TextOnColour { + const channels = [1, 3, 5].map((start) => Number.parseInt(hex.slice(start, start + 2), 16) / 255); + const [red = 0, green = 0, blue = 0] = channels.map((value) => (value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)); + const luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue; + return luminance > 0.179 ? 'dark' : 'light'; +} diff --git a/apps/admin/src/lib/ui/markdown.ts b/apps/admin/src/lib/ui/markdown.ts new file mode 100644 index 0000000..2160804 --- /dev/null +++ b/apps/admin/src/lib/ui/markdown.ts @@ -0,0 +1,53 @@ +/** + * The little Markdown an event description may use: paragraphs, bold, italic, links and bullet lists. Anything + * else (headings, images, HTML) shows as the text it was typed as, so the description can't break the page. + */ +import MarkdownIt from 'markdown-it'; + +// The "zero" preset turns every rule off; only the ones a description allows are turned back on. `html: false` +// escapes any HTML that is typed, and markdown-it refuses `javascript:` links on its own. +const markdown = new MarkdownIt('zero', { html: false, linkify: true }).enable(['emphasis', 'link', 'list', 'linkify', 'escape', 'entity']); + +/** A description as safe HTML, for its preview. */ +export function renderDescription(text: string): string { + return markdown.render(text); +} + +/** What a toolbar button does to the description. */ +export const DESCRIPTION_FORMATS = ['bold', 'italic', 'link', 'list'] as const; +export type DescriptionFormat = (typeof DESCRIPTION_FORMATS)[number]; + +/** The text and what is selected in it, as a textarea has them. */ +export type TextSelection = Readonly<{ text: string; start: number; end: number }>; + +const WRAPS = { bold: '**', italic: '_' } as const; + +/** + * The description after a toolbar button: bold and italic wrap the selection, a link wraps it as the link's words + * with the address selected to type over, and a list starts each selected line with "- ". The new selection + * covers what was formatted, so typing carries on from there. + */ +export function applyFormat({ text, start, end }: TextSelection, format: DescriptionFormat): TextSelection { + const before = text.slice(0, start); + const selected = text.slice(start, end); + const after = text.slice(end); + switch (format) { + case 'bold': + case 'italic': { + const mark = WRAPS[format]; + return { text: `${before}${mark}${selected}${mark}${after}`, start: start + mark.length, end: end + mark.length }; + } + case 'link': { + const words = selected || 'link text'; + const address = 'https://'; + const addressStart = start + words.length + 3; + return { text: `${before}[${words}](${address})${after}`, start: addressStart, end: addressStart + address.length }; + } + case 'list': { + const lineStart = before.lastIndexOf('\n') + 1; + const lines = text.slice(lineStart, end).split('\n'); + const listed = lines.map((line) => (line.startsWith('- ') ? line : `- ${line}`)).join('\n'); + return { text: `${text.slice(0, lineStart)}${listed}${after}`, start: lineStart, end: lineStart + listed.length }; + } + } +} diff --git a/apps/admin/tests/lib/form/last-time.test.ts b/apps/admin/tests/lib/form/last-time.test.ts new file mode 100644 index 0000000..8cf4372 --- /dev/null +++ b/apps/admin/tests/lib/form/last-time.test.ts @@ -0,0 +1,13 @@ +import { earlierEvents } from '../../../src/lib/form/last-time'; +import { sampleEvent } from '../../fixtures/events'; + +describe('the events that can be last time', () => { + it('are the earlier ones, the same kind first, newest first', () => { + const review = (title: string, date: string) => sampleEvent({ id: crypto.randomUUID(), title, date, category: 'review' }); + const social = sampleEvent({ id: crypto.randomUUID(), title: 'Games night', date: '2026-11-01', category: 'social' }); + const events = [review('Midterm review', '2026-10-15'), social, review('Final review', '2026-12-05'), review('Quiz review', '2026-11-05')]; + const current = { id: crypto.randomUUID(), date: '2026-12-01', category: 'review' as const }; + + expect(earlierEvents(current, events).map((event) => event.title)).toEqual(['Quiz review', 'Midterm review', 'Games night']); + }); +}); diff --git a/apps/admin/tests/lib/ui/documents.test.ts b/apps/admin/tests/lib/ui/documents.test.ts new file mode 100644 index 0000000..e350108 --- /dev/null +++ b/apps/admin/tests/lib/ui/documents.test.ts @@ -0,0 +1,29 @@ +import { checkDocument } from '../../../src/lib/ui/documents'; + +function fileOf(type: string, bytes = 1): File { + return new File([new Uint8Array(bytes)], 'resource', { type }); +} + +describe('a resource file', () => { + it('can be a PDF or a PowerPoint deck', () => { + expect(checkDocument(fileOf('application/pdf'))).toMatchObject({ kind: 'accepted', file: { extension: 'pdf' } }); + expect(checkDocument(fileOf('application/vnd.openxmlformats-officedocument.presentationml.presentation'))).toMatchObject({ + kind: 'accepted', + file: { extension: 'pptx' }, + }); + }); + + it('cannot be anything else, and says what it can be', () => { + expect(checkDocument(fileOf('application/zip'))).toEqual({ + kind: 'rejected', + reason: "That file isn't a PDF or a PowerPoint deck. Choose a .pdf or .pptx.", + }); + }); + + it('can be up to 20 MB', () => { + expect(checkDocument(fileOf('application/pdf', 21 * 1024 * 1024))).toEqual({ + kind: 'rejected', + reason: 'That file is 21.0 MB. Files can be up to 20 MB.', + }); + }); +}); diff --git a/apps/admin/tests/lib/ui/event-palette.test.ts b/apps/admin/tests/lib/ui/event-palette.test.ts new file mode 100644 index 0000000..550447e --- /dev/null +++ b/apps/admin/tests/lib/ui/event-palette.test.ts @@ -0,0 +1,25 @@ +import { DEFAULT_PALETTE, paletteColour, textOn } from '../../../src/lib/ui/event-palette'; + +describe('text on an event colour', () => { + it.each([ + ['#ffffff', 'dark'], + ['#ff9770', 'dark'], + ['#ffd670', 'dark'], + ['#0b5cff', 'light'], + ['#00832d', 'light'], + ['#000000', 'light'], + ] as const)('is %s on %s', (hex, text) => { + expect(textOn(hex)).toBe(text); + }); +}); + +describe('an event colour', () => { + it('is the one picked, with text that reads on it', () => { + expect(paletteColour('#0b5cff', DEFAULT_PALETTE.primary)).toEqual({ colour: '#0b5cff', text: 'light' }); + }); + + it('is the LCS yellow and pink when none is picked', () => { + expect(paletteColour(null, DEFAULT_PALETTE.primary)).toEqual({ colour: 'var(--yellow)', text: 'dark' }); + expect(paletteColour(null, DEFAULT_PALETTE.secondary)).toEqual({ colour: 'var(--pink)', text: 'dark' }); + }); +}); diff --git a/apps/admin/tests/lib/ui/markdown.test.ts b/apps/admin/tests/lib/ui/markdown.test.ts new file mode 100644 index 0000000..76035da --- /dev/null +++ b/apps/admin/tests/lib/ui/markdown.test.ts @@ -0,0 +1,44 @@ +import { applyFormat, renderDescription } from '../../../src/lib/ui/markdown'; + +describe('a description', () => { + it('shows bold, italic, links, lists and paragraphs', () => { + const html = renderDescription('Bring **questions** and _snacks_.\n\n- Pizza\n- [Slides](https://lauriercs.org/slides)'); + + expect(html).toContain('questions'); + expect(html).toContain('snacks'); + expect(html).toContain('
    \n
  • Pizza
  • '); + expect(html).toContain('Slides'); + }); + + it('shows headings, images and HTML as the text that was typed', () => { + const html = renderDescription('# Big\n\n![cat](https://x.com/cat.png)\n\n'); + + expect(html).not.toContain('

    '); + expect(html).not.toContain(' { + expect(renderDescription('[click](javascript:alert(1))')).not.toContain('href'); + }); +}); + +describe('the description toolbar', () => { + const text = 'Bring questions'; + + it('wraps the selection in bold or italic and keeps it selected', () => { + expect(applyFormat({ text, start: 6, end: 15 }, 'bold')).toEqual({ text: 'Bring **questions**', start: 8, end: 17 }); + expect(applyFormat({ text, start: 6, end: 15 }, 'italic')).toEqual({ text: 'Bring _questions_', start: 7, end: 16 }); + }); + + it('turns the selection into a link with the address selected', () => { + const linked = applyFormat({ text, start: 6, end: 15 }, 'link'); + + expect(linked.text).toBe('Bring [questions](https://)'); + expect(linked.text.slice(linked.start, linked.end)).toBe('https://'); + }); + + it('starts each selected line with a dash, once', () => { + expect(applyFormat({ text: 'Pizza\n- Pop', start: 2, end: 9 }, 'list').text).toBe('- Pizza\n- Pop'); + }); +}); From fce93f16060f65cc9dc315df79de252cfeeb13ee Mon Sep 17 00:00:00 2001 From: b4sleal Date: Sun, 29 Nov 2026 22:15:12 -0500 Subject: [PATCH 4/6] feat(admin): panels for an event's topics, partners, resources and last time --- .../src/components/events/EventExtras.tsx | 24 +++ .../components/events/EventLastTimePanel.tsx | 68 +++++++ .../components/events/EventPartnersPanel.tsx | 108 +++++++++++ .../components/events/EventResourcesPanel.tsx | 171 ++++++++++++++++++ .../components/events/EventTopicsPanel.tsx | 110 +++++++++++ .../src/components/events/ExtraPanel.tsx | 45 +++++ .../src/components/events/IconPicker.tsx | 56 ++++++ .../src/components/events/PanelSaveBar.tsx | 34 ++++ .../admin/src/components/events/TopicIcon.tsx | 17 ++ .../src/components/events/event-labels.ts | 32 ++++ 10 files changed, 665 insertions(+) create mode 100644 apps/admin/src/components/events/EventExtras.tsx create mode 100644 apps/admin/src/components/events/EventLastTimePanel.tsx create mode 100644 apps/admin/src/components/events/EventPartnersPanel.tsx create mode 100644 apps/admin/src/components/events/EventResourcesPanel.tsx create mode 100644 apps/admin/src/components/events/EventTopicsPanel.tsx create mode 100644 apps/admin/src/components/events/ExtraPanel.tsx create mode 100644 apps/admin/src/components/events/IconPicker.tsx create mode 100644 apps/admin/src/components/events/PanelSaveBar.tsx create mode 100644 apps/admin/src/components/events/TopicIcon.tsx create mode 100644 apps/admin/src/components/events/event-labels.ts diff --git a/apps/admin/src/components/events/EventExtras.tsx b/apps/admin/src/components/events/EventExtras.tsx new file mode 100644 index 0000000..b0028c1 --- /dev/null +++ b/apps/admin/src/components/events/EventExtras.tsx @@ -0,0 +1,24 @@ +/** + * Everything on an event's page that is a list of its own, under the event form: topics, partners, resources and + * last time. Each panel saves by itself, so it is only shown once the event exists. + */ +import type { Event } from '../../types/event'; +import { EventLastTimePanel } from './EventLastTimePanel'; +import { EventPartnersPanel } from './EventPartnersPanel'; +import { EventResourcesPanel } from './EventResourcesPanel'; +import { EventTopicsPanel } from './EventTopicsPanel'; + +export function EventExtras({ event }: { event: Event }) { + return ( + // The same columns as the form above, so the panels line up under its sheet. +
    +
    +

    On the event's page

    + + + + +
    +
    + ); +} diff --git a/apps/admin/src/components/events/EventLastTimePanel.tsx b/apps/admin/src/components/events/EventLastTimePanel.tsx new file mode 100644 index 0000000..9cbb757 --- /dev/null +++ b/apps/admin/src/components/events/EventLastTimePanel.tsx @@ -0,0 +1,68 @@ +/** + * "Last time" for an event: the earlier event it follows on from, so its page can link to that night's photos + * and resources. Picked from the events before it, same kind first. + */ +import { useState } from 'react'; +import { choicesFrom } from '../../hooks/choices'; +import { useEventRelated, useSaveRelated } from '../../hooks/useEventRelated'; +import { useEvents } from '../../hooks/useEvents'; +import { earlierEvents } from '../../lib/form/last-time'; +import { shortEventDayWithYear } from '../../lib/time/dates'; +import type { Event } from '../../types/event'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { ExtraPanel } from './ExtraPanel'; +import { PanelSaveBar } from './PanelSaveBar'; + +export function EventLastTimePanel({ event }: { event: Event }) { + const related = useEventRelated(event.id); + const save = useSaveRelated(event.id); + const events = choicesFrom(useEvents()); + return ( + + {(saved) => ( + + )} + + ); +} + +type LastTimeEditorProps = { + save: ReturnType; + /** The saved event's id, or empty for none. */ + saved: string; + choices: readonly Event[] | 'loading' | 'failed'; +}; + +function LastTimeEditor({ save, saved, choices }: LastTimeEditorProps) { + const [picked, setPicked] = useState(saved); + const loaded = typeof choices !== 'string'; + return ( + <> + + + save.mutate(picked === '' ? [] : [picked])} + /> + + ); +} diff --git a/apps/admin/src/components/events/EventPartnersPanel.tsx b/apps/admin/src/components/events/EventPartnersPanel.tsx new file mode 100644 index 0000000..d4cf000 --- /dev/null +++ b/apps/admin/src/components/events/EventPartnersPanel.tsx @@ -0,0 +1,108 @@ +/** + * "In collaboration with" for an event: the companies and groups it's run with, picked from Companies and saved + * as a whole. A partner missing from the list is added on Companies first. + */ +import { 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 { useEventPartners, useSavePartners } from '../../hooks/useEventPartners'; +import { PATHS } from '../../paths'; +import type { Company } from '../../types/company'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { ExtraPanel } from './ExtraPanel'; +import { PanelSaveBar } from './PanelSaveBar'; + +export function EventPartnersPanel({ eventId }: { eventId: string }) { + const partners = useEventPartners(eventId); + const save = useSavePartners(eventId); + const companies = choicesFrom(useCompanies()); + return ( + + {(saved) => } + + ); +} + +type PartnersEditorProps = { + save: ReturnType; + saved: readonly string[]; + companies: Choices; +}; + +function PartnersEditor({ save, saved, companies }: PartnersEditorProps) { + const [ids, setIds] = useState(saved); + const [changed, setChanged] = useState(false); + const known = typeof companies === 'string' ? [] : companies; + const byId = new Map(known.map((company) => [company.id, company])); + const left = known.filter((company) => !ids.includes(company.id)); + + function change(next: readonly string[]) { + setIds(next); + setChanged(true); + } + + return ( + <> + {ids.length === 0 ? ( +

    Just LCS. The site leaves "In collaboration with" out.

    + ) : ( +
      + {ids.map((id) => { + const company = byId.get(id); + const name = company?.name ?? 'A company'; + return ( +
    • +
    • + ); + })} +
    + )} + + +

    + Not in the list?{' '} + + Add it on Companies + + . +

    + save.mutate(ids, { onSuccess: () => setChanged(false) })} + /> + + ); +} diff --git a/apps/admin/src/components/events/EventResourcesPanel.tsx b/apps/admin/src/components/events/EventResourcesPanel.tsx new file mode 100644 index 0000000..467874e --- /dev/null +++ b/apps/admin/src/components/events/EventResourcesPanel.tsx @@ -0,0 +1,171 @@ +/** + * An event's resources: slides, recordings, practice exams, forms and other links or files, listed on its page. + * Each one is added or deleted straight away, and deleting asks first. + */ +import { zodResolver } from '@hookform/resolvers/zod'; +import { FileText, Link2, Trash } from 'lucide-react'; +import { useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useAddDocument, useDeleteDocument, useEventDocuments } from '../../hooks/useEventDocuments'; +import { EMPTY_RESOURCE_FORM, RESOURCE_SOURCES, ResourceFormSchema, type ResourceFormValues } from '../../lib/form/resource-form'; +import { messageFor } from '../../lib/server/errors'; +import { ACCEPTED_DOCUMENT_TYPES, checkDocument, DOCUMENT_RULES, type DocumentCheck } from '../../lib/ui/documents'; +import { DOCUMENT_KINDS, type EventDocument } from '../../types/event-document'; +import { Button } from '../ui/Button'; +import { ConfirmDialog } from '../ui/ConfirmDialog'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { FormField } from '../ui/FormField'; +import { Tag } from '../ui/Tag'; +import { DOCUMENT_KIND_NAMES } from './event-labels'; +import { ExtraPanel } from './ExtraPanel'; + +export function EventResourcesPanel({ eventId }: { eventId: string }) { + const documents = useEventDocuments(eventId); + return ( + + {(saved) => ( + <> + {saved.length === 0 ? ( +

    Nothing yet.

    + ) : ( +
      + {saved.map((document) => ( + + ))} +
    + )} + + + )} +
    + ); +} + +function ResourceRow({ document }: { document: EventDocument }) { + const remove = useDeleteDocument(document); + const [asking, setAsking] = useState(false); + const Icon = document.source.type === 'file' ? FileText : Link2; + return ( +
  • +
  • + ); +} + +const SOURCE_NAMES = { link: 'A link', file: 'A file' } as const; + +function AddResourceForm({ eventId }: { eventId: string }) { + const add = useAddDocument(eventId); + const { register, handleSubmit, formState, control, setValue, reset } = useForm({ resolver: zodResolver(ResourceFormSchema), defaultValues: EMPTY_RESOURCE_FORM }); + const [file, setFile] = useState(null); + const [fileMissing, setFileMissing] = useState(false); + const source = useWatch({ control, name: 'source' }); + const { errors } = formState; + + function submit(values: ResourceFormValues) { + const fields = { title: values.title, kind: values.kind }; + if (values.source === 'link') { + add.mutate({ fields, url: values.url.trim() }, { onSuccess: () => reset() }); + } else if (file?.kind === 'accepted') { + add.mutate({ fields, file: file.file }, { onSuccess: () => { reset(); setFile(null); } }); + } else { + setFileMissing(true); + } + } + + return ( +
    +
    + {RESOURCE_SOURCES.map((option) => ( + + ))} +
    +
    + + {(input) => } + + + {(input) => ( + + )} + +
    + {source === 'link' ? ( + + {(input) => } + + ) : ( + + {(input) => ( + { + const chosen = event.target.files?.[0]; + setFile(chosen ? checkDocument(chosen) : null); + setFileMissing(false); + }} + className="block w-full text-text-2 file:mr-4 file:min-h-11 file:rounded-full file:border-2 file:border-line file:bg-transparent file:px-5 file:font-display file:font-bold file:text-white hover:file:bg-slate" + /> + )} + + )} +
    + {add.isError && ( +

    + {messageFor(add.error)} +

    + )} + +
    +
    + ); +} diff --git a/apps/admin/src/components/events/EventTopicsPanel.tsx b/apps/admin/src/components/events/EventTopicsPanel.tsx new file mode 100644 index 0000000..61ba1b9 --- /dev/null +++ b/apps/admin/src/components/events/EventTopicsPanel.tsx @@ -0,0 +1,110 @@ +/** + * "What they'll cover" for an event: a list of topics, each a line of text with an icon, put in order with the + * arrows and saved as a whole. + */ +import { ArrowDown, ArrowUp, Plus, X } from 'lucide-react'; +import { useState } from 'react'; +import { useEventTopics, useSaveTopics } from '../../hooks/useEventTopics'; +import { type EventTopic, EventTopicSchema, type TopicFields } from '../../types/event-topic'; +import { Button } from '../ui/Button'; +import { FIELD_INPUT } from '../ui/field-styles'; +import { ExtraPanel } from './ExtraPanel'; +import { IconPicker } from './IconPicker'; +import { PanelSaveBar } from './PanelSaveBar'; +import { TopicIcon } from './TopicIcon'; + +export function EventTopicsPanel({ eventId }: { eventId: string }) { + const topics = useEventTopics(eventId); + // Here rather than in the editor, which starts over from each fresh load, so "Saved." outlives the reload. + const save = useSaveTopics(eventId); + return ( + + {(saved) => } + + ); +} + +/** A topic being edited. `key` tells rows apart while they move, before a new one has an id. */ +type TopicRow = TopicFields & { key: string }; + +const ICON_BUTTON = 'grid size-11 shrink-0 place-items-center rounded-field border-2 border-line text-text-2 transition-[color,border-color,transform] duration-150 hover:border-muted hover:text-white active:scale-97 disabled:opacity-40 disabled:hover:border-line'; + +type TopicsEditorProps = { save: ReturnType; saved: readonly EventTopic[] }; + +function TopicsEditor({ save, saved }: TopicsEditorProps) { + const [rows, setRows] = useState(() => saved.map(({ id, text, icon }) => ({ key: id, id, text, icon }))); + const [picking, setPicking] = useState(null); + const [changed, setChanged] = useState(false); + const picked = rows.find((row) => row.key === picking); + const problem = rows.map((row) => EventTopicSchema.shape.text.safeParse(row.text).error?.issues[0]?.message).find(Boolean) ?? null; + + function change(next: readonly TopicRow[]) { + setRows(next); + setChanged(true); + } + const update = (key: string, patch: Partial) => change(rows.map((row) => (row.key === key ? { ...row, ...patch } : row))); + 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); + } + + return ( + <> + {rows.length === 0 &&

    No topics yet. The site leaves this section out until there is one.

    } +
      + {rows.map((row, index) => ( +
    1. + + update(row.key, { text: event.target.value })} + className={FIELD_INPUT} + placeholder="e.g. Breaking into the tech industry" + /> + + + +
    2. + ))} +
    + + { + if (problem) return; + save.mutate(rows.map(({ id, text, icon }) => ({ id, text, icon })), { onSuccess: () => setChanged(false) }); + }} + /> + {picked && ( + { + update(picked.key, { icon }); + setPicking(null); + }} + onClose={() => setPicking(null)} + /> + )} + + ); +} diff --git a/apps/admin/src/components/events/ExtraPanel.tsx b/apps/admin/src/components/events/ExtraPanel.tsx new file mode 100644 index 0000000..e7a16ce --- /dev/null +++ b/apps/admin/src/components/events/ExtraPanel.tsx @@ -0,0 +1,45 @@ +/** + * One of the extras under an event's form (topics, partners, resources, last time): a titled card that loads its + * list and shows it once it's here. Loading and failing look the same in every panel, and a failure is never + * shown as an empty list. + */ +import type { UseQueryResult } from '@tanstack/react-query'; +import type { ReactNode } from 'react'; +import { messageFor } from '../../lib/server/errors'; +import { Button } from '../ui/Button'; + +type ExtraPanelProps = { + title: string; + /** One line on what it's for and where the site shows it. */ + intro: string; + query: UseQueryResult; + children: (data: T) => ReactNode; +}; + +export function ExtraPanel({ title, intro, query, children }: ExtraPanelProps) { + return ( +
    +

    {title}

    +

    {intro}

    + {children} +
    + ); +} + +function PanelBody({ query, children }: Pick, 'query' | 'children'>) { + switch (query.status) { + case 'pending': + return
    ; + case 'error': + return ( +
    +

    {messageFor(query.error)}

    + +
    + ); + case 'success': + return children(query.data); + } +} diff --git a/apps/admin/src/components/events/IconPicker.tsx b/apps/admin/src/components/events/IconPicker.tsx new file mode 100644 index 0000000..6637814 --- /dev/null +++ b/apps/admin/src/components/events/IconPicker.tsx @@ -0,0 +1,56 @@ +/** + * Picking a topic's icon: a few that suit most LCS topics, and a search through every Lucide icon by name + * ("chart", "mic"). Each icon's drawing is downloaded only when it's shown, so the full list costs little. + */ +import { iconNames } from 'lucide-react/dynamic'; +import { useState } from 'react'; +import { SearchField } from '../ui/SearchField'; +import { Sheet } from '../ui/Sheet'; +import { TopicIcon } from './TopicIcon'; + +const SUGGESTED = ['code-xml', 'briefcase', 'graduation-cap', 'users', 'lightbulb', 'rocket', 'chart-line', 'mic', 'book-open', 'trophy', 'handshake', 'coffee']; +// Enough to scan in one go; a longer list means the search should be narrower. +const MOST_RESULTS = 60; + +type IconPickerProps = { + topic: string; + current: string | null; + onPick: (name: string | null) => void; + onClose: () => void; +}; + +export function IconPicker({ topic, current, onPick, onClose }: IconPickerProps) { + const [search, setSearch] = useState(''); + const words = search.trim().toLowerCase().split(/[\s-]+/).filter(Boolean); + const found = words.length === 0 ? SUGGESTED : iconNames.filter((name) => words.every((word) => name.includes(word))).slice(0, MOST_RESULTS); + + return ( + + +

    {words.length === 0 ? 'Suggested' : `${found.length} found`}

    + {found.length === 0 ? ( +

    No icon has that in its name. Try a shorter word.

    + ) : ( +
      + {found.map((name) => ( +
    • + +
    • + ))} +
    + )} + +
    + ); +} diff --git a/apps/admin/src/components/events/PanelSaveBar.tsx b/apps/admin/src/components/events/PanelSaveBar.tsx new file mode 100644 index 0000000..eef2a2d --- /dev/null +++ b/apps/admin/src/components/events/PanelSaveBar.tsx @@ -0,0 +1,34 @@ +/** + * The save button at the bottom of an extras panel, with what happened beside it: "Saved." after a save, or why + * it failed. The button waits until there is something to save. + */ +import { messageFor } from '../../lib/server/errors'; +import { Button } from '../ui/Button'; + +type PanelSaveBarProps = { + /** What the button says, e.g. "Save topics". */ + label: string; + changed: boolean; + pending: boolean; + /** Set once a save has worked, until the next change. */ + saved: boolean; + /** Why the last save failed, or null. */ + error: unknown; + /** Why the list can't be saved as it is, e.g. a topic with no words, or null. */ + problem?: string | null; + onSave: () => void; +}; + +export function PanelSaveBar({ label, changed, pending, saved, error, problem = null, onSave }: PanelSaveBarProps) { + const note = problem ?? (error ? messageFor(error) : saved && !changed ? 'Saved.' : null); + return ( +
    +

    + {note} +

    + +
    + ); +} diff --git a/apps/admin/src/components/events/TopicIcon.tsx b/apps/admin/src/components/events/TopicIcon.tsx new file mode 100644 index 0000000..ca29796 --- /dev/null +++ b/apps/admin/src/components/events/TopicIcon.tsx @@ -0,0 +1,17 @@ +/** + * A topic's Lucide icon, loaded by name when it's shown. No name, or a name Lucide doesn't have (say, one it + * renamed), shows the default icon, the same one the site falls back to. + */ +import { Sparkles } from 'lucide-react'; +import { DynamicIcon, type IconName, iconNames } from 'lucide-react/dynamic'; + +const KNOWN: ReadonlySet = new Set(iconNames); + +function isIconName(name: string): name is IconName { + return KNOWN.has(name); +} + +export function TopicIcon({ name, className }: { name: string | null; className: string }) { + if (name === null || !isIconName(name)) return