v1.14.2-present: event schedules, venues and map blocks, Present mode and its phone remote #33

Merged
ngu-git-admin merged 40 commits from event-schedule into main 2026-11-21 23:02:06 +00:00
10 changed files with 604 additions and 23 deletions
Showing only changes of commit 5eebc20c4e - Show all commits

View file

@ -35,6 +35,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/<id>` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`. - Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/<id>` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Present remote: a presenting screen (`/events/:id/present`) shows a code; a phone at `/remote/<code>` steps, pauses, jumps and changes its setup, anyone with the code (`server/src/routes/present.js`, `src/pages/PresentRemote.tsx`). Server-sent events held in memory (one process); the API sends `X-Accel-Buffering: no`, so nginx needs no block of its own.
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.
- Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`. - Word import: Blog posts → Import from Word turns a .docx into an unpublished post (headings, paragraphs, lists, tables, links); nginx needs a block for `/api/admin/import/docx` with an 11m body limit: `docs/importing.md`.
- Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`. - Speed: nginx must gzip JS/CSS/JSON/SVG and speak HTTP/2; page HTML is `no-cache`; uploads get a `-640.webp` small copy made at upload and at boot: `docs/performance.md`.

View file

@ -214,11 +214,11 @@ const sectionsChild = {
export const CORE_PAGES = { home: "/", give: "/give", feedback: "/feedback", request: "/request", qr: "/qr", privacy: "/privacy", terms: "/terms" }; export const CORE_PAGES = { home: "/", give: "/give", feedback: "/feedback", request: "/request", qr: "/qr", privacy: "/privacy", terms: "/terms" };
/* Addresses a page can't take: the admin, the API, the uploads, the /* Addresses a page can't take: the admin, the API, the uploads, the
records' own pages and the account pages. */ records' own pages, the account pages and the remote. */
const RESERVED = [ const RESERVED = [
"admin", "api", "uploads", "assets", "pa", "go", "admin", "api", "uploads", "assets", "pa", "go",
"events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory", "events", "regions", "groups", "partners", "organizations", "teams", "awards", "people", "blog", "directory",
"sign-in", "account", "sitemap.xml", "robots.txt", "sign-in", "account", "remote", "sitemap.xml", "robots.txt",
]; ];
/* After a save: the address is one a page may have. */ /* After a save: the address is one a page may have. */

View file

@ -43,6 +43,7 @@ import imports from "./routes/import.js";
import files from "./routes/files.js"; import files from "./routes/files.js";
import countdown from "./routes/countdown.js"; import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js"; import redirects from "./routes/redirects.js";
import present from "./routes/present.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js"; import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
@ -137,7 +138,7 @@ app.use(
so each is capped well above its longest real body (a 5000 so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */ character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) }); const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody); for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile", "/api/present/*"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on /* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */ their own; a short line per report is plenty to go on. */
@ -202,6 +203,11 @@ app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 }));
app.route("/api", countdown); app.route("/api", countdown);
// Tighter limit on the write path than anything else gets. // Tighter limit on the write path than anything else gets.
// A presenting screen and its remotes, by the screen's code
// (routes/present.js): a cap far above tapping, far below guessing.
app.use("/api/present/*", rateLimit({ windowMs: 60_000, max: 300 }));
app.route("/api", present);
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 })); app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback); app.route("/api/feedback", feedback);
// Requests carry files: fewer again. // Requests carry files: fewer again.

View file

@ -413,6 +413,9 @@ export function metaFor(db, rawPath, user = null) {
// in particular, so never indexed or in the sitemap. // in particular, so never indexed or in the sitemap.
if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true }; if (ACCOUNT_PAGES[pathname]) return { ...meta, title: titled(site, ACCOUNT_PAGES[pathname]), noindex: true };
// A presenting screen's remote (src/pages/PresentRemote.tsx).
if (/^\/remote(\/|$)/.test(pathname)) return { ...meta, title: titled(site, "Remote"), noindex: true };
// A page of the site (site_pages): hidden is Not found below // A page of the site (site_pages): hidden is Not found below
// viewer; disabled stays out of search. // viewer; disabled stays out of search.
const page = pageAt(db, pathname); const page = pageAt(db, pathname);

View file

@ -0,0 +1,151 @@
/* ═══════════════════════════════════════════════════════════════
PRESENT REMOTE: a phone drives a presenting screen by its code
A screen (src/pages/EventPresent.tsx) opens /present/screen, a
stream that first says its code and key, then carries commands.
It posts what it shows (state) with the key. A remote
(src/pages/PresentRemote.tsx) opens /present/:code, a stream of
that state, and posts commands. Anyone with the code can drive
the screen: the code is the only lock, so it's long enough not to
guess at the rate limit set where this is mounted.
In memory only: one process, and a restart only makes each screen
reconnect (keeping its code when no one took it) and post its
state again. A screen gone for SWEEP_AFTER is forgotten.
═══════════════════════════════════════════════════════════════ */
import { randomBytes, randomInt } from "node:crypto";
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
const present = new Hono();
// No 0/O, 1/I/L: read off a screen across a room.
const LETTERS = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
const CODE = /^[A-Z0-9]{6}$/;
const PING_EVERY = 25_000; // under nginx's 60 second read timeout
const SWEEP_AFTER = 10 * 60_000;
const COMMANDS = ["next", "prev", "pause", "resume", "go", "setup", "start"];
// A screen's state before it first says.
const NOTHING_YET = { event: "", title: "", query: "", playing: false, paused: false, index: 0, slides: [] };
// code → { key, state, screen (its stream, or null), gone (ms), remotes (streams) }
const screens = new Map();
setInterval(() => {
const now = Date.now();
for (const [code, s] of screens) {
if (!s.screen && s.remotes.size === 0 && now - s.gone > SWEEP_AFTER) screens.delete(code);
}
}, 60_000).unref();
function newCode() {
for (;;) {
const code = Array.from({ length: 6 }, () => LETTERS[randomInt(LETTERS.length)]).join("");
// SCREEN would be the screen's own stream's address.
if (!screens.has(code) && code !== "SCREEN") return code;
}
}
const send = (stream, event, data) => stream.writeSSE({ event, data: JSON.stringify(data) }).catch(() => {});
function tellRemotes(s) {
for (const remote of s.remotes) send(remote, "state", { connected: !!s.screen, ...s.state });
}
// Holds a stream open, pinging, until the other end goes.
function hold(stream, onGone) {
return new Promise((resolve) => {
const ping = setInterval(() => stream.write(": ping\n\n").catch(() => {}), PING_EVERY);
stream.onAbort(() => {
clearInterval(ping);
onGone();
resolve();
});
});
}
/* A screen's stream. It asks for the code it had (code and key) and
gets it back unless that's wrong or another screen holds it now. */
present.get("/present/screen", (c) => {
let code = c.req.query("code");
const key = c.req.query("key");
let s = screens.get(code);
if (!s || s.key !== key || s.screen) {
code = newCode();
s = { key: randomBytes(16).toString("hex"), state: NOTHING_YET, screen: null, gone: 0, remotes: new Set() };
screens.set(code, s);
}
// Tells nginx to pass each event on as it's written.
c.header("X-Accel-Buffering", "no");
return streamSSE(c, async (stream) => {
s.screen = stream;
await send(stream, "hello", { code, key: s.key });
tellRemotes(s);
await hold(stream, () => {
if (s.screen !== stream) return;
s.screen = null;
s.gone = Date.now();
tellRemotes(s);
});
});
});
/* What the screen shows, for its remotes: shown as text there, so
only capped here. */
present.post("/present/:code/state", async (c) => {
const s = screens.get(c.req.param("code"));
const body = await c.req.json().catch(() => null);
if (!s || !body || body.key !== s.key) return c.json({ error: "Not found" }, 404);
const text = (v, max) => (typeof v === "string" ? v.slice(0, max) : "");
const count = (v) => (Number.isInteger(v) && v >= 0 ? v : 0);
s.state = {
event: text(body.event, 200),
title: text(body.title, 300),
query: text(body.query, 4000),
playing: body.playing === true,
paused: body.paused === true,
index: count(body.index),
slides: Array.isArray(body.slides) ? body.slides.slice(0, 500).map((name) => text(name, 150)) : [],
};
tellRemotes(s);
return c.body(null, 204);
});
// A remote's stream: the screen's state now and each time it changes.
present.get("/present/:code", (c) => {
const s = screens.get(c.req.param("code").toUpperCase());
if (!s) return c.json({ error: "No screen has that code." }, 404);
c.header("X-Accel-Buffering", "no");
return streamSSE(c, async (stream) => {
s.remotes.add(stream);
await send(stream, "state", { connected: !!s.screen, ...s.state });
await hold(stream, () => s.remotes.delete(stream));
});
});
/* A command for the screen: next, prev, pause, resume, go (to
`index`), setup (back to its setup) or start (playing `query`, the
setup's choices as EventPresent's address reads them). */
present.post("/present/:code/command", async (c) => {
const code = c.req.param("code").toUpperCase();
const s = CODE.test(code) ? screens.get(code) : null;
if (!s) return c.json({ error: "No screen has that code." }, 404);
if (!s.screen) return c.json({ error: "The screen isn't connected right now." }, 409);
const body = await c.req.json().catch(() => null);
if (!body || !COMMANDS.includes(body.do)) return c.json({ error: "Unknown command." }, 400);
const command = { do: body.do };
if (body.do === "go") {
if (!Number.isInteger(body.index) || body.index < 0) return c.json({ error: "Which slide?" }, 400);
command.index = body.index;
}
if (body.do === "start") {
if (typeof body.query !== "string" || body.query.length > 4000) return c.json({ error: "That setup is too long." }, 400);
command.query = body.query;
}
await send(s.screen, "command", command);
return c.body(null, 204);
});
export default present;

View file

@ -68,6 +68,7 @@ const PersonDetail = lazyPage(() => import("./pages/PersonDetail.tsx"))
const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx")) const BlogPost = lazyPage(() => import("./pages/BlogPost.tsx"))
const DirectoryPage = lazyPage(() => import("./pages/DirectoryPage.tsx")) const DirectoryPage = lazyPage(() => import("./pages/DirectoryPage.tsx"))
const EventPresent = lazyPage(() => import("./pages/EventPresent.tsx")) const EventPresent = lazyPage(() => import("./pages/EventPresent.tsx"))
const PresentRemote = lazyPage(() => import("./pages/PresentRemote.tsx"))
/*Admin Pages*/ /*Admin Pages*/
const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx")) const AdminLayout = lazyPage(() => import("./pages/admin/AdminLayout.tsx"))
@ -119,6 +120,15 @@ export default function App() {
</Suspense> </Suspense>
} }
/> />
{/* A phone driving a presenting screen, by its code. */}
<Route
path="/remote/:code?"
element={
<Suspense fallback={null}>
<PresentRemote />
</Suspense>
}
/>
<Route <Route
element={ element={
<Suspense fallback={null}> <Suspense fallback={null}>

View file

@ -18,7 +18,7 @@
import { visionColor } from "./color.ts"; import { visionColor } from "./color.ts";
const BASE = import.meta.env?.VITE_API_BASE ?? "/api"; export const BASE = import.meta.env?.VITE_API_BASE ?? "/api";
const DEFAULT_TTL = 60_000; const DEFAULT_TTL = 60_000;
/* A draft's preview (server/src/drafts.js): a tab opened from the /* A draft's preview (server/src/drafts.js): a tab opened from the

View file

@ -0,0 +1,88 @@
/* A presenting screen's link to its remotes (server/src/routes/
present.js, src/pages/PresentRemote.tsx): the code to show, the
commands as they come, and `report` for what the screen shows.
The code and its key are kept in this browser, so a reload or a
restart of the server keeps the same code. */
import { useCallback, useEffect, useRef, useState } from 'react'
import { BASE, post } from './api.ts'
export type RemoteCommand = {
do: 'next' | 'prev' | 'pause' | 'resume' | 'go' | 'setup' | 'start'
index?: number
query?: string
}
export type ScreenState = {
event: string
title: string
// EventPresent's address query: the setup's choices.
query: string
playing: boolean
paused: boolean
index: number
// Each slide's name, in order.
slides: string[]
}
const STORE = 'present-remote'
const RETRY = 3000
export function useScreenRemote(onCommand: (command: RemoteCommand) => void) {
const [code, setCode] = useState<string | null>(null)
const link = useRef<{ code: string; key: string } | null>(null)
const last = useRef<ScreenState | null>(null)
const handler = useRef(onCommand)
handler.current = onCommand
const send = (state: ScreenState) => {
const l = link.current
if (l) post(`/present/${l.code}/state`, { key: l.key, ...state }).catch(() => {})
}
useEffect(() => {
let source: EventSource | null = null
let retry = 0
const open = () => {
let saved: Record<string, string> = {}
try {
saved = JSON.parse(localStorage.getItem(STORE) ?? '{}')
} catch {
// Nothing kept: the server gives a new code.
}
source = new EventSource(`${BASE}/present/screen?${new URLSearchParams(saved)}`)
source.addEventListener('hello', (e) => {
link.current = JSON.parse((e as MessageEvent).data)
setCode(link.current!.code)
try {
localStorage.setItem(STORE, JSON.stringify(link.current))
} catch {
// Kept for this visit only.
}
if (last.current) send(last.current)
})
source.addEventListener('command', (e) => handler.current(JSON.parse((e as MessageEvent).data)))
// Reopened by hand, so it asks for its code again.
source.onerror = () => {
source?.close()
link.current = null
retry = window.setTimeout(open, RETRY)
}
}
open()
return () => {
window.clearTimeout(retry)
source?.close()
}
}, [])
const report = useCallback((state: ScreenState) => {
// Unchanged, eg. the page drawn again for something else.
if (JSON.stringify(state) === JSON.stringify(last.current)) return
last.current = state
send(state)
}, [])
return { code, report }
}

View file

@ -82,9 +82,14 @@
Keys while playing: arrows step, Space pauses, Escape leaves full Keys while playing: arrows step, Space pauses, Escape leaves full
screen (the browser's), S goes back to the setup. screen (the browser's), S goes back to the setup.
Remote: the screen has a code (useScreenRemote), shown on the setup
and with the controls. A phone at /remote/<code> (PresentRemote.tsx)
steps, pauses and jumps through the slides, and changes the setup
with this page's own Setup, which plays on the screen.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { ArrowDown, ArrowUp, ArrowsOut, CaretLeft, CaretRight, Check, DotsSixVertical, Gear, LinkSimple, Pause, Play } from '@phosphor-icons/react' import { ArrowDown, ArrowUp, ArrowsOut, CaretLeft, CaretRight, Check, DotsSixVertical, Gear, LinkSimple, Pause, Play, DeviceMobile } from '@phosphor-icons/react'
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
import { useParams, useSearchParams } from 'react-router-dom' import { useParams, useSearchParams } from 'react-router-dom'
@ -120,6 +125,7 @@ import { BRAND, accentText, readableOn, withAlpha } from '../lib/color.ts'
import { documentTitle } from '../lib/site.ts' import { documentTitle } from '../lib/site.ts'
import { preview } from '../lib/text.ts' import { preview } from '../lib/text.ts'
import { useDarkTheme } from '../lib/darkTheme.ts' import { useDarkTheme } from '../lib/darkTheme.ts'
import { useScreenRemote, type RemoteCommand, type ScreenState } from '../lib/useScreenRemote.ts'
import './EventPresent.css' import './EventPresent.css'
/* Each kind of slide, its address key and seconds when unset. */ /* Each kind of slide, its address key and seconds when unset. */
@ -244,13 +250,13 @@ type Slide = {
/* A part of the page: a heading (`headed`, else the event's title) /* A part of the page: a heading (`headed`, else the event's title)
and the blocks under it. */ and the blocks under it. */
type Section = { title: string; headed: boolean; blocks: ContentBlock[] } export type Section = { title: string; headed: boolean; blocks: ContentBlock[] }
/* A schedule block, numbered among the page's, with its days. */ /* A schedule block, numbered among the page's, with its days. */
type Schedule = { n: number; days: Day[]; tags: ScheduleTag[] } export type Schedule = { n: number; days: Day[]; tags: ScheduleTag[] }
/* Blocks left out of the presentation (095) are dropped; a left out /* Blocks left out of the presentation (095) are dropped; a left out
heading still starts its section, under the event's title. */ heading still starts its section, under the event's title. */
function sectionsOf(blocks: ContentBlock[], title: string): Section[] { export function sectionsOf(blocks: ContentBlock[], title: string): Section[] {
const sections: Section[] = [{ title, headed: false, blocks: [] }] const sections: Section[] = [{ title, headed: false, blocks: [] }]
for (const block of blocks) { for (const block of blocks) {
if (STARTS_SECTION.has(block.type)) { if (STARTS_SECTION.has(block.type)) {
@ -270,7 +276,7 @@ const lineCount = (entries: ContentBlockItem[]) =>
entries.reduce((n, entry) => n + 1 + (entry.kind === 'block' ? (entry.items?.length ?? 0) : 0), 0) entries.reduce((n, entry) => n + 1 + (entry.kind === 'block' ? (entry.items?.length ?? 0) : 0), 0)
const list = (value: string | null) => (value ? value.split(',').filter(Boolean) : null) const list = (value: string | null) => (value ? value.split(',').filter(Boolean) : null)
function readSettings(params: URLSearchParams) { export function readSettings(params: URLSearchParams) {
const seconds = Object.fromEntries( const seconds = Object.fromEntries(
KINDS.map((kind) => { KINDS.map((kind) => {
const value = Number(params.get(kind.key) ?? kind.seconds) const value = Number(params.get(kind.key) ?? kind.seconds)
@ -296,7 +302,7 @@ function readSettings(params: URLSearchParams) {
theme: THEMES.find((theme) => theme === params.get('theme')) ?? null, theme: THEMES.find((theme) => theme === params.get('theme')) ?? null,
} }
} }
type Settings = ReturnType<typeof readSettings> export type Settings = ReturnType<typeof readSettings>
type Picks = Pick<Settings, 'skipped' | 'hidden' | 'seconds' | 'only' | 'lists' | 'titles' | 'pictures'> type Picks = Pick<Settings, 'skipped' | 'hidden' | 'seconds' | 'only' | 'lists' | 'titles' | 'pictures'>
/* An entry or sub-item with its key (key()), carried through the /* An entry or sub-item with its key (key()), carried through the
@ -502,15 +508,29 @@ export default function EventPresent() {
const { data: event, loading, error, notFound, reload } = useEvent(id) const { data: event, loading, error, notFound, reload } = useEvent(id)
const sections = useMemo(() => (event ? sectionsOf(event.blocks ?? [], event.title) : []), [event]) const sections = useMemo(() => (event ? sectionsOf(event.blocks ?? [], event.title) : []), [event])
const schedules = useMemo(() => { const schedules = useMemo(() => schedulesOf(event?.blocks ?? []), [event])
const out = new Map<ContentBlock, Schedule>() const playing = params.get('play') === '1'
for (const block of event?.blocks ?? []) {
if (block.type !== 'schedule') continue // A remote's commands: the setup's here, the slides' the Player's.
const days = groupByDay(block.items ?? []) const [command, setCommand] = useState<RemoteCommand | null>(null)
if (days.length) out.set(block, { n: out.size, days, tags: block.tags ?? [] }) const remote = useScreenRemote((c) => {
} if (c.do === 'setup') {
return out setParams((was) => {
}, [event]) const next = new URLSearchParams(was)
next.delete('play')
return next
})
} else if (c.do === 'start') {
const next = new URLSearchParams(c.query)
next.set('play', '1')
setParams(next)
} else setCommand({ ...c })
})
const report = (state: Pick<ScreenState, 'paused' | 'index' | 'slides'>) =>
event && remote.report({ event: event.id, title: event.title, query: params.toString(), playing, ...state })
useEffect(() => {
if (!playing) report({ paused: false, index: 0, slides: [] })
})
useEffect(() => { useEffect(() => {
if (event) document.title = documentTitle(`${event.title}: present`) if (event) document.title = documentTitle(`${event.title}: present`)
@ -559,7 +579,7 @@ export default function EventPresent() {
} }
const settings = readSettings(params) const settings = readSettings(params)
if (params.get('play') === '1') { if (playing) {
return ( return (
<Player <Player
title={event.title} title={event.title}
@ -567,6 +587,9 @@ export default function EventPresent() {
look={look} look={look}
slides={ordered(buildSlides(sections, schedules, settings), settings.order)} slides={ordered(buildSlides(sections, schedules, settings), settings.order)}
screen={settings.screen} screen={settings.screen}
code={remote.code}
command={command}
report={report}
onSetup={() => { onSetup={() => {
const next = new URLSearchParams(params) const next = new URLSearchParams(params)
next.delete('play') next.delete('play')
@ -583,6 +606,7 @@ export default function EventPresent() {
sections={sections} sections={sections}
schedules={schedules} schedules={schedules}
settings={settings} settings={settings}
code={remote.code}
onPlay={(next) => { onPlay={(next) => {
// Full screen needs the click itself, so it's asked for here. // Full screen needs the click itself, so it's asked for here.
document.documentElement.requestFullscreen?.().catch(() => {}) document.documentElement.requestFullscreen?.().catch(() => {})
@ -592,9 +616,20 @@ export default function EventPresent() {
) )
} }
/* The page's schedule blocks with a day in them, numbered. */
export function schedulesOf(blocks: ContentBlock[]) {
const out = new Map<ContentBlock, Schedule>()
for (const block of blocks) {
if (block.type !== 'schedule') continue
const days = groupByDay(block.items ?? [])
if (days.length) out.set(block, { n: out.size, days, tags: block.tags ?? [] })
}
return out
}
/* The setup's choices as the address's query, playing (`play=1`): /* The setup's choices as the address's query, playing (`play=1`):
what Play goes to and Copy link copies. readSettings reads it. */ what Play goes to and Copy link copies. readSettings reads it. */
function addressFor(next: Settings): URLSearchParams { export function addressFor(next: Settings): URLSearchParams {
const out = new URLSearchParams() const out = new URLSearchParams()
if (next.skipped.size) out.set('skip', [...next.skipped].sort((a, b) => a - b).join(',')) if (next.skipped.size) out.set('skip', [...next.skipped].sort((a, b) => a - b).join(','))
if (next.hidden.size) out.set('hide', [...next.hidden].join(',')) if (next.hidden.size) out.set('hide', [...next.hidden].join(','))
@ -613,13 +648,14 @@ function addressFor(next: Settings): URLSearchParams {
/* ── Setup ──────────────────────────────────────────────────── */ /* ── Setup ──────────────────────────────────────────────────── */
function Setup({ export function Setup({
title, title,
back, back,
accent, accent,
sections, sections,
schedules, schedules,
settings, settings,
code,
onPlay, onPlay,
}: { }: {
title: string title: string
@ -628,6 +664,8 @@ function Setup({
sections: Section[] sections: Section[]
schedules: Map<ContentBlock, Schedule> schedules: Map<ContentBlock, Schedule>
settings: Settings settings: Settings
// This screen's remote code; none on the remote itself.
code?: string | null
onPlay: (settings: Settings) => void onPlay: (settings: Settings) => void
}) { }) {
const [skipped, setSkipped] = useState(settings.skipped) const [skipped, setSkipped] = useState(settings.skipped)
@ -645,7 +683,7 @@ function Setup({
const picked: Settings = { skipped, hidden, seconds, screen, only, order, theme, lists, titles, pictures } const picked: Settings = { skipped, hidden, seconds, screen, only, order, theme, lists, titles, pictures }
// The address that starts a screen with these choices, playing. // The address that starts a screen with these choices, playing.
const copyLink = () => { const copyLink = () => {
const link = `${window.location.origin}${window.location.pathname}?${addressFor(picked)}` const link = `${window.location.origin}${back}/present?${addressFor(picked)}`
navigator.clipboard navigator.clipboard
.writeText(link) .writeText(link)
.then(() => setCopied('yes')) .then(() => setCopied('yes'))
@ -684,6 +722,15 @@ function Setup({
Pick what to show and for how long, then Play. It loops until you stop it. Copy link (at the bottom) gives Pick what to show and for how long, then Play. It loops until you stop it. Copy link (at the bottom) gives
an address that starts a screen with these choices, playing, eg. to bookmark on a signage device. an address that starts a screen with these choices, playing, eg. to bookmark on a signage device.
</p> </p>
{code && (
<p className="mt-4 flex items-center gap-2 bg-raised p-4 text-ink shadow-sm">
<DeviceMobile aria-hidden="true" weight="bold" className="h-5 w-5 shrink-0" />
<span>
Run this screen from a phone: open {window.location.origin}/remote and enter{' '}
<strong className="font-mono text-lg tracking-widest">{code}</strong>
</span>
</p>
)}
</header> </header>
<section> <section>
@ -1210,6 +1257,9 @@ function Player({
look, look,
slides, slides,
screen, screen,
code,
command,
report,
onSetup, onSetup,
}: { }: {
title: string title: string
@ -1217,6 +1267,9 @@ function Player({
look?: EventPresentLook look?: EventPresentLook
slides: Slide[] slides: Slide[]
screen: number screen: number
code: string | null
command: RemoteCommand | null
report: (state: Pick<ScreenState, 'paused' | 'index' | 'slides'>) => void
onSetup: () => void onSetup: () => void
}) { }) {
const [index, setIndex] = useState(0) const [index, setIndex] = useState(0)
@ -1236,6 +1289,20 @@ function Player({
return () => window.clearTimeout(timer) return () => window.clearTimeout(timer)
}, [index, paused, seconds, slides.length]) }, [index, paused, seconds, slides.length])
// A remote's command, each a new object (EventPresent).
useEffect(() => {
if (command?.do === 'next') step(1)
else if (command?.do === 'prev') step(-1)
else if (command?.do === 'pause') setPaused(true)
else if (command?.do === 'resume') setPaused(false)
else if (command?.do === 'go') setIndex(Math.max(0, Math.min(command.index ?? 0, slides.length - 1)))
}, [command])
// What's showing, for the remotes.
useEffect(() => {
report({ paused, index: index % Math.max(slides.length, 1), slides: slides.map(slideName) })
})
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
if (e.key === 'ArrowRight') step(1) if (e.key === 'ArrowRight') step(1)
@ -1395,6 +1462,11 @@ function Player({
<span className="bg-raised px-3 py-2 text-sm text-muted shadow-md"> <span className="bg-raised px-3 py-2 text-sm text-muted shadow-md">
{index + 1} / {slides.length} {index + 1} / {slides.length}
</span> </span>
{code && (
<span className="bg-raised px-3 py-2 text-sm text-muted shadow-md">
Remote <span className="font-mono font-semibold tracking-widest text-ink">{code}</span>
</span>
)}
<button <button
type="button" type="button"
onClick={() => document.documentElement.requestFullscreen?.().catch(() => {})} onClick={() => document.documentElement.requestFullscreen?.().catch(() => {})}

250
src/pages/PresentRemote.tsx Normal file
View file

@ -0,0 +1,250 @@
/* ═══════════════════════════════════════════════════════════════
PRESENT REMOTE: /remote and /remote/:code
A phone driving a presenting screen (EventPresent.tsx) by the
code the screen shows (server/src/routes/present.js): what's on
it now, back, pause and next, any slide by name, back to its
setup, and the setup itself (EventPresent's Setup), whose Play
starts the screen with those choices. Anyone with the code can.
Outside the site's Layout, like the presentation.
═══════════════════════════════════════════════════════════════ */
import { ArrowLeft, CaretLeft, CaretRight, Gear, Pause, Play, SlidersHorizontal } from '@phosphor-icons/react'
import { useEffect, useMemo, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Setup, addressFor, readSettings, schedulesOf, sectionsOf } from './EventPresent.tsx'
import { BASE, post } from '../lib/api.ts'
import { useEvent } from '../lib/useContent.ts'
import { BRAND, accentText } from '../lib/color.ts'
import { documentTitle } from '../lib/site.ts'
import type { RemoteCommand, ScreenState } from '../lib/useScreenRemote.ts'
type Seen = ScreenState & { connected: boolean }
export default function PresentRemote() {
const { code } = useParams()
useEffect(() => {
document.title = documentTitle('Remote')
}, [])
return code ? <Connected code={code.toUpperCase()} /> : <EnterCode />
}
function EnterCode() {
const navigate = useNavigate()
const [code, setCode] = useState('')
return (
<main className="flex min-h-screen items-center justify-center bg-surface px-4 text-body">
<form
onSubmit={(e) => {
e.preventDefault()
if (code.trim()) navigate(`/remote/${encodeURIComponent(code.trim().toUpperCase())}`)
}}
className="w-full max-w-sm space-y-4 bg-raised p-6 shadow-md"
>
<h1 className="text-2xl font-bold text-ink">Remote</h1>
<label className="block">
<span className="text-sm text-muted">The code on the screen (with its controls, or on its setup)</span>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
autoFocus
autoCapitalize="characters"
autoComplete="off"
maxLength={6}
className="mt-1 w-full border border-muted/25 bg-surface px-3 py-2 font-mono text-2xl tracking-widest uppercase"
/>
</label>
<button type="submit" className="btn w-full bg-action px-5 py-3 text-white">
Connect
</button>
</form>
</main>
)
}
function Connected({ code }: { code: string }) {
const [seen, setSeen] = useState<Seen | null>(null)
const [lost, setLost] = useState(false)
const [tries, setTries] = useState(0)
const [problem, setProblem] = useState('')
const [editing, setEditing] = useState(false)
useEffect(() => {
setLost(false)
const source = new EventSource(`${BASE}/present/${encodeURIComponent(code)}`)
source.addEventListener('state', (e) => setSeen(JSON.parse((e as MessageEvent).data)))
// Closed is the server's no (no such code); otherwise it retries.
source.onerror = () => source.readyState === EventSource.CLOSED && setLost(true)
return () => source.close()
}, [code, tries])
const { data: event } = useEvent(seen?.event || undefined)
const sections = useMemo(() => (event ? sectionsOf(event.blocks ?? [], event.title) : []), [event])
const schedules = useMemo(() => schedulesOf(event?.blocks ?? []), [event])
const send = (command: RemoteCommand) => {
setProblem('')
post(`/present/${encodeURIComponent(code)}/command`, command).catch((err) => setProblem(err.message))
}
if (lost) {
return (
<main className="flex min-h-screen flex-col items-center justify-center gap-4 bg-surface px-4 text-body">
<p className="notice">No screen has the code {code} right now.</p>
<div className="flex gap-3">
<button type="button" onClick={() => setTries((n) => n + 1)} className="btn border border-muted/25 px-5 py-2 text-ink">
Try again
</button>
<a href="/remote" className="btn border border-muted/25 px-5 py-2 text-ink">
Another code
</a>
</div>
</main>
)
}
const accent = event?.present?.accent || event?.color || BRAND
if (editing && seen?.event && event) {
return (
<>
<div className="sticky top-0 z-10 flex items-center gap-3 bg-raised px-4 py-3 shadow-md">
<button type="button" onClick={() => setEditing(false)} className="btn inline-flex items-center gap-2 px-3 py-2 text-ink">
<ArrowLeft aria-hidden="true" weight="bold" className="h-4 w-4" />
Remote
</button>
<span className="text-sm text-muted">Play starts the screen with these choices.</span>
</div>
<Setup
// Fresh choices each time the screen's setup changes.
key={seen.query}
title={event.title}
back={`/events/${encodeURIComponent(event.id)}`}
accent={accent}
sections={sections}
schedules={schedules}
settings={readSettings(new URLSearchParams(seen.query))}
onPlay={(next) => {
send({ do: 'start', query: addressFor(next).toString() })
setEditing(false)
}}
/>
</>
)
}
const control = 'btn flex h-16 flex-1 items-center justify-center bg-raised text-ink shadow-md disabled:opacity-50'
const playing = !!seen?.event && seen.playing
const off = !seen?.connected
return (
<main className="min-h-screen bg-surface text-body">
<div className="h-2" style={{ background: accent }} />
<div className="mx-auto max-w-lg space-y-6 px-4 py-6">
<header>
<p className="text-sm font-semibold text-muted">
Remote <span className="font-mono tracking-widest">{code}</span>
</p>
<h1 className="text-2xl font-bold" style={{ color: accentText(accent) }}>
{seen?.event ? seen.title : 'Connecting…'}
</h1>
</header>
{seen && off && <p className="notice">The screen isn't connected right now. This page carries on when it is.</p>}
{seen?.event && (
<p className="bg-raised p-4 shadow-sm" aria-live="polite">
{playing ? (
<>
<span className="block text-sm text-muted">
Slide {seen.index + 1} of {seen.slides.length}
{seen.paused ? ', paused' : ''}
</span>
<span className="font-semibold text-ink">{seen.slides[seen.index]}</span>
</>
) : (
<span className="text-muted">The screen is on its setup. Change the setup to pick what it plays.</span>
)}
</p>
)}
{seen && playing && (
<div className="flex gap-3">
<button type="button" disabled={off} onClick={() => send({ do: 'prev' })} className={control} aria-label="Previous slide">
<CaretLeft weight="bold" className="h-6 w-6" aria-hidden="true" />
</button>
<button
type="button"
disabled={off}
onClick={() => send({ do: seen.paused ? 'resume' : 'pause' })}
className={control}
aria-label={seen.paused ? 'Play' : 'Pause'}
>
{seen.paused ? (
<Play weight="fill" className="h-6 w-6" aria-hidden="true" />
) : (
<Pause weight="bold" className="h-6 w-6" aria-hidden="true" />
)}
</button>
<button type="button" disabled={off} onClick={() => send({ do: 'next' })} className={control} aria-label="Next slide">
<CaretRight weight="bold" className="h-6 w-6" aria-hidden="true" />
</button>
</div>
)}
{seen?.event && (
<div className="flex flex-wrap gap-3">
<button
type="button"
disabled={off || !event}
onClick={() => setEditing(true)}
className="btn inline-flex items-center gap-2 border border-muted/25 px-4 py-2 text-ink disabled:opacity-50"
>
<SlidersHorizontal aria-hidden="true" weight="bold" className="h-4 w-4" />
Change setup
</button>
{playing && (
<button
type="button"
disabled={off}
onClick={() => send({ do: 'setup' })}
className="btn inline-flex items-center gap-2 border border-muted/25 px-4 py-2 text-ink disabled:opacity-50"
>
<Gear aria-hidden="true" weight="bold" className="h-4 w-4" />
Screen to its setup
</button>
)}
</div>
)}
<p role="status" className="text-sm text-muted">
{problem}
</p>
{seen && playing && seen.slides.length > 0 && (
<section>
<h2 className="mb-2 text-lg font-bold text-ink">Go to a slide</h2>
<ol className="divide-y divide-muted/15 bg-raised shadow-sm">
{seen.slides.map((name, i) => (
<li key={i}>
<button
type="button"
disabled={off}
onClick={() => send({ do: 'go', index: i })}
aria-current={i === seen.index ? 'true' : undefined}
className={`flex w-full gap-3 px-4 py-3 text-left hover:bg-tint ${i === seen.index ? 'bg-tint font-semibold text-ink' : ''}`}
>
<span className="w-6 shrink-0 text-right text-muted">{i + 1}</span>
<span>{name}</span>
</button>
</li>
))}
</ol>
</section>
)}
</div>
</main>
)
}