NGU-Web/src/lib/useScreenRemote.ts
Aidan Dona 5eebc20c4e Present: a remote, a phone at /remote/<code> drives a presenting screen
The screen shows a code on its setup and with its controls. Anyone with
it can step, pause and jump through the slides, send the screen back to
its setup, or change the setup and play it there. Server-sent events,
held in memory (routes/present.js); X-Accel-Buffering: no, so nginx
needs no block of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:51:27 -06:00

88 lines
2.7 KiB
TypeScript

/* 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 }
}