Compare commits

...
Author SHA1 Message Date
Waters ChurchandClaude Opus 5 aec9c47ed4 PCO Plan 1.8.0: the plan follows AbleSet, and auto-scroll stays in its tile
Three things, the first on its own.

**Auto-scroll moves the tile, not the board.** `scrollIntoView` walks up and
scrolls every ancestor that can scroll, so bringing the current item into
view dragged the whole dashboard with it whenever the board was taller than
the window. The list's own `scrollTop` is moved instead, measured from
rectangles because the rows' offset parent is the tile rather than the list.

**The current item fills as its song plays.** When an AbleSet module is
installed, configured and playing a song that IS the item on screen, that
item's background fills left to right with the song. The song is tied to a
plan item by the same name matching the live ProPresenter document already
uses, so a bar can never quietly fill the sermon while the band rehearses
something else.

**Its sections slide past, bottom right of that item.** Every section of the
song as a strip, the played ones dimmed, the one playing filling in turn and
kept centred — by moving that strip's own `scrollLeft`, for the same reason
as above. The chips are rebuilt only when the song changes; moving to the
next section just moves the classes, so the strip keeps its place.

Both are switches in the tile's gear, **Song progress** and **Song
sections**, and both draw nothing at all unless there is an AbleSet module
to follow: the server reports `available: false` for no module, a disabled
one, or one with no host, and re-checks every 15 s so installing AbleSet
later lights it up without a restart.

The server follows the AbleSet module over loopback exactly as it follows
ProPresenter's, and republishes a small slice — song, sections, playhead in
beats with a stamp — as its own `ableset` SSE event. Its own event because
it moves five times a second and must never drag the plan (items, teams)
onto the wire with it; the tile carries the playhead forward from the tempo
between packets.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-27 09:14:19 -04:00
michael 5f60cd563c Merge pull request 'Timers 1.4.2: ProPresenter digits no longer flick back a second' (#26) from claude/timers-second-phase into main 2026-09-27 09:05:46 -04:00
michael de32046553 Merge pull request 'AbleSet 1.0.0: follow AbleSet's setlist over OSC' (#17) from claude/proddash-ableset-module-6c2556 into main 2026-09-27 09:02:23 -04:00
Waters ChurchandClaude Opus 5.5 c1d9c59325 Merge origin/main into claude/proddash-ableset-module-6c2556
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 09:01:35 -04:00
Waters ChurchandClaude Fable 5 2f4c357bf5 Timers 1.4.2: ProPresenter digits no longer flick back a second
ProPresenter reports running timers as truncated whole seconds, and the
poller re-anchored the tiles' local count at the bottom of that second on
every 500 ms poll — so the displayed digit ran up to a second ahead and
got yanked back a step whenever a fresh poll sampled the next flip later
than the last one did. Tiles flickered ...12:33 → 12:34 → 12:33... about
once a second.

phase.js turns the quantized reports into one stable anchor per timer:
the only information in a poll is a FLIP (the report stepping one second
in the direction of travel), which dates the true boundary to the
midpoint of the two polls that straddle it. While reports stay consistent
with the anchor (±450 ms) the anchor holds, so tiles count along one
steady clock; a report the anchor can't explain (reset, seek, resume,
accumulated drift) re-anchors. Timers carry the anchor as a per-timer
asOf the client extrapolates from (optional in the provider contract,
documented in the guide); the client additionally refuses to tick a
running card backwards over sub-1.5 s jitter.

phase.selftest.js (66 checks) drives a simulated ProPresenter — truncated
reports, jittered polls — through the tracker and the client's render
math: digits never step backwards, dwells hold 1 s (the ~2 s zero-crossing
dwell is trunc's honest behavior), anchors stay within tolerance of the
true value, resets snap, pause/resume re-locks, 0.2% clock drift is
absorbed. Verified live against tools/pp-timers-mock.js: 78 s of 100 ms
DOM sampling across four running cards — every step ±1 in the card's own
direction, dwells 998–1002 ms, zero regressions; upstream kill/restart
still recovers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-27 08:46:50 -04:00
michael 7a736b3db1 Merge pull request 'PCO Plan 1.7.0: a Teams tile — who is scheduled, with photos' (#23) from claude/pco-teams-tile into main 2026-09-24 15:27:59 -04:00
Waters ChurchandClaude Opus 5 6c0aee5abf Teams tile: one Colors group, no Positions switches
Colors and Status colors were two groups asking the same question, so they
are one: team header, the tints and the three status colours together.

The Positions switches go entirely — the team switches already decide what
a tile shows, and "Group by position" still arranges what is left. With
them go GET /positions and positionOptions().

Two rules the tile was breaking on the way past: a gear group may carry no
`help` (rule 5), and only hide-toggles belong in Show (rule 8) — so the
group blurbs are gone and the Columns picker sits loose at the top beside
the team switches.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 15:15:34 -04:00
Waters ChurchandClaude Opus 5 6d0f8828c1 PCO Plan 1.7.0: a Teams tile — who is scheduled, with photos
The module now offers two tiles in the + picker, Plan and Teams, sharing
the one Planning Center connection and the one poll.

Teams draws the current plan's team and position assignments: each team as
a band of its people, with the person's photo, their position and a dot for
confirmed / unconfirmed / declined. Photos are proxied and cached by the
module (GET /team-avatar/<planPersonId>) so no browser ever talks to
Planning Center; a person with no photo gets their initials.

Everything shown is the tile's own choice, so two tiles can differ:
- Teams and Positions — a switch per team and per position, all on until
  someone flips one (GET /teams, GET /positions feed the lists)
- Colours — a picker for the team headers, or Tint teams to give each its
  own, optionally carried into the rows, plus the header fade and pickers
  for the three statuses
- Show — twelve switches (top bar, team headers and counts, avatars,
  positions, group by position, status, notes, declined and unconfirmed
  people, teams nobody is on, columns)

Server: team_members?include=team,person rides a slow lane (re-read on a
plan change, else at most once a minute) and can never fail the plan read —
a lost roster keeps the last good one and says so. The service type's own
team list is read too, cached ten minutes: Planning Center only returns a
team once somebody is scheduled on it, so that list is the only way to show
a team nobody has signed up for.

No shell changes: picker entries carrying their own instanceSchema, the
colour field and multiselects all already exist.

tools/pco-mock.js grows team_members, the service type's teams and stand-in
avatar images, including a declined person, people with no photo and a team
nobody is on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 12:42:57 -04:00
christian 8ca88ba10b Merge pull request 'Resi Cues: the countdown to the next cue, on the board and as a timer' (#22) from claude/resi-stage-cues into main 2026-09-24 12:19:49 -04:00
christianandClaude Opus 5 a8d1b8e159 Resi Cues becomes a real module, and Companion keeps the stage timer
Yesterday's version of this was a Python script under `modules/` with a
LaunchAgent to keep it alive — which the guide rules out in as many words:
everything a module does runs inside its server entry, no companion programs
or daemons an operator starts by hand. It also could not put anything on a
dashboard, which is half of what it was wanted for. Both halves are now in
the right place.

`modules/resi-cues/` is an ordinary module. Its tile is one number as large as
the tile allows — the countdown to the next Resi cue, the cue's name above it,
the playhead and the cue just passed underneath, and the whole cue list behind
a tile switch. It also declares `"provides": ["timers"]` and serves `/timers`
and `/timers/stream`, so the countdown and the playhead turn up among the
ProPresenter timers in the Timers module without either side knowing about
the other.

The countdown ticks in the browser. The server sends the playhead with the
instant it was true and whether playback is running, and the tile adds the
elapsed time since; the Timers module extrapolates from `startedAt` the same
way. So a snapshot only has to be sent when something structural changes — a
new cue, a pause, a seek — rather than at 1 Hz to every open dashboard.

`resi.js` holds the part worth reading twice. Resi republishes a decoder's
position only every few seconds, on an irregular cadence, and each reading is
already stale when it appears; a countdown built straight from it sits seconds
behind and lurches. So every reading is kept as media time minus wall time and
the largest recent value is trusted — the reading that arrived with the least
delay — which a slow round trip cannot drag backwards. A reading outside the
link's measured noise floor counts as a seek: drop the lock, snap, and re-read
the cue list at once instead of on its timer. Playback is only called paused
once the playhead has been still for longer than Resi's own cadence, because a
fixed timeout mistakes a slow update for a stop and freezes the countdown
mid-service.

Driving the ProPresenter timer on the stage screen is Companion's job now. It
is already a service on that machine, so nothing new has to be kept alive, and
this module no longer has to reach ProPresenter at all — it only has to be
right about Resi, which is the hard part.

`resi.test.js` drives the estimator on a fake clock against nine simulated
Resi profiles — cadences of one to twelve seconds, staleness to three,
irregular timing, variable round trips — covering lock-on, a fired cue, a seek
backwards, a pause, and a pause longer than the offset window. A punctual
fixture proves nothing here: against one, three separate breakages of the
estimator go unnoticed. `server.test.js` runs the real server entry against a
canned Resi account and checks what the two consumers actually read, including
the `/timers` shape field by field. Every mutation tried against either turns
them red.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 12:08:55 -04:00
christianandClaude Opus 5 82c552955d Resi cue countdowns reach the stage screen without Companion
The ask was a Stream Deck button showing the time until the next Resi cue.
What it turned into is simpler: ProPresenter already renders countdowns, and
it already has an HTTP API, so nothing has to sit in between except something
that knows when the next cue is.

`resi_to_propresenter.py` watches a decoder's playhead and keeps a
ProPresenter countdown timer armed with the seconds until its next cue, with
the cue's name as a stage message beside it. Both halves of that come from
Resi's cloud rather than the decoder — the decoder reports its position
upstream and `central.resi.io` hands it back — so there is nothing to install
at the decoder end and nothing polling it every second.

The playhead is estimated rather than repeated. Resi republishes `position`
only every few seconds, irregularly, and each reading is already stale when
it appears; sent straight through, the countdown sat three seconds behind and
lurched. So each reading is kept as media time minus wall time and the
largest recent value is trusted — the reading that arrived with the least
delay — which a slow round trip can no longer drag backwards. A reading
outside the link's measured noise floor counts as a seek: drop the lock, snap,
and re-read the cue list immediately instead of on its timer. Playback is
only called paused once the playhead has been still for longer than Resi's own
cadence, because a fixed timeout mistakes a slow update for a stop and freezes
the countdown mid-service.

This is not a tile. There is no `module.json`, so `readManifests` skips the
folder and it never reaches the + picker; it lives under `modules/` because
that is where the production tooling lives. That is also why it carries a
README when no real module does — there is no *Included modules* entry it
could have instead — and the repo README says so where the module list ends.

`install-agent.command` sets up a LaunchAgent so it runs from login and
restarts if it stops. It deliberately runs a copy in Application Support: a
login agent cannot read `~/Documents` without Full Disk Access, and macOS
answers "Operation not permitted" rather than asking. Settings live there too,
outside the checkout, the same way module config does. The Resi password is
read from the Keychain and never written to disk; with none set the agent
says so once and waits rather than relaunching in a loop.

`test_playhead.py` drives the estimator on a fake clock against nine
simulated Resi profiles — update cadences of one to twelve seconds, staleness
to three, irregular timing, variable round trips — and six of seven deliberate
breakages of the estimator turn it red. `test_end_to_end.py` runs the real
loop against a real ProPresenter with a simulated decoder, and has: it armed
for the first cue, counted down in step, rolled over to the second and stopped
when the cues ran out. Neither covers the live Resi calls, which need real
credentials.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 11:35:40 -04:00
christian ea3a920d5e Merge pull request 'Service Times 1.0.0: every campus's services, and what production can't use' (#20) from claude/service-times-module into main 2026-09-24 11:34:38 -04:00
christian f542b34b6c Merge remote-tracking branch 'origin/main' into claude/service-times-module
# Conflicts:
#	README.md
2026-09-24 11:33:48 -04:00
christian a1ea9262c6 Merge pull request 'Band Lineup's docs move to where every other module's live' (#21) from claude/band-lineup-docs-tidy into main 2026-09-24 11:31:03 -04:00
christianandClaude Opus 5 098562c088 Band Lineup's docs move to where every other module's live
Two things were out of place. `modules/band-lineup/README.md` was the only
README inside any of the eight modules — the guide's folder shape is manifest,
client, server, assets, and every other module is described in this README's
*Included modules* instead. It was also describing a module that no longer
exists: photos and birthdays "come from Planning Center", guests "pinned per
slot", and a refresh interval the manifest has never had.

The entry here had drifted the same way, calling the Drive folder somewhere
to put "manual photos" and the board something Planning Center fills. It is
the other way round now, and has been since 1.10: the board is shared server
state and the source of truth, the photo library fills it, and Sync is
auto-fill that only touches slots nobody placed by hand. The entry says that,
and picks up the Choir spot and the title-bar columns while it is there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 11:30:17 -04:00
christian 408dea7923 Merge pull request 'Band Lineup Display snapshot catches up: 1.3.6 → 1.3.10' (#19) from claude/band-lineup-display-1-3-10 into main 2026-09-24 11:24:56 -04:00
christianandClaude Opus 5 3ca960baf6 Service Times 1.0.0: every campus's services, and what production can't use
Four campuses run different Sunday schedules and take their resi feed from one
of two broadcast origins. When a service goes wrong — a machine crashes, a feed
is unusable — the booth has to know which service at which campus can be
altered, and which campuses are riding on the one that broke. That lived in
people's heads and in messages.

The times come from the church website rather than from configuration, because
the site is what stays current when services change through the year. Each
campus page carries a "Times" block; the module reads it and re-reads it on a
timer. Two things on those pages are not services and are excluded on purpose:
the main-office hours in every page's footer, and the "Office Hours" block
Apollo Beach carries inside its own Times section. The parse is bounded to the
Times heading and stops at either.

A mark on a service — issue, replay, do not use, with a note, and for a resi
campus which of the origin's services it is taking — is the booth's shared
answer, so it lives in the module's server state and reaches every tile over
SSE. Per-tile settings would let two campuses disagree about whether the 9:30 is
going out. Marks are written to the data directory so a restart mid-morning
does not lose them, and they expire after 36 hours so last week's never greet a
new Sunday.

Campuses added by hand in admin are a stopgap for a site that has not caught up
yet: as soon as the website publishes that campus, the site's times take over
and the admin health line says the manual line can be removed.

Verified: the parser against all five live campus pages, and 31 unit tests plus
16 client checks, each proven to fail under mutation — both parse guards, the
merge rule, dependent recording, and three client behaviours. The suite is run
here under JavaScriptCore, since this machine has no Node.

Not verified here: the module guide's resilience checklist needs a running
ProdDash — upstream loss and recovery, two tiles side by side, and tile removal
leaving no timers behind.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 16:57:48 -04:00
christianandClaude Opus 5 882a418a0f Band Lineup Display snapshot catches up: 1.3.6 → 1.3.10
The reference fork had drifted four builds behind the app actually running
backstage. What it was missing is Birthday Mode, the feature the ProdDash
module was ported with and this snapshot never had:

- main.js grows the Planning Center birthday fetch (`pcoFetchBirthday`),
  mm-dd normalising, and a `pco-test-birthdays` IPC handler behind the
  settings pane's Test Birthdays button.
- renderer.js gains the whole celebration: the Wednesday→Tuesday birthday
  week, the canvas confetti loop, the gold glow, and the controls that switch
  it on and set its intensity.
- index.html and styles.css carry the Birthday Mode block in settings.

Purely additive — 597 lines in, four out, and those four are the version and
build number. Source only, as the fork has always been: `.claude/` settings
stay as they are (the local copy's are one machine's accumulated permissions,
and it has no launch.json to give), and the stray test file beside them is not
part of the app.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 16:37:54 -04:00
Waters ChurchandClaude Opus 5.5 9192eed318 AbleSet 1.0.1: a remounted tile asks for the state instead of waiting
Every gear change remounts the tile, and the remounted tile joins the
page's shared stream mid-flow, so it heard nothing until AbleSet next
changed — with the transport stopped, never. Tiles went blank until a
reload. The tile now fetches /state when it starts and whenever the
stream (re)opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 16:07:13 -04:00
Waters ChurchandClaude Opus 5.5 41fd76817c AbleSet 1.0.0: follow AbleSet's setlist over OSC
A new module that subscribes to AbleSet's OSC API (UDP 39051) and streams
what it is playing to ten tiles: Now Playing (song, tempo, meter, duration,
time left, section, progress bar, next song, songs left), Song Sections
(a sliding strip, or a lottery wheel from the title bar), Setlist,
Transport, Tempo, Song Time, Set Time, Section, Next Song and Status, each
coloured by its state. The song and set countdowns are offered to the
Timers module.

A heartbeat watchdog resubscribes when AbleSet goes quiet (a restarted
AbleSet forgets its subscribers). Time left falls back to the song length
and playhead when AbleSet stops sending it (Live disconnected).

tools/ableset-mock.js plays a setlist over the same API for testing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 14:24:19 -04:00
michael 0e618ea5d3 Merge pull request 'SPL Meter 0.4.1: name a dead input, and stop the spectrogram smearing its labels' (#16) from claude/spl-silent-input into main 2026-09-23 10:03:23 -04:00
Waters ChurchandClaude Opus 5 c8b51c6c2f Spectrogram: stop dragging the labels along with the picture
The spectrogram scrolled by copying the visible canvas onto itself one step
along. That canvas already held the frequency labels and gridlines, because
they were drawn straight onto it, so every frame smeared them sideways and
left a trail. Arrived with the labels in 0.3.0; the gridlines did it too.

Only measured pixels belong on a surface that scrolls. The history now lives
on its own offscreen canvas that holds nothing but spectrum, and the visible
canvas is repainted from scratch each frame — history first, annotations
over the top. Nothing drawn as an annotation can reach the scroll buffer by
construction, rather than by remembering to clear the right strip.

The layout was muddled in the same place and is fixed with it: the gutter
used to be reserved along the bottom while the labels were drawn down the
left, overlapping the plot. Labels now sit beside the axis they describe —
down the left when frequency runs vertically, with room for "12.5k", and
along the bottom when it runs horizontally.

Verified both orientations by fingerprinting the gutter and the plot two and
a half seconds apart: gutter identical, plot changed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 09:58:32 -04:00
Waters ChurchandClaude Opus 5 c464e5b4ca SPL Meter 0.4.0: a dead input must not look like a quiet room
AB's meter appeared to halt for a day and a half. Nothing had halted: the
capture child had run continuously since the machine was restarted, never
stalled, never exited, and was delivering twenty frames a second. Every one
of them was digital silence, because Dante Via stopped passing audio after
the reboot — the Timers module's LTC listener, on channel 16 of the same
device, had been reporting no signal for exactly as long.

The module's part in that was reporting "ok" through all of it and drawing
a steady -83, which is the -200 floor plus the +117 calibration offset. A
plausible number on a wall is believed, and a green dot beside it says the
number is worth believing. That is worse than showing nothing.

So silence is now a state the module names. Below -150 dBFS unweighted the
input is not quiet, it is absent: a microphone in a silent room still reads
about -83, and even a muted converter dithers. Five seconds of that on every
channel and health() goes to error naming the device and how long it has
been dead, the tiles stop drawing a level and say "No audio" with how long,
and the status dot goes red.

Verified both directions, which is the half that matters: BlackHole with
nothing routed into it is caught in five seconds, and a real microphone in a
quiet room at -49 dBFS is never flagged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 09:54:27 -04:00
michael f4d50f5e95 Merge pull request 'PCO Plan 1.6.0: the message document is matched by the plan's own name' (#15) from claude/pco-message-match into main 2026-09-22 16:56:49 -04:00
Waters ChurchandClaude Fable 5.1 c73d0a3aac PCO Plan 1.6.0: the message document is matched by the plan's own name
The current item followed the live ProPresenter document by title alone,
and a sermon's document is named after the sermon — Waters names them
"YYMMDD Series Title - Part #" — never after its plan item. So the last
song stayed current through the whole message: North Attleboro on 20 Sept
spent 65 minutes on one song in two of its three services.

A live document that reads like the plan itself — its date code, series
title and part — now lands on the plan's message item: an item titled
Message, Sermon or Teaching, else the first item under such a header. A
date code naming another day is a firm no, so last week's sermon stays
unplaced. Position in the ProPresenter playlist breaks a tie between
equal names, only while the playlist mirrors the plan item for item, and
never places a document on its own.

The log now says what it never said: every feed drop and reconnect, which
item the message document will land on, what placed each item and how,
and a live document that is not in the plan.

matching.test.js: 27 checks built from both campuses' real 27 Sept plans
and ProPresenter playlists.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 13:06:53 -04:00
michael 441cfe3882 Merge pull request 'Grid density: cut the board finer or coarser, per browser' (#14) from claude/grid-size into main 2026-09-22 11:45:51 -04:00
Waters ChurchandClaude Fable 5.1 7ca65a845f Grid Size: the stepper's row is a name and a number
The Layouts menu row reads "Grid Size  − 12 +": the label is the setting's
name, the readout is the bare column count, and the default/finer/coarser
caption under the label is gone. The buttons keep their tooltips.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 11:35:26 -04:00
Waters ChurchandClaude Fable 5.1 e383070a9e Grid density: a coarser board settles its tiles instead of stacking them
Stepping the grid coarser pulled tiles past the right edge back in and
left them wherever that put them — on top of one another, which the
board never allows under a drag. Tiles now settle in reading order: one
that would land on a tile already settled takes the first free spot, the
same rule a newly added tile follows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 11:26:05 -04:00
Waters ChurchandClaude Fable 5.1 2af7ef27ba Grid density: cut the board finer or coarser, per browser
Twelve columns fit a booth monitor and nothing else well: on a 4K wall a
three-wide tile is nearly a thousand pixels, and on a small screen four tiles
across is the most the grid allows. A stepper in the Layouts menu now cuts
the board into 8, 10, 12, 16, 20 or 24 columns. Row height follows the
column width, so cells keep their shape and a 3×2 tile is still a 3×2 tile,
only smaller — finer lets tiles be smaller so more fit, coarser suits a
screen read close up.

It is this browser's choice, not the server's: two displays at one location
can want different densities, so it saves with the layout — the local one
and a named one on the server — and a named layout comes back at the density
it was arranged on, which the load message says. An older layout with no
density is the default twelve.

Tiles keep their grid units when the density changes; the board simply gets
denser or coarser around them, and a tile now past the right edge is pulled
in. A module's minSize is enforced in cells as declared, so on a finer grid a
tile can be smaller than it could at twelve, which is the point; a new tile's
defaultSize is scaled to the density so it lands at about the size its author
meant. Leaving fullscreen goes back to the chosen density rather than the
stylesheet's twelve — that reset predates any notion of a chosen density.

Shell 1.9.0. The round-trip test carries gridCols and drops a value off the
scale.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:19:49 -04:00
michael 5107b06f8c Merge pull request 'Band Lineup joins the repo — Christian's module, ready for every install' (#13) from claude/band-lineup-module into main 2026-09-22 09:44:18 -04:00
Waters ChurchandClaude Fable 5.1 5fb90190ae Band Lineup 1.11.0: into the catalog, and to the guide's rules
The module arrived in the previous commit exactly as it runs in North
Attleboro. This brings it to the interface rules every module follows and
puts it where the admin page can offer it.

The three hide-toggles — names, mic labels, parallax — sat in a folded
"Show / hide" group. Rule 8 puts four or fewer at the top of the gear with
no group at all, so they are ungrouped and first; the Birthday group keeps
its switch. The test-mode select loses its help line (rule 5). Everything
else in the gear was already within the rules, and every title-bar control
was already an icon with a tooltip.

The Planning Center mock moves out of the module folder to tools/, beside
the other upstream mocks, so an install does not download a development
tool with the module; README and CLAUDE.md say how to run it. The version
goes to 1.11.0 so the copy already installed on NA is offered the update
from the repo, and the module joins the README's list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 09:19:34 -04:00
christian 684f06abed Band Lineup module, as it runs in North Attleboro
The backstage stage board as a ProdDash tile: everyone scheduled on the
band, vocal and production teams for the upcoming Planning Center plan,
placed into their mic slot with photo, name and mic/pack label. Birthdays
in the service week get confetti. The display half of the standalone Band
Lineup Electron app, ported to a module — imported here exactly as
installed on NA-Ingest (v1.10.1), so the repo is where it lives from now on.
2026-09-22 09:15:22 -04:00
michael 3435a0625e Merge pull request 'Layouts keep every tile they are given, and show what is on offer' (#12) from claude/layout-audit into main 2026-09-21 13:30:53 -04:00
Waters ChurchandClaude Fable 5.1 a7e40ee1a8 Layouts keep every tile they are given, and show what is on offer
The bug behind this: for seventeen days the server rebuilt each saved tile
from the fields it knew and dropped the rest — including `variant`, so a
layout of five different timers came back from the server as five "All
timers". The client had carried `variant` since multi-tile modules arrived;
the server was the one that lagged, and it is the part of ProdDash that
always will (a booth updates weeks after the dev machine). So the server
stops deciding which tile fields exist: it checks the shape of the ones it
knows, keeps any other small plain-JSON field a tile carries, drops only
retired ones, stamps the file `v: 2`, and refuses a layout over a hundred
tiles instead of quietly saving the first hundred. A test round-trips a
fully-populated tile plus one the server has never heard of, and fails if
anything is lost.

Then the rule the arrangement is loaded by. A layout keeps every tile it is
given; the board shows the ones whose module is installed and enabled and —
for a tile added from a picker entry — whose entry is offered right now. The
rest keep their place and draw nothing, and appear the moment the registry
offers them again: a Service timer waits for PCO Plan, a transcript for its
channel. Never the module's default in their place. Because a module's entry
list can change with no event to mark it (PCO Plan comes back and, seconds
later, the timers module is offering its timers again), the registry is
re-read every few seconds while anything is folded away, and not at all
otherwise. The timers module's placeholder card for a missing solo timer
goes with this: nothing is drawn, the dot says why.

Loading says what it did — "Loaded 'FOH': 9 tiles, 2 not shown — Service,
#ops aren't offered right now" — with Undo in the message. Saving over a
name asks first, and the server keeps the copy it replaced one back; Admin →
Saved layouts gets Restore previous, which swaps the two so a restore is one
restore from undone. The browser keeps one good copy of its own layout
behind the live one and falls back to it when the live one will not parse.

Shell 1.8.0, timers 1.4.1. The layouts already saved on the booth machines
had their variants stripped before this and have to be saved again from a
browser that still holds the right tiles — nothing here recovers what the
files no longer contain.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-20 12:02:34 -04:00
michael c075655817 Merge pull request 'An update that goes wrong is no longer the end of it' (#11) from claude/update-safety into main 2026-09-17 16:30:42 -04:00
michael 48d0f5a04a Merge pull request 'SPL Meter: measure the room, not just watch it' (#10) from claude/spl-meter-module into main 2026-09-17 16:18:11 -04:00
Waters ChurchandClaude Opus 5 12f6e22187 An update that goes wrong is no longer the end of it
Two things the audit found, both about the archive path every shipped .app
uses.

**Settings could be wiped.** The update kept config/modules.json and
config/layouts/ by name, but not config/proddash.json — which holds the admin
PIN, the theme and the forge pointer. On an install whose data directory IS
the app's own config/ (an unwritable Application Support, or PRODDASH_DATA_DIR
aimed inside the app), an update wrote the repo's shipped defaults over it:
the theme went, and admin silently unlocked. Nothing inside the data
directory is written now, wherever it happens to sit, and the two legacy
names stay listed for an install whose state never moved out.

**A bad update was unrecoverable.** No rollback, and a fresh .app would not
help: seeding only replaces an *older* copy, and a broken one carries a
higher version — so the fix was deleting a folder nothing told you about.
Three changes, in the order they catch things:

- The download must parse before anything is swapped in. `node --check`
  against the new server.js, and a failure is reported with the syntax error
  and leaves the running copy untouched.
- Past that, the copy being replaced is set aside as `app.previous`, and
  dropped once the new version has stayed up ninety seconds — so that folder
  existing means "the last update has not proven itself yet", and never
  anything older.
- The launcher, which already gives up after four stops in two minutes, now
  looks for that folder before it does and puts the old copy back. Once: if
  the old one will not run either, the update was not the problem.

The launcher half only reaches a machine with a new .app; the server half
travels by the normal update.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 16:16:46 -04:00
Waters ChurchandClaude Opus 5 87929bfd0b Don't take the server down when the module unmounts
Deploying 0.3.0 to AB crashed the ProdDash server on restart:

  TypeError: Cannot read properties of null (reading 'streams')
      at server.js:273  req.on('close', () => state.streams.delete(res))

teardown() nulls `state` and then ends every open stream, which fires each
request's close handler — and the handler reached back through the `state`
it had just discarded. Any re-init with a browser connected would do it, so
saving admin config while a dashboard was open was enough to stop the whole
server, every module with it.

The stream handler now closes over this mount's Set rather than the module's
state: after teardown it deletes from a set nobody reads, which is harmless.
The same hazard existed anywhere a callback could outlive the mount — the
keepalive ping, a frame arriving from the listener mid-teardown, and the
/measure interval — and each is closed over or guarded now.

Reproduced first (open an SSE client, save config, watch it fall over) and
confirmed fixed against the same sequence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 16:06:47 -04:00
Waters ChurchandClaude Opus 5 46d44d494b Keep the banding caveat where the band plan is built
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 16:00:34 -04:00
Waters ChurchandClaude Opus 5 44fd0b10ba SPL Meter 0.3.0: bring the tiles to the interface rules
Rebasing onto main landed rules 5 to 11, which this module predates and
broke in three places.

Rule 5 — no explanatory text in a tile's gear: the Banding and Smoothing
fields each carried a paragraph. The Banding one said something true and
worth knowing, that below roughly 200 Hz the window length limits real
resolution however fine the setting, so it moves to the source where the
band plan is built rather than being lost. Option labels shortened with it.

Rule 11 — one control per action: the spectrogram offered its axis both as
a gear field and as a title-bar button. The button stays, since that is
what was asked for, and the field is gone. The setting still persists with
the tile; saveInstanceSettings keeps keys that no schema declares.

Rule 9 — title-bar controls are icons: the axis button was drawing a "⇆"
as a label. It is an inline SVG now, with the tooltip carrying the words
and naming the current direction rather than the action.

Rule 8 also asks that a tile can switch off what it draws, so the readout
gained a Caption toggle and both graphs gained Labels.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 16:00:17 -04:00
Waters ChurchandClaude Opus 5 543795f9fd Let the SPL readout fill its tile
The number was capped at 6rem, so a readout given half a wall stopped
growing at the size it reached in a small tile.

Removing the cap was not enough on its own. Sizing text off container units
means choosing a coefficient for some assumed number of characters, and the
value here is not a fixed width: the coefficient that fills a tile nicely
for "-45.9" pushes "-100.5" nine percent out through the side. Measured it
rather than guessed — the tile now sets a trial size, reads the width the
actual text wants, and scales to fit. That runs only when the tile size or
the length of the reading changes, not on every frame.

It now fills about 98% of the width wherever width is the limit and 92% of
the height wherever height is, at every tile size from 180x70 up to
1400x700, with no overflow on either axis. The CSS keeps a conservative
size for the first paint before the measurement has run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 15:56:27 -04:00
Waters ChurchandClaude Opus 5 d2d4207fe4 SPL Meter 0.2.0: one measurement, many views
Every control asked for here is a view choice, so none of them may reach
the capture child — two dashboards watching the same room must be able to
disagree about how to draw it without disturbing the measurement or each
other. That set the shape of the change: the child now sends everything
anyone might ask for, once, and each tile folds it down.

Averaging (was "Reading") is Fast, Slow, Inf and None, and the child
computes and sends all four every frame. Fast and Slow are the IEC time
constants, Inf is Leq since reset, None is the block with no time constant
at all. The admin-wide time constant is gone — it was never a property of
the room.

Banding is 1/3 through 1/48 octave. The wire always carries 1/48, and
because every banding offered divides 48 a coarser band is an exact sum of
finer ones in the power domain. Nothing is resampled and no tile's choice
is visible to another. The transform grew to 16384 points to have bins fine
enough to mean it; below roughly 200 Hz a 1/48 band is still narrower than
one bin, which the Banding help says out loud rather than pretending.

Each tile kind now carries its own settings, which is the fix for the
complaint that started this: the RTA was offering an alarm threshold and a
metric picker that did nothing to it. An entry's instanceSchema replaces the
module's, so a gear popover only holds controls that change that tile.

Also: frequency labels in three tiers that thin out as a tile narrows
instead of smearing, gridlines off by default on both graphs, RTA smoothing
as a damping factor on the drawn value only, a title-bar toggle to swap the
spectrogram's axes, and the threshold blurb removed.

Settings saved by 0.1.0 are mapped forward — a layout on a wall should not
start reading dashes because a field was renamed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 15:56:27 -04:00
Waters ChurchandClaude Opus 5 e90ae51495 Never build the capture tool on the event loop
The missing-binary fallback was a spawnSync, copied from the LTC listener
where the source is a third the size and builds in a few seconds. On the
production Mac this file took nearly two minutes, and spawnSync held the
Node event loop for every second of it: one module's optional helper froze
the entire dashboard, every other module with it, and then did it again
thirty seconds later on retry.

The build is now a plain spawn that reports "building" and calls start()
itself when it lands, so nothing waits on it. A failed build says so once
instead of spinning, and a build that never finishes is given up on after
five minutes.

The real lesson is the one in the comment: the binary should already be
there. It is built beside the app, or copied from any Mac of the same
architecture. Building on the machine that might be running a service is
the fallback, not the plan.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 15:56:27 -04:00
Waters ChurchandClaude Opus 5 188d1c878d SPL Meter module: measure the room, not just watch it
A sound level meter that lives in ProdDash rather than beside it. Takes an
audio input the way the Timers module's LTC reader does, and offers four
tiles: the level as a big number, per-channel bars with peak hold, a
third-octave RTA, and a scrolling spectrogram.

The measurement happens in spl-capture.swift, not in Node and not in the
browser. LTC gets away with piping raw samples upstream because the decode
is cheap and single-channel; sound level is filtering and FFTs over every
channel at the device's rate, so the child does the work and only the
answers cross the pipe. That costs nothing in dependencies — Accelerate
ships with macOS, and the whole thing builds in two seconds with a plain
swiftc, exactly like ltc-capture.

The weighting filters are the part worth checking rather than trusting, so
`spl-capture --selftest` prints them against the IEC 61672 table. A- and
C-weighting land within 0.15 dB from 31.5 Hz to 4 kHz and exactly 0 dB at
1 kHz. The top octave is where the bilinear transform runs out of room: at
48 kHz the 16 kHz point sits about 3 dB low even with the pole pair
prewarped, and at 96 kHz that falls to 0.6 dB. It is a rounding error on a
broadband number and a real limit all the same, which is why the selftest
prints both rates instead of a pass mark.

Cross-checked against REW on the same microphone: after removing the fixed
calibration offset the two agree to a standard deviation of 0.5 dB on live
room noise.

Uncalibrated is a state the module says out loud — every tile reads dBFS
and labels it, so nobody mistakes a relative number for sound pressure. The
/measure route averages the calibrator tone in the power domain and hands
back the offset to paste into settings; a module cannot write its own admin
config, so that last step stays manual on purpose.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 15:56:27 -04:00
michael 5025e12b71 Merge pull request 'Rules for a clean interface, and the modules brought to them' (#9) from claude/module-rules into main 2026-09-17 15:52:59 -04:00
michael 3009b39453 Merge pull request 'Twelve themes, and the Theme section folds away' (#8) from claude/themes into main 2026-09-17 15:52:24 -04:00
michael 41f64f3a13 Merge pull request 'Admin PIN: the fields say enough' (#7) from claude/admin-pin-trim into main 2026-09-17 15:51:34 -04:00
Waters ChurchandClaude Opus 5 12f0b20e5f Rules for a clean interface, and the modules brought to them
Seven rules join the four in the module guide, as rules 5 to 11: no
explanatory text in a tile's gear and no label over three words; server-side
settings in configSchema only; a tile setting changes that tile alone;
hide-toggles ungrouped when there are four or fewer and in a folded "Show"
group when there are five or more; title-bar controls are icons with
tooltips, never names; anything needing words belongs in the gear; and one
control per action, either place but not both.

Two passages said the opposite and now say the same thing — "keep labels
short and put the explanation there" is scoped to configSchema, and "icon
buttons, short labels" becomes icons with no labels at all. CLAUDE.md
carries the summary.

Then the modules. Nothing here changes a setting key or a default, so saved
layouts, named layouts and every tile already on a wall keep working; group
names, labels, help and fold state are presentation and are not stored.

- pco-plan: sixteen labels cut to three words or fewer ("Tint items by type
  (song / media / other)" is now "Tint by type"), "Show / hide" renamed
  "Show" and folded. Its one remaining help line stays by request: the top
  bar's template needs its separator syntax spelled out, which the variable
  chips beside it cannot convey, so rule 5 carves out template fields.
- propresenter-timers: the "Timers ▾" menu was the only named control left
  in any title bar. It is a stopwatch icon now, with the count riding
  alongside it while some timers are hidden — setLabel() writes over the
  button's contents, so the count needed ProdCom's badge treatment rather
  than a label. "Show" folds; the Colours help goes.
- propresenter-now-next: "Show" folds, in the manifest and in the Now
  entry's own copy.
- prodcom-transcript: "Show channel icons" loses the redundant verb.

slack and clock were already compliant and are untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 14:22:06 -04:00
Waters ChurchandClaude Opus 5 f72170b4e1 The folding section reads as a heading first
Theme's title was coming out at the normal weight — <summary> does not
inherit an <h1>'s boldness, so sitting it under .admin-h1 got the size,
colour and spacing but not the type. It now matches the other section
headings exactly.

The caret moved to the right of the words. A marker in front pushes the
heading out of line with every other one on the page; behind it, the section
still reads as "Theme" first and the caret only says there is more.

Written as the pattern rather than as Theme's own styling: any section that
folds is a <details class="admin-fold"> headed by a
<summary class="admin-h1 admin-fold-title">, and the whole row is the target.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 13:22:11 -04:00
Waters ChurchandClaude Opus 5 ea1eac1c28 Twelve themes, and the Theme section folds away
Seven more palettes: Midnight (indigo, violet), Moss (forest floor, lime),
Plum (aubergine, purple), Sepia (warm brown with a cool teal — Ember's
arrangement reversed), Blackout (true black for a dark room, where any glow
off the screen carries), Paper (the warm light one, next to Daylight's cool
white) and Iron, which has no colour of its own: its accent is near-white, so
the only hues on screen are a module's own and the red and amber that mean
something.

Each holds the line the first five set. Text on panel lands between 14.8:1
and 19.8:1, muted between 5.8:1 and 7.4:1, and every accent clears its own
theme's danger red and warning amber by more than Ember already does — the
narrowest of the new ones is Moss at 54 degrees of hue, against Ember's 18.

The Theme section now starts folded, wearing the same disclosure triangle as
a module's config groups. A building picks its palette once and then wants
the rest of the page, which was getting further down the screen with every
swatch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 13:16:47 -04:00
Waters ChurchandClaude Opus 5 ea8be2ac76 Admin PIN: the fields say enough
The paragraph under the PIN fields explained what the PIN covers and how to
clear it by hand — and only someone already past the PIN could read it, so
the recovery note was never where it was needed. Gone, with the dead style
and the element lookup that hung off it.

The live line under the heading stays: it is the only thing that says
whether admin is locked, and the only warning that a passcode in the
server's environment outranks whatever is set here.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 13:05:53 -04:00
michael 82e6386c73 Merge pull request 'Shell 1.6.0: bars that tuck away, and every edge resizes' (#6) from claude/tile-chrome into main 2026-09-17 12:44:07 -04:00
michael f5eb611872 Merge pull request 'README: the Slack module joins the list of included modules' (#5) from claude/readme-slack-module into main 2026-09-17 12:43:31 -04:00
michael d52cfcc48e Merge pull request 'Slack 1.2.1: a clearer Send tile, and a send target you can see' (#4) from claude/slack-send-target into main 2026-09-17 12:42:48 -04:00
michael 7d46cfbd8f Merge pull request 'ProPresenter 1.1.0: a Now tile, and switches for everything on it' (#3) from claude/propresenter-now into main 2026-09-17 12:41:53 -04:00
michael 7a5b57dc56 Merge pull request 'Admin sits behind a 6-digit PIN' (#1) from claude/admin-pin into main 2026-09-17 12:40:31 -04:00
Waters ChurchandClaude Opus 5 7f50fa0ba9 A pin on the title bar, and no more notch
Pointing at a tile's top edge already brings its bar back, which left the
notch doing half a job: it could still hide a bar, but hiding one tile at a
time stopped being the interesting question once the whole dashboard could
fold its bars at once. It is gone.

In its place, a pin beside each tile's label. Pinned, that tile keeps its
bar while auto-hide is on — for the one or two tiles whose controls are
wanted at a glance. It sits next to the label rather than out with the gear
and ✕ because it is about the bar, not about the tile's contents, and it
stays faint until the tile is pointed at or the pin is on, so a wall of
unpinned tiles is not a wall of pins.

Fullscreen keeps its own rule: every bar folds, pinned or not, because that
is a mode for watching. What it loses with the notch it gets back better —
the same hover at a tile's top edge peeks a bar there too, and now as an
overlay, so peeking no longer pushes the tile's content down and disturbs
the auto-fit. The peek timer the notch needed goes with it.

Per-tile `headHidden` gives way to `headPinned` in the layout, on disk and
on the server.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 12:04:59 -04:00
Waters ChurchandClaude Opus 5 68f0ba806d Tiles resize from anywhere, so nothing marks the spots
Every edge and both bottom corners resize now, so the little marks that used
to appear on hover were pointing at the whole rim. They are gone — corners,
edges and the seam pill alike — and the cursor over an edge is what says it
can be dragged, the way a window's own edges do it. The seam still shows
itself while it is actually being dragged, which says what is moving rather
than where you may push.

With nothing drawn, the grips could be made to cover the rim properly: the
top strip now runs corner to corner instead of stopping 24px short, the
sides run from it down to the bottom corners, and the bottom strip fills
between those. No dead spots left along an edge.

The side grips also stopped standing down at a seam. They only did so to
avoid stacking three marks in one place, and it cost real ground: a tile
taller than its neighbour lost its whole side, not just the part the seam
covers. The seam sits above them anyway, so it still wins where it exists
and the rest of the edge now works.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 11:52:45 -04:00
Waters ChurchandClaude Opus 5 8e579ecb34 Shell 1.6.0: bars that tuck away, and every edge resizes
Three things about arranging a dashboard.

**Auto-hide bars.** A new button left of ⛶ folds every tile's title bar away
at once, for a windowed screen that should read like a wall display.
Fullscreen already did this for watching; this is the windowed equivalent,
asked for by hand. It starts off and saves with the layout, so a booth's
named layout loads with the bars already tucked away.

**A hidden bar is not a gone bar.** Folded away — by that switch or by a
tile's own notch — the bar leaves the flow and parks just above its tile, so
the module keeps the whole body and nothing reflows as the bar comes and
goes. Point at the tile's top edge and it slides back in over the content,
where its buttons click and its width drags the tile exactly as before. A
dashboard can now be arranged with every bar out of the way, which is the
point of hiding them.

**Every edge resizes.** The top, left and right edges join the bottom one:
each moves only itself, so the tile grows into the space beside it while the
opposite edge stays put, stopping at a neighbour or at the module's own
minimum. Where two tiles meet, that boundary already belongs to the seam
pill between them — it moves both edges and leaves no gap — so the two
tiles' side marks step aside there rather than offer a second, different
control on the same pixels.

One fix underneath: saving a named layout was dropping each tile's variant,
title, minimum size and hidden-bar state, so a saved "Now" tile came back as
the full Now/Next card and a solo timer came back with a full tile's
settings. The layout file now carries them — and the new switch with them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 11:39:34 -04:00
Waters ChurchandClaude Opus 5 f0be37796b Slack 1.2.1: a clearer Send tile, and a send target you can see
The line above the message box said "Sending as Apollo Beach → #ops" with a
Lock button beside it. The box's own placeholder already reads "Message
#ops…" and the title bar already has a Lock, so both went. Quick replies
keeps its line: it has no placeholder, so that is the only place its target
is named.

The bigger thing behind it: until a transcript was clicked, a send went to
the first channel in the admin list whether or not that channel was on the
dashboard — so a board showing only #ops would quietly aim at #general. The
target now falls to the first configured channel whose transcript is
actually up, which with a single transcript is that one. Only when the page
shows no transcript at all does it fall back to the first configured
channel.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 19:58:57 -04:00
Waters ChurchandClaude Opus 5 52d700df3d ProPresenter 1.1.0: a Now tile, and switches for everything on it
The + picker now offers the module two ways. "Now / Next" is the card as it
was. "Now" is the live item on its own: the gradient comes off the card and
fills the tile edge to edge, the border, radius and box go, and the playlist
name and live dot float over the colour instead of sitting above it. A wall
of them reads as panels of colour rather than cards on a background.

Every part of the tile is now a switch in a "Show" group in the gear —
playlist, live status, the NOW and NEXT labels, slide count, progress bar,
the next list and its item tags. One or two words each, no descriptions. The
Now entry carries its own six, since the three Next ones have nothing to act
on there.

Two things the tile still insists on. Trouble overrides the switches: the
top row and the live chip come back the moment the feed drops, whatever is
switched off, because a tile that has stopped updating must never look like
one with nothing live. And at the Now tile's shortest sizes the floating top
row would sit on the title, so below the height it needs it goes — the
header dot and the title itself still say what is wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 19:39:55 -04:00
Waters ChurchandClaude Opus 5 7690ae1fad Merge main into the admin PIN branch
Both sides added to the same two places — the environment-variable list in
server.js and the settings table in the README — because the forge work and
the PIN work each documented a new setting. Everything from both is kept.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 18:57:27 -04:00
Waters ChurchandClaude Opus 5 6dabd9d8a1 Admin sits behind a 6-digit PIN
The passcode machinery existed but could only be set by hand in a config
file, so in practice every install left admin open to anyone on the
network. It is now a PIN you set from the admin page itself.

- Six digits, stored as a scrypt hash in this machine's proddash.json —
  never in the clear, since that file gets copied between machines.
- The unlock card takes the PIN and submits itself on the sixth digit.
  Five wrong tries from one address locks it out for 30 seconds, and the
  right PIN is refused during the lockout.
- Changing or turning off the PIN asks for the current one, so a browser
  left open on the admin page cannot be used to take the machine over.
  Whoever sets it keeps their session rather than being bounced to the
  card they just built.
- This is the shell's own PIN and guards /admin and the admin API only.
  Dashboards stay open, and it is unrelated to a module's PIN — Slack's
  4-8 digit send PIN still guards sending, separately and independently.
- Ways back in if it is forgotten: PRODDASH_PASSCODE in the environment
  (which overrides the PIN), or delete adminPin from proddash.json and
  restart. Both are in the README and on the page itself.
- The older free-text adminPasscode still works, so an existing install
  keeps running.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 10:46:41 -04:00
74 changed files with 15410 additions and 494 deletions
+3
View File
@@ -14,3 +14,6 @@ modules/propresenter-timers/ltc-capture
# the launcher's build output, and its cache of the Node runtime it embeds
launcher/macos/build/
launcher/macos/.cache/
# Compiled per-machine, source sits next to it (see spl-capture.swift).
modules/spl-meter/spl-capture
+8
View File
@@ -32,12 +32,20 @@ title-bar controls). The rules that matter most:
and bump the module's `version` on every change.
- Browsers never call upstream services directly; the module's server routes
proxy everything (no CORS, secrets stay server-side).
- **Keep the interface clean** (guide rules 5-11): no `help` and no label
over three words in a tile's gear; server-side settings in `configSchema`
only; a tile setting changes that tile alone; hide-toggles ungrouped when
there are four or fewer, in a folded **Show** group when there are five or
more; title-bar controls are icons with tooltips, never labels, and never
repeat something the gear already offers.
- Style with the shell's CSS variables only, scoped under
`[data-module="<id>"]`; survive upstream loss (reconnect + `setStatus`).
- Verify against the guide's testing section and resilience checklist. Mocks
for the existing upstreams: `node tools/prodcom-mock.js` (ProdCom) and
`node band-lineup-display/tmp/pp-mock.js 1599` (ProPresenter).
`node tools/slack-mock.js 24716` (Slack; run ProdDash with `SLACK_API_BASE=http://127.0.0.1:24716/api`).
`node tools/pco-band-mock.js 24710` (Planning Center for Band Lineup; run ProdDash with `BAND_LINEUP_API_BASE=http://127.0.0.1:24710`).
`node tools/ableset-mock.js 39071` (AbleSet over OSC/UDP; point the AbleSet module at `127.0.0.1:39071`; `--stopped`, `--no-live`, `--speed 4`).
## Reference code (read-only forks — don't develop these here)
+178 -24
View File
@@ -99,9 +99,18 @@ with this machine's shell settings — the same keys as the checked-in
| Key | Meaning |
| --- | --- |
| `port` | Port ProdDash serves on (default `24500`). The macOS launcher writes this one, so the port it is set to holds however ProdDash is started. |
| `adminPasscode` | If set, the admin page asks for this shared passcode. Leave `""` for none — it's a plain-HTTP LAN tool. |
| `adminPin` | The admin PIN, as a scrypt hash. **Set it in the admin page's Admin PIN section**, not by hand — 6 digits, and only the hash is stored. Absent means admin is open to anyone on the network. |
| `adminPasscode` | An older free-text passcode. Still honoured, so an existing install keeps working; new installs should use `adminPin`. |
| `forge` | Where updates and module installs are fetched from. Absent or `"github"` uses GitHub; a Gitea or Forgejo base URL such as `"http://10.3.8.90:3000"` uses a server of your own. Set it per machine in the data directory, alongside `repo`. |
| `theme` | The dashboard palette: `booth` (default), `harbor`, `graphite`, `ember` or `daylight`. The admin page's **Theme** section writes this one — see [Themes](#themes). |
| `theme` | The dashboard palette: `booth` (default), `harbor`, `graphite`, `ember`, `daylight`, `midnight`, `moss`, `plum`, `sepia`, `blackout`, `paper` or `iron`. The admin page's **Theme** section writes this one — see [Themes](#themes). |
**Locked out?** Delete `adminPin` from the data directory's `proddash.json`
and restart, or start the server with `PRODDASH_PASSCODE` set — that passcode
overrides the PIN and always gets you in.
Only `/admin` and the admin API are behind the PIN. Dashboards stay open, so a
wall display needs no PIN, and it is unrelated to a module's own PIN (Slack's
4–8 digit send PIN, say), which guards that module's actions only.
**Updating from your own git server.** ProdDash fetches one `tar.gz` of the
branch — nothing else — so any Gitea or Forgejo works. Point `forge` at its
@@ -131,12 +140,26 @@ ignored from then on.
The whole dashboard — every tile, on every browser — draws with one palette,
chosen in the admin page's **Theme** section and switched live: pick a swatch
and open dashboards change without a reload. Five presets ship: **Booth**
(the default dark, mint accent), **Harbor** (deep navy, cyan), **Graphite**
(neutral charcoal, electric blue), **Ember** (warm broadcast black, orange)
and **Daylight**, a light palette for a front-of-house desk in daytime. Each
keeps the status colours apart — the accent is never near the danger red or
the warning amber — and muted text readable in a dark booth. The choice is
and open dashboards change without a reload. The section starts folded —
a building picks its palette once — and holds twelve presets:
| | |
|---|---|
| **Booth** | the default dark, mint accent |
| **Harbor** | deep navy, cyan |
| **Graphite** | neutral charcoal, electric blue |
| **Ember** | warm broadcast black, orange |
| **Daylight** | a cool light palette, for a front-of-house desk in daytime |
| **Midnight** | indigo night, violet |
| **Moss** | forest floor, lime |
| **Plum** | aubergine, purple |
| **Sepia** | warm brown room, cool teal — Ember's arrangement reversed |
| **Blackout** | true black, cyan, for a dark room where any glow carries |
| **Paper** | the warm light one, indigo accent |
| **Iron** | no colour of its own: a near-white accent, so the only hues on screen are a module's own and the red and amber that mean something |
Each keeps the status colours apart — the accent is never near the danger red
or the warning amber — and muted text readable in a dark booth. The choice is
stored as `theme` in the data directory's `proddash.json` (table above), so
it holds across restarts and updates; a browser remembers the last theme it
saw and applies it before the server answers, so nothing flashes. Modules
@@ -177,7 +200,18 @@ below. Nothing is installed without someone clicking.
no local changes — otherwise the banner says why and you update with git).
A plain folder (no `.git`) has the repo archive unpacked over it; files
removed upstream are left behind but harmless. Settings and layouts are
never touched. **What changed** opens the commit comparison on GitHub.
never touched — nothing inside the data directory is written, even on an
install where that directory *is* the app's own `config/`. **What changed**
opens the commit comparison on the forge.
- **If an update goes wrong**: the download has to parse before anything is
swapped in, so a truncated or mangled `server.js` is refused with the
reason and the running copy is left exactly as it was. Past that, the copy
being replaced is set aside as `app.previous` next to the app folder, and
dropped once the new version has stayed up for ninety seconds — so that
folder existing means "the last update has not proven itself yet". The
macOS app watches for a version that will not stay up (four stops in two
minutes) and puts the old one back by itself, once, with a notification.
Running some other way, the way back is a rename: `mv app.previous app`.
- **Restarting**: after an update the server exits with code 75 and starts
its own replacement, which waits for the port to free up. If you supervise
ProdDash with your own launcher, set `PRODDASH_LAUNCHER=1` so the server
@@ -189,13 +223,17 @@ below. Nothing is installed without someone clicking.
- **+** — add any enabled module; multiple tiles of the same module are
fine (e.g. two transcripts filtered to different channels).
- Drag a tile by its **title bar** to move it; drag either **bottom
corner** to resize; **✕** removes it. Hover a tile and a small pill
appears on its **bottom edge** — drag it to change just the height. If
another tile sits directly below, the pill moves the shared edge instead,
trading rows between the two so the column keeps its total height. Tiles
sit flush — when two share a vertical edge, hover the seam and the same
kind of pill appears; drag it to trade width (macOS split-view style).
- Drag a tile by its **title bar** to move it; **✕** removes it.
- **Resize from any edge or bottom corner**, the way a window resizes:
nothing is drawn on a tile to mark the spots — the cursor over an edge is
what says it can be dragged. An edge moves only itself, so the tile grows
or shrinks into the space beside it while the opposite edge stays put,
stopping at a neighbour or at the module's own minimum size. Two
exceptions, both of which move a *shared* edge instead: with another tile
directly below, the bottom edge trades rows between the two so the column
keeps its total height; and where two tiles meet side by side, the seam
between them trades width (macOS split-view style), showing itself only
while you drag it.
- **Fullscreen** (the ⛶ button) is a viewing mode: the menu bar hides (its
green lip at the top-left brings it back, minus the Admin button), the
occupied columns stretch to the full width, and every column runs to the
@@ -205,9 +243,21 @@ below. Nothing is installed without someone clicking.
gap; alone in its columns it stays as it is. Nothing is saved — the layout
reverts when you leave fullscreen. A layout deeper than the screen keeps
its normal row height and scrolls.
- A tile's actions (menus, text size, clear…) live in its **title bar**;
the small **notch** on the bar's bottom edge hides/shows the whole bar
for a clean wall-display look. The menu bar's handle is the **ProdDash
- A tile's actions (menus, text size, clear…) live in its **title bar**.
- **Auto-hide bars** (the button left of ⛶) folds every title bar away, for
a windowed screen that should read like a wall display. A folded bar is
not a gone bar: point at the tile's top edge and it slides back in over
the content, where its buttons click and its width drags the tile exactly
as before — so a dashboard can be arranged with every bar out of the way.
The switch is off on a fresh dashboard and saves with the layout —
including a named layout on the server, so a booth loads its screen with
the bars already tucked away. Fullscreen folds every bar regardless, and
the same hover brings one back there too.
- The **pin** beside a tile's title keeps *that* tile's bar showing while
auto-hide is on — for the one or two tiles whose controls are wanted at
a glance. It turns the accent colour when it is on and saves with the
layout. Fullscreen still folds a pinned bar with the rest.
- The menu bar's own handle is the **ProdDash
name itself**, wrapped in a translucent green pill at the left — click it
to hide the bar; the slim green lip it leaves at the top-left edge brings
the bar back. It stays at the left so it never sits on top of a tile's
@@ -216,7 +266,21 @@ below. Nothing is installed without someone clicking.
display options) — these belong to this browser's layout, not the server.
- The **grid icon** — save the current arrangement to the server under a
name, load a named layout (it becomes a local copy — browsers are never
linked), or reset this browser's dashboard.
linked), or reset this browser's dashboard. Loading says what it did —
*Loaded "FOH": 9 tiles, 2 not shown — Service, #ops aren't offered right
now* — with **Undo** in the message to get back the arrangement you had.
A tile whose module or picker entry isn't offered at the moment keeps its
place and shows nothing, then appears when it is; it is never replaced by
the module's default tile. Saving over an existing name asks first, and
the server keeps the copy it replaced: **Restore previous** in Admin →
Saved layouts swaps it back (and swapping again undoes that). The menu's
**Grid Size** stepper sets how many columns this browser cuts the board into —
8 to 24, 12 by default. Finer lets tiles be smaller so more fit across (a
4K wall), coarser suits a small screen read close up; row height follows,
so tiles keep their shape and simply change size. Going coarser, a tile
that no longer fits where it was moves to the first free spot rather than
onto another tile. It saves with the layout, so a named layout comes back
at the density it was arranged on.
- Every tile has a **status dot**: green = live, amber = connecting,
red = upstream unreachable (hover it for details). Tiles reconnect
automatically.
@@ -231,7 +295,13 @@ below. Nothing is installed without someone clicking.
Tile settings: channel icons, direction and timestamps.
- **ProPresenter** — what's live and what's next, with slide progress,
driven by the shared `propresenter-core` client (ProPresenter 7/20).
The + picker offers two tiles: **Now / Next**, the full card, and **Now**,
the live item alone with the gradient filling the tile edge to edge — a
wall panel that says one thing.
Admin config: ProPresenter endpoint (host : port), password.
Tile settings: a **Show** group of switches for the playlist name, live
status, NOW and NEXT labels, slide count, progress bar, the next list and
its item tags, plus tidy titles.
- **Timers** — live ProPresenter timers (countdown, countdown-to-time,
elapsed) and LTC timecode as auto-sized cards. The + picker lists every
discovered timer (and the LTC card) as its own tile, or add "All timers"
@@ -253,18 +323,48 @@ below. Nothing is installed without someone clicking.
session (Start ProdDash.command) and approve the one-time prompt; a server
started over SSH or by bare launchd silently captures zeros. (Engine
self-test: `node modules/propresenter-timers/ltc.selftest.js`.)
- **PCO Plan** — the order of service from Planning Center Services: every
- **PCO Plan** — Planning Center Services, as two tiles in the + picker:
**Plan** (the order of service) and **Teams** (who is scheduled).
**Plan** shows every
plan item with its scheduled start time, length, type, song key,
description and item notes. When the ProPresenter module is running it
follows that module's live item, highlights the matching plan item, dims
what's done and shows the elapsed vs planned runtime and how far
ahead/behind the service is. Admin config is the connection: Planning
ahead/behind the service is. Items are matched by name — a document named
like the Planning Center item or its song, tags and all. The message is
the exception: a sermon's document is named after the sermon, so a live
document that reads like the plan itself — its date code, series title
and part, as in `260927 Where is Your Faith? - Part 6` — is taken as the
message and lands on the plan's message item (an item titled Message,
Sermon or Teaching, else the first item under such a header). Admin
config is the connection: Planning
Center credentials (Personal Access Token app ID + secret, or an OAuth
token), the service type (a list grouped by your Planning Center folders)
and an optional pinned plan. Everything about the display is per tile
(gear menu): the top-bar text (placeholders such as
`{series} • {part} | {serviceType} • {date}`), colors, text size, and a
show/hide checklist for every detail.
With an **AbleSet** module installed and configured, the Plan tile also
follows the band: while AbleSet plays a song that is the item on screen,
that item's background fills as the song goes, and its sections slide past
in a strip at the bottom right of the item, the one playing filling in
turn. Both are switches in the tile's gear (**Song progress**, **Song
sections**), and both are simply absent when there is no AbleSet module, it
is switched off, or it has no host — nothing to turn off and nothing to
explain.
**Teams** shows the same plan's team and position assignments — each team
as a band of its people, with their photo (fetched through ProdDash, never
by the browser; initials when Planning Center has none) and a dot for
confirmed, unconfirmed or declined. Its gear menu picks which teams and
which positions appear, groups people under their position or lists them
plainly, and sets the colours: one for the team headers, or **Tint teams**
to give each team its own, optionally carried into the rows. Teams nobody
has signed up for are hidden until you ask for them — that list comes from
the service type, since Planning Center only returns a team once somebody
is on it.
- **Slack** — live transcripts of this location's Slack channels, plus
PIN-protected sending as the location. The + picker lists one transcript
tile per configured channel, titled `#channel`, and two send surfaces (one
@@ -288,6 +388,57 @@ below. Nothing is installed without someone clicking.
as `Label | Message` — add `| #channel` to bind one to a channel — and up
to eight quick emojis).
Tile settings: avatars, timestamps, names and channel notices.
- **Resi Cues** — how long until the next Resi cue point, for a campus
running video from another site. The tile is one number, as large as it
will go: the countdown to the next cue, its name above it, and the playhead
and the cue just passed underneath. It also offers that countdown and the
playhead to the **Timers** module, so they can sit among the ProPresenter
timers instead of in a tile of their own.
Both the cue list and the decoder's position come from Resi's cloud rather
than the decoder — the decoder reports upstream and central.resi.io hands it
back — so nothing is installed at the decoder end. Resi republishes a
position only every few seconds and each reading is already stale, so the
playhead is estimated between readings rather than repeated; a countdown
built straight from Resi's number sits seconds behind and moves in lurches.
Admin config: Resi login and password, which decoder to follow (the list is
read from the account), and a folded **Timing** group for the poll
intervals and a position trim.
Tile settings: cue name, previous cue, playhead, cue list.
- **Band Lineup** — the backstage stage board: everyone on stage in their mic
slot with photo, name and mic/pack label, on one shared board that every
screen sees the same way — whoever edits it changes it everywhere, over SSE.
A photo library fills it: point the module at a Google Drive folder shared
"anyone with the link" (file name → person's name) or at a folder on the
ProdDash machine, and photos added or removed there follow. **Edit** in the
title bar opens that library — drag a photo onto a slot, drag between slots
to swap, rename or clear. Planning Center is optional auto-fill on top, not
the source of truth: **Sync** reads the upcoming plan's team members and
drops each into the slot matching their position, filling only slots nobody
placed by hand, so a guest pinned on Thursday survives Sunday's sync.
Birthdays in the service week (Wednesday→Tuesday) bring a gold glow and
raining confetti, and a Choir button adds the extra spot for the weeks there
is one. Admin config: Planning Center credentials, service type and plan, the
teams to include, the stage slots (one mic/pack label per line, in stage
order), default columns, and the photo folder. Tile settings: parallax,
names, mic labels, and birthday confetti with its intensity and a test
picker — columns are − / + in the title bar.
- **Service Times** — every campus's Sunday service times, read from the
church website and re-read on a timer, so the board follows the site when
the times change through the year. Any service can be marked for
production — issue, replay, or do not use — with a note, and a campus
taking resi records which of the origin's services it is playing. Marking
a broadcast service "do not use" flags every campus riding on it, which is
the question the board exists to answer. Marks are shared by every tile
and every browser, survive a restart, and expire on their own so last
week's never greet a new Sunday. The + picker offers the whole board or a
single campus.
Admin config is in four groups: **Website** (address, which campuses to
follow, refresh interval), **Broadcast** (the campuses the broadcast comes
from, and each other campus's resi source), **Manual campuses** (a stopgap
for a campus the site has not published yet — the website takes over as
soon as it does) and **Marks** (how long a mark lives).
Tile settings: campuses, card or list layout, and a **Show** group for the
day, role, resi source, campuses fed, notes and the updated line.
- **Clock** — a big booth clock; also the smallest possible module and the
reference for module authors.
@@ -299,8 +450,11 @@ timers + timecode on `127.0.0.1:1600`), `node tools/pco-mock.js`
(Planning Center Services on `127.0.0.1:24700` — run ProdDash with
`PCO_PLAN_API_BASE=http://127.0.0.1:24700`) and
`node tools/slack-mock.js 24716` (the Slack Web API on `127.0.0.1:24716` —
run ProdDash with `SLACK_API_BASE=http://127.0.0.1:24716/api`). See the
testing section of the [module guide](docs/MODULE-GUIDE.md).
run ProdDash with `SLACK_API_BASE=http://127.0.0.1:24716/api`) and
`node tools/pco-band-mock.js 24710` (Planning Center for the Band Lineup
board — a plan, its team members, birthdays and photos — run ProdDash with
`BAND_LINEUP_API_BASE=http://127.0.0.1:24710`). See the testing section of
the [module guide](docs/MODULE-GUIDE.md).
## Install as a desktop web app
+28
View File
@@ -57,9 +57,37 @@
<option value="">Choose service type</option>
</select>
<button type="button" class="btn btn-small" id="btn-pco-sync">Sync Upcoming</button>
<button type="button" class="btn btn-small" id="btn-pco-test-birthdays">Test Birthdays</button>
<button type="button" class="btn btn-small" id="btn-pco-disconnect">Disconnect</button>
</div>
<div class="pco-status" id="pco-status">Planning Center is not connected.</div>
<div class="pco-status pco-birthday-result" id="pco-birthday-result"></div>
<div class="bday-block">
<div class="bday-head">
<span class="bday-title">Birthday Mode 🎂</span>
<label class="bday-switch">
<input type="checkbox" id="bday-enabled" />
<span class="bday-switch-label">On</span>
</label>
</div>
<div class="bday-controls" id="bday-controls">
<div class="bday-line">
<span class="bday-line-label">Intensity</span>
<div class="seg-inline" id="bday-intensity" role="group" aria-label="Birthday intensity">
<button type="button" data-int="subtle">Subtle</button>
<button type="button" data-int="full">Full</button>
</div>
</div>
<div class="bday-line">
<span class="bday-line-label">Force on <em>(test)</em></span>
<select id="bday-test" class="pco-select bday-test-select" aria-label="Force birthday on a person for testing">
<option value="">Off</option>
</select>
</div>
<div class="bday-hint">Birthdays celebrate for the whole service week (Wednesday→Tuesday). Force is for testing only — it clears when the app restarts.</div>
</div>
</div>
<div class="pco-position-builder">
<select id="pco-position-option" class="pco-select" aria-label="Planning Center position">
<option value="">Choose position</option>
+167 -1
View File
@@ -238,6 +238,47 @@ async function pcoRequestJson(target, credentials, searchParams) {
return payload || { data: [] };
}
/**
* Like pcoRequestJson but never throws on an HTTP error — returns the status so callers can tell
* "no access" (401/403) apart from "no such record" (404) apart from success. Used by the People
* birthdate probe/fetch, where the whole point is to report what the token is actually allowed to do.
*/
async function pcoFetchStatus(target, credentials, searchParams) {
const url = buildPcoUrl(target, searchParams);
const response = await fetch(url, {
headers: {
Accept: 'application/json',
Authorization: pcoAuthHeader(credentials),
'User-Agent': pcoUserAgent(),
},
});
const text = await response.text();
let payload = null;
try {
payload = text ? JSON.parse(text) : null;
} catch {
payload = null;
}
return { status: response.status, ok: response.ok, payload };
}
/**
* Fetch one person's birthday from the People API as "MM-DD" (year discarded). Services and People
* share the same person id, so the Services person id we already store doubles as the People id.
* Returns { status, birthday, fieldPresent } — birthday '' when the field is null/absent.
*/
async function pcoFetchBirthday(personId, credentials) {
if (!personId) return { status: 0, birthday: '', fieldPresent: false };
const { status, ok, payload } = await pcoFetchStatus(
`/people/v2/people/${encodeURIComponent(personId)}`,
credentials,
{ 'fields[Person]': 'birthdate' },
);
if (!ok) return { status, birthday: '', fieldPresent: false };
const attrs = payload?.data?.attributes || {};
return { status, birthday: normalizeBirthdayMmdd(attrs.birthdate), fieldPresent: 'birthdate' in attrs };
}
async function pcoFetchAll(target, credentials, searchParams) {
let nextUrl = buildPcoUrl(target, searchParams).toString();
const data = [];
@@ -275,6 +316,15 @@ function emptyState() {
pcoDisplayPositions: [],
proPresenter: { enabled: false, host: '', port: 0, playlistUuid: '', playlistName: '' },
displayServer: { enabled: false, port: DEFAULT_DISPLAY_PORT },
birthdayMode: { enabled: true, intensity: 'subtle' },
};
}
/** Birthday Mode display settings (the per-person test override is NOT persisted — it lives only in the renderer). */
function normalizeBirthdayMode(entry) {
return {
enabled: entry?.enabled === undefined ? true : Boolean(entry.enabled),
intensity: entry?.intensity === 'full' ? 'full' : 'subtle',
};
}
@@ -308,9 +358,26 @@ function normalizeSavedLibraryPerson(person) {
source: person?.source === 'pco' ? 'pco' : 'local',
pcoPersonId: typeof person?.pcoPersonId === 'string' ? person.pcoPersonId : '',
pcoPlanPersonId: typeof person?.pcoPlanPersonId === 'string' ? person.pcoPlanPersonId : '',
// "MM-DD" only — we deliberately never persist the birth year (month + day is all
// Birthday Mode needs, and it keeps a volunteer's age off this machine). '' = none on file.
birthday: normalizeBirthdayMmdd(person?.birthday),
};
}
/** Coerce a Planning Center birthdate ("YYYY-MM-DD", or an already-trimmed "MM-DD") to "MM-DD", or '' if absent/invalid. */
function normalizeBirthdayMmdd(raw) {
const s = String(raw || '').trim();
const full = s.match(/^\d{4}-(\d{2})-(\d{2})$/); // PCO People birthdate shape
if (full) return `${full[1]}-${full[2]}`;
const md = s.match(/^(\d{2})-(\d{2})$/);
if (md) {
const mm = Number(md[1]);
const dd = Number(md[2]);
if (mm >= 1 && mm <= 12 && dd >= 1 && dd <= 31) return `${md[1]}-${md[2]}`;
}
return '';
}
function normalizeTeamName(value) {
return String(value || '').trim().toLowerCase();
}
@@ -627,6 +694,20 @@ async function syncUpcomingPcoPlan(payload) {
return a.displayName.localeCompare(b.displayName, undefined, { sensitivity: 'base' });
});
// Pull each scheduled person's birthday from the People API (best-effort: a blocked token or a
// person with no date on file just yields '' and never fails the sync). Fetched once per unique
// person so a member in two positions isn't queried twice.
const birthdayByPerson = new Map();
for (const member of scheduledMembers) {
if (!member.personId || birthdayByPerson.has(member.personId)) continue;
try {
const { birthday } = await pcoFetchBirthday(member.personId, credentials);
birthdayByPerson.set(member.personId, birthday || '');
} catch {
birthdayByPerson.set(member.personId, '');
}
}
const oldPcoFiles = new Set(
(Array.isArray(baseState.library) ? baseState.library : [])
.filter((entry) => entry?.source === 'pco' && typeof entry?.fileName === 'string')
@@ -652,6 +733,7 @@ async function syncUpcomingPcoPlan(payload) {
source: 'pco',
pcoPersonId: member.personId,
pcoPlanPersonId: member.planPersonId,
birthday: birthdayByPerson.get(member.personId) || '',
});
}
@@ -731,6 +813,7 @@ async function syncUpcomingPcoPlan(payload) {
const atWriteTime = await loadStateRaw();
nextState.proPresenter = normalizeProPresenterConfig(atWriteTime.proPresenter);
nextState.displayServer = normalizeDisplayServerConfig(atWriteTime.displayServer);
nextState.birthdayMode = normalizeBirthdayMode(atWriteTime.birthdayMode);
await saveStateRaw(nextState);
for (const fileName of oldPcoFiles) {
@@ -1222,6 +1305,7 @@ function migrateState(data) {
pcoDisplayPositions: normalizePcoDisplayPositions(data.pcoDisplayPositions),
proPresenter: normalizeProPresenterConfig(data.proPresenter),
displayServer: normalizeDisplayServerConfig(data.displayServer),
birthdayMode: normalizeBirthdayMode(data.birthdayMode),
lineup: data.lineup.map((e) => {
if (!e || typeof e !== 'object') return { personId: '', label: '' };
return {
@@ -1432,7 +1516,10 @@ ipcMain.handle('save-state', async (_e, payload) => {
// The renderer never edits this (it is changed through the display-* IPC handlers), so
// always carry the stored value forward rather than letting a save blank it out.
const displayServer = normalizeDisplayServerConfig(existing.displayServer);
await saveStateRaw({ library, layout, parallaxEnabled, slotLabels, slotNames, lineup, pcoServiceTypeId, pcoDisplayPositions, proPresenter, displayServer });
const birthdayMode = payload?.birthdayMode
? normalizeBirthdayMode(payload.birthdayMode)
: normalizeBirthdayMode(existing.birthdayMode);
await saveStateRaw({ library, layout, parallaxEnabled, slotLabels, slotNames, lineup, pcoServiceTypeId, pcoDisplayPositions, proPresenter, displayServer, birthdayMode });
return true;
});
@@ -1511,6 +1598,85 @@ ipcMain.handle('pco-sync-upcoming-plan', async (_e, payload) => {
return syncUpcomingPcoPlan(payload);
});
/**
* Diagnostic behind the "Test Birthdays" button: does this Personal Access Token actually reach the
* People API and read birthdates, and how many synced band members have one on file. Read-only.
*/
ipcMain.handle('pco-test-birthdays', async () => {
const credentials = await loadPcoCredentials();
if (!credentials) return { connected: false };
// 1. Can the token read the People API at all?
let probe;
try {
probe = await pcoFetchStatus('/people/v2/people', credentials, { per_page: 1, 'fields[Person]': 'birthdate' });
} catch (err) {
return { connected: true, canRead: false, reason: 'network', detail: err instanceof Error ? err.message : String(err) };
}
if (!probe.ok) {
const detail =
probe.payload?.errors?.map((e) => e.detail || e.title).filter(Boolean).join(' | ') ||
`${probe.status}`;
return { connected: true, canRead: false, status: probe.status, detail };
}
const sampleAttrs = probe.payload?.data?.[0]?.attributes || null;
const fieldExposed = sampleAttrs ? 'birthdate' in sampleAttrs : true;
// 2. Coverage across the people we've actually synced (unique by person id).
const state = await loadStateRaw();
const seen = new Set();
const targets = [];
for (const p of Array.isArray(state.library) ? state.library : []) {
if (p?.source !== 'pco' || !p?.pcoPersonId || seen.has(p.pcoPersonId)) continue;
seen.add(p.pcoPersonId);
targets.push(p);
}
let withBirthday = 0;
let notFound = 0;
let errors = 0;
const found = [];
for (const p of targets) {
let r;
try {
r = await pcoFetchBirthday(p.pcoPersonId, credentials);
} catch {
errors += 1;
continue;
}
if (r.status === 404) { notFound += 1; continue; }
if (r.status && r.status >= 400) { errors += 1; continue; }
if (r.birthday) {
withBirthday += 1;
found.push({ name: String(p.lastName || p.originalName || 'Unknown').trim() || 'Unknown', mmdd: r.birthday });
}
}
// Soonest upcoming birthday, for a concrete "it works" line.
const today = new Date();
const daysUntil = (mmdd) => {
const [mm, dd] = mmdd.split('-').map(Number);
let next = new Date(today.getFullYear(), mm - 1, dd);
const midnight = new Date(today.getFullYear(), today.getMonth(), today.getDate());
if (next < midnight) next = new Date(today.getFullYear() + 1, mm - 1, dd);
return Math.round((next - midnight) / 86400000);
};
const sortedFound = [...found].sort((a, b) => daysUntil(a.mmdd) - daysUntil(b.mmdd));
const nextUp = sortedFound[0] ? { ...sortedFound[0], inDays: daysUntil(sortedFound[0].mmdd) } : null;
return {
connected: true,
canRead: true,
fieldExposed,
total: targets.length,
withBirthday,
notFound,
errors,
found: sortedFound.slice(0, 8),
nextUp,
};
});
ipcMain.handle('pp-status', async () => {
return {
enabled: ppConfig.enabled,
+2 -2
View File
@@ -1,8 +1,8 @@
{
"name": "band-lineup-display",
"productName": "Band Lineup",
"version": "1.3.6",
"buildNumber": "92",
"version": "1.3.10",
"buildNumber": "96",
"description": "Stage lineup photos with mic/pack labels",
"main": "main.js",
"scripts": {
+1
View File
@@ -14,6 +14,7 @@ contextBridge.exposeInMainWorld('lineup', {
pcoServiceTypes: () => ipcRenderer.invoke('pco-service-types'),
pcoPositionOptions: (serviceTypeId) => ipcRenderer.invoke('pco-position-options', serviceTypeId),
pcoSyncUpcomingPlan: (payload) => ipcRenderer.invoke('pco-sync-upcoming-plan', payload),
pcoTestBirthdays: () => ipcRenderer.invoke('pco-test-birthdays'),
onMenuAddPhotos: (cb) => {
ipcRenderer.on('menu-add-photos', () => cb());
},
+273 -1
View File
@@ -3,7 +3,7 @@ if (window.__bandLineupRendererLoaded) {
} else {
window.__bandLineupRendererLoaded = true;
/**
* @typedef {{ id: string, fileName: string, originalName: string, lastLabel: string, lastName: string, source?: string, pcoPersonId?: string, pcoPlanPersonId?: string }} LibraryPerson
* @typedef {{ id: string, fileName: string, originalName: string, lastLabel: string, lastName: string, source?: string, pcoPersonId?: string, pcoPlanPersonId?: string, birthday?: string }} LibraryPerson
* @typedef {{ personId: string, label: string }} StageSlot
* @typedef {{ teamName: string, positionName: string, count: number }} PcoDisplayPosition
*/
@@ -27,6 +27,10 @@ let pcoDisplayPositions = [];
let pcoPositionOptions = [];
let slotLabelMemory = [];
let slotNameMemory = [];
/** Birthday Mode display settings (persisted). */
let birthdayMode = { enabled: true, intensity: 'subtle' };
/** Person id forced into Birthday Mode for testing — in-memory only, never saved, clears on restart. */
let birthdayTestPersonId = '';
/** @type {StageSlot[]} */
let stageSlots = createEmptySlots();
const imageUrlCache = new Map();
@@ -65,7 +69,13 @@ const btnApplyLayout = document.getElementById('btn-apply-layout');
const btnToggleParallax = document.getElementById('btn-toggle-parallax');
const btnPcoConnect = document.getElementById('btn-pco-connect');
const btnPcoSync = document.getElementById('btn-pco-sync');
const btnPcoTestBirthdays = document.getElementById('btn-pco-test-birthdays');
const btnPcoDisconnect = document.getElementById('btn-pco-disconnect');
const pcoBirthdayResult = document.getElementById('pco-birthday-result');
const bdayEnabled = document.getElementById('bday-enabled');
const bdayIntensity = document.getElementById('bday-intensity');
const bdayControls = document.getElementById('bday-controls');
const bdayTestSelect = document.getElementById('bday-test');
const btnPcoAddPosition = document.getElementById('btn-pco-add-position');
const inputLayoutCols = document.getElementById('layout-cols');
const inputLayoutRows = document.getElementById('layout-rows');
@@ -244,6 +254,7 @@ function setPcoStatus(message, isError = false) {
function setPcoControlsEnabled(enabled) {
btnPcoConnect.disabled = !enabled;
btnPcoSync.disabled = !enabled;
btnPcoTestBirthdays.disabled = !enabled;
btnPcoDisconnect.disabled = !enabled;
btnPcoAddPosition.disabled = !enabled;
pcoServiceTypeSelect.disabled = !enabled;
@@ -427,6 +438,9 @@ function applyLoadedState(data) {
source: person?.source === 'pco' ? 'pco' : 'local',
pcoPersonId: typeof person?.pcoPersonId === 'string' ? person.pcoPersonId : '',
pcoPlanPersonId: typeof person?.pcoPlanPersonId === 'string' ? person.pcoPlanPersonId : '',
// Carried through so a routine save doesn't wipe birthdays a PCO sync stored (main.js
// re-validates the "MM-DD" shape on write); Birthday Mode reads this.
birthday: typeof person?.birthday === 'string' ? person.birthday : '',
}))
: [];
const savedColumns = Number.parseInt(String(data?.layout?.columns ?? DEFAULT_COLUMNS), 10);
@@ -451,6 +465,11 @@ function applyLoadedState(data) {
pcoServiceTypeSelect.value = pcoServiceTypeId;
renderPcoDisplayPositions();
stageSlots = normalizeLineup(data.lineup, getStageSlotCount());
birthdayMode = {
enabled: data?.birthdayMode?.enabled === undefined ? true : Boolean(data.birthdayMode.enabled),
intensity: data?.birthdayMode?.intensity === 'full' ? 'full' : 'subtle',
};
syncBirthdayControls();
}
function updateSlotSizeReadout() {
@@ -528,6 +547,7 @@ function scheduleSave() {
slotLabels: slotLabelMemory,
slotNames: slotNameMemory,
lineup: stageSlots,
birthdayMode,
});
}, 250);
}
@@ -950,6 +970,132 @@ function parallaxMotionVars(seedText) {
};
}
/* ---------------- Birthday Mode ---------------- */
const BIRTHDAY_COLORS = ['#f5c451', '#ff6b81', '#4fd1c5', '#a78bfa', '#ffffff'];
/** Live confetti canvases; a single rAF loop drives them and prunes any whose tile was rebuilt. */
const birthdayCanvases = new Set();
let birthdayRaf = null;
/**
* The 7 "MM-DD" dates of the current celebration week, which runs Wednesday→Tuesday. A birthday
* anywhere in this window celebrates all week (so it's already up for the weekend services).
* Cached per week; birthdayTick() re-renders the stage when the window rolls over to a new Wednesday.
*/
let birthdayWeekCache = { key: '', set: null };
function birthdayWeekSet() {
const now = new Date();
const daysSinceWed = (now.getDay() - 3 + 7) % 7; // getDay: Sun=0…Wed=3…Sat=6
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysSinceWed);
const key = `${start.getFullYear()}-${start.getMonth()}-${start.getDate()}`;
if (birthdayWeekCache.key === key && birthdayWeekCache.set) return birthdayWeekCache.set;
const set = new Set();
for (let i = 0; i < 7; i += 1) {
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
set.add(`${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`);
}
birthdayWeekCache = { key, set };
return set;
}
/** Is this person celebrating this week — their birthday falls in the current Wed→Tue window, or they're the test override. */
function isBirthdayActive(person) {
if (!birthdayMode.enabled || !person) return false;
if (birthdayTestPersonId && person.id === birthdayTestPersonId) return true;
return typeof person.birthday === 'string' && person.birthday.length === 5 && birthdayWeekSet().has(person.birthday);
}
/** Re-render the stage when the celebration week rolls over (the app can stay open for days). */
function birthdayTick() {
const before = birthdayWeekCache.key;
birthdayWeekSet();
if (before && birthdayWeekCache.key !== before) void renderStage();
}
setInterval(birthdayTick, 15 * 60 * 1000);
function birthdayMakeParticle(w, h, intensity, seedY) {
const ribbon = Math.random() < 0.55;
return {
x: Math.random() * w,
y: seedY != null ? seedY : Math.random() * h,
w: ribbon ? 4 + Math.random() * 4 : 5 + Math.random() * 5,
h: ribbon ? 9 + Math.random() * 8 : 0,
ribbon,
color: BIRTHDAY_COLORS[(Math.random() * BIRTHDAY_COLORS.length) | 0],
rot: Math.random() * Math.PI * 2,
vr: -0.14 + Math.random() * 0.28,
sway: 0.6 + Math.random() * 1.1,
phase: Math.random() * Math.PI * 2,
vy: (intensity === 'subtle' ? 0.6 : 1.0) * (1.1 + Math.random() * 1.5),
};
}
function birthdaySeedCanvas(c, w, h) {
const base = c._intensity === 'subtle' ? 26 : 64;
const count = Math.max(10, Math.round((base * (w * h)) / (300 * 500)));
c._parts = Array.from({ length: count }, () => birthdayMakeParticle(w, h, c._intensity));
}
// The confetti ALWAYS animates — this is a celebration effect, so it intentionally ignores the
// OS "reduced motion" setting (which was freezing the confetti mid-fall on the backstage machine).
function birthdayStepCanvas(c) {
const w = c.clientWidth;
const h = c.clientHeight;
if (!w || !h) return; // not laid out yet — try again next frame
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (c._w !== w || c._h !== h) {
c.width = w * dpr;
c.height = h * dpr;
c._ctx = c.getContext('2d');
c._ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
c._w = w;
c._h = h;
birthdaySeedCanvas(c, w, h);
}
const ctx = c._ctx;
ctx.clearRect(0, 0, w, h);
for (const p of c._parts) {
p.phase += 0.03;
p.y += p.vy;
p.x += Math.sin(p.phase) * p.sway;
p.rot += p.vr;
if (p.y > h + 16) Object.assign(p, birthdayMakeParticle(w, h, c._intensity, -16));
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(p.rot);
ctx.fillStyle = p.color;
if (p.ribbon) ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
else { ctx.beginPath(); ctx.arc(0, 0, p.w / 2, 0, Math.PI * 2); ctx.fill(); }
ctx.restore();
}
}
function birthdayLoop() {
for (const c of [...birthdayCanvases]) {
if (!c.isConnected) { birthdayCanvases.delete(c); continue; }
birthdayStepCanvas(c);
}
birthdayRaf = birthdayCanvases.size ? window.requestAnimationFrame(birthdayLoop) : null;
}
function birthdayRegisterCanvas(canvas, intensity) {
canvas._intensity = intensity;
birthdayCanvases.add(canvas);
if (!birthdayRaf) birthdayRaf = window.requestAnimationFrame(birthdayLoop);
}
/** Rain confetti (plus a soft gold glow) onto a tile whose person is celebrating. */
function applyBirthdayEffects(tile, photoArea) {
const intensity = birthdayMode.intensity === 'full' ? 'full' : 'subtle';
tile.classList.add('birthday', `birthday-${intensity}`);
const confetti = document.createElement('canvas');
confetti.className = 'birthday-confetti';
confetti.setAttribute('aria-hidden', 'true');
photoArea.appendChild(confetti);
birthdayRegisterCanvas(confetti, intensity);
}
function createPhotoTile(person, href, slotIndex, parallaxAssets) {
void parallaxAssets;
const tile = document.createElement('article');
@@ -1002,6 +1148,7 @@ function createPhotoTile(person, href, slotIndex, parallaxAssets) {
photoArea.appendChild(nameBadge);
photoArea.appendChild(removeBtn);
if (isBirthdayActive(person)) applyBirthdayEffects(tile, photoArea);
tile.appendChild(photoArea);
return tile;
}
@@ -1156,6 +1303,7 @@ async function renderLibrary() {
async function renderAll() {
await renderStage();
await renderLibrary();
renderBirthdayTestOptions();
}
async function importNewPeople(added) {
@@ -1170,6 +1318,7 @@ async function importNewPeople(added) {
source: 'local',
pcoPersonId: '',
pcoPlanPersonId: '',
birthday: '',
});
}
await renderLibrary();
@@ -1232,6 +1381,97 @@ async function syncUpcomingPlanFromPco() {
}
}
const BIRTHDAY_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function formatBirthdayMmdd(mmdd) {
const parts = String(mmdd || '').split('-');
const mm = Number(parts[0]);
const dd = Number(parts[1]);
if (!(mm >= 1 && mm <= 12) || !(dd >= 1 && dd <= 31)) return '';
return `${BIRTHDAY_MONTHS[mm - 1]} ${dd}`;
}
function setPcoBirthdayResult(message, tone) {
if (!pcoBirthdayResult) return;
pcoBirthdayResult.textContent = message || '';
pcoBirthdayResult.style.display = message ? '' : 'none';
pcoBirthdayResult.style.color = tone === 'error' ? '#ffb1b1' : tone === 'good' ? '#8fe0b0' : '#9ea7bc';
}
async function testPcoBirthdays() {
setPcoControlsEnabled(false);
setPcoBirthdayResult('Checking Planning Center for birthday access…', 'info');
try {
const r = await window.lineup.pcoTestBirthdays();
if (!r || r.connected === false) {
setPcoBirthdayResult('Connect Planning Center first, then test birthday access.', 'error');
return;
}
if (!r.canRead) {
const why = r.reason === 'network'
? `Couldn't reach Planning Center (${r.detail || 'network error'}).`
: `This token can't read People birthdays${r.status ? ` (HTTP ${r.status})` : ''}${r.detail ? ` — ${r.detail}` : ''}.`;
setPcoBirthdayResult(`✕ ${why} Birthday Mode needs People access on the token.`, 'error');
return;
}
// Access works. Report coverage across synced band members.
if (r.total === 0) {
setPcoBirthdayResult('✓ People access works. Sync an upcoming plan, then test again to see how many musicians have a birthday on file.', 'good');
return;
}
const bits = [`✓ People access works — ${r.withBirthday} of ${r.total} synced ${r.total === 1 ? 'person has' : 'people have'} a birthday on file.`];
if (r.nextUp) {
const when = r.nextUp.inDays === 0 ? 'today 🎂' : r.nextUp.inDays === 1 ? 'tomorrow' : `in ${r.nextUp.inDays} days`;
bits.push(`Next up: ${r.nextUp.name} (${formatBirthdayMmdd(r.nextUp.mmdd)}, ${when}).`);
}
if (r.notFound) bits.push(`${r.notFound} not matched in People.`);
setPcoBirthdayResult(bits.join(' '), r.withBirthday > 0 ? 'good' : 'info');
} catch (error) {
setPcoBirthdayResult(error instanceof Error ? error.message : 'Birthday test failed.', 'error');
} finally {
setPcoControlsEnabled(true);
}
}
/* ---------------- Birthday Mode controls ---------------- */
/** Reflect current birthdayMode settings onto the controls (called after load). */
function syncBirthdayControls() {
if (bdayEnabled) bdayEnabled.checked = birthdayMode.enabled;
if (bdayIntensity) {
for (const b of bdayIntensity.querySelectorAll('button')) {
b.setAttribute('aria-pressed', b.dataset.int === birthdayMode.intensity ? 'true' : 'false');
}
}
if (bdayControls) bdayControls.style.opacity = birthdayMode.enabled ? '' : '0.45';
}
/** Rebuild the "Force on (test)" dropdown from whoever is currently on the stage. */
function renderBirthdayTestOptions() {
if (!bdayTestSelect) return;
const previous = birthdayTestPersonId;
bdayTestSelect.innerHTML = '<option value="">Off</option>';
const seen = new Set();
stageSlots.forEach((slot, index) => {
if (!slot.personId || seen.has(slot.personId)) return;
const person = getPerson(slot.personId);
if (!person) return;
seen.add(slot.personId);
const option = document.createElement('option');
option.value = person.id;
const name = String(getStageName(index, person) || person.lastName || 'Unknown').trim();
const label = String(slotLabelMemory[index] || '').trim();
option.textContent = label ? `${name} — ${label}` : name;
bdayTestSelect.appendChild(option);
});
// Keep the current override selected if that person is still on stage; otherwise drop it.
if (previous && seen.has(previous)) {
bdayTestSelect.value = previous;
} else if (previous) {
birthdayTestPersonId = '';
bdayTestSelect.value = '';
}
}
/* ---------------- Setup panel tabs ---------------- */
/** Set while a tab switch blurs the port field, so the blur handler doesn't commit. */
@@ -1257,6 +1497,7 @@ function activatePanelTab(name) {
}
// The readout measures a stage slot, so it can only be filled in once its pane is laid out.
if (name === 'pictures') window.requestAnimationFrame(updateSlotSizeReadout);
if (name === 'pco') renderBirthdayTestOptions();
}
/* ---------------- Studio displays (hosting the Now/Next page on the LAN) ---------------- */
@@ -1733,6 +1974,36 @@ btnPcoSync.addEventListener('click', () => {
void syncUpcomingPlanFromPco();
});
btnPcoTestBirthdays.addEventListener('click', () => {
revealChrome();
void testPcoBirthdays();
});
if (bdayEnabled) {
bdayEnabled.addEventListener('change', () => {
birthdayMode.enabled = bdayEnabled.checked;
syncBirthdayControls();
scheduleSave();
void renderStage();
});
}
if (bdayIntensity) {
bdayIntensity.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-int]');
if (!btn) return;
birthdayMode.intensity = btn.dataset.int === 'full' ? 'full' : 'subtle';
syncBirthdayControls();
scheduleSave();
void renderStage();
});
}
if (bdayTestSelect) {
bdayTestSelect.addEventListener('change', () => {
birthdayTestPersonId = bdayTestSelect.value || '';
void renderStage();
});
}
btnPcoDisconnect.addEventListener('click', async () => {
revealChrome();
setPcoControlsEnabled(false);
@@ -1744,6 +2015,7 @@ btnPcoDisconnect.addEventListener('click', async () => {
renderPcoPositionOptions();
scheduleSave();
setPcoStatus('Planning Center disconnected.');
setPcoBirthdayResult('');
} catch (error) {
setPcoStatus(error instanceof Error ? error.message : 'Could not disconnect Planning Center.', true);
} finally {
+126
View File
@@ -331,6 +331,105 @@ body {
color: #9ea7bc;
}
.pco-birthday-result {
min-height: 0;
line-height: 1.45;
}
.pco-birthday-result:empty {
display: none;
}
/* ---- Birthday Mode settings ---- */
.bday-block {
margin-top: 14px;
border-top: 1px solid #23232c;
padding-top: 12px;
}
.bday-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.bday-title {
font-size: 13px;
font-weight: 700;
color: #e7e7ef;
}
.bday-switch {
display: inline-flex;
align-items: center;
gap: 6px;
cursor: pointer;
font-size: 12px;
color: #9ea7bc;
}
.bday-controls {
margin-top: 10px;
display: flex;
flex-direction: column;
gap: 10px;
}
.bday-line {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.bday-line-label {
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: #8a8a99;
min-width: 74px;
}
.bday-line-label em {
font-style: normal;
text-transform: none;
letter-spacing: 0;
color: #6d6d7a;
}
.seg-inline {
display: inline-flex;
gap: 4px;
background: #0e0e14;
border: 1px solid #23232c;
border-radius: 9px;
padding: 3px;
}
.seg-inline button {
appearance: none;
border: 0;
background: transparent;
color: #9ea7bc;
font: inherit;
font-size: 12px;
font-weight: 600;
padding: 5px 12px;
border-radius: 6px;
cursor: pointer;
}
.seg-inline button[aria-pressed="true"] {
background: #f5c451;
color: #241a02;
}
.bday-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: #c6cada;
cursor: pointer;
}
.bday-test-select {
flex: 1;
min-width: 150px;
}
.bday-hint {
font-size: 11px;
color: #6d6d7a;
}
.pco-position-builder {
display: none;
grid-template-columns: minmax(0, 1fr) auto;
@@ -624,6 +723,33 @@ body {
font-weight: 500;
}
/* ---- Birthday Mode tile effects ---- */
.tile.birthday-subtle {
animation: bdayGlowSubtle 3.4s ease-in-out infinite;
}
.tile.birthday-full {
animation: bdayGlowFull 2.2s ease-in-out infinite;
}
@keyframes bdayGlowSubtle {
0%, 100% { box-shadow: inset 0 0 0 2px rgba(245, 196, 81, 0.55), 0 0 14px rgba(245, 196, 81, 0.18); }
50% { box-shadow: inset 0 0 0 2px rgba(245, 196, 81, 0.85), 0 0 20px rgba(245, 196, 81, 0.32); }
}
@keyframes bdayGlowFull {
0%, 100% { box-shadow: inset 0 0 0 3px rgba(245, 196, 81, 0.8), 0 0 20px rgba(245, 196, 81, 0.42); }
50% { box-shadow: inset 0 0 0 3px #ffd873, 0 0 34px rgba(245, 196, 81, 0.66); }
}
/* Birthday Mode intentionally keeps animating even under OS "reduced motion" — it's a celebration
the operator opts into, and freezing it leaves confetti stuck mid-fall. */
.birthday-confetti {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
}
.tile .remove {
position: absolute;
top: 6px;
+84 -24
View File
@@ -34,6 +34,46 @@ people running the booth depend on them.
The admin page refuses to install a module whose requirement the running
shell doesn't meet, and it offers updates by comparing versions.
### Keeping the interface clean
A dashboard is read across a booth, at a glance, by someone doing three
other things. These rules are what keep every tile looking like one product
instead of six. They are as binding as the four above.
5. **No explanatory text in a tile's gear.** No `help` on an
`instanceSchema` field or an `instanceGroups` entry. Labels are **three
words at most, one or two preferred** — "Slide count", "Item tags",
"Running clock". A control that cannot be understood in three words is
not a display choice; it belongs in `configSchema`, where `help` is
welcome and expected. *One exception:* a `template` field may keep a
single `help` line naming its placeholders, which nobody can guess.
6. **Server-side settings are admin-only.** Anything the module's server
acts on — a host, a credential, what to fetch, how often to poll — is
`configSchema`. `instanceSchema` is display choices and nothing else:
what this tile shows, and how big.
7. **A tile setting changes that tile and nothing else.** Never another
tile, never the module as a whole, never the server. If two tiles must
agree on something, it is either admin config or page state the shell
owns — not a setting each tile keeps its own copy of.
8. **Offer toggles for the elements you draw.** Every tile should let the
operator switch off the parts it does not need. **One to four toggles:**
give them no `group` at all, so they sit unlabelled at the top of the
gear. **Five or more:** one group named **Show**, `collapsed: true`,
`columns: 2`. Nothing else goes in that group — colours, formats and
text belong in groups of their own.
9. **Title-bar controls are icons.** No `label` on `addButton` or
`addMenu`; the tooltip carries the words, and `docs` above covers drawing
the icon. A small state indicator may ride alongside an icon — ProdCom's
channel button shows a count while a filter is on — but a control is
never named in the bar.
10. **If a control needs words to explain it, it is not a title-bar
control.** Put it in the gear. The bar is for actions whose icon and
tooltip say everything: refresh, clear, jump to latest, bigger text.
11. **One control per action.** Whatever has a dedicated title-bar button is
not offered again in the gear, and the reverse. Text size is A− / A+ up
there, never a "Text size" field; a timestamps button in the bar means
no timestamps switch below it.
## The shape of a module
A module is one folder dropped into `modules/`:
@@ -96,7 +136,7 @@ the app); its settings are kept for a later reinstall.
| `client` | yes | Client entry file, loaded as an ES module. |
| `server` | no | Server entry file (CommonJS), loaded with `require()`. |
| `style` | no | A stylesheet the shell injects once per module. |
| `minSize`, `defaultSize` | no | Tile size in grid cells (12 columns wide; rows are ~72 px). Defaults: min 1×1, default 4×3. |
| `minSize`, `defaultSize` | no | Tile size in grid cells, declared for the default grid (12 columns, 72 px rows). Defaults: min 1×1, default 4×3. A dashboard may cut its board finer or coarser (8–24 columns, from the Layouts menu; row height follows). `defaultSize` is scaled to that density when a tile is added, so a new tile lands at about the size you meant; `minSize` is enforced in cells as declared, so on a finer grid a tile can be made smaller than it could at 12. |
| `configSchema` | no | **Admin config** — server-wide settings (URLs, ports, keys) edited once at `/admin` for everyone. |
| `instanceSchema` | no | **Per-tile settings** — chosen in each tile's gear menu and stored with that browser's layout (filters, text sizes, display options). They apply as they are changed, so keep them to display choices. |
| `tiles` | no | Fixed multi-tile list for client-only modules; server modules export a dynamic `tiles()` instead. See **Presenting multiple tiles**. |
@@ -177,14 +217,18 @@ the group name:
`help` on a field puts one line of guidance under its control — allowed
placeholders, where a value comes from. Keep labels short and put the
explanation there.
explanation there. **This is for `configSchema` only**: a tile's gear
carries no explanations at all (rule 5), so a setting that needs one is
telling you it belongs in admin.
`group` and `help` work on `instanceSchema` fields too, and a manifest
`group` works on `instanceSchema` fields too, and a manifest
`instanceGroups` map plays the `configGroups` role for the tile's gear
popover (`collapsed: true | false`, `columns`, `help`, `toggle`). That is how
a module with a long show/hide checklist keeps the popover usable — see
`pco-plan`. Display choices belong there, per tile; admin config is for
connections. The popover itself is a small window beside the tile — sized to
popover (`collapsed: true | false`, `columns`, `toggle` — but not `help`,
per rule 5). That is how a module with a long show/hide checklist keeps the
popover usable: five or more hide-toggles go in one **Show** group, folded
by default, and fewer than five go in no group at all — see `pco-plan` for
the long form and `slack` for the short one. Display choices belong there,
per tile; admin config is for connections. The popover itself is a small window beside the tile — sized to
its content, moved by the slim bar on top, closed by clicking anywhere else
or pressing Escape — so a tile never has to be big enough to hold its own
settings, and a change can be watched as it lands. Under everything you
@@ -354,22 +398,25 @@ menu.setLabel('Channels (2/4) ▾'); // update the button text any time
```
Everything you add is removed automatically when your instance stops, so a
remount never duplicates controls. Keep them compact (icon buttons, short
labels): the title bar is 32 px tall and shared with the tile's name. Draw
icons as inline SVG rather than characters — a glyph such as ✕ or + takes
its size from whatever font each browser picks; text-size buttons are a
drawn − and +.
remount never duplicates controls. **Icons only, no labels** (rule 9): the
title bar is 32 px tall and shared with the tile's name, and the tooltip
says what the icon means. Draw icons as inline SVG rather than characters —
a glyph such as ✕ or + takes its size from whatever font each browser
picks; text-size buttons are a drawn − and +. A small state indicator may
ride alongside an icon (ProdCom's channel button carries a count while a
filter is on); a name may not.
**One control per action.** Whatever has a dedicated header button is not
offered again in the gear popover: text size is A− / A+ up here (persisted
through `saveInstanceSettings({ textSize })`, read back with a sane
fallback), never a "Text size" field in `instanceSchema`; a timestamps or
newest-first toggle in the header means no such switch in the gear. The
**One control per action** (rule 11). Whatever has a dedicated header button
is not offered again in the gear popover: text size is − / + up here
(persisted through `saveInstanceSettings({ textSize })`, read back with a
sane fallback), never a "Text size" field in `instanceSchema`; a timestamps
or newest-first toggle in the header means no such switch in the gear. The
gear is for display choices that have no button of their own.
One more thing to know: the user can hide the whole title bar with the
small notch on its bottom edge (a clean-view mode for wall displays). Your
controls disappear with it, so nothing essential — status, reconnects,
One more thing to know: the whole title bar folds away when the dashboard
auto-hides it, and always in fullscreen (a clean-view mode for wall
displays) — it comes back only while the pointer is at the tile's top edge.
Your controls fold away with it, so nothing essential — status, reconnects,
live data — may exist *only* as a header control.
`sse(path, handlers)` handlers:
@@ -545,10 +592,17 @@ module.exports = {
- When the user adds an entry, its `settings` overlay your `instanceSchema`
defaults in that tile's instance settings, the entry's `name` becomes the
tile's title, and `moduleApi.variant` carries its `id`.
- The tile keeps its variant id and title even if the entry later vanishes
from your list (a timer deleted in ProPresenter, a page removed in admin).
**Your client decides what that means** — show a clear "no longer
configured" state rather than erroring.
- **A tile is shown only while its entry is offered.** The shell mounts a
tile added from an entry only when that entry (or one of its `aliases`) is
in your list right now; otherwise the tile keeps its place in the layout,
draws nothing, and appears the moment your list offers it again — a
Service timer waits for PCO Plan, a transcript for its channel. So your
client is never asked to render an entry you did not offer at mount time.
One case is still yours: an entry that vanishes *after* the tile mounted
(a timer deleted in ProPresenter mid-service). Render nothing for it — no
placeholder, no error — and the shell folds the tile away at its next
registry refresh. Never fall back to your default view in its place: five
different timers turning into five "All timers" is worse than five gaps.
- A client-only module can declare a fixed list as a `tiles` array in
`module.json` instead (same entry shape).
- An empty list (or no `tiles` at all) keeps today's behavior: one picker
@@ -630,6 +684,7 @@ clock, and any module that offers some. A module offers timers by:
| `state` | `running`, `paused`, `stopped` (finished; value frozen), `idle` (exists, hasn't started — a timer that will start at 11:00). |
| `startedAt` | ms epoch when it last started running; the consumer extrapolates from here, so a running timer never needs a fast poll. |
| `elapsedMs`, `remainingMs` | The values at `updatedAt`; `null` when not meaningful for the kind. |
| `asOf` | Optional, per timer: ms epoch this timer's durations were measured, when that differs from the snapshot's `updatedAt` (e.g. a value phase-locked to an upstream's second flips). Consumers extrapolate from it instead. |
| `targetMs` | Planned length (elapsed) or full length (countdown), or `null`. Lets the consumer colour overruns. |
| `status` | Optional one-liner the consumer shows beside the time — the current item, "ahead 1:20". `tone`: `ok`, `warn`, `danger`, `muted`. |
| `detail` | Optional second line. |
@@ -757,6 +812,11 @@ client-side failures (a tile that fails to start says so in the tile).
Application ID + Secret under PCO Plan in `/admin`, save, then pick
"Sunday Service" from the Service type list. Its item titles match
`pp-mock.js`, so running both mocks exercises the ProPresenter matching.
- AbleSet: `node tools/ableset-mock.js 39071` — a setlist playing through
over AbleSet's OSC API (UDP): sections, a tempo and meter per song, a
section that loops twice, a song queued out of order, heartbeats.
`--stopped`, `--no-live` and `--speed 4` exercise the other states. Point
the AbleSet module at host `127.0.0.1`, port `39071`.
**The resilience checklist** — every module must pass this before it's done:
@@ -103,6 +103,45 @@ enum ProdDash {
}
}
/**
Go back to the copy ProdDash set aside before its last update.
A version that will not stay up is the one state this app cannot talk its
way out of: the admin page went down with it, and installing a fresh
`.app` does nothing, because seeding only replaces an *older* copy and a
broken one carries a higher version. So ProdDash writes `app.previous`
before it overwrites itself and drops it again once the new version has
stayed up — meaning that folder exists only while an update is still
unproven. This puts it back.
Returns the version restored, or nil when there is nothing to go back to.
*/
@discardableResult
static func restorePrevious(root: URL, log: (String) -> Void) -> String? {
let fm = FileManager.default
let previous = URL(fileURLWithPath: root.path + ".previous")
guard isRoot(previous) else { return nil }
let version = shellVersion(root: previous)
let named = version.isEmpty ? "(unknown version)" : version
let broken = URL(fileURLWithPath: root.path + ".broken")
do {
try? fm.removeItem(at: broken)
if fm.fileExists(atPath: root.path) { try fm.moveItem(at: root, to: broken) }
try fm.moveItem(at: previous, to: root)
makeWritable(root)
try? fm.removeItem(at: broken)
log("rolled ProdDash back to \(named) — the copy it replaced")
return named
} catch {
log("could not roll back to the previous copy: \(error.localizedDescription)")
// Leave something runnable behind rather than nothing at all.
if !fm.fileExists(atPath: root.path), fm.fileExists(atPath: broken.path) {
try? fm.moveItem(at: broken, to: root)
}
return nil
}
}
/// Files copied out of a bundle can arrive read-only, and this copy is
/// exactly where ProdDash writes its own updates.
private static func makeWritable(_ root: URL) {
+19 -1
View File
@@ -65,6 +65,8 @@ final class ServerController: ObservableObject {
private var restartAfterExit = false
private var startedAt: Date?
private var crashTimes: [Date] = []
/// One roll-back per bad update: a second would just swap copies forever.
private var rolledBack = false
private var pendingRestart: DispatchWorkItem?
private var healthTimer: Timer?
private var healthMisses = 0
@@ -299,7 +301,7 @@ final class ServerController: ObservableObject {
child = nil
healthy = false
let ranFor = startedAt.map { Date().timeIntervalSince($0) } ?? 0
if ranFor > 60 { crashTimes.removeAll() } // a long healthy run clears the slate
if ranFor > 60 { crashTimes.removeAll(); rolledBack = false } // a long healthy run clears the slate
if restartAfterExit {
restartAfterExit = false
@@ -328,6 +330,22 @@ final class ServerController: ObservableObject {
crashTimes = crashTimes.filter { Date().timeIntervalSince($0) < 120 }
guard settings.restartOnCrash, crashTimes.count < 4 else {
// Before giving up: if an update is still unproven, the copy it
// replaced is sitting right there. Going back beats sitting dark,
// and only once — if the old one will not run either, the problem
// is not the update.
if settings.restartOnCrash, !rolledBack, let root = rootURL,
let restored = ProdDash.restorePrevious(root: root, log: { [log] in log.launcher($0) }) {
rolledBack = true
crashTimes.removeAll()
state = .stopped
message = "Rolled back to ProdDash \(restored) — starting…"
Notifier.shared.post(title: "ProdDash rolled back",
body: "The new version would not stay up. Back on \(restored).")
refreshEnvironment()
start()
return
}
let why = settings.restartOnCrash
? "ProdDash stopped \(crashTimes.count) times in two minutes — leaving it stopped."
: "ProdDash \(how)."
+727
View File
@@ -0,0 +1,727 @@
/* AbleSet — client part.
One factory draws every AbleSet tile; `moduleApi.variant` says which one
(the server's tiles() list). All of them read the same stream: `state`
whenever something changes, `pos` five times a second while playing.
Between packets the playhead and the countdowns are extrapolated from the
tempo and the clock, so bars glide instead of stepping. */
const VIEWS = ['now', 'sections', 'setlist', 'transport', 'tempo', 'song-time', 'set-time', 'section', 'next-song', 'status'];
/* AbleSet names its colours after Live's palette; these are close enough to
read as the same colour on a dark tile. Unknown names draw no colour. */
const NAMED_COLORS = {
red: '#ff4d4f', orange: '#ff8f3a', yellow: '#f5d442', lime: '#a3e635', green: '#34d399',
mint: '#5eead4', teal: '#2dd4bf', cyan: '#22d3ee', sky: '#38bdf8', blue: '#3b82f6',
indigo: '#6366f1', purple: '#a855f7', violet: '#8b5cf6', magenta: '#e879f9', pink: '#f472b6',
rose: '#fb7185', brown: '#b0794a', gray: '#9ca3af', grey: '#9ca3af', white: '#f5f5f5',
};
const ICON_STRIP = '<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="1.5" y="5" width="4" height="6" rx="1"/><rect x="6.5" y="4" width="4" height="8" rx="1"/><rect x="11.5" y="5" width="3" height="6" rx="1"/></svg>';
const ICON_WHEEL = '<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5h8M3 6h10M3 10h10M4 13.5h8"/><rect x="2" y="5" width="12" height="6" rx="1.2"/></svg>';
function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
/** 83 → "01:23", 3725 → "1:02:05". Whole seconds round down, as AbleSet's own display does. */
function fmt(sec) {
if (sec == null || !Number.isFinite(sec)) return '--:--';
const s = Math.max(0, Math.floor(sec + 1e-6));
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const ss = String(s % 60).padStart(2, '0');
return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${String(m).padStart(2, '0')}:${ss}`;
}
function fmtBpm(t) {
if (t == null) return '--';
return (Math.round(t * 100) / 100).toString();
}
function colorFor(value) {
if (!value) return null;
if (/^#[0-9a-f]{6}$/i.test(value)) return value;
return NAMED_COLORS[String(value).toLowerCase()] || null;
}
export default function create({ root, moduleApi }) {
const view = VIEWS.includes(moduleApi.variant) ? moduleApi.variant
: moduleApi.variant ? '' : 'now'; // an entry that vanished draws nothing
const prefs = () => moduleApi.instanceSettings || {};
const on = (k) => prefs()[k] !== false;
let state = null;
let pos = { beats: null, remainingSong: null, remainingSet: null };
let posAt = 0;
let stream = null;
let raf = 0;
let resizeObserver = null;
let tickTimer = null;
/* ── moving values, extrapolated to this frame ─────────────────── */
const moving = () => Boolean(state && state.reachable && state.playing);
const dt = () => (moving() ? (performance.now() - posAt) / 1000 : 0);
function beatsNow() {
if (pos.beats == null) return null;
const t = state?.tempo;
return t ? pos.beats + dt() * (t / 60) : pos.beats;
}
const songLeft = () => (pos.remainingSong == null ? null : Math.max(0, pos.remainingSong - dt()));
const setLeft = () => (pos.remainingSet == null ? null : Math.max(0, pos.remainingSet - dt()));
function fraction(start, end, b) {
if (start == null || end == null || b == null || end <= start) return null;
return Math.min(1, Math.max(0, (b - start) / (end - start)));
}
function songsLeft() {
if (!state?.song || state.song.index == null) return null;
return Math.max(0, state.setlist.songs.length - state.song.index - 1);
}
/** Beats per bar from the time signature (Live counts quarter notes). */
function beatsPerBar() {
const ts = state?.timeSig;
return ts && ts[0] > 0 && ts[1] > 0 ? (ts[0] * 4) / ts[1] : 4;
}
/** Bar and beat within the song, 1-based. */
function barBeat() {
const b = beatsNow();
const start = state?.song?.start ?? 0;
if (b == null) return null;
const rel = Math.max(0, b - start);
const bpb = beatsPerBar();
const ts = state?.timeSig || [4, 4];
const beatLen = 4 / (ts[1] || 4);
const bar = Math.floor(rel / bpb) + 1;
const beat = Math.floor((rel % bpb) / beatLen + 1e-6) + 1;
return { bar, beat, of: ts[0] || 4 };
}
function tone(sec) {
if (sec == null || !moving()) return '';
const warn = Number(prefs().warnAt ?? 30);
const alert = Number(prefs().alertAt ?? 10);
if (sec <= alert) return 'alert';
if (sec <= warn) return 'warn';
return '';
}
/* ── fitting one-line text to its box ──────────────────────────── */
/** Shrink a nowrap element until it fits the width its parent gives it. */
function fit(el) {
if (!el || !el.isConnected) return;
el.style.fontSize = '';
const max = parseFloat(getComputedStyle(el).fontSize) || 16;
const avail = el.parentElement ? el.parentElement.clientWidth : el.clientWidth;
let size = max;
for (let i = 0; i < 3 && el.scrollWidth > avail + 0.5 && size > 9; i += 1) {
size = Math.max(9, size * (avail / el.scrollWidth) * 0.98);
el.style.fontSize = `${size}px`;
}
}
const fitAll = () => root.querySelectorAll('[data-fit]').forEach(fit);
/** Set text, refitting only when it changed. */
function text(el, value) {
if (!el) return;
const v = String(value ?? '');
if (el.textContent === v) return;
el.textContent = v;
if (el.hasAttribute('data-fit')) fit(el);
}
function show(el, visible) {
if (el) el.hidden = !visible;
}
/* ── skeleton per view ─────────────────────────────────────────── */
root.innerHTML = `<div class="as-root as-${view || 'none'}"><div class="as-offline" hidden></div><div class="as-body"></div></div>`;
const shell = root.firstElementChild;
const body = shell.querySelector('.as-body');
const offlineEl = shell.querySelector('.as-offline');
const $ = (sel) => body.querySelector(sel);
const BAR = `<div class="as-bar"><div class="as-bar-done"></div><div class="as-bar-sect"><div class="as-bar-played"></div></div></div>`;
const SKELETONS = {
now: `
<div class="as-title-box"><div class="as-title" data-fit></div></div>
<div class="as-badges">
<span class="as-badge b-tempo"></span><span class="as-badge b-meter"></span><span class="as-badge b-dur"></span><span class="as-badge b-clock"></span><span class="as-badge b-section"></span>
</div>
${BAR}
<div class="as-next">
<div class="as-next-label">Next:</div>
<div class="as-next-box"><div class="as-next-title" data-fit></div></div>
<div class="as-left"></div>
</div>`,
sections: `
<div class="as-song-name" data-fit></div>
<div class="as-viewport"><div class="as-track"></div></div>`,
setlist: `
<div class="as-set-head"><span class="as-set-name"></span></div>
<div class="as-list"></div>
<div class="as-set-foot"></div>`,
transport: `
<div class="as-big-box"><div class="as-big" data-fit></div></div>
<div class="as-sub"><span class="as-pos"></span><span class="as-loop"></span></div>`,
tempo: `
<div class="as-big-box"><div class="as-big" data-fit><span class="as-bpm"></span><small> BPM</small></div></div>
<div class="as-sub"><span class="as-meter"></span></div>
<div class="as-beats"></div>`,
'song-time': `
<div class="as-caption" data-fit></div>
<div class="as-big-box"><div class="as-big" data-fit></div></div>
<div class="as-sub as-sub-time"></div>
${BAR}`,
'set-time': `
<div class="as-caption" data-fit>Set</div>
<div class="as-big-box"><div class="as-big" data-fit></div></div>
<div class="as-sub"><span class="as-left-count"></span><span class="as-end"></span></div>`,
section: `
<div class="as-big-box"><div class="as-big" data-fit></div></div>
<div class="as-sub"><span class="as-next-sect"></span><span class="as-count"></span></div>
<div class="as-sect-bar"><div></div></div>`,
'next-song': `
<div class="as-caption">Next</div>
<div class="as-big-box"><div class="as-big" data-fit></div></div>
<div class="as-sub"><span class="as-next-dur"></span></div>
<div class="as-queued" hidden></div>`,
status: `<div class="as-rows"></div>`,
};
body.innerHTML = SKELETONS[view] || '';
/* ── shared pieces ─────────────────────────────────────────────── */
/** The three-part song bar: played sections, this section, the playhead. */
function paintBar(bar) {
if (!bar) return;
const s = state?.song;
const sect = state?.section;
const b = beatsNow();
const len = s && s.end > s.start ? s.end - s.start : 0;
const at = (v) => (len ? Math.min(100, Math.max(0, ((v - s.start) / len) * 100)) : 0);
const sStart = sect && sect.start != null ? at(sect.start) : 0;
const sEnd = sect && sect.end != null ? at(sect.end) : 0;
const head = b != null ? at(b) : 0;
bar.style.setProperty('--done', `${sStart}%`);
bar.style.setProperty('--sect-l', `${sStart}%`);
bar.style.setProperty('--sect-w', `${Math.max(0, sEnd - sStart)}%`);
const inSect = sEnd > sStart ? Math.min(100, Math.max(0, ((head - sStart) / (sEnd - sStart)) * 100)) : 0;
bar.style.setProperty('--played', `${inSect}%`);
}
function songTint(el, hex) {
if (hex) el.style.setProperty('--song', hex);
else el.style.removeProperty('--song');
el.classList.toggle('has-song-color', Boolean(hex));
}
/* ── NOW PLAYING ───────────────────────────────────────────────── */
const nowView = {
render() {
const s = state;
const song = s.song;
text($('.as-title'), song ? song.name : s.setlist.name || 'No song');
shell.classList.toggle('is-playing', moving());
songTint(shell, on('songColors') && song ? colorFor(song.color) : null);
text($('.b-tempo'), s.tempo != null ? `${fmtBpm(s.tempo)} BPM` : '');
text($('.b-meter'), s.timeSig ? `${s.timeSig[0]}/${s.timeSig[1]}` : '');
text($('.b-dur'), song && song.duration != null ? fmt(song.duration) : '');
const sect = s.section;
text($('.b-section'), sect ? sect.name : '');
const sc = on('songColors') && sect ? colorFor(sect.color) : null;
$('.b-section').style.color = sc || '';
show($('.b-tempo'), on('showTempo') && s.tempo != null);
show($('.b-meter'), on('showMeter') && Boolean(s.timeSig));
show($('.b-dur'), on('showDuration') && song?.duration != null);
show($('.b-clock'), on('showClock') && pos.remainingSong != null);
show($('.b-section'), on('showSection') && Boolean(sect?.name));
show($('.as-bar'), on('showProgress') && Boolean(song));
const next = s.queued?.type === 'song' ? { name: s.queued.song } : s.nextSong;
text($('.as-next-label'), s.queued?.type === 'song' ? 'Queued:' : 'Next:');
$('.as-next').classList.toggle('is-queued', s.queued?.type === 'song');
text($('.as-next-title'), next ? next.name : 'End of set');
show($('.as-next-label'), on('showNext'));
show($('.as-next-box'), on('showNext'));
show($('.as-left'), on('showLeft') && songsLeft() != null);
this.frame();
},
frame() {
const left = songLeft();
const clockMode = prefs().clock || 'remaining';
const dur = state.song?.duration;
const elapsed = dur != null && left != null ? Math.max(0, dur - left) : null;
const clock = clockMode === 'elapsed' ? fmt(elapsed)
: clockMode === 'both' ? `${fmt(elapsed)} / -${fmt(left)}` : `-${fmt(left)}`;
const c = $('.b-clock');
text(c, clock);
c.dataset.tone = tone(left);
paintBar($('.as-bar'));
const n = songsLeft();
if (n != null) text($('.as-left'), `${n} song${n === 1 ? '' : 's'} (${fmt(setLeft())}) left`);
},
};
/* ── SONG SECTIONS: a strip, or a lottery wheel ────────────────── */
const WHEEL_STEP = 30; // degrees between wheel faces
let sectionKey = '';
let wheelButton = null;
const sectionsView = {
style() { return prefs().style === 'wheel' ? 'wheel' : 'strip'; },
build() {
const track = $('.as-track');
const list = state.sections || [];
const key = `${state.song?.name}|${list.map((x) => x.name).join('|')}`;
if (key === sectionKey && track.children.length === list.length) return;
sectionKey = key;
track.innerHTML = list.map((x, i) => `<div class="as-pill" data-i="${i}"><span class="as-pill-fill"></span><span class="as-pill-text">${esc(x.name)}</span></div>`).join('')
|| '<div class="as-pill is-empty"><span class="as-pill-text">No sections</span></div>';
this.jump();
},
/** Place without gliding — a new song, or strip ↔ wheel, lands in one step. */
jump() {
const track = $('.as-track');
track.classList.add('no-anim');
requestAnimationFrame(() => requestAnimationFrame(() => track.classList.remove('no-anim')));
},
render() {
const wheel = this.style() === 'wheel';
shell.classList.toggle('is-wheel', wheel);
shell.classList.toggle('is-playing', moving());
text($('.as-song-name'), state.song ? state.song.name : '');
show($('.as-song-name'), on('showSong') && Boolean(state.song));
this.build();
const cur = state.section?.index ?? -1;
const nxt = state.nextSection?.index ?? -1;
const pills = $('.as-track').children;
for (const el of pills) {
const i = Number(el.dataset.i);
if (Number.isNaN(i)) continue;
el.classList.toggle('is-past', i < cur);
el.classList.toggle('is-current', i === cur);
el.classList.toggle('is-next', i === nxt);
const c = on('sectionColors') ? colorFor(state.sections[i]?.color) || (i === cur ? colorFor(state.section?.color) : null) : null;
if (c) el.style.setProperty('--sect', c);
else el.style.removeProperty('--sect');
el.classList.toggle('has-color', Boolean(c));
}
this.place();
this.frame();
},
place() {
const track = $('.as-track');
const vp = $('.as-viewport');
const cur = Math.max(0, state.section?.index ?? 0);
const pills = [...track.children];
if (this.style() === 'wheel') {
const h = vp.clientHeight / 3.4;
const r = (h / 2) / Math.tan((WHEEL_STEP / 2) * (Math.PI / 180));
track.style.setProperty('--face-h', `${h}px`);
pills.forEach((el, i) => {
const d = i - cur;
el.style.transform = `translateY(-50%) rotateX(${-d * WHEEL_STEP}deg) translateZ(${r}px)`;
el.style.opacity = Math.abs(d) * WHEEL_STEP > 75 ? "0" : String(1 - Math.abs(d) * 0.3);
});
track.style.transform = `translateZ(${-r}px)`;
} else {
pills.forEach((el) => { el.style.transform = ''; el.style.opacity = ''; });
const el = pills[cur] || pills[0];
if (!el) return;
const center = el.offsetLeft + el.offsetWidth / 2;
track.style.transform = `translateX(${vp.clientWidth / 2 - center}px)`;
}
},
frame() {
const cur = state.section?.index ?? -1;
const el = $('.as-track').children[cur];
if (!el) return;
const f = fraction(state.section.start, state.section.end, beatsNow());
el.style.setProperty('--p', on('showProgress') && f != null ? `${f * 100}%` : '0%');
},
toggleStyle() {
const next = this.style() === 'wheel' ? 'strip' : 'wheel';
moduleApi.saveInstanceSettings({ style: next });
this.syncButton();
this.jump();
if (state) this.render();
},
syncButton() {
if (!wheelButton) return;
const wheel = this.style() === 'wheel';
wheelButton.innerHTML = wheel ? ICON_STRIP : ICON_WHEEL;
wheelButton.title = wheel ? 'Strip view' : 'Wheel view';
},
};
/* ── SETLIST ───────────────────────────────────────────────────── */
let listKey = '';
let lastScrolled = -2;
const setlistView = {
render() {
const s = state;
text($('.as-set-name'), s.setlist.name || 'Setlist');
const list = $('.as-list');
const songs = s.setlist.songs;
const key = JSON.stringify([songs, on('showDurations'), on('songColors')]);
if (key !== listKey) {
listKey = key;
lastScrolled = -2;
list.innerHTML = songs.map((x, i) => {
const c = on('songColors') ? colorFor(x.color) : null;
return `<div class="as-row" data-i="${i}"${c ? ` style="--song:${c}"` : ''}>
<span class="as-row-fill"></span>
${c ? '<span class="as-swatch"></span>' : ''}
<span class="as-row-name">${esc(x.name)}</span>
${on('showDurations') ? `<span class="as-row-dur">${x.duration != null ? fmt(x.duration) : ''}</span>` : ''}
</div>`;
}).join('') || '<div class="as-empty">No setlist</div>';
}
const cur = s.song?.index ?? -1;
const nxt = s.nextSong?.index ?? -1;
const q = s.queued?.type === 'song' ? s.queued.songIndex : -1;
for (const row of list.children) {
const i = Number(row.dataset.i);
if (Number.isNaN(i)) continue;
row.classList.toggle('is-past', i < cur);
row.classList.toggle('is-current', i === cur);
row.classList.toggle('is-next', i === nxt && q < 0);
row.classList.toggle('is-queued', i === q);
row.hidden = !on('showPlayed') && i < cur;
}
shell.classList.toggle('is-playing', moving());
if (cur !== lastScrolled && list.children[cur]) {
lastScrolled = cur;
const row = list.children[cur];
list.scrollTo({ top: Math.max(0, row.offsetTop - list.clientHeight * 0.3), behavior: 'smooth' });
}
show($('.as-set-foot'), on('showTotal'));
this.frame();
},
frame() {
const row = $('.as-list').children[state.song?.index ?? -1];
if (row && state.song) {
const f = fraction(state.song.start, state.song.end, beatsNow());
row.style.setProperty('--p', `${(f ?? 0) * 100}%`);
}
const n = songsLeft();
text($('.as-set-foot'), n == null ? '' : `${n} song${n === 1 ? '' : 's'} left · ${fmt(setLeft())}`);
},
};
/* ── TRANSPORT ─────────────────────────────────────────────────── */
const transportView = {
render() {
const s = state;
let word = 'Stopped';
let t = 'muted';
if (s.loading) { word = 'Loading'; t = 'warn'; }
else if (!s.live) { word = 'No Live'; t = 'alert'; }
else if (s.recording && s.playing) { word = 'Recording'; t = 'alert'; }
else if (s.countingIn) { word = 'Count-in'; t = 'warn'; }
else if (s.playing && (s.loop.inSection || s.sectionLoop?.mode)) { word = 'Looping'; t = 'warn'; }
else if (s.playing) { word = 'Playing'; t = 'ok'; }
else if (s.paused) { word = 'Paused'; t = 'warn'; }
text($('.as-big'), word);
shell.dataset.tone = t;
const loop = s.sectionLoop?.mode
? `Section loop${s.sectionLoop.count ? ` ×${s.sectionLoop.count}` : ''}`
: s.loop.inSection ? 'Section loop' : '';
text($('.as-loop'), loop);
show($('.as-loop'), on('showLoop') && Boolean(loop));
show($('.as-pos'), on('showPosition'));
this.frame();
},
frame() {
const bb = barBeat();
text($('.as-pos'), bb ? `Bar ${bb.bar} · ${bb.beat}` : '');
},
};
/* ── TEMPO ─────────────────────────────────────────────────────── */
let beatCount = 0;
const tempoView = {
render() {
const s = state;
text($('.as-bpm'), fmtBpm(s.tempo));
fit($('.as-big'));
text($('.as-meter'), s.timeSig ? `${s.timeSig[0]}/${s.timeSig[1]}` : '');
show($('.as-meter'), on('showMeter'));
const n = Math.min(16, Math.max(1, s.timeSig ? s.timeSig[0] : 4));
const beats = $('.as-beats');
if (beatCount !== n) {
beatCount = n;
beats.innerHTML = Array.from({ length: n }, (_, i) => `<i class="${i === 0 ? 'is-down' : ''}"></i>`).join('');
}
show(beats, on('showBeats'));
shell.classList.toggle('is-playing', moving());
this.frame();
},
frame() {
const bb = moving() ? barBeat() : null;
const lights = $('.as-beats').children;
for (let i = 0; i < lights.length; i += 1) lights[i].classList.toggle('is-lit', Boolean(bb) && bb.beat === i + 1);
},
};
/* ── SONG TIME ─────────────────────────────────────────────────── */
const songTimeView = {
render() {
const song = state.song;
text($('.as-caption'), song ? song.name : 'Song');
show($('.as-caption'), on('showSong'));
show($('.as-bar'), on('showProgress') && Boolean(song));
this.frame();
},
frame() {
const left = songLeft();
const dur = state.song?.duration;
const elapsed = dur != null && left != null ? Math.max(0, dur - left) : null;
const mode = prefs().clock || 'remaining';
text($('.as-big'), mode === 'elapsed' ? fmt(elapsed) : `-${fmt(left)}`);
text($('.as-sub-time'), mode === 'both' ? `${fmt(elapsed)} of ${fmt(dur)}` : dur != null ? `of ${fmt(dur)}` : '');
shell.dataset.tone = tone(left) || (moving() ? 'ok' : 'muted');
paintBar($('.as-bar'));
},
};
/* ── SET TIME ──────────────────────────────────────────────────── */
const setTimeView = {
render() {
text($('.as-caption'), state.setlist.name || 'Set');
show($('.as-left-count'), on('showLeft'));
show($('.as-end'), on('showEnd'));
shell.dataset.tone = moving() ? 'ok' : 'muted';
this.frame();
},
frame() {
const left = setLeft();
text($('.as-big'), fmt(left));
const n = songsLeft();
text($('.as-left-count'), n == null ? '' : `${n} song${n === 1 ? '' : 's'} left`);
const end = left != null ? new Date(Date.now() + left * 1000) : null;
text($('.as-end'), end ? `Ends ${end.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}` : '');
},
};
/* ── SECTION ───────────────────────────────────────────────────── */
const sectionView = {
render() {
const sect = state.section;
text($('.as-big'), sect ? sect.name : '—');
const c = on('sectionColors') && sect ? colorFor(sect.color) : null;
songTint(shell, c);
const nx = state.queued?.type === 'section' ? state.queued.section : state.nextSection?.name;
text($('.as-next-sect'), nx ? `→ ${nx}` : '');
show($('.as-next-sect'), on('showNext') && Boolean(nx));
show($('.as-count'), on('showCount'));
show($('.as-sect-bar'), on('showCount'));
this.frame();
},
frame() {
const sect = state.section;
const b = beatsNow();
const looping = Boolean(state.sectionLoop?.mode || state.loop.inSection);
let label = '';
let t = moving() ? 'ok' : 'muted';
if (sect && sect.end != null && b != null) {
const leftBeats = Math.max(0, sect.end - b);
const bpb = beatsPerBar();
const beatLen = 4 / (state.timeSig?.[1] || 4);
if (looping) { label = 'Looping'; t = 'warn'; }
else if (leftBeats <= bpb + 1e-6) {
const n = Math.max(1, Math.ceil(leftBeats / beatLen - 1e-6));
label = `${n} beat${n === 1 ? '' : 's'}`;
if (moving()) t = 'warn';
} else {
const n = Math.ceil(leftBeats / bpb - 1e-6);
label = `${n} bars`;
}
const f = fraction(sect.start, sect.end, b);
$('.as-sect-bar').style.setProperty('--p', `${(f ?? 0) * 100}%`);
}
text($('.as-count'), label);
shell.dataset.tone = t;
},
};
/* ── NEXT SONG ─────────────────────────────────────────────────── */
const nextSongView = {
render() {
const n = state.nextSong;
text($('.as-big'), n ? n.name : 'End of set');
text($('.as-next-dur'), n?.duration != null ? fmt(n.duration) : '');
show($('.as-next-dur'), on('showDuration') && n?.duration != null);
const q = state.queued;
const qText = q ? (q.type === 'section' ? `Queued: ${q.section}${q.song ? ` (${q.song})` : ''}` : `Queued: ${q.song}`) : '';
text($('.as-queued'), qText);
show($('.as-queued'), on('showQueued') && Boolean(q));
shell.dataset.tone = q ? 'warn' : n ? '' : 'muted';
},
frame() {},
};
/* ── STATUS ────────────────────────────────────────────────────── */
const statusView = {
render() {
const s = state;
const rows = [
['AbleSet', s.reachable ? 'Connected' : 'No answer', s.reachable ? 'ok' : 'alert'],
['Ableton Live', !s.reachable ? '—' : s.live ? 'Connected' : 'Not connected', !s.reachable ? 'muted' : s.live ? 'ok' : 'alert'],
];
if (s.loading) rows.push(['Project', 'Loading…', 'warn']);
if (s.recording) rows.push(['Recording', 'On', 'alert']);
if (on('showSetlist')) rows.push(['Setlist', s.setlist.name || '—', s.setlist.name ? '' : 'muted']);
if (on('showAudio')) {
if (!s.audio.length) rows.push(['Audio interface', 'None', 'muted']);
for (const a of s.audio) {
const map = {
armed: ['Armed', 'ok'], sceneA: ['Main (A)', 'ok'], sceneB: ['Backup (B)', 'warn'], alarm: ['Alarm', 'alert'],
};
const [label, t] = map[a.status] || [a.status || 'Connected', ''];
rows.push([a.name, s.reachable ? label : '—', s.reachable ? t : 'muted']);
}
}
$('.as-rows').innerHTML = rows.map(([k, v, t]) => `<div class="as-srow" data-tone="${t}"><i></i><span class="as-sk">${esc(k)}</span><span class="as-sv">${esc(v)}</span></div>`).join('');
const worst = rows.some((r) => r[2] === 'alert') ? 'alert' : rows.some((r) => r[2] === 'warn') ? 'warn' : 'ok';
shell.dataset.tone = worst;
},
frame() {},
};
const VIEW_IMPL = {
now: nowView, sections: sectionsView, setlist: setlistView, transport: transportView, tempo: tempoView,
'song-time': songTimeView, 'set-time': setTimeView, section: sectionView, 'next-song': nextSongView, status: statusView,
};
const impl = VIEW_IMPL[view];
/* ── drawing loop ──────────────────────────────────────────────── */
function render() {
if (!impl || !state) return;
const offline = !state.reachable && view !== 'status';
shell.classList.toggle('is-offline', offline);
show(offlineEl, offline);
if (offline) {
text(offlineEl, !state.configured ? 'Set the AbleSet host in /admin' : 'AbleSet offline');
}
impl.render();
loop();
}
function loop() {
if (raf || !moving()) return;
const step = () => {
raf = 0;
if (!state || !moving()) return;
impl.frame();
raf = requestAnimationFrame(step);
};
raf = requestAnimationFrame(step);
}
function reportStatus() {
if (!state) return moduleApi.setStatus('connecting', 'Connecting…');
if (!state.configured) return moduleApi.setStatus('error', 'No AbleSet host set in /admin');
if (!state.reachable) return moduleApi.setStatus('error', state.lastError ? `AbleSet: ${state.lastError}` : 'Waiting for AbleSet to answer');
if (!state.live) return moduleApi.setStatus('connecting', 'AbleSet is up, but Ableton Live is not connected');
return moduleApi.setStatus('ok', state.setlist.name ? `AbleSet · ${state.setlist.name}` : 'AbleSet');
}
function applyState(next) {
if (!next || typeof next !== 'object') return;
takePos(next.pos);
state = next;
reportStatus();
render();
}
/* The page's one stream is shared, so a tile mounted onto it (a gear
change remounts the tile) joins mid-flow and hears nothing until
AbleSet next changes — which, stopped, may be never. Ask for the state. */
let stopped = false;
async function backfill() {
try {
const res = await moduleApi.fetch('/state');
if (!res.ok) return;
const body = await res.json();
if (!stopped) applyState(body.state);
} catch { /* the stream's error handler reports the outage */ }
}
function takePos(p) {
if (!p) return;
pos = p;
posAt = performance.now();
}
return {
start() {
if (!impl) return;
moduleApi.setStatus('connecting', 'Connecting…');
if (view === 'sections') {
wheelButton = moduleApi.header.addButton({
icon: ICON_WHEEL,
title: 'Wheel view',
onClick: () => sectionsView.toggleStyle(),
});
sectionsView.syncButton();
}
stream = moduleApi.sse('/stream', {
open() { backfill(); },
error() {
moduleApi.setStatus('error', 'Lost the ProdDash stream — reconnecting');
},
events: {
state(e) {
let next;
try { next = JSON.parse(e.data); } catch { return; }
applyState(next);
},
pos(e) {
try { takePos(JSON.parse(e.data)); } catch { return; }
if (state && !moving()) impl.frame();
loop();
},
},
});
backfill();
resizeObserver = new ResizeObserver(() => {
fitAll();
if (view === 'sections' && state) sectionsView.place();
});
resizeObserver.observe(shell);
// Stopped tiles still have a clock to keep honest (Set Time's end time).
tickTimer = setInterval(() => { if (state && !moving()) impl.frame(); }, 1000);
},
stop() {
stopped = true;
if (stream) stream.close();
stream = null;
cancelAnimationFrame(raf);
raf = 0;
clearInterval(tickTimer);
if (resizeObserver) resizeObserver.disconnect();
root.innerHTML = '';
},
};
}
+36
View File
@@ -0,0 +1,36 @@
{
"id": "ableset",
"name": "AbleSet",
"version": "1.0.1",
"proddash": ">=1.5.0",
"description": "The song AbleSet is playing — tempo, time left, sections, setlist and status",
"permissions": [
{
"kind": "local-network",
"reason": "Following AbleSet on this network"
}
],
"provides": ["timers"],
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": {
"w": 1,
"h": 1
},
"defaultSize": {
"w": 8,
"h": 4
},
"configSchema": {
"ableset": {
"type": "endpoint",
"label": "AbleSet",
"default": {
"host": "",
"port": 39051
},
"help": "The Mac running AbleSet (e.g. AB-Tracks.local). 39051 is AbleSet's OSC port; it only changes if someone changed it in AbleSet's settings."
}
}
}
+101
View File
@@ -0,0 +1,101 @@
'use strict';
/**
* The slice of OSC 1.0 AbleSet speaks — messages and bundles with int32,
* float32, string, blob, true/false/nil — encoded and decoded with Buffer
* alone, so the module needs nothing outside Node.
*/
function pad4(n) {
return (n + 3) & ~3;
}
function encodeString(s) {
const raw = Buffer.from(String(s), 'utf8');
const out = Buffer.alloc(pad4(raw.length + 1));
raw.copy(out);
return out;
}
/**
* One message. Arguments are typed by their JS value: integers are int32,
* other numbers float32, booleans T/F, null nil, everything else a string.
*/
function encodeMessage(address, args = []) {
let tags = ',';
const parts = [];
for (const a of args) {
if (a === null || a === undefined) {
tags += 'N';
} else if (typeof a === 'boolean') {
tags += a ? 'T' : 'F';
} else if (typeof a === 'number' && Number.isInteger(a)) {
tags += 'i';
const b = Buffer.alloc(4);
b.writeInt32BE(a);
parts.push(b);
} else if (typeof a === 'number') {
tags += 'f';
const b = Buffer.alloc(4);
b.writeFloatBE(a);
parts.push(b);
} else {
tags += 's';
parts.push(encodeString(a));
}
}
return Buffer.concat([encodeString(address), encodeString(tags), ...parts]);
}
function readString(buf, at) {
let end = at;
while (end < buf.length && buf[end] !== 0) end += 1;
if (end >= buf.length) throw new Error('unterminated OSC string');
return { value: buf.toString('utf8', at, end), next: pad4(end + 1) };
}
function decodeMessage(buf, out) {
const addr = readString(buf, 0);
let at = addr.next;
const args = [];
if (at < buf.length && buf[at] === 0x2c) {
const tagStr = readString(buf, at);
at = tagStr.next;
for (const t of tagStr.value.slice(1)) {
switch (t) {
case 'i': args.push(buf.readInt32BE(at)); at += 4; break;
case 'f': args.push(buf.readFloatBE(at)); at += 4; break;
case 'd': args.push(buf.readDoubleBE(at)); at += 8; break;
case 'h': args.push(Number(buf.readBigInt64BE(at))); at += 8; break;
case 's': case 'S': { const s = readString(buf, at); args.push(s.value); at = s.next; break; }
case 'b': { const n = buf.readInt32BE(at); args.push(buf.subarray(at + 4, at + 4 + n)); at = pad4(at + 4 + n); break; }
case 'T': args.push(true); break;
case 'F': args.push(false); break;
case 'N': args.push(null); break;
case 'I': args.push(Infinity); break;
case 't': at += 8; break;
default: throw new Error(`unsupported OSC type tag "${t}"`);
}
}
}
out.push({ address: addr.value, args });
}
/** Every message in a packet, bundles flattened, in order. */
function decodePacket(buf, out = []) {
if (buf.length >= 16 && buf.toString('ascii', 0, 8) === '#bundle\0') {
let at = 16; // "#bundle\0" + 8-byte timetag
while (at + 4 <= buf.length) {
const n = buf.readInt32BE(at);
at += 4;
if (n <= 0 || at + n > buf.length) break;
decodePacket(buf.subarray(at, at + n), out);
at += n;
}
return out;
}
decodeMessage(buf, out);
return out;
}
module.exports = { encodeMessage, decodePacket };
+719
View File
@@ -0,0 +1,719 @@
'use strict';
/**
* AbleSet — server part.
*
* Owns the one connection to AbleSet: an OSC subscription over UDP (AbleSet
* listens on 39051). `/subscribe auto <port>` makes AbleSet push every value
* that changes to our socket, `/getValues` fills in everything that is
* already true, and AbleSet's `/heartbeat` every 2 s is how we know it is
* still there — when heartbeats stop (AbleSet quit, the Mac slept, the
* network dropped) we keep asking again every few seconds until it answers,
* because a restarted AbleSet has forgotten its subscribers.
*
* The raw values become one view-model, streamed to every tile:
*
* GET /state → { state } (instant paint)
* GET /stream → SSE: `state` on any change, `pos` while playing
* GET /timers(/stream) → song and set countdowns for the Timers module
*
* `pos` carries only what moves every frame (playhead, time left); the
* tiles extrapolate between packets from the tempo, so 5 packets a second
* draws a smooth playhead.
*/
const dgram = require('dgram');
const dns = require('dns');
const { encodeMessage, decodePacket } = require('./osc');
const HEARTBEAT_MS = 15000; // SSE keepalive comment
const SILENT_MS = 5000; // no heartbeat for this long → AbleSet is gone
const RESUBSCRIBE_MS = 3000; // how often to ask again while it is gone
const POS_MS = 200; // playhead packets to tiles while playing
const COALESCE_MS = 40; // AbleSet sends a section change as a burst of addresses
const FINE_MS = 100; // fine-position throttle we ask AbleSet for
/** Things AbleSet can send that no tile draws — kept off the wire. */
const EXCLUDES = ['!/mixer/**', '!/lyrics/**', '!/cues/**', '!/devices/**', '!/settings/**', '!/midi/**', '!/shared/**'];
let current = null;
function emptyState() {
return {
reachable: false,
configured: false,
lastError: '',
live: false,
loading: false,
playing: false,
paused: false,
recording: false,
countingIn: false,
tempo: null,
timeSig: null,
setlist: { name: '', songs: [] },
song: null,
section: null,
nextSection: null,
sections: [],
nextSong: null,
queued: null,
loop: { enabled: false, start: null, end: null, inSection: false },
audio: [],
version: '',
pos: emptyPos(),
};
}
function emptyPos() {
return { beats: null, remainingSong: null, remainingSet: null };
}
module.exports = {
init({ config, log }) {
const ep = config.ableset && typeof config.ableset === 'object' ? config.ableset : {};
const host = String(ep.host || '').trim();
const port = Number(ep.port) || 39051;
const configured = Boolean(host);
const values = new Map(); // OSC address → args, as AbleSet last said
const streams = new Set(); // tile SSE clients
const timerStreams = new Set(); // Timers-module SSE clients
let lastHeard = 0;
let lastAsked = 0;
let resolved = '';
let lastError = '';
let sock = null;
let stopped = false;
let coalesce = null;
let lastFrame = '';
let lastTimersFrame = '';
// Playhead and countdowns, each as "value at a moment" so they can be
// extrapolated to any other moment. AbleSet's time-left values are whole
// seconds; restamping on every one of them makes a countdown stutter, so
// a model is only moved when AbleSet disagrees with it by over a second.
const beatsModel = { value: null, at: 0 };
const songModel = { value: null, at: 0 };
const setModel = { value: null, at: 0 };
const num = (a, i = 0) => {
const v = values.get(a);
const n = v ? Number(v[i]) : NaN;
return v && v[i] !== null && Number.isFinite(n) ? n : null;
};
const str = (a, i = 0) => {
const v = values.get(a);
return v && v[i] != null ? String(v[i]) : '';
};
const arr = (a) => values.get(a) || [];
const flag = (a) => num(a) === 1 || values.get(a)?.[0] === true;
const isPlaying = () => flag('/global/isPlaying');
const tempo = () => num('/global/tempo');
function extrapolate(model, sign) {
if (model.value == null) return null;
if (!isPlaying()) return model.value;
return model.value + sign * (Date.now() - model.at) / 1000;
}
function beatsNow() {
if (beatsModel.value == null) return null;
const t = tempo();
if (!isPlaying() || !t) return beatsModel.value;
return beatsModel.value + ((Date.now() - beatsModel.at) / 1000) * (t / 60);
}
function nudge(model, reported) {
if (reported == null) { model.value = null; return; }
const predicted = extrapolate(model, -1);
if (predicted == null || Math.abs(predicted - reported) > 1.05 || !isPlaying()) {
model.value = reported;
model.at = Date.now();
} else {
// Keep the running model; re-base it so the stamp stays recent.
model.value = predicted;
model.at = Date.now();
}
}
function colorOf(a) {
const v = values.get(a);
if (!v) return null;
const name = v[0] == null ? '' : String(v[0]);
const hex = v[1] == null ? '' : String(v[1]);
return name && name !== 'default' && /^#[0-9a-f]{6}$/i.test(hex) ? hex : null;
}
function part(prefix) {
const name = str(`${prefix}Name`);
if (!name && num(`${prefix}Index`) == null) return null;
const index = num(`${prefix}Index`);
if (index != null && index < 0) return null;
return {
name,
index,
start: num(`${prefix}Start`),
end: num(`${prefix}End`),
duration: num(`${prefix}Duration`),
color: colorOf(`${prefix}Color`),
};
}
function audioInterfaces() {
const out = [];
const names = arr('/audioInterfaces/names');
const statuses = arr('/audioInterfaces/status');
names.forEach((n, i) => {
out.push({ name: String(n || `Interface ${i + 1}`), status: String(statuses[i] || '') });
});
// AbleSet 2 reports its PlayAUDIO12 on its own addresses.
if (!names.length && flag('/playaudio12/isConnected')) {
const scene = num('/playaudio12/scene');
out.push({ name: 'PlayAUDIO12', status: scene === 2 ? 'sceneB' : scene === 1 ? 'sceneA' : '' });
}
return out;
}
function buildState() {
const songs = arr('/setlist/songs');
const durations = arr('/setlist/songDurations');
const colors = arr('/setlist/songColors');
const sectionNames = arr('/setlist/sections');
const sectionColors = arr('/setlist/sectionColors');
const song = part('/setlist/activeSong');
const qIdx = values.get('/setlist/queuedIndex') || [];
const qName = values.get('/setlist/queuedName') || [];
const queuedType = str('/setlist/queuedType');
const ts = values.get('/global/timeSignature');
return {
reachable: isReachable(),
configured,
lastError,
live: flag('/global/isConnected'),
loading: flag('/global/isLoadingFile'),
playing: isPlaying(),
paused: flag('/global/isPaused'),
recording: flag('/global/isRecording'),
countingIn: flag('/setlist/isCountingIn'),
tempo: tempo(),
timeSig: ts && ts.length >= 2 && ts[0] != null ? [Number(ts[0]), Number(ts[1])] : null,
setlist: {
name: str('/setlist/name'),
songs: songs.map((name, i) => ({
name: String(name ?? ''),
duration: durations[i] == null ? null : Number(durations[i]),
color: typeof colors[i] === 'string' && colors[i] !== 'default' ? colors[i] : null,
})),
},
song,
section: part('/setlist/activeSection'),
nextSection: part('/setlist/nextSection'),
sections: sectionNames.map((name, i) => ({
name: String(name ?? ''),
color: typeof sectionColors[i] === 'string' && sectionColors[i] !== 'default' ? sectionColors[i] : null,
})),
sectionLoop: {
mode: str('/setlist/activeSectionLoopMode'),
count: num('/setlist/activeSectionLoopCount'),
},
nextSong: part('/setlist/nextSong'),
queued: queuedType && qIdx[0] != null && Number(qIdx[0]) >= 0
? { type: queuedType, song: String(qName[0] ?? ''), section: String(qName[1] ?? ''), songIndex: Number(qIdx[0]), sectionIndex: qIdx[1] == null ? -1 : Number(qIdx[1]) }
: null,
loop: {
enabled: flag('/setlist/loopEnabled'),
start: num('/setlist/loopStart'),
end: num('/setlist/loopEnd'),
inSection: flag('/setlist/isInActiveSectionLoop'),
},
audio: audioInterfaces(),
version: str('/version/app'),
pos: buildPos(),
};
}
/**
* Time left, as AbleSet counts it. AbleSet only sends these while Live is
* connected; without them the song's length and the playhead still say
* how far there is to go, and the set is the rest of the setlist on top.
*/
function songLeftNow() {
const reported = extrapolate(songModel, -1);
if (reported != null) return reported;
const dur = num('/setlist/activeSongDuration');
const start = num('/setlist/activeSongStart');
const end = num('/setlist/activeSongEnd');
const b = beatsNow();
if (dur == null || start == null || end == null || end <= start || b == null) return null;
return Math.max(0, dur * (1 - Math.min(1, Math.max(0, (b - start) / (end - start)))));
}
function setLeftNow() {
const reported = extrapolate(setModel, -1);
if (reported != null) return reported;
const song = songLeftNow();
const idx = num('/setlist/activeSongIndex');
if (song == null || idx == null) return null;
return song + arr('/setlist/songDurations').slice(idx + 1).reduce((a, d) => a + (Number(d) || 0), 0);
}
function buildPos() {
const round = (v, d) => (v == null ? null : Math.round(v * d) / d);
return {
beats: round(beatsNow(), 1000),
remainingSong: round(songLeftNow(), 100),
remainingSet: round(setLeftNow(), 100),
};
}
function isReachable() {
return lastHeard > 0 && Date.now() - lastHeard < SILENT_MS;
}
/* ── fan-out ─────────────────────────────────────────────────── */
function send(set, payload) {
for (const res of set) {
try { res.write(payload); } catch { set.delete(res); }
}
}
function broadcastState() {
coalesce = null;
const state = buildState();
// Change detection ignores the moving parts, which `pos` carries.
const { pos, ...still } = state;
const frame = JSON.stringify(still);
if (frame !== lastFrame) {
lastFrame = frame;
if (streams.size) send(streams, `event: state\ndata: ${JSON.stringify(state)}\n\n`);
}
broadcastTimers();
}
function scheduleState() {
if (!coalesce) coalesce = setTimeout(broadcastState, COALESCE_MS);
}
function broadcastTimers() {
if (!timerStreams.size) return;
const snap = timersSnapshot();
const { updatedAt, ...rest } = snap;
const key = JSON.stringify(rest.timers.map((t) => [t.state, t.label, t.status, t.targetMs]));
if (key === lastTimersFrame) return;
lastTimersFrame = key;
send(timerStreams, `event: timers\ndata: ${JSON.stringify(snap)}\n\n`);
}
function timersSnapshot() {
const now = Date.now();
const playing = isPlaying();
const reachable = isReachable();
const song = part('/setlist/activeSong');
const remSong = songLeftNow();
const remSet = setLeftNow();
const state = !reachable ? 'idle' : playing ? 'running' : remSong != null ? 'paused' : 'idle';
const ms = (s) => (s == null ? null : Math.max(0, Math.round(s * 1000)));
const songElapsed = song?.duration != null && remSong != null ? ms(song.duration - remSong) : null;
const songs = arr('/setlist/songs');
const idx = num('/setlist/activeSongIndex');
const left = idx == null ? null : Math.max(0, songs.length - idx - 1);
return {
source: 'ableset',
label: 'AbleSet',
updatedAt: now,
timers: [
{
id: 'song',
label: 'Song',
kind: 'countdown',
state,
startedAt: playing && songElapsed != null ? now - songElapsed : null,
elapsedMs: songElapsed,
remainingMs: ms(remSong),
targetMs: ms(song?.duration),
status: song ? { text: song.name, tone: reachable ? 'ok' : 'muted' } : null,
detail: str('/setlist/activeSectionName') || null,
},
{
id: 'set',
label: 'Set',
kind: 'countdown',
state,
startedAt: null,
elapsedMs: null,
remainingMs: ms(remSet),
targetMs: null,
status: str('/setlist/name') ? { text: str('/setlist/name'), tone: 'muted' } : null,
detail: left == null ? null : `${left} song${left === 1 ? '' : 's'} left`,
},
],
};
}
/* ── OSC in ──────────────────────────────────────────────────── */
const FAST = new Set([
'/global/beatsPosition', '/global/finePosition', '/setlist/activeSongProgress',
'/setlist/activeSectionProgress', '/setlist/remainingTimeInSong', '/setlist/remainingTimeInSet',
'/global/humanPosition', '/global/currentMeasure', '/global/measureOrPosition',
'/global/cpuAverage', '/global/cpuPeak', '/heartbeat', '/subscribed',
]);
function onMessage(m) {
const { address, args } = m;
if (address === '/global/finePosition' || address === '/global/beatsPosition') {
const v = Number(args[0]);
if (Number.isFinite(v)) {
// A whole-beat report while fine ones flow would drag the playhead back.
if (address === '/global/beatsPosition' && values.has('/global/finePosition')
&& Math.abs((beatsNow() ?? v) - v) < 1) return void values.set(address, args);
beatsModel.value = v;
beatsModel.at = Date.now();
}
} else if (address === '/setlist/remainingTimeInSong') {
nudge(songModel, args[0] == null ? null : Number(args[0]));
} else if (address === '/setlist/remainingTimeInSet') {
nudge(setModel, args[0] == null ? null : Number(args[0]));
} else if (address === '/global/isPlaying') {
// Freeze the models at the moment the transport changed.
const b = beatsNow();
if (b != null) { beatsModel.value = b; beatsModel.at = Date.now(); }
for (const mdl of [songModel, setModel]) {
const v = extrapolate(mdl, -1);
if (v != null) { mdl.value = v; mdl.at = Date.now(); }
}
}
values.set(address, args);
if (!FAST.has(address)) scheduleState();
}
/* ── connection ──────────────────────────────────────────────── */
function ask() {
if (!sock || stopped) return;
lastAsked = Date.now();
dns.lookup(host, { family: 4 }, (err, addr) => {
if (stopped || !sock) return;
if (err) {
lastError = `can't find ${host} (${err.code || err.message})`;
scheduleState();
return;
}
resolved = addr;
const myPort = sock.address().port;
const out = (address, args) => {
try {
sock.send(encodeMessage(address, args), port, addr, (e) => {
if (e) lastError = e.message;
});
} catch (e) {
lastError = e.message;
}
};
out('/subscribe', ['auto', myPort, 'ProdDash', FINE_MS, ...EXCLUDES]);
out('/getValues', ['auto', myPort]);
});
}
const watchdog = setInterval(() => {
if (!configured || stopped) return;
const wasReachable = lastHeard > 0 && Date.now() - lastHeard < SILENT_MS + 1000;
if (!isReachable()) {
if (wasReachable) {
log(`no heartbeat from AbleSet at ${host} — asking again`);
lastError = 'AbleSet stopped answering';
scheduleState();
}
if (Date.now() - lastAsked >= RESUBSCRIBE_MS) ask();
}
}, 1000);
watchdog.unref?.();
// While playing, the playhead goes out five times a second. While
// stopped it only goes out when it moved — a jump, a scrub.
let lastPos = '';
const posTimer = setInterval(() => {
if (!streams.size || !isReachable()) return;
const frame = JSON.stringify(buildPos());
if (!isPlaying() && frame === lastPos) return;
lastPos = frame;
send(streams, `event: pos\ndata: ${frame}\n\n`);
}, POS_MS);
posTimer.unref?.();
const keepalive = setInterval(() => {
send(streams, ': ping\n\n');
send(timerStreams, ': ping\n\n');
// The Timers module derives running values itself; a fresh anchor now
// and then keeps a long song honest.
if (timerStreams.size) {
lastTimersFrame = '';
broadcastTimers();
}
}, HEARTBEAT_MS);
keepalive.unref?.();
if (configured) {
sock = dgram.createSocket('udp4');
sock.on('message', (buf, rinfo) => {
if (resolved && rinfo.address !== resolved) return; // only AbleSet talks to us
let msgs;
try {
msgs = decodePacket(buf);
} catch (e) {
log(`unreadable OSC packet from ${rinfo.address}: ${e.message}`);
return;
}
const wasReachable = isReachable();
lastHeard = Date.now();
if (!wasReachable) {
lastError = '';
log(`AbleSet at ${host} (${rinfo.address}) is answering`);
scheduleState();
}
for (const m of msgs) onMessage(m);
});
sock.on('error', (e) => {
lastError = e.message;
log(`OSC socket error: ${e.message}`);
});
sock.bind(0, () => {
log(`following AbleSet at ${host}:${port}`);
ask();
});
} else {
log('no AbleSet host configured — set one in /admin');
}
current = {
streams,
timerStreams,
getState: buildState,
getTimers: timersSnapshot,
};
return {
stop() {
stopped = true;
clearInterval(watchdog);
clearInterval(posTimer);
clearInterval(keepalive);
clearTimeout(coalesce);
if (sock) {
// Be polite: tell AbleSet to stop sending to a port nobody reads.
const s = sock;
sock = null;
try {
if (resolved) s.send(encodeMessage('/unsubscribe', ['auto', s.address().port]), port, resolved, () => { try { s.close(); } catch { /* closed */ } });
else s.close();
} catch {
try { s.close(); } catch { /* closed */ }
}
}
for (const set of [streams, timerStreams]) {
for (const res of set) { try { res.end(); } catch { /* gone */ } }
set.clear();
}
if (current && current.streams === streams) current = null;
},
health() {
if (!configured) return { status: 'error', message: 'No AbleSet host configured' };
if (isReachable()) {
const live = flag('/global/isConnected') ? '' : ' — Ableton Live is not connected';
const set = str('/setlist/name');
return { status: live ? 'connecting' : 'ok', message: `Following ${host}${set ? ` · ${set}` : ''}${live}` };
}
if (lastError) return { status: 'error', message: `AbleSet at ${host}: ${lastError}` };
return { status: 'connecting', message: `Waiting for AbleSet at ${host}:${port} to answer…` };
},
};
},
/**
* One picker entry per tile kind. Each carries only the gear settings its
* tile can act on (guide rules 5–8): four or fewer switches sit loose, the
* Now Playing card's longer list folds into a Show group.
*/
tiles() {
const sw = (label, extra = {}) => ({ type: 'switch', label, default: true, ...extra });
const clock = {
type: 'select',
label: 'Song time',
default: 'remaining',
options: [
{ value: 'remaining', label: 'Time left' },
{ value: 'elapsed', label: 'Elapsed' },
{ value: 'both', label: 'Both' },
],
};
const warnAt = { type: 'number', label: 'Warn at (s)', default: 30, group: 'Colours' };
const alertAt = { type: 'number', label: 'Alert at (s)', default: 10, group: 'Colours' };
return [
{
id: 'now',
name: 'Now Playing',
description: 'The song, its tempo, time left, section, progress and what comes next',
defaultSize: { w: 8, h: 4 },
minSize: { w: 3, h: 2 },
instanceSchema: {
clock,
songColors: sw('Song colours', { default: false }),
showTempo: sw('Tempo', { group: 'Show' }),
showMeter: sw('Time signature', { group: 'Show' }),
showDuration: sw('Duration', { group: 'Show' }),
showClock: sw('Song time', { group: 'Show' }),
showSection: sw('Section', { group: 'Show' }),
showProgress: sw('Progress bar', { group: 'Show' }),
showNext: sw('Next song', { group: 'Show' }),
showLeft: sw('Songs left', { group: 'Show' }),
warnAt,
alertAt,
},
instanceGroups: { Show: { collapsed: true, columns: 2 }, Colours: { collapsed: true, columns: 2 } },
},
{
id: 'sections',
name: 'Song Sections',
description: 'Where the song is — its sections sliding past, as a strip or a wheel',
defaultSize: { w: 8, h: 2 },
minSize: { w: 2, h: 1 },
instanceSchema: {
showProgress: sw('Section progress'),
showSong: sw('Song name', { default: false }),
sectionColors: sw('Section colours', { default: false }),
},
},
{
id: 'setlist',
name: 'Setlist',
description: 'Every song in the set, played, playing and to come',
defaultSize: { w: 3, h: 6 },
minSize: { w: 2, h: 2 },
instanceSchema: {
showDurations: sw('Durations'),
showPlayed: sw('Played songs'),
showTotal: sw('Time left'),
songColors: sw('Song colours', { default: false }),
},
},
{
id: 'transport',
name: 'Transport',
description: 'Playing, stopped, counting in or looping, in colour',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
showPosition: sw('Bar and beat'),
showLoop: sw('Loop'),
},
},
{
id: 'tempo',
name: 'Tempo',
description: 'BPM and time signature, with a light on every beat',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
showMeter: sw('Time signature'),
showBeats: sw('Beat lights'),
},
},
{
id: 'song-time',
name: 'Song Time',
description: 'Time left in the song, turning amber then red near the end',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
clock,
showSong: sw('Song name'),
showProgress: sw('Progress bar'),
warnAt,
alertAt,
},
instanceGroups: { Colours: { collapsed: true, columns: 2 } },
},
{
id: 'set-time',
name: 'Set Time',
description: 'Time left in the whole set and how many songs remain',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
showLeft: sw('Songs left'),
showEnd: sw('End time'),
},
},
{
id: 'section',
name: 'Section',
description: 'The section playing now, what is next, and the count to the change',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
showNext: sw('Next section'),
showCount: sw('Countdown'),
sectionColors: sw('Section colours', { default: false }),
},
},
{
id: 'next-song',
name: 'Next Song',
description: 'The song after this one, and anything queued',
defaultSize: { w: 3, h: 2 },
minSize: { w: 1, h: 1 },
instanceSchema: {
showDuration: sw('Duration'),
showQueued: sw('Queued'),
},
},
{
id: 'status',
name: 'AbleSet Status',
description: 'AbleSet, Ableton Live and audio interface health at a glance',
defaultSize: { w: 3, h: 3 },
minSize: { w: 2, h: 1 },
instanceSchema: {
showAudio: sw('Audio interfaces'),
showSetlist: sw('Setlist name'),
},
},
];
},
routes() {
const sendJson = (res, code, body) => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
};
const openSse = (req, res, set, first) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write('retry: 3000\n\n');
res.write(first);
if (!set) return void res.end();
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
set.add(res);
req.on('close', () => set.delete(res));
};
return {
'GET /state': (req, res) => sendJson(res, 200, { state: current ? current.getState() : emptyState() }),
'GET /stream': (req, res) => {
const state = current ? current.getState() : emptyState();
openSse(req, res, current ? current.streams : null, `event: state\ndata: ${JSON.stringify(state)}\n\n`);
},
'GET /timers': (req, res) => sendJson(res, 200, current ? current.getTimers() : { source: 'ableset', label: 'AbleSet', updatedAt: Date.now(), timers: [] }),
'GET /timers/stream': (req, res) => {
const snap = current ? current.getTimers() : { source: 'ableset', label: 'AbleSet', updatedAt: Date.now(), timers: [] };
openSse(req, res, current ? current.timerStreams : null, `event: timers\ndata: ${JSON.stringify(snap)}\n\n`);
},
};
},
};
+416
View File
@@ -0,0 +1,416 @@
/* AbleSet tiles. Every size hangs off the tile itself (container units), so
a tile reads the same at 2×1 on a laptop as at 12×6 on a wall. Colours are
the shell's variables; a tone (ok / warn / alert / muted) picks among them,
and AbleSet's own song or section colour arrives as --song when a tile is
set to use it. */
[data-module="ableset"] .as-root {
--tone: var(--text);
--live: var(--accent);
position: absolute;
inset: 0;
container-type: size;
overflow: hidden;
user-select: none;
-webkit-user-select: none;
color: var(--text);
font-variant-numeric: tabular-nums;
}
[data-module="ableset"] .as-root.has-song-color { --live: var(--song); }
[data-module="ableset"] .as-root[data-tone="ok"] { --tone: var(--accent); }
[data-module="ableset"] .as-root[data-tone="warn"] { --tone: var(--warn); }
[data-module="ableset"] .as-root[data-tone="alert"] { --tone: var(--danger); }
[data-module="ableset"] .as-root[data-tone="muted"] { --tone: var(--muted); }
[data-module="ableset"] .as-body {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: center;
padding: clamp(4px, 4cqmin, 28px);
gap: clamp(2px, 2.5cqh, 18px);
min-width: 0;
}
[data-module="ableset"] [hidden] { display: none !important; }
[data-module="ableset"] .as-offline {
position: absolute;
top: clamp(3px, 3cqmin, 14px);
right: clamp(4px, 4cqmin, 18px);
z-index: 2;
font-size: clamp(9px, 6cqmin, 15px);
font-weight: 700;
color: var(--danger);
text-transform: uppercase;
letter-spacing: 0.04em;
}
[data-module="ableset"] .as-root.is-offline .as-body { opacity: 0.35; filter: grayscale(0.7); }
[data-module="ableset"] [data-fit] {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
/* ── the song bar: played sections · this section · the playhead ── */
[data-module="ableset"] .as-bar {
--done: 0%;
--sect-l: 0%;
--sect-w: 0%;
--played: 0%;
position: relative;
flex-shrink: 0;
height: clamp(4px, 5.5cqh, 26px);
border-radius: 999px;
overflow: hidden;
background: color-mix(in srgb, var(--live) 14%, var(--panel));
}
[data-module="ableset"] .as-bar-done {
position: absolute;
inset: 0 auto 0 0;
width: var(--done);
background: color-mix(in srgb, var(--live) 32%, var(--panel));
}
[data-module="ableset"] .as-bar-sect {
position: absolute;
top: 0;
bottom: 0;
left: var(--sect-l);
width: var(--sect-w);
background: color-mix(in srgb, var(--live) 55%, var(--panel));
overflow: hidden;
}
[data-module="ableset"] .as-bar-played {
position: absolute;
inset: 0 auto 0 0;
width: var(--played);
background: linear-gradient(90deg,
color-mix(in srgb, var(--live) 70%, var(--panel)) 0%,
color-mix(in srgb, var(--live) 70%, var(--panel)) calc(100% - 3.5cqw),
color-mix(in srgb, var(--live) 70%, var(--text)) 100%);
}
/* ── NOW PLAYING ─────────────────────────────────────────────────── */
[data-module="ableset"] .as-now .as-body {
align-items: center;
padding-inline: clamp(6px, 7cqw, 90px);
gap: clamp(3px, 4cqh, 30px);
}
[data-module="ableset"] .as-now .as-title-box,
[data-module="ableset"] .as-now .as-next-box { width: 100%; display: flex; justify-content: center; min-width: 0; }
[data-module="ableset"] .as-now .as-title {
font-size: clamp(14px, 20cqh, 170px);
font-weight: 800;
line-height: 1.05;
letter-spacing: -0.01em;
color: var(--text);
transition: color 0.3s;
}
[data-module="ableset"] .as-now.is-playing .as-title { color: var(--live); }
[data-module="ableset"] .as-now .as-bar { width: 100%; }
[data-module="ableset"] .as-badges {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: clamp(3px, 1.8cqh, 16px);
max-width: 100%;
}
[data-module="ableset"] .as-badge {
font-size: clamp(9px, 7cqh, 44px);
font-weight: 700;
line-height: 1;
padding: 0.28em 0.5em;
border-radius: 0.22em;
background: color-mix(in srgb, var(--text) 12%, var(--panel));
color: color-mix(in srgb, var(--text) 80%, var(--accent));
white-space: nowrap;
}
[data-module="ableset"] .as-badge.b-section {
color: var(--text);
text-transform: uppercase;
background: color-mix(in srgb, var(--text) 7%, var(--panel));
}
[data-module="ableset"] .as-badge.b-clock[data-tone="warn"] { color: var(--accent-text); background: var(--warn); }
[data-module="ableset"] .as-badge.b-clock[data-tone="alert"] { color: var(--accent-text); background: var(--danger); }
[data-module="ableset"] .as-next {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
min-width: 0;
gap: clamp(1px, 0.6cqh, 6px);
}
[data-module="ableset"] .as-next-label {
font-size: clamp(8px, 5cqh, 30px);
font-weight: 700;
color: color-mix(in srgb, var(--live) 55%, var(--muted));
}
[data-module="ableset"] .as-next.is-queued .as-next-label { color: var(--warn); }
[data-module="ableset"] .as-next-title {
font-size: clamp(11px, 12cqh, 90px);
font-weight: 500;
line-height: 1.1;
color: color-mix(in srgb, var(--live) 45%, var(--muted));
}
[data-module="ableset"] .as-left {
font-size: clamp(8px, 6cqh, 36px);
color: color-mix(in srgb, var(--live) 40%, var(--muted));
}
/* ── SONG SECTIONS ──────────────────────────────────────────────── */
[data-module="ableset"] .as-sections .as-body { padding: clamp(3px, 3cqmin, 16px) 0; gap: clamp(2px, 2cqh, 10px); }
[data-module="ableset"] .as-sections .as-song-name {
flex-shrink: 0;
text-align: center;
padding: 0 clamp(4px, 3cqw, 20px);
font-size: clamp(9px, 13cqh, 28px);
font-weight: 700;
color: var(--muted);
}
[data-module="ableset"] .as-viewport {
position: relative;
flex: 1;
min-height: 0;
overflow: hidden;
-webkit-mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
}
[data-module="ableset"] .as-track {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: flex;
align-items: center;
gap: clamp(4px, 2cqw, 18px);
transition: transform 0.65s cubic-bezier(0.22, 0.9, 0.3, 1);
will-change: transform;
}
[data-module="ableset"] .as-track.no-anim,
[data-module="ableset"] .as-track.no-anim .as-pill { transition: none !important; }
[data-module="ableset"] .as-pill {
--p: 0%;
--sect: var(--accent);
position: relative;
flex-shrink: 0;
display: flex;
align-items: center;
height: min(78%, 22cqw);
padding: 0 0.8em;
border-radius: 0.35em;
font-size: clamp(9px, 26cqh, 64px);
font-weight: 700;
line-height: 1;
white-space: nowrap;
overflow: hidden;
color: var(--muted);
background: color-mix(in srgb, var(--text) 8%, var(--panel));
border: 2px solid transparent;
transition: background 0.4s, color 0.4s, border-color 0.4s, opacity 0.5s, transform 0.65s cubic-bezier(0.22, 0.9, 0.3, 1);
}
[data-module="ableset"] .as-pill.has-color { background: color-mix(in srgb, var(--sect) 22%, var(--panel)); }
[data-module="ableset"] .as-pill.is-past { opacity: 0.45; }
[data-module="ableset"] .as-pill.is-next { border-color: color-mix(in srgb, var(--sect) 60%, transparent); color: var(--text); }
[data-module="ableset"] .as-pill.is-current {
color: var(--accent-text);
background: color-mix(in srgb, var(--sect) 55%, var(--panel));
}
[data-module="ableset"] .as-pill-fill {
position: absolute;
inset: 0 auto 0 0;
width: 0;
background: var(--sect);
}
[data-module="ableset"] .as-pill.is-current .as-pill-fill { width: var(--p); }
[data-module="ableset"] .as-pill-text { position: relative; }
[data-module="ableset"] .as-pill.is-empty { color: var(--muted); }
/* the lottery wheel: faces on a drum turning towards the viewer */
[data-module="ableset"] .is-wheel .as-viewport {
perspective: 900px;
-webkit-mask-image: linear-gradient(180deg, transparent, #000 22%, #000 78%, transparent);
mask-image: linear-gradient(180deg, transparent, #000 22%, #000 78%, transparent);
}
[data-module="ableset"] .is-wheel .as-track {
--face-h: 30px;
inset: 50% 0 auto 0;
display: block;
height: 0;
transform-style: preserve-3d;
transition: none;
}
[data-module="ableset"] .is-wheel .as-pill {
position: absolute;
left: 50%;
top: 0;
translate: -50% 0;
height: var(--face-h);
justify-content: center;
min-width: 55%;
max-width: 94%;
font-size: clamp(9px, calc(var(--face-h) * 0.55), 72px);
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
}
/* ── SETLIST ─────────────────────────────────────────────────────── */
[data-module="ableset"] .as-setlist .as-body { justify-content: flex-start; gap: 6px; padding: 8px; }
[data-module="ableset"] .as-set-head {
flex-shrink: 0;
font-size: 0.8rem;
font-weight: 700;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="ableset"] .as-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 3px; scrollbar-width: thin; }
[data-module="ableset"] .as-row {
--p: 0%;
--song: var(--accent);
position: relative;
display: flex;
align-items: center;
gap: 0.5em;
padding: 0.35em 0.55em;
border-radius: 6px;
font-size: clamp(11px, 5.5cqw, 19px);
background: color-mix(in srgb, var(--text) 5%, transparent);
overflow: hidden;
flex-shrink: 0;
}
[data-module="ableset"] .as-row-fill { position: absolute; inset: 0 auto 0 0; width: 0; background: color-mix(in srgb, var(--accent) 22%, transparent); }
[data-module="ableset"] .as-row.is-current .as-row-fill { width: var(--p); }
[data-module="ableset"] .as-row-name { position: relative; flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
[data-module="ableset"] .as-row-dur { position: relative; color: var(--muted); font-size: 0.85em; }
[data-module="ableset"] .as-swatch { position: relative; width: 0.55em; height: 0.55em; border-radius: 50%; background: var(--song); flex-shrink: 0; }
[data-module="ableset"] .as-row.is-past { opacity: 0.4; }
[data-module="ableset"] .as-row.is-current { font-weight: 700; color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, transparent); box-shadow: inset 3px 0 0 var(--accent); }
[data-module="ableset"] .as-row.is-next { box-shadow: inset 3px 0 0 color-mix(in srgb, var(--text) 40%, transparent); }
[data-module="ableset"] .as-row.is-queued { box-shadow: inset 3px 0 0 var(--warn); color: var(--warn); }
[data-module="ableset"] .as-set-foot { flex-shrink: 0; font-size: 0.85rem; color: var(--muted); text-align: right; }
[data-module="ableset"] .as-empty { color: var(--muted); padding: 1em; text-align: center; }
/* ── single readouts: transport, tempo, times, section, next ────── */
[data-module="ableset"] .as-big-box { display: flex; justify-content: center; min-width: 0; width: 100%; }
[data-module="ableset"] .as-big {
font-size: clamp(14px, 38cqh, 220px);
font-weight: 800;
line-height: 1;
color: var(--tone);
text-align: center;
transition: color 0.3s;
}
[data-module="ableset"] .as-big small { font-size: 0.35em; font-weight: 700; color: var(--muted); }
[data-module="ableset"] .as-caption {
text-align: center;
font-size: clamp(8px, 12cqh, 30px);
font-weight: 700;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
[data-module="ableset"] .as-sub {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 0.25em 1em;
font-size: clamp(8px, 12cqh, 34px);
color: var(--muted);
text-align: center;
white-space: nowrap;
}
[data-module="ableset"] .as-sub:empty { display: none; }
/* A tone washes the tile's background, so a wall of them reads at a glance. */
[data-module="ableset"] .as-transport,
[data-module="ableset"] .as-song-time,
[data-module="ableset"] .as-section,
[data-module="ableset"] .as-status,
[data-module="ableset"] .as-next-song {
background: color-mix(in srgb, var(--tone) 9%, transparent);
transition: background 0.3s;
}
[data-module="ableset"] .as-root[data-tone="muted"],
[data-module="ableset"] .as-root[data-tone=""] { background: none; }
[data-module="ableset"] .as-transport .as-big { text-transform: uppercase; font-size: clamp(12px, 34cqh, 180px); }
[data-module="ableset"] .as-transport .as-loop { color: var(--warn); font-weight: 700; }
[data-module="ableset"] .as-tempo .as-big { color: var(--text); }
[data-module="ableset"] .as-beats { display: flex; justify-content: center; gap: clamp(3px, 3cqw, 14px); flex-shrink: 0; }
[data-module="ableset"] .as-beats i {
width: clamp(6px, 11cqh, 30px);
aspect-ratio: 1;
border-radius: 50%;
background: color-mix(in srgb, var(--text) 14%, var(--panel));
transition: background 0.08s;
}
[data-module="ableset"] .as-beats i.is-lit { background: var(--text); }
[data-module="ableset"] .as-beats i.is-down.is-lit { background: var(--accent); }
[data-module="ableset"] .as-song-time .as-bar { height: clamp(3px, 5cqh, 14px); }
[data-module="ableset"] .as-section .as-big { text-transform: uppercase; }
[data-module="ableset"] .as-section.has-song-color .as-big { color: var(--song); }
[data-module="ableset"] .as-section .as-count { color: var(--tone); font-weight: 700; }
[data-module="ableset"] .as-sect-bar {
--p: 0%;
height: clamp(3px, 4cqh, 12px);
border-radius: 999px;
background: color-mix(in srgb, var(--text) 12%, var(--panel));
overflow: hidden;
flex-shrink: 0;
}
[data-module="ableset"] .as-sect-bar > div { height: 100%; width: var(--p); background: var(--tone); }
[data-module="ableset"] .as-next-song .as-big { color: var(--text); font-size: clamp(12px, 30cqh, 150px); }
[data-module="ableset"] .as-queued {
align-self: center;
font-size: clamp(8px, 11cqh, 28px);
font-weight: 700;
padding: 0.2em 0.6em;
border-radius: 0.3em;
color: var(--accent-text);
background: var(--warn);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
/* ── STATUS ──────────────────────────────────────────────────────── */
[data-module="ableset"] .as-status .as-body { justify-content: flex-start; padding: 8px 10px; }
[data-module="ableset"] .as-rows { display: flex; flex-direction: column; gap: 4px; }
[data-module="ableset"] .as-srow {
--dot: var(--muted);
display: flex;
align-items: center;
gap: 0.55em;
font-size: clamp(11px, 4.5cqw, 18px);
padding: 0.3em 0.5em;
border-radius: 6px;
background: color-mix(in srgb, var(--dot) 10%, transparent);
}
[data-module="ableset"] .as-srow[data-tone="ok"] { --dot: var(--accent); }
[data-module="ableset"] .as-srow[data-tone="warn"] { --dot: var(--warn); }
[data-module="ableset"] .as-srow[data-tone="alert"] { --dot: var(--danger); }
[data-module="ableset"] .as-srow[data-tone=""] { --dot: var(--text); background: color-mix(in srgb, var(--text) 5%, transparent); }
[data-module="ableset"] .as-srow i { width: 0.6em; height: 0.6em; border-radius: 50%; background: var(--dot); flex-shrink: 0; }
[data-module="ableset"] .as-sk { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
[data-module="ableset"] .as-sv { font-weight: 700; color: var(--dot); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 60%; }
[data-module="ableset"] .as-srow[data-tone=""] .as-sv { color: var(--text); }
+299
View File
@@ -0,0 +1,299 @@
// Band Lineup — client. Renders the shared stage board from /state + /stream.
// The Edit button opens an editor: an uploaded-photo library you drag (or click)
// into slots, plus rename / clear / upload / delete. Edits go to the server and
// come back over SSE, so every Band Lineup screen stays in sync. Birthday week
// (Wed→Tue) rains confetti.
const CONFETTI_COLORS = ['#f5c451', '#ff6b81', '#4fd1c5', '#a78bfa', '#ffffff'];
export default function create({ root, moduleApi }) {
let stream = null;
let state = null;
let editing = false;
let choirBtn = null;
let selectedLibId = ''; // click-to-place fallback for touch
const canvases = new Set();
let raf = null;
// Auto-scroll the editor while dragging a photo (native DnD won't do it reliably).
let dragScrolling = false;
let dragY = 0;
let dragBody = null;
let dragRaf = null;
function startDragAutoScroll() {
if (dragRaf) return;
const tick = () => {
if (!dragScrolling || !dragBody || !dragBody.isConnected) { dragRaf = null; return; }
const r = dragBody.getBoundingClientRect();
const zone = 90; // generous edge band so you don't have to be pixel-accurate
let dy = 0;
if (dragY < r.top + zone) dy = -Math.ceil((r.top + zone - dragY) / 4) - 3;
else if (dragY > r.bottom - zone) dy = Math.ceil((dragY - (r.bottom - zone)) / 4) + 3;
if (dy) dragBody.scrollTop += dy;
dragRaf = requestAnimationFrame(tick);
};
dragRaf = requestAnimationFrame(tick);
}
function stopDragAutoScroll() { dragScrolling = false; if (dragRaf) { cancelAnimationFrame(dragRaf); dragRaf = null; } }
/* ---------- confetti (always animates) ---------- */
function makeParticle(w, h, intensity, seedY) {
const ribbon = Math.random() < 0.55;
return {
x: Math.random() * w, y: seedY != null ? seedY : Math.random() * h,
w: ribbon ? 4 + Math.random() * 4 : 5 + Math.random() * 5, h: ribbon ? 9 + Math.random() * 8 : 0, ribbon,
color: CONFETTI_COLORS[(Math.random() * CONFETTI_COLORS.length) | 0],
rot: Math.random() * Math.PI * 2, vr: -0.14 + Math.random() * 0.28,
sway: 0.6 + Math.random() * 1.1, phase: Math.random() * Math.PI * 2,
vy: (intensity === 'subtle' ? 0.6 : 1.0) * (1.1 + Math.random() * 1.5),
};
}
function seed(c, w, h) { const base = c._intensity === 'subtle' ? 26 : 64; const n = Math.max(10, Math.round((base * (w * h)) / (300 * 500))); c._parts = Array.from({ length: n }, () => makeParticle(w, h, c._intensity)); }
function step(c) {
const w = c.clientWidth, h = c.clientHeight; if (!w || !h) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (c._w !== w || c._h !== h) { c.width = w * dpr; c.height = h * dpr; c._ctx = c.getContext('2d'); c._ctx.setTransform(dpr, 0, 0, dpr, 0, 0); c._w = w; c._h = h; seed(c, w, h); }
const ctx = c._ctx; ctx.clearRect(0, 0, w, h);
for (const p of c._parts) {
p.phase += 0.03; p.y += p.vy; p.x += Math.sin(p.phase) * p.sway; p.rot += p.vr;
if (p.y > h + 16) Object.assign(p, makeParticle(w, h, c._intensity, -16));
ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.rot); ctx.fillStyle = p.color;
if (p.ribbon) ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h); else { ctx.beginPath(); ctx.arc(0, 0, p.w / 2, 0, Math.PI * 2); ctx.fill(); }
ctx.restore();
}
}
function loop() { for (const c of [...canvases]) { if (!c.isConnected) { canvases.delete(c); continue; } step(c); } raf = canvases.size ? requestAnimationFrame(loop) : null; }
function addConfetti(host, intensity) { const c = document.createElement('canvas'); c.className = 'bl-confetti'; c._intensity = intensity; host.appendChild(c); canvases.add(c); if (!raf) raf = requestAnimationFrame(loop); }
/* ---------- helpers ---------- */
function initials(name) { const p = String(name || '').trim().split(/\s+/).filter(Boolean).slice(0, 2); return p.length ? p.map((x) => x[0]).join('').toUpperCase() : ''; }
// Per-tile Columns wins; 0 falls back to the admin default.
function resolveCols() { const per = Number(moduleApi.instanceSettings.columns) || 0; return Math.max(1, per > 0 ? per : (Number(state && state.columns) || 7)); }
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
function photoNode(person, cls) {
if (person && person.photo) { const img = el('img', cls || 'bl-img'); img.alt = ''; img.src = person.photo; img.loading = 'lazy'; return img; }
return el('div', 'bl-initials', initials(person && person.name));
}
async function api(pathStr, opts) { try { return await moduleApi.fetch(pathStr, opts); } catch { return null; } }
/* ---------- display board ---------- */
function stopConfetti() { canvases.clear(); if (raf) { cancelAnimationFrame(raf); raf = null; } }
function render() {
stopConfetti();
stopParallax();
root.innerHTML = '';
if (choirBtn) choirBtn.classList.toggle('active', !!(state && state.choir));
if (editing) { renderEditor(); return; }
const board = el('div', 'bl-board');
if (!state) { board.classList.add('bl-message'); board.textContent = 'Connecting…'; root.appendChild(board); return; }
const s = moduleApi.instanceSettings;
const birthdays = s.birthdays !== false;
const intensity = s.birthdayIntensity === 'full' ? 'full' : 'subtle';
const testIndex = birthdays ? String(s.birthdayTest || '') : '';
const cols = resolveCols();
const rows = Math.max(1, Math.ceil((state.slots ? state.slots.length : 1) / cols));
board.style.setProperty('--bl-cols', cols);
board.style.setProperty('--bl-rows', rows);
for (const slot of state.slots || []) {
const cell = el('div', 'bl-slot');
const person = slot.person;
if (person) {
const tile = el('div', 'bl-tile');
const photo = el('div', 'bl-photo');
photo.appendChild(photoNode(person));
const celebrating = birthdays && (person.celebrating || (testIndex !== '' && testIndex === String(slot.index)));
if (celebrating) { tile.classList.add('bl-birthday', `bl-birthday-${intensity}`); addConfetti(photo, intensity); }
if (s.showNames !== false && person.name) photo.appendChild(el('div', 'bl-name', person.name));
tile.appendChild(photo);
if (s.showLabels !== false && slot.label) tile.appendChild(el('div', 'bl-label', slot.label));
cell.appendChild(tile);
} else {
const empty = el('div', 'bl-tile bl-empty');
empty.appendChild(el('div', 'bl-label bl-label-empty', slot.label || `Slot ${slot.index + 1}`));
cell.appendChild(empty);
}
board.appendChild(cell);
}
root.appendChild(board);
applyParallax(board, s.parallax !== false);
reportStatus();
}
/* ---------- parallax: each photo drifts on its own, automatically ---------- */
let parallaxRaf = null;
let parallaxImgs = [];
function stopParallax() { if (parallaxRaf) { cancelAnimationFrame(parallaxRaf); parallaxRaf = null; } parallaxImgs = []; }
function applyParallax(board, on) {
stopParallax();
const imgs = [...board.querySelectorAll('.bl-img')];
if (!on) { imgs.forEach((i) => { i.style.transform = ''; }); return; }
// Give each image its own gentle, endless drift — different amplitude, speed and phase,
// so the wall never looks frozen and no two photos move together. No mouse needed.
parallaxImgs = imgs.map((img) => ({
img,
ax: 4 + Math.random() * 5, ay: 4 + Math.random() * 5,
// Very slow: a full drift cycle takes roughly a minute, so the motion only
// registers if you actually watch for it.
sx: 0.03 + Math.random() * 0.05, sy: 0.03 + Math.random() * 0.05,
px: Math.random() * Math.PI * 2, py: Math.random() * Math.PI * 2,
}));
const tick = () => {
const t = performance.now() / 1000;
for (const p of parallaxImgs) {
if (!p.img.isConnected) continue;
p.img.style.transform = `scale(1.08) translate(${(Math.sin(t * p.sx + p.px) * p.ax).toFixed(2)}px, ${(Math.cos(t * p.sy + p.py) * p.ay).toFixed(2)}px)`;
}
parallaxRaf = requestAnimationFrame(tick);
};
parallaxRaf = requestAnimationFrame(tick);
}
function reportStatus() {
if (!state) return moduleApi.setStatus('connecting', 'Connecting…');
if (state.configured && !state.reachable) return moduleApi.setStatus('error', state.lastError || 'Planning Center unreachable');
return moduleApi.setStatus('ok', state.plan?.dates ? `Plan: ${state.plan.dates}` : 'Ready');
}
/* ---------- editor ---------- */
function renderEditor() {
// No top bar: the photo source is managed in Admin (Google Drive link). Edit mode is just the
// board on top and the picture picker (library) below it.
const wrap = el('div', 'bl-editor bl-editor-nobar');
const body = el('div', 'bl-editor-body');
// Feed the drag auto-scroller the pointer position anywhere over the editor.
body.addEventListener('dragover', (e) => { dragY = e.clientY; });
// Slots (drop targets)
const boardEl = el('div', 'bl-edit-board');
boardEl.style.setProperty('--bl-cols', resolveCols());
for (const slot of state?.slots || []) {
const cell = el('div', 'bl-edit-slot');
cell.dataset.index = String(slot.index);
const photo = el('div', 'bl-edit-photo');
photo.appendChild(slot.person ? photoNode(slot.person) : el('div', 'bl-edit-drop', '+'));
cell.appendChild(photo);
// An occupied card is a drag SOURCE too — move/swap it to another slot.
if (slot.person) {
cell.draggable = true;
cell.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', 'slot:' + slot.index); e.dataTransfer.effectAllowed = 'move';
dragBody = body; dragScrolling = true; startDragAutoScroll();
});
cell.addEventListener('dragend', stopDragAutoScroll);
}
const nameRow = el('div', 'bl-edit-namerow');
const nameBtn = el('button', 'bl-edit-name', (slot.person && slot.person.name) || 'Name…');
nameBtn.addEventListener('click', () => renameSlot(slot.index, slot.person ? slot.person.name : ''));
nameRow.appendChild(nameBtn);
if (slot.person) { const clr = el('button', 'bl-edit-clear', '×'); clr.title = 'Clear'; clr.addEventListener('click', () => api(`/slot/${slot.index}/clear`, { method: 'POST' })); nameRow.appendChild(clr); }
cell.appendChild(nameRow);
cell.appendChild(el('div', 'bl-edit-label', slot.label || `Slot ${slot.index + 1}`));
// drop
cell.addEventListener('dragover', (e) => { e.preventDefault(); cell.classList.add('bl-drop-over'); });
cell.addEventListener('dragleave', () => cell.classList.remove('bl-drop-over'));
cell.addEventListener('drop', (e) => {
e.preventDefault(); stopDragAutoScroll(); cell.classList.remove('bl-drop-over');
const data = e.dataTransfer.getData('text/plain') || '';
if (data.startsWith('lib:')) assign(slot.index, data.slice(4));
else if (data.startsWith('slot:')) { const from = data.slice(5); if (from !== String(slot.index)) api(`/move?from=${from}&to=${slot.index}`, { method: 'POST' }); }
});
cell.addEventListener('click', (e) => { if (e.target.closest('.bl-edit-name') || e.target.closest('.bl-edit-clear')) return; if (selectedLibId) assign(slot.index, selectedLibId); });
boardEl.appendChild(cell);
}
body.appendChild(boardEl);
// Library
const lib = el('div', 'bl-library');
const list = state?.library || [];
if (!list.length) lib.appendChild(el('div', 'bl-lib-empty', 'No photos yet — set a Google Drive folder link in Admin, or hit Sync. Then drag a photo onto a slot.'));
for (const person of list) {
const item = el('div', 'bl-lib-item'); item.draggable = true; item.dataset.id = person.id;
if (person.id === selectedLibId) item.classList.add('bl-lib-selected');
const ph = el('div', 'bl-lib-photo'); ph.appendChild(photoNode(person, 'bl-lib-img')); item.appendChild(ph);
const nm = el('button', 'bl-lib-name', person.name || 'Name…');
nm.addEventListener('click', (e) => { e.stopPropagation(); renameLibrary(person.id, person.name); });
item.appendChild(nm);
const del = el('button', 'bl-lib-del', '×'); del.title = 'Delete photo';
del.addEventListener('click', (e) => { e.stopPropagation(); if (confirm(`Delete ${person.name || 'this photo'} from the library?`)) api(`/library/${person.id}/delete`, { method: 'POST' }); });
item.appendChild(del);
item.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('text/plain', 'lib:' + person.id); e.dataTransfer.effectAllowed = 'copy';
dragBody = body; dragScrolling = true; startDragAutoScroll();
});
item.addEventListener('dragend', stopDragAutoScroll);
item.addEventListener('click', () => { selectedLibId = selectedLibId === person.id ? '' : person.id; renderEditor(); });
lib.appendChild(item);
}
body.appendChild(lib);
wrap.appendChild(body);
root.innerHTML = '';
root.appendChild(wrap);
}
function assign(slotIndex, personId) {
selectedLibId = '';
api(`/assign?slot=${slotIndex}&personId=${encodeURIComponent(personId)}`, { method: 'POST' });
}
function renameSlot(slotIndex, currentName) {
const name = prompt('Name for this spot (leave blank to remove a name-only spot):', currentName || '');
if (name === null) return;
api(`/slot/${slotIndex}/name?name=${encodeURIComponent(name.trim())}`, { method: 'POST' });
}
function renameLibrary(id, currentName) {
const name = prompt('Rename this photo:', currentName || '');
if (name === null) return;
api(`/library/${id}?name=${encodeURIComponent(name.trim())}`, { method: 'POST' });
}
/* ---------- lifecycle ---------- */
return {
start() {
moduleApi.setStatus('connecting', 'Connecting…');
const SYNC_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6"/><path d="M1 20v-6h6"/><path d="M3.5 9a9 9 0 0 1 14.9-3.4L23 10M1 14l4.6 4.4A9 9 0 0 0 20.5 15"/></svg>';
const EDIT_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>';
moduleApi.header.addButton({
icon: SYNC_ICON,
title: 'Sync',
onClick() { moduleApi.setStatus('connecting', 'Syncing with Planning Center…'); api('/sync', { method: 'POST' }); },
});
const editBtn = moduleApi.header.addButton({ icon: EDIT_ICON, title: 'Edit board', onClick() { editing = !editing; editBtn.classList.toggle('active', editing); render(); } });
// Columns −/+ (touch-friendly; replaces the gear number field).
const MINUS_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><path d="M5 12h14"/></svg>';
const PLUS_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>';
const bumpCols = (d) => {
const max = Math.max(1, state && state.slots ? state.slots.length : 12);
const next = Math.max(1, Math.min(max, resolveCols() + d));
moduleApi.saveInstanceSettings({ columns: next });
render();
};
moduleApi.header.addButton({ icon: MINUS_ICON, title: 'Fewer columns', onClick() { bumpCols(-1); } });
moduleApi.header.addButton({ icon: PLUS_ICON, title: 'More columns', onClick() { bumpCols(1); } });
const CHOIR_ICON = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="18" r="2.5"/><circle cx="17" cy="16" r="2.5"/><path d="M8.5 18V5l11-2v13"/><path d="M8.5 8.5l11-2"/></svg>';
choirBtn = moduleApi.header.addButton({ icon: CHOIR_ICON, title: 'Choir', onClick() { api('/choir', { method: 'POST' }); } });
moduleApi.fetch('/state').then((r) => r.json()).then((d) => { state = d.state; render(); }).catch(() => {});
stream = moduleApi.sse('/stream', {
error() { reportStatus(); },
events: {
state(e) {
try { state = JSON.parse(e.data); } catch { return; }
// While editing, don't yank a rename prompt out from under the user:
// re-render the editor only (state carries board + library).
render();
},
},
});
},
onResize() {},
stop() {
if (stream) { stream.close(); stream = null; }
stopConfetti();
stopParallax();
stopDragAutoScroll();
root.innerHTML = '';
},
};
}
+198
View File
@@ -0,0 +1,198 @@
'use strict';
/**
* Slot ↔ Planning Center position matching for the Band Lineup module.
*
* A "slot" is a mic/pack label the operator wrote for a spot on stage, e.g.
* "[LEADER, VOX 1, ACOUSTIC] MIX 1". A scheduled person carries their PCO
* team-position name, e.g. "Vox 1" or "Acoustic / Worship Leader". We assign
* people to slots by loose token overlap — the same logic the backstage
* Electron app used, lifted here unchanged so the board matches what the booth
* is used to. Pure functions only: no I/O, so this file is unit-testable.
*/
function normalizeTeamName(value) {
return String(value || '').trim().toLowerCase();
}
/** Does a person's PCO team count as a band/stage team we display? `keywords` comes from admin config. */
function isAllowedTeamName(value, keywords) {
const normalized = normalizeTeamName(value);
if (!normalized) return false;
return (keywords || []).some((kw) => {
const k = normalizeTeamName(kw);
return k && (normalized === k || normalized.includes(k));
});
}
function normalizeLabel(value) {
return String(value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/** Fold a single token to a canonical instrument/role word (drops mic/pack noise, pluralises down). */
function normalizeToken(token) {
const normalized = String(token || '').trim().toLowerCase();
if (!normalized) return '';
if (/^\d+$/.test(normalized)) return '';
if (['mix', 'mic', 'slot', 'channel', 'ch', 'pack', 'wireless', 'input', 'headset'].includes(normalized)) return '';
if (['vox', 'vocal', 'vocalist', 'vocalists', 'vocals', 'singer', 'singers'].includes(normalized)) return 'vocals';
if (['keys', 'keyboard', 'keyboards'].includes(normalized)) return 'keys';
if (['drum', 'drums', 'drummer', 'drummers'].includes(normalized)) return 'drums';
if (['perc', 'percussionist', 'percussionists'].includes(normalized)) return 'percussion';
if (['gtr', 'guitar', 'guitars'].includes(normalized)) return 'guitar';
if (['electric', 'electricguitar'].includes(normalized)) return 'electric';
if (['acoustic', 'acousticguitar'].includes(normalized)) return 'acoustic';
if (['b', 'bandleader', 'leader', 'lead'].includes(normalized)) return normalized === 'b' ? '' : 'leader';
if (['worship', 'calltoworship'].includes(normalized)) return normalized === 'calltoworship' ? 'call' : normalized;
if (normalized.endsWith('s') && normalized.length > 4) return normalized.slice(0, -1);
return normalized;
}
function labelTokens(value) {
const normalized = normalizeLabel(value);
if (!normalized) return [];
const tokens = normalized.split(' ').map((t) => normalizeToken(t)).filter(Boolean);
if (!tokens.length && normalized) return [normalized];
return [...new Set(tokens)];
}
/**
* The role part of a slot label to match on: the bracketed content when present
* ("[VOX 2] MIX 2" → "VOX 2, "), else the whole label ("STAGE MANAGER"). This
* drops the "MIX n / MC n / HEADSET" mic-assignment noise so a mic number can't
* be mistaken for a position number.
*/
function slotRoleText(label) {
const brackets = String(label || '').match(/\[([^\]]*)\]/g);
if (brackets && brackets.length) return brackets.map((b) => b.slice(1, -1)).join(', ');
return String(label || '');
}
/** The set of standalone numbers in a label ("vox 2" → {"2"}). */
function numbersIn(value) {
return new Set(normalizeLabel(value).split(' ').filter((t) => /^\d+$/.test(t)));
}
/** 0–~140 similarity between a slot label and a PCO position name; higher is a better fit. */
function scoreMatch(slotLabel, positionLabel) {
const slotNormalized = normalizeLabel(slotLabel);
const positionNormalized = normalizeLabel(positionLabel);
if (!slotNormalized || !positionNormalized) return 0;
// A numbered role only matches the same number: "Vox 3" must not take "Vox 2".
const slotNums = numbersIn(slotLabel);
const posNums = numbersIn(positionLabel);
if (slotNums.size && posNums.size && ![...posNums].some((n) => slotNums.has(n))) return 0;
if (slotNormalized === positionNormalized) return 120;
if (slotNormalized.includes(positionNormalized) || positionNormalized.includes(slotNormalized)) return 95;
const slotTokens = labelTokens(slotLabel);
const positionTokens = labelTokens(positionLabel);
if (!slotTokens.length || !positionTokens.length) return 0;
const positionSet = new Set(positionTokens);
const slotSet = new Set(slotTokens);
const overlap = slotTokens.filter((t) => positionSet.has(t));
if (!overlap.length) return 0;
const overlapCount = overlap.length;
const slotCoverage = overlapCount / slotSet.size;
const positionCoverage = overlapCount / positionSet.size;
const sharedPhrase = overlap.join(' ');
let score = Math.round(slotCoverage * 70 + positionCoverage * 20 + overlapCount * 4);
if (slotCoverage === 1) score += 18;
if (positionCoverage === 1) score += 10;
if (sharedPhrase && slotNormalized.includes(sharedPhrase) && positionNormalized.includes(sharedPhrase)) score += 8;
return score;
}
/**
* Assign scheduled members to the ordered slot list. Greedy by best score, each
* member used once. Returns an array aligned to `slots`, each entry the chosen
* member or null. `MIN_SCORE` keeps a weak coincidence from claiming a slot.
*/
const MIN_SCORE = 60;
function assignMembersToSlots(slots, members) {
const pool = members.slice();
return slots.map((slotLabel) => {
const role = slotRoleText(slotLabel);
let bestIndex = -1;
let bestScore = MIN_SCORE - 1;
for (let i = 0; i < pool.length; i += 1) {
const score = scoreMatch(role, pool[i].label);
if (score > bestScore) { bestScore = score; bestIndex = i; }
}
if (bestIndex < 0) return null;
return pool.splice(bestIndex, 1)[0];
});
}
/**
* Best library photo for a Planning Center person, matched by name so Sync can use the folder
* photo instead of the PCO headshot. Handles full names, "First L" and first-name-only files,
* preferring the most specific. Returns the entry, or null when there's no confident, UNAMBIGUOUS
* match (e.g. two people share a first name and the photo is first-name-only) — then PCO's photo is used.
* `entries` is [{ ...whatever, name }].
*/
function bestLibraryMatch(pcoName, entries) {
const target = normalizeLabel(pcoName);
if (!target) return null;
const T = target.split(' ').filter(Boolean);
const scoreOf = (name) => {
const ln = normalizeLabel(name);
if (!ln) return 0;
if (ln === target) return 100; // exact full name
const L = ln.split(' ').filter(Boolean);
if (!L.length || !T.length) return 0;
// Align the library name against a leading run of the person's name, token by token.
// Every library token must equal the person's token in that position — except the LAST
// library token, which may be an initial/prefix ("m" of "Moniz"). This makes "Brian M"
// match "Brian Moniz" and "Alex" match "Alex Gaitan", but NOT "Alex" → "Alexander Zinni".
let ok = true; let exact = 0; let usedPrefix = false;
for (let k = 0; k < L.length; k += 1) {
const lt = L[k]; const tt = T[k];
if (!tt) { ok = false; break; }
if (lt === tt) { exact += 1; continue; }
if (k === L.length - 1 && tt.startsWith(lt)) { usedPrefix = true; continue; }
ok = false; break;
}
if (ok) {
if (L.length >= 2) return usedPrefix ? 86 : 92; // "brian m" / "alex gaitan"
if (exact === 1) return 90; // first name matches exactly ("alex")
if (usedPrefix) return 45; // "alex" vs "alexander" — too ambiguous
}
// Otherwise: a library surname that appears anywhere in the person's name.
const last = L[L.length - 1];
if (last && last.length >= 3 && T.includes(last)) return 78;
return 0;
};
let best = null;
let bestScore = 0;
let tie = false;
for (const e of entries) {
const s = scoreOf(e.name);
if (s > bestScore) { bestScore = s; best = e; tie = false; }
else if (s === bestScore && s > 0) tie = true;
}
if (bestScore < 60 || tie) return null; // no confident / unambiguous winner → PCO photo
return best;
}
module.exports = {
normalizeTeamName,
isAllowedTeamName,
bestLibraryMatch,
normalizeLabel,
normalizeToken,
labelTokens,
slotRoleText,
numbersIn,
scoreMatch,
assignMembersToSlots,
MIN_SCORE,
};
+67
View File
@@ -0,0 +1,67 @@
'use strict';
const assert = require('assert');
const { assignMembersToSlots, isAllowedTeamName, slotRoleText, scoreMatch } = require('./matching');
const SLOTS = [
'[LEADER, VOX 1, ACOUSTIC] MIX 1', '[VOX 2] MIX 2', '[VOX 3] MIX 3', '[VOX 4] MIX 4',
'[GUITAR, LEAD] MIX 5', '[BASS] MIX 6', '[VOX 5] MIX 7', '[PIANO]', '[DRUMS]',
'[KEYS 2]', '[CALL TO WORSHIP] MC2', 'STAGE MANAGER', '[MC] MC1', '[SPEAKER] HEADSET',
];
const M = (label) => ({ label, name: label });
const members = [
M('Vox 3'), M('Vox 2'), M('Vox 1'), M('Guitar / Lead'), M('Bass'), M('Piano'), M('Drums'), M('MC'), M('Keys 2'),
];
const out = assignMembersToSlots(SLOTS, members).map((m) => (m ? m.label : null));
// Numbered vocals land in the RIGHT slot (this is the swap bug we fixed).
assert.strictEqual(out[0], 'Vox 1', 'slot 0 → Vox 1');
assert.strictEqual(out[1], 'Vox 2', 'slot 1 → Vox 2');
assert.strictEqual(out[2], 'Vox 3', 'slot 2 → Vox 3');
assert.strictEqual(out[3], null, 'slot 3 (Vox 4) unfilled — nobody scheduled');
assert.strictEqual(out[4], 'Guitar / Lead', 'slot 4 → Guitar/Lead');
assert.strictEqual(out[5], 'Bass', 'slot 5 → Bass');
assert.strictEqual(out[6], null, 'slot 6 (Vox 5) unfilled');
assert.strictEqual(out[7], 'Piano', 'slot 7 → Piano');
assert.strictEqual(out[8], 'Drums', 'slot 8 → Drums');
assert.strictEqual(out[9], 'Keys 2', 'slot 9 → Keys 2');
assert.strictEqual(out[12], 'MC', 'slot 12 → MC');
// A different number never matches.
assert.strictEqual(scoreMatch(slotRoleText('[VOX 2] MIX 2'), 'Vox 3'), 0, 'Vox 3 must not match Vox 2 slot');
// Mic number no longer pollutes: Vox 7 must not grab "[VOX 5] MIX 7".
assert.strictEqual(scoreMatch(slotRoleText('[VOX 5] MIX 7'), 'Vox 7'), 0, 'Vox 7 must not match the MIX 7 slot');
// Team allow-list (singular stems match plurals/variants via substring).
assert.ok(isAllowedTeamName('Band', ['band', 'vocal']));
assert.ok(isAllowedTeamName('Vocals', ['band', 'vocal']));
assert.ok(isAllowedTeamName('Vocal Team', ['band', 'vocal']));
assert.ok(!isAllowedTeamName('Video', ['band', 'vocal', 'production']));
console.log('matching.test.js: all assertions passed ✓');
console.log('assignment:', JSON.stringify(out));
// --- bestLibraryMatch: folder-photo → PCO person by name ---
{
const { bestLibraryMatch } = require('./matching');
const name = (n) => (e) => (e ? e.name : null);
const lib = [
{ id: 'a', name: 'Alex' }, { id: 'g', name: 'AlexG' }, { id: 'bm', name: 'Brian M' },
{ id: 'c', name: 'Courtney' }, { id: 'gn', name: 'Gaitan' }, { id: 'wes', name: 'Wes' },
];
const pick = (n, list = lib) => { const e = bestLibraryMatch(n, list); return e ? e.name : null; };
assert.strictEqual(pick('Alex Gaitan'), 'Alex', 'first name matches "Alex"');
assert.strictEqual(pick('Brian Moniz'), 'Brian M', '"Brian M" matches "Brian Moniz"');
assert.strictEqual(pick('Courtney Maranda'), 'Courtney', 'first name matches');
assert.strictEqual(pick('Alexander Zinni'), null, '"Alex" must NOT grab "Alexander Zinni"');
assert.strictEqual(pick('Wes Carter'), 'Wes', 'first name matches "Wes"');
// surname-named photo
assert.strictEqual(pick('Someone Gaitan'), 'Gaitan', 'surname photo matches by last name');
// two people share a first name + only a first-name photo → ambiguous only if two matches tie;
// here a single "Alex" photo still maps to whoever's first name is exactly Alex.
assert.strictEqual(pick('Alex Johnson'), 'Alex', 'first-name photo maps to any exact-first-name person');
// exact full name beats a first-name photo
assert.strictEqual(pick('Alex Gaitan', [{ id: 'x', name: 'Alex Gaitan' }, { id: 'a', name: 'Alex' }]), 'Alex Gaitan', 'exact full name wins');
// tie → no match (two identical-scoring photos)
assert.strictEqual(bestLibraryMatch('Chris Smith', [{ id: '1', name: 'Chris' }, { id: '2', name: 'Chris' }]), null, 'ambiguous tie → null');
console.log('bestLibraryMatch: all assertions passed ✓');
}
+154
View File
@@ -0,0 +1,154 @@
{
"id": "band-lineup",
"name": "Band Lineup",
"version": "1.11.0",
"proddash": ">=1.4.0",
"description": "Stage lineup photos with mic/pack labels — a drag-in photo library plus optional Planning Center auto-fill",
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": {
"w": 4,
"h": 3
},
"defaultSize": {
"w": 8,
"h": 5
},
"configGroups": {
"Planning Center credentials": {
"collapsed": "whenSet",
"help": "Create a Personal Access Token at api.planningcenteronline.com and paste its Client ID + Secret here, or paste an OAuth 2.0 access token instead. Reading photos and birthdays needs People access on the token. Saved secrets never reach browsers."
},
"Stage": {
"help": "One mic/pack label per line, in the order they sit on stage. Scheduled people are matched into these by their Planning Center position (e.g. a line '[VOX 2] MIX 2' takes whoever is scheduled on Vox 2). Blank lines are empty spots."
},
"Photo library": {
"help": "Paste a Google Drive folder share link (set the folder to 'Anyone with the link → Viewer'). Every image is imported (file name → person's name) and kept in sync — add or remove photos in Drive and the board follows. A local folder path also works. If Drive can't be read, the board falls back to Planning Center photos."
}
},
"configSchema": {
"appId": {
"type": "string",
"label": "Client ID",
"default": "",
"group": "Planning Center credentials"
},
"secret": {
"type": "password",
"label": "Secret",
"default": "",
"group": "Planning Center credentials"
},
"accessToken": {
"type": "password",
"label": "OAuth 2.0 access token (instead of Client ID + Secret)",
"default": "",
"group": "Planning Center credentials"
},
"serviceTypeId": {
"type": "select",
"label": "Service type",
"default": "",
"optionsRoute": "/service-types"
},
"planId": {
"type": "select",
"label": "Plan",
"default": "",
"options": [
{
"value": "",
"label": "Automatic — today's plan, else the next upcoming"
}
],
"optionsRoute": "/plans",
"optionsDependsOn": "serviceTypeId"
},
"teams": {
"type": "text",
"label": "Teams to include",
"default": "Band\nWorship\nVocal\nProduction\nCommunication",
"help": "One team name (or keyword) per line. A person on any matching Planning Center team is eligible for the board."
},
"slots": {
"type": "text",
"label": "Stage slots",
"default": "[LEADER, VOX 1, ACOUSTIC] MIX 1\n[VOX 2] MIX 2\n[VOX 3] MIX 3\n[VOX 4] MIX 4\n[GUITAR, LEAD] MIX 5\n[BASS] MIX 6\n[VOX 5] MIX 7\n[PIANO]\n[DRUMS]\n[KEYS 2]\n[CALL TO WORSHIP] MC2\nSTAGE MANAGER\n[MC] MC1\n[SPEAKER] HEADSET",
"group": "Stage"
},
"columns": {
"type": "number",
"label": "Columns",
"default": 7,
"group": "Stage",
"help": "Default slots per row (each screen can still adjust with the − / + buttons in its title bar)."
},
"photoFolder": {
"type": "string",
"label": "Google Drive folder link",
"default": "",
"group": "Photo library",
"help": "e.g. https://drive.google.com/drive/folders/… (a local folder path also works). Leave blank to use Planning Center photos only."
}
},
"instanceGroups": {
"Birthday": {
"toggle": "birthdays"
}
},
"instanceSchema": {
"showNames": {
"type": "boolean",
"label": "Names",
"default": true
},
"showLabels": {
"type": "boolean",
"label": "Mic labels",
"default": true
},
"parallax": {
"type": "boolean",
"label": "Parallax motion",
"default": true
},
"birthdays": {
"type": "switch",
"label": "Birthday confetti",
"default": true,
"group": "Birthday"
},
"birthdayIntensity": {
"type": "select",
"label": "Intensity",
"default": "subtle",
"group": "Birthday",
"showWhen": "birthdays",
"options": [
{
"value": "subtle",
"label": "Subtle"
},
{
"value": "full",
"label": "Full"
}
]
},
"birthdayTest": {
"type": "select",
"label": "Force on (test)",
"default": "",
"group": "Birthday",
"showWhen": "birthdays",
"options": [
{
"value": "",
"label": "Off"
}
],
"optionsRoute": "/people"
}
}
}
+764
View File
@@ -0,0 +1,764 @@
'use strict';
/**
* Band Lineup — server part.
*
* Owns the shared stage board and the uploaded-photo library, plus the one
* Planning Center connection. The board is server-side and global: whoever
* edits it (drag a library photo onto a slot, rename, clear) changes it for
* every Band Lineup tile on every screen, over SSE. Planning Center sync is an
* optional auto-fill — it only fills slots nobody has placed by hand. Browsers
* never talk to Planning Center directly.
*
* GET /state → { state } (board + library; instant paint)
* GET /stream → SSE `state` events (change-detected, heartbeat)
* GET /library → { people } (the drag-in photo library)
* GET /service-types → { options } (admin "Service type" select)
* GET /plans → { options } (admin "Plan" select)
* GET /people → { options } (gear "Force birthday" select)
* GET /photo/<file> → image bytes (library + cached PCO photos)
* POST /library/<id> → rename / set birthday / replace photo (raw image body; ?name=&birthday=)
* POST /library/<id>/delete→ remove from the library and any slot
* POST /assign → ?slot=&personId= place a library person in a slot
* POST /move → ?from=&to= move or swap one slot's occupant
* POST /slot/<index>/name → ?name= rename the occupant (or make a name-only spot)
* POST /slot/<index>/clear → empty the slot
* POST /choir → ?on=1|0 toggle the extra CHOIR slot (shared)
* POST /sync → run a Planning Center + photo-folder sync now
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { isAllowedTeamName, assignMembersToSlots, bestLibraryMatch } = require('./matching');
const DEFAULT_API_BASE = 'https://api.planningcenteronline.com';
const API_BASE = String(process.env.BAND_LINEUP_API_BASE || process.env.PCO_PLAN_API_BASE || DEFAULT_API_BASE).replace(/\/+$/, '');
const SERVICES = '/services/v2';
const PEOPLE = '/people/v2';
const REQUEST_TIMEOUT_MS = 12000;
const PHOTO_TIMEOUT_MS = 15000;
const MIN_POLL_S = 10;
const RETRY_MS = 15000;
const HEARTBEAT_MS = 15000;
const MODULE_ID = 'band-lineup';
const MAX_UPLOAD = 20 * 1024 * 1024;
let current = null; // set by init(), read by routes; rebuilt together on remount
/* ── data directory (library + board + photo cache live here, never in the repo) ── */
function resolveDataDir() {
const home = os.homedir();
const fromEnv = String(process.env.PRODDASH_DATA_DIR || '').trim();
const root = path.join(__dirname, '..', '..');
if (fromEnv) return path.resolve(root, fromEnv);
if (process.platform === 'win32') return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'ProdDash');
if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', 'ProdDash');
return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'proddash');
}
/* ── small helpers ─────────────────────────────────────────────────── */
function lines(text) { return String(text || '').split('\n').map((s) => s.trim()); }
function nonEmptyLines(text) { return lines(text).filter(Boolean); }
function localYmd(d) { return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }
function birthdayMmdd(raw) {
const s = String(raw || '').trim();
const full = s.match(/^\d{4}-(\d{2})-(\d{2})$/);
if (full) return `${full[1]}-${full[2]}`;
return /^\d{2}-\d{2}$/.test(s) ? s : '';
}
function birthdayWeekSet(now = new Date()) {
const daysSinceWed = (now.getDay() - 3 + 7) % 7;
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysSinceWed);
const set = new Set();
for (let i = 0; i < 7; i += 1) {
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
set.add(`${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`);
}
return set;
}
function extFromContentType(ct) {
const t = String(ct || '').toLowerCase();
if (t.includes('png')) return 'png';
if (t.includes('webp')) return 'webp';
if (t.includes('gif')) return 'gif';
return 'jpg';
}
function contentTypeForFile(file) {
const e = path.extname(file).toLowerCase();
if (e === '.png') return 'image/png';
if (e === '.webp') return 'image/webp';
if (e === '.gif') return 'image/gif';
return 'image/jpeg';
}
function json(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
}
function readJsonFile(file, fallback) { try { return JSON.parse(fs.readFileSync(file, 'utf8')) || fallback; } catch { return fallback; } }
function newId() { return crypto.randomBytes(6).toString('hex'); }
function photoUrlFor(file) { return file ? `/api/modules/${MODULE_ID}/photo/${encodeURIComponent(file)}` : ''; }
/* ── Planning Center client ────────────────────────────────────────── */
function createPcoClient(config) {
const token = String(config.accessToken || '').trim();
const appId = String(config.appId || '').trim();
const secret = String(config.secret || '');
let auth = '';
if (token) auth = `Bearer ${token}`;
else if (appId && secret) auth = 'Basic ' + Buffer.from(`${appId}:${secret}`).toString('base64');
const configured = Boolean(auth);
async function get(target, params) {
const url = new URL(/^https?:\/\//.test(target) ? target : API_BASE + target);
for (const [k, v] of Object.entries(params || {})) url.searchParams.set(k, String(v));
let response;
try {
response = await fetch(url, { headers: { Authorization: auth, Accept: 'application/json' }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
} catch (err) {
const e = new Error(`Planning Center unreachable: ${err?.message || err}`); e.network = true; throw e;
}
if (!response.ok) { const e = new Error(`Planning Center ${response.status}`); e.status = response.status; throw e; }
const text = await response.text();
return text ? JSON.parse(text) : {};
}
async function getAll(target, params) {
const data = []; const included = []; let next = null;
let query = { per_page: 100, ...(params || {}) }; let guard = 0;
do {
const body = next ? await get(next) : await get(target, query);
if (Array.isArray(body.data)) data.push(...body.data);
if (Array.isArray(body.included)) included.push(...body.included);
next = body?.links?.next || null; query = null; guard += 1;
} while (next && guard < 50);
return { data, included };
}
return { configured, get, getAll };
}
/* ── Google Drive (public "anyone with the link" folder, no API key) ── */
const DRIVE_TIMEOUT_MS = 30000;
const DRIVE_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/537.36';
/** Pull the folder id out of a Drive share link (or '' if it isn't a Drive folder link). */
function parseDriveFolderId(s) {
const str = String(s || '');
if (!/drive\.google\.com/i.test(str)) return '';
const m = /\/folders\/([A-Za-z0-9_-]{10,})/.exec(str) || /[?&]id=([A-Za-z0-9_-]{10,})/.exec(str);
return m ? m[1] : '';
}
/** List a public folder's files via Drive's embedded folder view — [{ id, name }]. */
async function driveList(folderId) {
const resp = await fetch(`https://drive.google.com/embeddedfolderview?id=${encodeURIComponent(folderId)}#list`, {
headers: { 'User-Agent': DRIVE_UA }, redirect: 'follow', signal: AbortSignal.timeout(DRIVE_TIMEOUT_MS),
});
if (!resp.ok) throw new Error(`Drive folder list ${resp.status}`);
const html = await resp.text();
const out = []; const seen = new Set();
const re = /id="entry-([A-Za-z0-9_-]{20,})"[\s\S]*?flip-entry-title[^>]*>([^<]+)</g;
let m;
while ((m = re.exec(html))) {
const id = m[1]; const name = m[2].trim();
if (id && !seen.has(id)) { seen.add(id); out.push({ id, name }); }
}
return out;
}
/** Download one public Drive file at full resolution (falls back to a large thumbnail). */
async function driveFetchImage(fileId) {
const base = 'https://drive.usercontent.google.com/download';
const opts = { headers: { 'User-Agent': DRIVE_UA }, redirect: 'follow', signal: AbortSignal.timeout(DRIVE_TIMEOUT_MS) };
let resp = await fetch(`${base}?id=${fileId}&export=download`, opts);
let ct = String(resp.headers.get('content-type') || '');
if (resp.ok && ct.startsWith('image/')) return { buf: Buffer.from(await resp.arrayBuffer()), ext: extFromContentType(ct) };
// Large-file virus-scan interstitial: grab the confirm token and retry.
if (ct.includes('text/html')) {
const html = await resp.text();
const conf = /name="confirm"\s+value="([^"]+)"/.exec(html) || /[?&]confirm=([0-9A-Za-z_-]+)/.exec(html);
const uuid = /name="uuid"\s+value="([^"]+)"/.exec(html);
if (conf) {
resp = await fetch(`${base}?id=${fileId}&export=download&confirm=${conf[1]}${uuid ? `&uuid=${uuid[1]}` : ''}`, opts);
ct = String(resp.headers.get('content-type') || '');
if (resp.ok && ct.startsWith('image/')) return { buf: Buffer.from(await resp.arrayBuffer()), ext: extFromContentType(ct) };
}
}
const th = await fetch(`https://drive.google.com/thumbnail?id=${fileId}&sz=w2000`, opts);
const tct = String(th.headers.get('content-type') || '');
if (th.ok && tct.startsWith('image/')) return { buf: Buffer.from(await th.arrayBuffer()), ext: extFromContentType(tct) };
throw new Error('not an image');
}
/* ── the module ────────────────────────────────────────────────────── */
module.exports = {
init({ config, log }) {
const streams = new Set();
const dataDir = path.join(resolveDataDir(), MODULE_ID);
const photoDir = path.join(dataDir, 'photos');
const libraryPath = path.join(dataDir, 'library.json');
const boardPath = path.join(dataDir, 'board.json');
try { fs.mkdirSync(photoDir, { recursive: true }); } catch (err) { log(`cannot create ${photoDir}: ${err?.message || err}`); }
const slots = nonEmptyLines(config.slots).length ? lines(config.slots) : [];
const teamKeywords = nonEmptyLines(config.teams).length ? nonEmptyLines(config.teams) : ['band', 'worship', 'vocal', 'production', 'communication'];
const columns = Math.max(1, Number(config.columns) || 7);
const serviceTypeId = String(config.serviceTypeId || '').trim();
const planIdCfg = String(config.planId || '').trim();
// Photos folder: the admin "Photos folder" field wins when set; otherwise it's whatever the
// tile's "Choose folder…" picker saved into module state. Admin can't host a native picker
// (the shell renders plain fields), so the picker lives in the tile as the no-typing option.
const settingsPath = path.join(dataDir, 'settings.json');
const settings = readJsonFile(settingsPath, {}) || {};
const photoFolder = String(config.photoFolder || settings.photoFolder || '').trim(); // admin field (Drive link or local path)
let choirOn = Boolean(settings.choir); // optional extra "CHOIR" slot, toggled from the tile
function saveSettings() { try { fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2)); } catch (err) { log(`save settings failed: ${err?.message || err}`); } }
const CHOIR_LABEL = 'CHOIR';
// The board's slots plus an extra CHOIR spot when the toggle is on. Its index is slots.length,
// so its assignment persists in board.json across toggles.
const effectiveSlots = () => (choirOn ? slots.concat([CHOIR_LABEL]) : slots);
const pco = createPcoClient(config);
// Persisted, shared editor state.
let library = readJsonFile(libraryPath, {}); // { id: { name, file, birthday } }
let board = readJsonFile(boardPath, {}); // { slotIndex: { personId, name } }
function saveLibrary() { try { fs.writeFileSync(libraryPath, JSON.stringify(library, null, 2)); } catch (err) { log(`save library failed: ${err?.message || err}`); } }
function saveBoard() { try { fs.writeFileSync(boardPath, JSON.stringify(board, null, 2)); } catch (err) { log(`save board failed: ${err?.message || err}`); } }
let latest = clearedState();
let lastFrame = '';
let celebrateTimer = null;
let drivePollTimer = null;
let watcher = null;
let watchDebounce = null;
let stopped = false;
let syncing = false;
function clearedState() {
return {
configured: pco.configured, serviceTypeSet: Boolean(serviceTypeId),
reachable: false, lastError: '', lastFetched: 0, columns,
plan: null,
slots: effectiveSlots().map((label, index) => ({ index, label, person: null })),
library: [], choir: choirOn,
};
}
function libraryList() {
return Object.entries(library)
.map(([id, v]) => ({ id, name: v.name || '', photo: photoUrlFor(v.file || ''), birthday: v.birthday || '' }))
.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
}
function broadcast() {
if (!streams.size) return;
let frame; try { frame = JSON.stringify(latest); } catch { return; }
if (frame === lastFrame) return;
lastFrame = frame;
const payload = `event: state\ndata: ${frame}\n\n`;
for (const res of streams) { try { res.write(payload); } catch { streams.delete(res); } }
}
async function listPlans(stId) {
const [future, past] = await Promise.all([
pco.get(`${SERVICES}/service_types/${encodeURIComponent(stId)}/plans`, { filter: 'future', order: 'sort_date', per_page: 6 }),
pco.get(`${SERVICES}/service_types/${encodeURIComponent(stId)}/plans`, { filter: 'past', order: '-sort_date', per_page: 2 }),
]);
const rows = [...(future.data || []), ...(past.data || [])];
return rows.map((rec) => ({
id: String(rec.id), sortDate: Date.parse(rec.attributes?.sort_date || '') || 0,
title: String(rec.attributes?.title || rec.attributes?.series_title || '').trim(),
dates: String(rec.attributes?.dates || rec.attributes?.short_dates || '').trim(),
}));
}
function pickPlan(plans) {
if (planIdCfg) return plans.find((p) => p.id === planIdCfg) || { id: planIdCfg, title: '', dates: '' };
const todayY = localYmd(new Date());
const today = plans.find((p) => p.sortDate && localYmd(new Date(p.sortDate)) === todayY);
if (today) return today;
const now = Date.now();
const upcoming = plans.filter((p) => p.sortDate >= now - 12 * 3600000).sort((a, b) => a.sortDate - b.sortDate);
return upcoming[0] || plans.sort((a, b) => b.sortDate - a.sortDate)[0] || null;
}
async function cachePcoPhoto(personId, url) {
if (!url) return '';
const hash = crypto.createHash('sha1').update(url).digest('hex').slice(0, 8);
const existing = fs.existsSync(photoDir) ? fs.readdirSync(photoDir).find((f) => f.startsWith(`pco-${personId}-${hash}.`)) : null;
if (existing) return existing;
try {
const resp = await fetch(url, { signal: AbortSignal.timeout(PHOTO_TIMEOUT_MS) });
if (!resp.ok) return '';
const buf = Buffer.from(await resp.arrayBuffer());
if (!buf.length) return '';
const file = `pco-${personId}-${hash}.${extFromContentType(resp.headers.get('content-type'))}`;
fs.writeFileSync(path.join(photoDir, file), buf);
return file;
} catch { return ''; }
}
/**
* Import a folder of photos into the library and keep it in sync: new files are added
* (filename → name), changed files refreshed, and files removed from the folder dropped
* from the library (and any slot they filled). Manually-uploaded photos (no folderKey) are
* left alone, so a folder and hand-uploads can coexist. Returns true if anything changed.
*/
const IMG_RE = /\.(jpe?g|png|webp|gif)$/i;
const cleanNameFromFile = (f) => f.replace(/\.[^.]+$/, '').replace(/[_-]+/g, ' ').trim();
function extOf(f) { const m = f.match(IMG_RE); const e = (m ? m[1] : 'jpg').toLowerCase(); return e === 'jpeg' ? 'jpg' : e; }
function scanFolder() {
if (!photoFolder) return false;
let names; try { names = fs.readdirSync(photoFolder); } catch { return false; } // folder gone/unreadable
const files = names.filter((n) => IMG_RE.test(n));
const present = new Set(files);
const byKey = new Map();
for (const [id, v] of Object.entries(library)) if (v.folderKey) byKey.set(v.folderKey, id);
let changed = false;
for (const f of files) {
let mtime = 0; try { mtime = fs.statSync(path.join(photoFolder, f)).mtimeMs; } catch { continue; }
const id = byKey.get(f);
try {
if (id) {
const v = library[id];
if (v.mtime === mtime && v.file) continue; // unchanged
const dest = `lib-${id}.${extOf(f)}`;
fs.copyFileSync(path.join(photoFolder, f), path.join(photoDir, dest));
if (v.file && v.file !== dest) { try { fs.unlinkSync(path.join(photoDir, v.file)); } catch { /* ignore */ } }
v.file = dest; v.mtime = mtime; changed = true; // keep any in-app rename/birthday
} else {
const nid = newId();
const dest = `lib-${nid}.${extOf(f)}`;
fs.copyFileSync(path.join(photoFolder, f), path.join(photoDir, dest));
library[nid] = { name: cleanNameFromFile(f), file: dest, birthday: '', folderKey: f, mtime };
changed = true;
}
} catch (err) { log(`folder import of ${f} failed: ${err?.message || err}`); }
}
for (const [id, v] of Object.entries(library)) {
if (v.folderKey && !present.has(v.folderKey)) {
if (v.file) { try { fs.unlinkSync(path.join(photoDir, v.file)); } catch { /* ignore */ } }
delete library[id];
for (const [slot, b] of Object.entries(board)) if (b && b.personId === id) delete board[slot];
changed = true;
}
}
// De-duplicate: a hand-uploaded photo that shares a name with a folder photo is dropped
// (the folder wins), and any slot it filled repoints to the folder photo. Fixes the case
// where someone uploaded people by hand and then pointed at a folder of the same people.
const folderByName = new Map();
for (const [id, v] of Object.entries(library)) if (v.folderKey && v.name) folderByName.set(normName(v.name), id);
for (const [id, v] of Object.entries(library)) {
if (v.folderKey || !v.name) continue;
const keepId = folderByName.get(normName(v.name));
if (!keepId) continue;
if (v.file) { try { fs.unlinkSync(path.join(photoDir, v.file)); } catch { /* ignore */ } }
for (const [slot, b] of Object.entries(board)) if (b && b.personId === id) b.personId = keepId;
delete library[id];
changed = true;
}
if (changed) { saveLibrary(); saveBoard(); }
return changed;
}
// Import a public Google Drive folder into the library (file name → name), keeping it in sync.
// Keyed by Drive file id (folderKey "drive:<id>"). On a list failure we keep the last-good library.
async function scanDrive(folderId) {
let files;
try { files = await driveList(folderId); } catch (err) { log(`Drive list failed: ${err?.message || err}`); return false; }
files = files.filter((f) => IMG_RE.test(f.name));
const present = new Set(files.map((f) => `drive:${f.id}`));
const have = new Set();
for (const v of Object.values(library)) if (v.folderKey && v.folderKey.startsWith('drive:')) have.add(v.folderKey);
let changed = false;
for (const f of files) {
const key = `drive:${f.id}`;
if (have.has(key)) continue; // already imported (by Drive file id)
let img;
try { img = await driveFetchImage(f.id); } catch (err) { log(`Drive image ${f.name} failed: ${err?.message || err}`); continue; }
const nid = newId();
const dest = `lib-${nid}.${img.ext}`;
try { fs.writeFileSync(path.join(photoDir, dest), img.buf); library[nid] = { name: cleanNameFromFile(f.name), file: dest, birthday: '', folderKey: key }; changed = true; }
catch (err) { log(`write ${dest} failed: ${err?.message || err}`); }
}
for (const [id, v] of Object.entries(library)) {
if (v.folderKey && v.folderKey.startsWith('drive:') && !present.has(v.folderKey)) {
if (v.file) { try { fs.unlinkSync(path.join(photoDir, v.file)); } catch { /* ignore */ } }
delete library[id];
for (const [slot, b] of Object.entries(board)) if (b && b.personId === id) delete board[slot];
changed = true;
}
}
// Drive photo wins over a same-named hand-upload (repoint any slot to it).
const driveByName = new Map();
for (const [id, v] of Object.entries(library)) if (v.folderKey && v.folderKey.startsWith('drive:') && v.name) driveByName.set(normName(v.name), id);
for (const [id, v] of Object.entries(library)) {
if ((v.folderKey && v.folderKey.startsWith('drive:')) || !v.name) continue;
const keepId = driveByName.get(normName(v.name));
if (!keepId) continue;
if (v.file) { try { fs.unlinkSync(path.join(photoDir, v.file)); } catch { /* ignore */ } }
for (const [slot, b] of Object.entries(board)) if (b && b.personId === id) b.personId = keepId;
delete library[id]; changed = true;
}
if (changed) { saveLibrary(); saveBoard(); }
return changed;
}
// Import the configured photo source — a Drive folder link, or a local folder path.
async function syncPhotos() {
const fid = parseDriveFolderId(photoFolder);
if (fid) return scanDrive(fid);
if (photoFolder) return scanFolder();
return false;
}
function startWatch() {
if (parseDriveFolderId(photoFolder)) return; // Drive folders are polled, not fs.watched
if (!photoFolder) return;
try {
watcher = fs.watch(photoFolder, { persistent: false }, () => {
clearTimeout(watchDebounce);
watchDebounce = setTimeout(() => { if (!stopped && scanFolder()) rebuildLocal(); }, 800);
});
log(`watching photo folder ${photoFolder}`);
} catch (err) { log(`cannot watch photo folder: ${err?.message || err}`); }
}
function setChoir(on) { choirOn = Boolean(on); settings.choir = choirOn; saveSettings(); rebuildLocal(); }
// Remove cached PCO photos no longer referenced. Library files (lib-*) are never pruned here.
function prunePcoPhotos(keep) {
let files; try { files = fs.readdirSync(photoDir); } catch { return; }
for (const f of files) { if (f.startsWith('pco-') && !keep.has(f)) { try { fs.unlinkSync(path.join(photoDir, f)); } catch { /* ignore */ } } }
}
const normName = (s) => String(s || '').trim().toLowerCase().replace(/\s+/g, ' ');
// Resolve one board slot to a display person (or null). The board is the source of truth —
// there is no live PCO overlay, so clearing a slot stays cleared until the next Sync. A PCO
// entry prefers a same-named library photo, so uploading a photo updates the board without a re-sync.
function resolveSlot(i, weekSet, keep) {
const e = board[String(i)];
if (!e) return null;
let name = '', file = '', birthday = '', manual = true, personId = '';
if (e.pco) {
// The photo (folder photo, or PCO headshot) was chosen at Sync time — use it as-is.
manual = false; personId = e.pco.personId || '';
name = String(e.pco.name || '').trim();
file = e.pco.file || '';
birthday = e.pco.birthday || '';
} else if (e.personId) {
const lib = library[e.personId];
if (!lib) return null; // its library photo was deleted → slot is empty
personId = e.personId;
name = String(e.name || lib.name || '').trim();
file = lib.file || ''; birthday = lib.birthday || '';
} else if (e.name) {
name = String(e.name).trim();
} else return null;
if (file) keep.add(file);
return { name, photo: photoUrlFor(file), birthday, celebrating: Boolean(birthday) && weekSet.has(birthday), manual, personId };
}
// Repaint the display from the board (no Planning Center calls). Cheap — used after every edit
// and on a slow timer so a birthday week rolling over lights up on its own.
function renderBoard() {
const weekSet = birthdayWeekSet();
const keep = new Set();
const outSlots = effectiveSlots().map((label, i) => ({ index: i, label, person: resolveSlot(i, weekSet, keep) }));
for (const v of Object.values(library)) if (v.file) keep.add(v.file);
prunePcoPhotos(keep);
latest = {
configured: pco.configured, serviceTypeSet: Boolean(serviceTypeId),
reachable: latest.reachable, lastError: latest.lastError || '', lastFetched: latest.lastFetched || 0,
columns, plan: latest.plan || null, slots: outSlots, library: libraryList(), choir: choirOn,
};
}
function rebuildLocal() { renderBoard(); broadcast(); }
// Pull the current plan from Planning Center and write matched people INTO the board. Fills only
// slots nobody placed by hand; drops PCO entries no longer scheduled; leaves manual placements be.
async function syncNow() {
if (syncing) return;
syncing = true;
try {
await syncPhotos(); // import the photo source (Drive folder or local path) on every sync
if (pco.configured && serviceTypeId) {
const plan = pickPlan(await listPlans(serviceTypeId));
latest.plan = plan ? { title: plan.title, dates: plan.dates } : null;
if (!plan) { latest.reachable = true; latest.lastError = 'No plan found for that service type.'; }
else {
const tm = await pco.getAll(`${SERVICES}/service_types/${encodeURIComponent(serviceTypeId)}/plans/${encodeURIComponent(plan.id)}/team_members`, { include: 'person,team' });
const byKey = new Map((tm.included || []).map((e) => [`${e.type}:${e.id}`, e]));
const members = []; const seen = new Set();
for (const m of tm.data || []) {
const status = String(m.attributes?.status || '').trim();
if (status === 'D' || /^declined$/i.test(status)) continue;
const personId = String(m.relationships?.person?.data?.id || '');
const team = byKey.get(`Team:${String(m.relationships?.team?.data?.id || '')}`);
if (!isAllowedTeamName(String(team?.attributes?.name || ''), teamKeywords)) continue;
const person = byKey.get(`Person:${personId}`);
members.push({
personId,
name: String(person?.attributes?.full_name || person?.attributes?.name || m.attributes?.name || 'Unknown').trim() || 'Unknown',
label: String(m.attributes?.team_position_name || '').trim(),
photoUrl: String(person?.attributes?.photo_url || person?.attributes?.photo_thumbnail_url || '').trim(),
});
if (personId) seen.add(personId);
}
const bdays = new Map();
for (const id of seen) { try { const b = await pco.get(`${PEOPLE}/people/${encodeURIComponent(id)}`, { 'fields[Person]': 'birthdate' }); bdays.set(id, birthdayMmdd(b?.data?.attributes?.birthdate)); } catch { bdays.set(id, ''); } }
for (const m of members) m.birthday = bdays.get(m.personId) || '';
const libEntries = Object.entries(library).map(([id, v]) => ({ id, name: v.name, file: v.file }));
// Slots a person is sitting in by hand — don't fill them, and don't place that same person twice.
const eff = effectiveSlots();
const openIdx = []; const manualNames = new Set();
for (let i = 0; i < eff.length; i += 1) {
const e = board[String(i)];
if (e && (e.personId || e.name)) {
const nm = e.personId ? (library[e.personId] && library[e.personId].name) : e.name;
if (nm) manualNames.add(normName(nm));
} else openIdx.push(i);
}
const pool = members.filter((m) => !manualNames.has(normName(m.name)));
const assigned = assignMembersToSlots(openIdx.map((i) => eff[i]), pool);
for (let k = 0; k < openIdx.length; k += 1) {
const i = openIdx[k]; const m = assigned[k];
if (m) {
const lib = bestLibraryMatch(m.name, libEntries); // folder photo wins over the PCO headshot
const file = lib && lib.file ? lib.file : await cachePcoPhoto(m.personId, m.photoUrl);
board[String(i)] = { pco: { name: m.name, file, birthday: m.birthday || '', personId: m.personId } };
} else if (board[String(i)] && board[String(i)].pco) {
delete board[String(i)]; // was synced, no longer on the plan
}
}
saveBoard();
latest.reachable = true; latest.lastError = ''; latest.lastFetched = Date.now();
log(`synced ${members.length} scheduled from ${plan.dates || plan.id}`);
} // end else (plan found)
} // end if (Planning Center configured)
} catch (err) {
latest.reachable = false; latest.lastError = err?.message || String(err);
log(`sync failed: ${err?.message || err}`);
} finally {
syncing = false;
renderBoard(); broadcast();
}
}
const heartbeat = setInterval(() => { for (const res of streams) { try { res.write(': ping\n\n'); } catch { streams.delete(res); } } }, HEARTBEAT_MS);
heartbeat.unref?.();
// Repaint on a slow timer so a birthday week (Wed→Tue) rolling over lights up unattended.
celebrateTimer = setInterval(() => { if (!stopped) rebuildLocal(); }, 15 * 60 * 1000);
celebrateTimer.unref?.();
// A Drive folder can't be fs.watched — re-import it on a slow timer so photos added/removed
// in Drive show up without a manual Sync.
drivePollTimer = setInterval(() => {
if (stopped || !parseDriveFolderId(photoFolder)) return;
syncPhotos().then((ch) => { if (ch) rebuildLocal(); }).catch(() => {});
}, 5 * 60 * 1000);
drivePollTimer.unref?.();
if (pco.configured && serviceTypeId) log('ready — press Sync to load the plan from Planning Center');
else log('manual board (add Planning Center credentials + a service type in /admin to enable Sync)');
rebuildLocal(); // paint the saved board immediately
startWatch(); // local folders keep in sync via fs.watch (Drive folders are polled)
syncPhotos().then((ch) => { if (ch) rebuildLocal(); }).catch((err) => log(`initial photo import failed: ${err?.message || err}`));
current = {
streams, getLatest: () => latest, pco, listPlans, photoDir,
library, board, saveLibrary, saveBoard, rebuildLocal, refresh: () => syncNow(), slots,
photoUrlFor, libraryList,
setChoir, choirOn: () => choirOn,
};
return {
stop() {
stopped = true; if (celebrateTimer) clearInterval(celebrateTimer); if (drivePollTimer) clearInterval(drivePollTimer); clearInterval(heartbeat);
if (watcher) { try { watcher.close(); } catch { /* gone */ } watcher = null; }
if (watchDebounce) clearTimeout(watchDebounce);
for (const res of streams) { try { res.end(); } catch { /* gone */ } }
streams.clear(); if (current && current.streams === streams) current = null;
},
health() {
if (!pco.configured || !serviceTypeId) return { status: 'ok', message: 'Manual board (add Planning Center to enable Sync)' };
if (latest.lastError) return { status: 'error', message: latest.lastError };
if (latest.reachable) return { status: 'ok', message: latest.plan?.dates ? `Synced: ${latest.plan.dates}` : 'Synced' };
return { status: 'ok', message: 'Ready — press Sync to load the plan' };
},
};
},
routes({ log }) {
// Read an image request body (raw bytes) with a size cap.
function readBody(req, cb) {
const chunks = []; let size = 0; let bad = false;
req.on('data', (c) => { size += c.length; if (size > MAX_UPLOAD) { bad = true; req.destroy(); } else chunks.push(c); });
req.on('end', () => cb(bad ? null : Buffer.concat(chunks)));
req.on('error', () => cb(null));
}
return {
'GET /state': (req, res) => json(res, 200, { state: current ? current.getLatest() : null }),
'GET /stream': (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
res.write('retry: 3000\n\n');
res.write(`event: state\ndata: ${JSON.stringify(current ? current.getLatest() : null)}\n\n`);
if (!current) return void res.end();
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
current.streams.add(res);
req.on('close', () => current && current.streams.delete(res));
},
'GET /library': (req, res) => json(res, 200, { people: current ? current.libraryList() : [] }),
// Update a library entry: ?name=&birthday= and/or a replacement image body. /library/<id>/delete removes it.
'POST /library/*': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
const rest = decodeURIComponent(req.wildcard || '').replace(/^\/+/, '');
const del = /\/delete$/.test(rest);
const id = rest.replace(/\/delete$/, '').trim();
const entry = current.library[id];
if (!entry) return json(res, 404, { error: 'No such library photo.' });
if (del) {
if (entry.file) { try { fs.unlinkSync(path.join(current.photoDir, entry.file)); } catch { /* ignore */ } }
delete current.library[id];
for (const [slot, v] of Object.entries(current.board)) if (v && v.personId === id) delete current.board[slot];
current.saveLibrary(); current.saveBoard(); current.rebuildLocal();
return json(res, 200, { ok: true });
}
const q = new URLSearchParams(req.search || '');
readBody(req, (buf) => {
if (q.has('name')) entry.name = String(q.get('name') || '').trim();
if (q.has('birthday')) entry.birthday = birthdayMmdd(q.get('birthday'));
if (buf && buf.length) {
if (entry.file) { try { fs.unlinkSync(path.join(current.photoDir, entry.file)); } catch { /* ignore */ } }
const file = `lib-${id}.${extFromContentType(req.headers['content-type'])}`;
try { fs.writeFileSync(path.join(current.photoDir, file), buf); entry.file = file; } catch (err) { return json(res, 500, { error: `write failed: ${err?.message || err}` }); }
}
current.saveLibrary(); current.rebuildLocal();
json(res, 200, { ok: true });
});
},
// Toggle the extra CHOIR slot on/off (?on=1|0, or omit to flip). Shared across all screens.
'POST /choir': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
const p = new URLSearchParams(req.search || '');
const on = p.has('on') ? (p.get('on') === '1' || p.get('on') === 'true') : !current.choirOn();
current.setChoir(on);
json(res, 200, { ok: true, choir: on });
},
// Move (or swap) one slot's occupant to another slot: ?from=<i>&to=<j>.
'POST /move': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
const p = new URLSearchParams(req.search || '');
const from = String(p.get('from') || ''); const to = String(p.get('to') || '');
if (!/^\d+$/.test(from) || !/^\d+$/.test(to) || from === to) return json(res, 400, { error: 'Bad move.' });
const a = current.board[from]; const b = current.board[to];
if (a === undefined) delete current.board[to]; else current.board[to] = a;
if (b === undefined) delete current.board[from]; else current.board[from] = b;
current.saveBoard(); current.rebuildLocal();
json(res, 200, { ok: true });
},
// Place a library person in a slot: ?slot=<index>&personId=<id> (empty personId clears the slot).
'POST /assign': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
const q = new URLSearchParams(req.search || '');
const slot = String(q.get('slot') || '').trim();
const personId = String(q.get('personId') || '').trim();
if (!/^\d+$/.test(slot)) return json(res, 400, { error: 'Bad slot.' });
if (personId && !current.library[personId]) return json(res, 404, { error: 'No such library photo.' });
if (personId) current.board[slot] = { personId, name: '' };
else delete current.board[slot];
current.saveBoard(); current.rebuildLocal();
json(res, 200, { ok: true });
},
// Rename a slot's occupant, or make a name-only spot (no photo). /slot/<index>/clear empties it.
'POST /slot/*': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
const rest = decodeURIComponent(req.wildcard || '').replace(/^\/+/, '');
const clearing = /\/clear$/.test(rest);
const index = rest.replace(/\/(clear|name)$/, '').trim();
if (!/^\d+$/.test(index)) return json(res, 400, { error: 'Bad slot.' });
if (clearing) { delete current.board[index]; current.saveBoard(); current.rebuildLocal(); return json(res, 200, { ok: true }); }
const q = new URLSearchParams(req.search || '');
const name = String(q.get('name') || '').trim();
const existing = current.board[index] || { personId: '', name: '' };
existing.name = name;
if (!existing.personId && !name) delete current.board[index];
else current.board[index] = existing;
current.saveBoard(); current.rebuildLocal();
json(res, 200, { ok: true });
},
// Force an immediate Planning Center refresh (the "Sync" button). Auto-fill also
// runs on its own timer; this just does it now.
'POST /sync': (req, res) => {
if (!current) return json(res, 503, { error: 'Module not running.' });
current.refresh(); // scans the photos folder + pulls the plan if Planning Center is configured
json(res, 200, { ok: true });
},
'GET /people': (req, res) => {
const state = current ? current.getLatest() : null;
const options = [{ value: '', label: 'Off' }];
for (const slot of state?.slots || []) if (slot.person && slot.person.name) options.push({ value: String(slot.index), label: slot.person.name });
json(res, 200, { options });
},
'GET /photo/*': (req, res) => {
if (!current) return void res.writeHead(404).end();
const name = path.basename(decodeURIComponent(req.wildcard || '').replace(/^\/+/, ''));
if (!name || name.includes('..')) return void res.writeHead(400).end();
fs.readFile(path.join(current.photoDir, name), (err, buf) => {
if (err) return void res.writeHead(404).end();
res.writeHead(200, { 'Content-Type': contentTypeForFile(name), 'Cache-Control': 'public, max-age=60' });
res.end(buf);
});
},
'GET /service-types': async (req, res) => {
if (!current) return json(res, 503, { options: [], error: 'Module not running.' });
if (!current.pco.configured) return json(res, 200, { options: [], error: 'No Planning Center credentials yet.' });
try {
const [folderBody, stBody] = await Promise.all([current.pco.getAll(`${SERVICES}/folders`), current.pco.getAll(`${SERVICES}/service_types`)]);
const folders = new Map();
for (const f of folderBody.data || []) folders.set(String(f.id), { name: String(f.attributes?.name || 'Folder'), parentId: f.relationships?.parent?.data?.id ? String(f.relationships.parent.data.id) : '' });
const pathOf = (parentId) => { const names = []; let id = parentId; const seen = new Set(); while (id && folders.has(id) && !seen.has(id)) { seen.add(id); names.unshift(folders.get(id).name); id = folders.get(id).parentId; } return names.join(' › '); };
const options = (stBody.data || []).map((st) => ({ value: String(st.id), label: String(st.attributes?.name || 'Service type'), group: pathOf(st.relationships?.parent?.data?.id ? String(st.relationships.parent.data.id) : '') })).sort((a, b) => a.group.localeCompare(b.group) || a.label.localeCompare(b.label));
json(res, 200, { options });
} catch (err) { log(`service type list failed: ${err?.message || err}`); json(res, err?.status === 401 ? 401 : 502, { options: [], error: err?.message || String(err) }); }
},
'GET /plans': async (req, res) => {
if (!current) return json(res, 503, { options: [] });
const params = new URLSearchParams(req.search || '');
const stId = String(params.get('serviceTypeId') || '').trim();
const auto = { value: '', label: 'Automatic — today\'s plan, else the next upcoming' };
if (!current.pco.configured || !stId) return json(res, 200, { options: [auto] });
try {
const plans = await current.listPlans(stId); const now = Date.now();
const ordered = [...plans.filter((p) => p.sortDate >= now - 12 * 3600000).sort((a, b) => a.sortDate - b.sortDate), ...plans.filter((p) => p.sortDate < now - 12 * 3600000).sort((a, b) => b.sortDate - a.sortDate)];
json(res, 200, { options: [auto, ...ordered.map((p) => ({ value: p.id, label: [p.dates, p.title].filter(Boolean).join(' — ') || p.id }))] });
} catch (err) { json(res, 502, { options: [auto], error: err?.message || String(err) }); }
},
};
},
};
+232
View File
@@ -0,0 +1,232 @@
/* Band Lineup — scoped to the tile, themed only through the shell's variables. */
[data-module="band-lineup"] .bl-board {
height: 100%;
overflow: hidden;
display: grid;
grid-template-columns: repeat(var(--bl-cols, 7), minmax(0, 1fr));
grid-template-rows: repeat(var(--bl-rows, 2), minmax(0, 1fr));
gap: 6px;
padding: 6px;
}
[data-module="band-lineup"] .bl-message {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: var(--muted);
padding: 16px;
font-size: 0.95em;
}
[data-module="band-lineup"] .bl-slot {
min-width: 0;
min-height: 0;
}
[data-module="band-lineup"] .bl-tile {
display: flex;
flex-direction: column;
border-radius: 10px;
overflow: hidden;
background: var(--panel);
border: 1px solid var(--border);
height: 100%;
position: relative;
}
[data-module="band-lineup"] .bl-photo {
position: relative;
flex: 1;
min-height: 0;
overflow: hidden;
background: color-mix(in srgb, var(--bg) 70%, black);
}
[data-module="band-lineup"] .bl-img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center top;
display: block;
transition: transform 0.12s ease-out;
will-change: transform;
}
[data-module="band-lineup"] .bl-initials {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 2.4em;
font-weight: 800;
color: color-mix(in srgb, var(--muted) 70%, transparent);
letter-spacing: 0.04em;
}
[data-module="band-lineup"] .bl-name {
position: absolute;
top: 6px;
left: 6px;
right: 6px;
max-width: calc(100% - 12px);
padding: 3px 7px;
border-radius: 6px;
background: color-mix(in srgb, var(--bg) 82%, transparent);
color: var(--text);
font-size: 0.74em;
font-weight: 700;
line-height: 1.12;
z-index: 5;
/* Show the whole name — wrap onto more lines rather than clipping with an ellipsis. */
white-space: normal;
overflow-wrap: break-word;
word-break: break-word;
hyphens: auto;
}
[data-module="band-lineup"] .bl-label {
padding: 5px 6px;
font-size: 0.72em;
font-weight: 600;
text-align: center;
color: var(--text);
background: color-mix(in srgb, var(--bg) 60%, transparent);
border-top: 1px solid var(--border);
min-height: 1.6em;
display: flex;
align-items: center;
justify-content: center;
word-break: break-word;
}
[data-module="band-lineup"] .bl-empty {
border-style: dashed;
opacity: 0.55;
}
[data-module="band-lineup"] .bl-empty .bl-label {
background: transparent;
border-top: none;
margin: auto;
color: var(--muted);
}
/* ---- Birthday effects (confetti canvas + gold glow ring) ---- */
[data-module="band-lineup"] .bl-confetti {
position: absolute;
inset: 0;
z-index: 3;
pointer-events: none;
}
[data-module="band-lineup"] .bl-birthday-subtle {
animation: bl-glow-subtle 3.4s ease-in-out infinite;
}
[data-module="band-lineup"] .bl-birthday-full {
animation: bl-glow-full 2.2s ease-in-out infinite;
}
@keyframes bl-glow-subtle {
0%, 100% { box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--accent) 55%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 20%, transparent); }
50% { box-shadow: inset 0 0 0 2px var(--accent), 0 0 20px color-mix(in srgb, var(--accent) 34%, transparent); }
}
@keyframes bl-glow-full {
0%, 100% { box-shadow: inset 0 0 0 3px color-mix(in srgb, var(--accent) 80%, transparent), 0 0 20px color-mix(in srgb, var(--accent) 42%, transparent); }
50% { box-shadow: inset 0 0 0 3px var(--accent), 0 0 34px color-mix(in srgb, var(--accent) 66%, transparent); }
}
/* ---- Editor (Edit button): board drop-targets + uploaded-photo library ---- */
[data-module="band-lineup"] .bl-btn {
border: 1px solid var(--border);
background: var(--panel);
color: var(--text);
border-radius: 6px;
padding: 5px 11px;
font: inherit;
font-size: 0.82em;
cursor: pointer;
}
[data-module="band-lineup"] .bl-btn.primary { background: var(--accent); color: var(--accent-text); border-color: transparent; }
[data-module="band-lineup"] .bl-btn:hover { border-color: var(--accent); }
[data-module="band-lineup"] .bl-editor {
position: absolute;
inset: 0;
z-index: 20;
display: flex;
flex-direction: column;
background: var(--bg);
}
[data-module="band-lineup"] .bl-editor-bar {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-bottom: 1px solid var(--border);
flex: 0 0 auto;
}
[data-module="band-lineup"] .bl-editor-bar b { color: var(--text); }
[data-module="band-lineup"] .bl-editor-spacer { flex: 1; }
[data-module="band-lineup"] .bl-folder { display: flex; align-items: center; gap: 6px; min-width: 0; }
[data-module="band-lineup"] .bl-folder-path { font-size: 0.72em; color: var(--muted); max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
[data-module="band-lineup"] .bl-editor-body { flex: 1; min-height: 0; overflow: auto; padding: 10px; }
[data-module="band-lineup"] .bl-edit-board {
display: grid;
grid-template-columns: repeat(var(--bl-cols, 7), minmax(0, 1fr));
gap: 6px;
margin-bottom: 12px;
}
[data-module="band-lineup"] .bl-edit-slot {
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
background: var(--panel);
display: flex;
flex-direction: column;
}
[data-module="band-lineup"] .bl-edit-slot.bl-drop-over { border-color: var(--accent); box-shadow: inset 0 0 0 2px var(--accent); }
[data-module="band-lineup"] .bl-edit-photo { position: relative; aspect-ratio: 3 / 4; background: color-mix(in srgb, var(--bg) 70%, black); overflow: hidden; }
[data-module="band-lineup"] .bl-edit-photo .bl-img { width: 100%; height: 100%; object-fit: cover; object-position: center top; }
[data-module="band-lineup"] .bl-edit-drop {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
color: var(--muted); font-size: 1.6em; border: 1px dashed var(--border);
}
[data-module="band-lineup"] .bl-edit-namerow { display: flex; align-items: center; gap: 2px; padding: 2px; }
[data-module="band-lineup"] .bl-edit-name {
flex: 1; min-width: 0; text-align: left; background: transparent; border: 0;
color: var(--text); font: inherit; font-size: 0.72em; font-weight: 600; padding: 3px 4px;
cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-radius: 4px;
}
[data-module="band-lineup"] .bl-edit-name:hover { background: color-mix(in srgb, var(--accent) 16%, transparent); }
[data-module="band-lineup"] .bl-edit-clear {
flex: 0 0 auto; width: 20px; height: 20px; border: 0; border-radius: 4px;
background: color-mix(in srgb, var(--danger) 18%, transparent); color: var(--danger); cursor: pointer; font-size: 0.9em; line-height: 1;
}
[data-module="band-lineup"] .bl-edit-label { padding: 3px 5px 5px; font-size: 0.64em; color: var(--muted); text-align: center; border-top: 1px solid var(--border); word-break: break-word; }
[data-module="band-lineup"] .bl-library {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(78px, 1fr));
gap: 6px;
border-top: 1px solid var(--border);
padding-top: 10px;
}
[data-module="band-lineup"] .bl-lib-empty { grid-column: 1 / -1; color: var(--muted); font-size: 0.85em; padding: 10px 2px; }
[data-module="band-lineup"] .bl-lib-item {
position: relative; border: 1px solid var(--border); border-radius: 8px; overflow: hidden;
background: var(--panel); cursor: grab; display: flex; flex-direction: column;
}
[data-module="band-lineup"] .bl-lib-item:active { cursor: grabbing; }
[data-module="band-lineup"] .bl-lib-selected { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent); }
[data-module="band-lineup"] .bl-lib-photo { position: relative; aspect-ratio: 3 / 4; background: color-mix(in srgb, var(--bg) 70%, black); overflow: hidden; }
[data-module="band-lineup"] .bl-lib-img { width: 100%; height: 100%; object-fit: cover; object-position: center top; pointer-events: none; }
[data-module="band-lineup"] .bl-lib-name {
border: 0; background: transparent; color: var(--text); font: inherit; font-size: 0.68em; font-weight: 600;
padding: 3px 4px; text-align: center; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
[data-module="band-lineup"] .bl-lib-del {
position: absolute; top: 3px; right: 3px; width: 18px; height: 18px; border: 0; border-radius: 4px;
background: color-mix(in srgb, var(--bg) 60%, transparent); color: var(--text); cursor: pointer; font-size: 0.85em; line-height: 1;
}
[data-module="band-lineup"] .bl-lib-del:hover { background: var(--danger); color: #fff; }
+154 -1
View File
@@ -1,5 +1,9 @@
/* PCO Plan — client part.
The module presents two tiles and this is the entry for both: the Teams
tile (picker entry "teams") is built by teams-client.js, everything below
draws the Plan tile.
The server part reads Planning Center and (optionally) follows the
ProPresenter module's live item; this tile only renders the plan it is
streamed. What is shown is this tile's own choice (gear menu →
@@ -8,6 +12,8 @@
(saved with the tile, 14 px until someone presses one); /admin only holds
the connection settings. */
import createTeams from "./teams-client.js";
const REFRESH_SVG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
/* the text-size buttons: a drawn − and + at the icon size, like every other header icon */
@@ -15,6 +21,12 @@ const MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" st
const PLUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>';
export default function create({ root, moduleApi }) {
// Tiles added as "Teams" carry that variant and have their own settings.
if (moduleApi.variant === "teams") return createTeams({ root, moduleApi });
return createPlan({ root, moduleApi });
}
function createPlan({ root, moduleApi }) {
let state = null;
let skew = 0; // server clock − local clock, ms
let feedOffline = false;
@@ -22,6 +34,7 @@ export default function create({ root, moduleApi }) {
let ticker = null;
let lastCurrentId = null;
let lastListKey = '';
let absView = null; // what the server says AbleSet is doing, if anything
let userScrolledAt = 0;
root.innerHTML = `
@@ -481,6 +494,133 @@ export default function create({ root, moduleApi }) {
renderLiveMarks();
}
/* ── AbleSet: the song playing under the current item ──────────────
Everything here draws only when the server says there is an AbleSet
module, it is configured and reachable, and the song it is playing is
the plan item on screen. Any of those missing and the tile looks
exactly as it did before AbleSet existed. */
/** The playhead now, in beats, carried forward from the last packet. */
function absBeatsNow() {
if (!absView || absView.beats == null) return null;
if (!absView.playing || !absView.tempo) return absView.beats;
const since = Math.max(0, serverNow() - absView.at) / 1000;
return absView.beats + since * (absView.tempo / 60);
}
function absFraction(part) {
const beats = absBeatsNow();
if (beats == null || !part || part.start == null || part.end == null) return null;
const span = part.end - part.start;
if (!(span > 0)) return null;
return Math.max(0, Math.min(1, (beats - part.start) / span));
}
/** The row AbleSet's song belongs to — only ever the current one. */
function absRow() {
const a = absView;
if (!a || !a.available || !a.reachable || !a.song || !a.itemId) return null;
if (a.itemId !== lastCurrentId) return null;
return listEl.querySelector(`.pp-row[data-id="${CSS.escape(a.itemId)}"]`) || null;
}
/** Keep the playing section visible in the strip — this strip, nothing else. */
function absScrollSections(strip) {
const active = strip.querySelector('.pp-abs-sec.is-now');
if (!active) return;
const box = strip.getBoundingClientRect();
const rect = active.getBoundingClientRect();
const delta = (rect.left - box.left) - (strip.clientWidth - rect.width) / 2;
if (Math.abs(delta) < 1) return;
strip.scrollTo({ left: strip.scrollLeft + delta, behavior: 'smooth' });
}
function renderAbleSet() {
const row = absRow();
// Anything left on a row that is no longer the one goes.
for (const stale of listEl.querySelectorAll('.pp-fill, .pp-abs-sections')) {
if (!row || !row.contains(stale)) stale.remove();
}
if (!row) return;
if (on('absProgress')) {
const fraction = absFraction(absView.song);
if (fraction == null) {
row.querySelector('.pp-fill')?.remove();
} else {
let fill = row.querySelector('.pp-fill');
if (!fill) {
fill = document.createElement('div');
fill.className = 'pp-fill';
row.prepend(fill); // behind the row's content, which the stylesheet lifts
}
fill.style.width = `${(fraction * 100).toFixed(2)}%`;
}
} else {
row.querySelector('.pp-fill')?.remove();
}
if (on('absSections') && absView.sections.length) {
const main = row.querySelector('.pp-col-main');
let strip = row.querySelector('.pp-abs-sections');
if (!strip && main) {
strip = document.createElement('div');
strip.className = 'pp-abs-sections';
main.appendChild(strip);
}
if (strip) {
// The chips are rebuilt only when the song's sections change. Moving
// on to the next section just moves the classes: rebuilding would
// throw the strip's scroll away thirteen times a song.
const key = absView.sections.map((s) => s.name).join('\u0000');
if (strip.dataset.key !== key) {
strip.dataset.key = key;
strip.dataset.now = '';
strip.innerHTML = '';
for (const section of absView.sections) {
const chip = document.createElement('span');
chip.className = 'pp-abs-sec';
chip.textContent = section.name;
strip.appendChild(chip);
}
}
const now = absView.section?.index ?? -1;
if (strip.dataset.now !== String(now)) {
strip.dataset.now = String(now);
[...strip.children].forEach((chip, i) => {
chip.classList.toggle('is-now', i === now);
chip.classList.toggle('is-done', i < now);
if (i !== now) chip.style.removeProperty('--pp-sec-fill');
});
requestAnimationFrame(() => absScrollSections(strip));
}
const active = strip.children[now];
if (active) {
const fraction = absFraction(absView.section);
active.style.setProperty('--pp-sec-fill', fraction == null ? '0%' : `${(fraction * 100).toFixed(1)}%`);
}
}
} else {
row.querySelector('.pp-abs-sections')?.remove();
}
}
/**
* Centre a row in this tile's own list. `scrollIntoView` would walk up and
* scroll every ancestor that can scroll with it, which on a dashboard taller
* than the window drags the whole board; moving `listEl.scrollTop` moves
* this tile and nothing else. Measured from rectangles rather than
* `offsetTop` because the rows' offset parent is the tile, not the list.
*/
function keepInView(row) {
const list = listEl.getBoundingClientRect();
const rect = row.getBoundingClientRect();
const delta = (rect.top - list.top) - (listEl.clientHeight - rect.height) / 2;
if (Math.abs(delta) < 1) return;
listEl.scrollTo({ top: listEl.scrollTop + delta, behavior: 'smooth' });
}
/** Current / done classes and the elapsed timers, without rebuilding rows. */
function renderLiveMarks() {
const live = state?.live || {};
@@ -519,11 +659,12 @@ export default function create({ root, moduleApi }) {
}
if (!h.endedAt) elapsedEl.classList.add('is-running');
}
renderAbleSet();
if (currentId !== lastCurrentId) {
lastCurrentId = currentId;
if (currentId && tilePrefs().autoScroll !== false && Date.now() - userScrolledAt > 8000) {
const row = listEl.querySelector(`.pp-row[data-id="${CSS.escape(currentId)}"]`);
row?.scrollIntoView({ block: 'center', behavior: 'smooth' });
if (row) keepInView(row);
}
}
}
@@ -598,6 +739,7 @@ export default function create({ root, moduleApi }) {
}
function tick() {
renderAbleSet();
if (!state?.plan) return;
renderClock();
if (state.live?.following && on('showItemRuntime')) renderLiveMarks();
@@ -609,6 +751,7 @@ export default function create({ root, moduleApi }) {
if (!payload || typeof payload !== 'object' || !payload.state) return;
state = payload.state;
if (Number.isFinite(payload.now)) skew = payload.now - Date.now();
if (payload.ableset) absView = payload.ableset;
feedOffline = false;
render();
}
@@ -629,6 +772,16 @@ export default function create({ root, moduleApi }) {
accept(JSON.parse(ev.data));
} catch { /* a bad frame is not fatal */ }
},
// Its own event, several a second while a song plays: redraw that one
// row rather than the whole list.
ableset(ev) {
try {
absView = JSON.parse(ev.data);
} catch {
return;
}
if (state) renderAbleSet();
},
},
});
}
+177 -3
View File
@@ -2,10 +2,12 @@
/**
* Title matching for the PCO Plan module — the one answer to "is this
* ProPresenter document that Planning Center thing?", used twice:
* ProPresenter document that Planning Center thing?", used three ways:
*
* - mapping the document ProPresenter has live to a plan item (the
* highlight and the item runtimes), and
* highlight and the item runtimes) — placeDocument(), below,
* - recognising the message document, which is named after the sermon
* and never after its plan item — the message rule, below, and
* - recognising the documents an admin picked as the service start / end
* cues (see service-timing.js).
*
@@ -82,4 +84,176 @@ function isCue(liveName, cueDocument) {
return Boolean(cueDocument) && similarity(liveName, cueDocument) >= TRIGGER_THRESHOLD;
}
module.exports = { MATCH_THRESHOLD, TRIGGER_THRESHOLD, cleanTitle, normalize, similarity, isCue };
/* ── the message rule ──────────────────────────────────────────────────
A sermon's ProPresenter document is named after the sermon, never after
the plan item that stands for it ("Message", "Resi Message"), so no name
comparison can place it — and the previous song stayed "current" through
a whole message. What the document's name does carry is the plan's own
identity. Waters names them "YYMMDD Series Title - Part #": the plan's
date, its series title and its title. A live document that reads like
the plan is the plan's message, and lands on the plan's message item,
however that item happens to be titled. */
const MESSAGE_WORDS = /\b(message|sermon|teaching|homily)\b/i;
const MESSAGE_WORD_ONLY = /^\s*(message|sermon|teaching|homily)\s*$/i;
/** Undated, the name must read like "Series Title Part #" at least this closely… */
const MESSAGE_THRESHOLD = 0.75;
/** …dated with this plan's date, it need only resemble the series or the title. */
const DATED_MESSAGE_THRESHOLD = 0.6;
/** The leading "YYMMDD" / "YYYYMMDD" of a document name as a calendar day, or null. */
function leadingDateCode(raw) {
const m = /^\s*(\d{8}|\d{6})(?!\d)/.exec(String(raw || ''));
if (!m) return null;
const code = m[1];
const y = code.length === 8 ? Number(code.slice(0, 4)) : 2000 + Number(code.slice(0, 2));
const mo = Number(code.slice(-4, -2));
const d = Number(code.slice(-2));
if (mo < 1 || mo > 12 || d < 1 || d > 31) return null;
return { y, m: mo, d };
}
/** The local calendar day of an epoch-ms instant, in the same shape. */
function dayOf(ms) {
const t = new Date(Number(ms));
if (!Number.isFinite(t.getTime())) return null;
return { y: t.getFullYear(), m: t.getMonth() + 1, d: t.getDate() };
}
function sameDay(a, b) {
return Boolean(a && b) && a.y === b.y && a.m === b.m && a.d === b.d;
}
/**
* Does this live document read like the plan itself — "260927 Where is Your
* Faith? - Part 6" for the plan "Where is Your Faith?" / "Part 6" dated
* 27 Sept 2026? Returns { score, dated } or null.
*
* A date code naming another day is a firm no: last week's sermon is not
* this plan's message. A date code naming the plan's day is strong evidence,
* so the rest need only resemble the series or the title. Without a date
* the name must read like series + title together — and carry the title
* when the plan has both, so a series bumper ("Where is Your Faith?") is
* not taken for the sermon.
*/
function messageDocumentScore(name, plan) {
const series = String(plan?.seriesTitle || '').trim();
const title = String(plan?.title || '').trim();
if (!series && !title) return null;
const code = leadingDateCode(name);
const planDay = plan?.sortDate ? dayOf(plan.sortDate) : null;
if (code && planDay && !sameDay(code, planDay)) return null;
const dated = Boolean(code && planDay);
const full = [series, title].filter(Boolean).join(' ');
const fullScore = similarity(name, full);
if (dated) {
const score = Math.max(fullScore, series ? similarity(name, series) : 0, title ? similarity(name, title) : 0);
return score >= DATED_MESSAGE_THRESHOLD ? { score, dated: true } : null;
}
if (fullScore < MESSAGE_THRESHOLD) return null;
if (series && title && similarity(name, title) < DATED_MESSAGE_THRESHOLD) return null;
return { score: fullScore, dated: false };
}
/**
* The plan item that stands for the message: an item titled with the word
* ("Message", "Resi Message" — a bare "Message" first), else the first item
* under a header so titled (a "Sermon" section whose one item is the sermon's
* own title). Null when the plan has no such slot.
*/
function messageItemOf(items) {
let best = null;
let inSection = false;
for (const it of Array.isArray(items) ? items : []) {
if (!it) continue;
const title = String(it.title || '');
if (it.itemType === 'header') {
inSection = MESSAGE_WORDS.test(title);
continue;
}
const rank = MESSAGE_WORD_ONLY.test(title) ? 3 : MESSAGE_WORDS.test(title) ? 2 : inSection ? 1 : 0;
if (rank && (!best || rank > best.rank)) best = { item: it, rank };
if (rank === 3) break;
}
return best ? best.item : null;
}
/**
* Does ProPresenter's playlist mirror the plan item for item? ProPresenter
* builds a Planning Center playlist that way — every plan item, headers
* included, each flagged as PCO — until an operator adds something of their
* own (a song tag, say), which shifts every position after it. Same length,
* headers in the same places and every item PCO-flagged is the test.
*/
function playlistMirrorsPlan(ppItems, items) {
if (!Array.isArray(ppItems) || !Array.isArray(items) || !items.length || ppItems.length !== items.length) return false;
return ppItems.every((p, i) => Boolean(p?.isPco) && (p?.type === 'header') === (items[i]?.itemType === 'header'));
}
/** Best plan item by title, the ones ahead of the current item winning ties. */
function bestByName(name, items, all, ctx) {
const currentIdx = items.findIndex((it) => it.id === ctx?.currentItemId);
const hint = ctx?.hint;
const wanted = hint && hint.mirror && Number.isInteger(hint.index) && hint.index >= 0 ? all[hint.index] : null;
let best = null;
for (let i = 0; i < items.length; i += 1) {
const item = items[i];
const score = Math.max(similarity(name, item.title), item.song ? similarity(name, item.song.title) : 0);
if (score < MATCH_THRESHOLD) continue;
// Distance ahead of the current item (wrapping so items behind rank last).
const dist = currentIdx < 0 ? i : (i - currentIdx + items.length) % items.length;
const atPosition = Boolean(wanted && item.id === wanted.id);
const candidate = { item, score, dist, atPosition };
if (!best || score > best.score + 0.001) {
best = candidate;
continue;
}
if (Math.abs(score - best.score) > 0.001) continue;
if ((atPosition && !best.atPosition) || (atPosition === best.atPosition && dist < best.dist)) best = candidate;
}
return best ? { item: best.item, score: best.score, via: 'name' } : null;
}
/**
* Where a live ProPresenter document sits in the plan: { item, score, via }
* or null. `ctx` is { items, plan, currentItemId, hint }; `hint` (optional)
* is { index, mirror } — the document's position in the ProPresenter
* playlist and whether that playlist mirrors the plan (playlistMirrorsPlan).
*
* By name first: the item (or song) title most like the document's name,
* the ones ahead of the current item winning ties — a near miss lands on the
* right row. Then the message rule: a document that reads like the plan
* itself lands on the plan's message item. It overrides a name hit that is
* anything short of identical — a song called "Faith" must not catch
* "260927 Where is Your Faith? - Part 6" — outright when the document is
* dated with the plan's day, and when it reads better otherwise. Position
* is never a match on its own: it only breaks a tie between equally good
* names, and only while the playlist mirrors the plan.
*/
function placeDocument(name, ctx) {
const all = Array.isArray(ctx?.items) ? ctx.items : [];
const items = all.filter((it) => it && it.itemType !== 'header');
if (!items.length) return null;
const byName = bestByName(name, items, all, ctx);
const asMessage = messageDocumentScore(name, ctx?.plan);
const messageItem = asMessage ? messageItemOf(all) : null;
if (messageItem && (!byName || (byName.score < 0.999 && (asMessage.dated || asMessage.score > byName.score)))) {
return { item: messageItem, score: asMessage.score, via: asMessage.dated ? 'message document, dated' : 'message document' };
}
return byName;
}
module.exports = {
MATCH_THRESHOLD,
TRIGGER_THRESHOLD,
MESSAGE_THRESHOLD,
cleanTitle,
normalize,
similarity,
isCue,
leadingDateCode,
messageDocumentScore,
messageItemOf,
playlistMirrorsPlan,
placeDocument,
};
+280
View File
@@ -0,0 +1,280 @@
'use strict';
/**
* Unit tests for the PCO Plan module's document matching — placing what
* ProPresenter has live onto a plan item, and the message rule.
*
* node modules/pco-plan/matching.test.js
*
* Plain Node, no dependencies; exits non-zero on the first failure. The two
* plans are the campuses' real 27 Sept 2026 plans and ProPresenter playlists
* as they stood on 22 Sept, so the expectations read like a Sunday would.
*/
const assert = require('assert');
const {
MESSAGE_THRESHOLD,
leadingDateCode,
messageDocumentScore,
messageItemOf,
playlistMirrorsPlan,
placeDocument,
} = require('./matching');
let passed = 0;
function test(name, fn) {
try {
fn();
passed += 1;
console.log(` ok ${name}`);
} catch (err) {
console.log(` FAIL ${name}\n ${err.message}`);
process.exitCode = 1;
throw err;
}
}
const SUNDAY = new Date(2026, 8, 27, 9, 30).getTime(); // 27 Sept 2026, 9:30 local — the plan's sort date
const PLAN = { id: '91274523', title: 'Part 6', seriesTitle: 'Where is Your Faith?', sortDate: SUNDAY };
const header = (id, title) => ({ id, itemType: 'header', title, song: null });
const item = (id, title, itemType = 'item', song = null) => ({ id, itemType, title, song: song ? { title: song } : null });
const pp = (name, type = 'presentation', isPco = true) => ({ name, type, isPco, isHidden: false });
// North Attleboro — the message is an item called "Message", linked in
// ProPresenter to the bumper video; the sermon slides are their own document.
const NA = [
header('h0', 'Doors Open'),
item('1', 'Preservice'),
item('2', '5 Minute Countdown', 'media'),
item('3', 'MC Announcements', 'media'),
header('h4', 'Worship'),
item('5', 'Call To Worship', 'media'),
item('6', 'Alleluia', 'song', 'Alleluia'),
item('7', 'What a God', 'song', 'What a God'),
item('8', 'Baptisms', 'media'),
item('9', 'Promised Land', 'song', 'Promised Land'),
item('10', 'Be Praised', 'song', 'Be Praised'),
header('h11', 'Message'),
item('12', 'Message'),
item('13', 'Standing Salvation Moment', 'media'),
header('h14', 'Closing'),
item('15', 'Postservice', 'song', '-Postservice'),
];
const NA_PP = [
pp('Doors Open', 'header'), pp('Preservice'), pp('5 Minute Countdown'), pp('MC Announcements'),
pp('Worship', 'header'), pp('Call To Worship'), pp('Alleluia - [ Full ]'), pp('What a God - [ Full ]'),
pp('Baptisms'), pp('Promised Land - [ Full ]'), pp('Be Praised - [ Full ]'),
pp('Message', 'header'), pp('Message Bumper'), pp('Standing Salvation Moment'),
pp('Closing', 'header'), pp('Postservice'),
];
// Apollo Beach — the message is the media item "Resi Message".
const AB = [
item('0', 'Pre Service Meeting', 'media'),
header('h1', 'Doors Open'),
item('2', 'Pre Service', 'media'),
item('3', '5 Minute Countdown', 'media'),
item('4', 'MC Announcements', 'media'),
header('h5', 'Worship'),
item('6', 'Call To Worship', 'media'),
item('7', 'Alleluia', 'song', 'Alleluia'),
item('8', 'What a God', 'song', 'What a God'),
item('9', 'The Blood', 'song', 'The Blood'),
item('10', 'Be Praised (feat. Kymberli Joye)', 'song', 'Be Praised'),
header('h11', 'Message'),
item('12', 'Resi Message', 'media'),
item('13', 'Standing Salvation Moment', 'media'),
header('h14', 'Closing'),
item('15', 'Post Service', 'media'),
];
const SERMON = '260927 Where is Your Faith? - Part 6';
const place = (name, items, extra = {}) => placeDocument(name, { items, plan: PLAN, currentItemId: '', ...extra });
const titleOf = (hit) => (hit ? hit.item.title : null);
console.log('date codes');
test('YYMMDD and YYYYMMDD lead a document name; anything else is not a date', () => {
assert.deepStrictEqual(leadingDateCode(SERMON), { y: 2026, m: 9, d: 27 });
assert.deepStrictEqual(leadingDateCode('20260927 Where is Your Faith? - Part 6'), { y: 2026, m: 9, d: 27 });
assert.strictEqual(leadingDateCode('9-27-26 Where is Your Faith?'), null);
assert.strictEqual(leadingDateCode('1234567 seven digits'), null);
assert.strictEqual(leadingDateCode('261340 no such month'), null);
assert.strictEqual(leadingDateCode('Alleluia'), null);
assert.strictEqual(leadingDateCode(''), null);
});
console.log('the message rule');
test('a document named like the plan, dated with its day, is the message', () => {
const hit = messageDocumentScore(SERMON, PLAN);
assert.ok(hit, 'recognised');
assert.strictEqual(hit.dated, true);
assert.strictEqual(hit.score, 1);
});
test("last week's document is not this plan's message", () => {
assert.strictEqual(messageDocumentScore('260920 Where is Your Faith? - Part 5', PLAN), null);
assert.strictEqual(messageDocumentScore('260920 Where is Your Faith? - Part 6', PLAN), null, 'even with the right part: the date names another day');
});
test('undated, series and part together still read as the message', () => {
const plain = messageDocumentScore('Where is Your Faith? - Part 6', PLAN);
assert.ok(plain && plain.dated === false && plain.score === 1);
const tagged = messageDocumentScore('Where Is Your Faith - Part 6 - [ Notes ]', PLAN);
assert.ok(tagged && tagged.score >= MESSAGE_THRESHOLD, 'tags and punctuation do not matter');
});
test('a series bumper is not the sermon', () => {
assert.strictEqual(messageDocumentScore('Where is Your Faith?', PLAN), null, 'the series alone, undated');
assert.strictEqual(messageDocumentScore('Where is Your Faith? Bumper', PLAN), null);
});
test("dated with the plan's day, the part alone is enough", () => {
const hit = messageDocumentScore('260927 Part 6', PLAN);
assert.ok(hit && hit.dated);
});
test('a dated document about something else is not the message', () => {
assert.strictEqual(messageDocumentScore('260927 Announcements', PLAN), null);
assert.strictEqual(messageDocumentScore('260927 Baptism Video', PLAN), null);
});
test('songs are not the message', () => {
assert.strictEqual(messageDocumentScore('What a God - [ Full ]', PLAN), null);
assert.strictEqual(messageDocumentScore('Alleluia', PLAN), null);
assert.strictEqual(messageDocumentScore('Message Bumper', PLAN), null);
});
test('a plan with neither series nor title has no message document', () => {
assert.strictEqual(messageDocumentScore(SERMON, { sortDate: SUNDAY }), null);
assert.strictEqual(messageDocumentScore(SERMON, null), null);
});
test('a plan without a date still recognises its own name', () => {
const hit = messageDocumentScore(SERMON, { title: 'Part 6', seriesTitle: 'Where is Your Faith?' });
assert.ok(hit && hit.dated === false && hit.score === 1);
});
console.log('the message item');
test('an item called Message is the message item; so is Resi Message', () => {
assert.strictEqual(messageItemOf(NA).id, '12');
assert.strictEqual(messageItemOf(AB).id, '12');
});
test('a bare "Message" beats an item that only contains the word', () => {
const withBumper = [...NA.slice(0, 12), item('12a', 'Message Bumper', 'media'), ...NA.slice(12)];
assert.strictEqual(messageItemOf(withBumper).id, '12');
assert.strictEqual(messageItemOf([item('a', 'Message Bumper', 'media')]).id, 'a', 'alone, it is the slot');
});
test('under a Sermon header, the first item is the message whatever it is called', () => {
const plan = [header('h', 'Worship'), item('1', 'Alleluia', 'song', 'Alleluia'), header('s', 'Sermon'), item('2', 'Living Hope'), item('3', 'Response')];
assert.strictEqual(messageItemOf(plan).id, '2');
});
test('a plan without a message slot has none', () => {
assert.strictEqual(messageItemOf([header('h', 'Worship'), item('1', 'Alleluia', 'song', 'Alleluia')]), null);
assert.strictEqual(messageItemOf([header('m', 'Message')]), null, 'a header with nothing under it');
assert.strictEqual(messageItemOf([]), null);
assert.strictEqual(messageItemOf(null), null);
});
console.log('the playlist mirror');
test("ProPresenter's Planning Center playlist mirrors the plan, headers and all", () => {
assert.strictEqual(playlistMirrorsPlan(NA_PP, NA), true);
});
test('an item the operator added, a header out of place or a non-PCO item breaks the mirror', () => {
const extra = [...NA_PP.slice(0, 10), pp('The Blood TAG'), ...NA_PP.slice(10)];
assert.strictEqual(playlistMirrorsPlan(extra, NA), false, 'a song tag shifts everything after it');
const shifted = [...NA_PP];
[shifted[3], shifted[4]] = [shifted[4], shifted[3]];
assert.strictEqual(playlistMirrorsPlan(shifted, NA), false);
const local = NA_PP.map((x, i) => (i === 8 ? pp('Baptisms', 'presentation', false) : x));
assert.strictEqual(playlistMirrorsPlan(local, NA), false);
assert.strictEqual(playlistMirrorsPlan([], []), false);
assert.strictEqual(playlistMirrorsPlan(null, NA), false);
});
console.log('placing what is live');
test('songs and media land by name, tags and all', () => {
const god = place('What a God - [ Full ]', NA);
assert.strictEqual(titleOf(god), 'What a God');
assert.strictEqual(god.via, 'name');
assert.strictEqual(titleOf(place('Resi Message - [ MEDIA ]', AB)), 'Resi Message');
assert.strictEqual(titleOf(place('Greatly To Be Praised - [ Full ]', AB)), 'Be Praised (feat. Kymberli Joye)', 'by the song title');
assert.strictEqual(titleOf(place('Pre Service - [ Sunday ]', AB)), 'Pre Service');
});
test('the sermon document lands on the message item at both campuses', () => {
const na = place(SERMON, NA);
assert.strictEqual(titleOf(na), 'Message');
assert.strictEqual(na.via, 'message document, dated');
assert.strictEqual(titleOf(place(SERMON, AB)), 'Resi Message');
assert.strictEqual(place('Where is Your Faith? - Part 6', NA).via, 'message document', 'undated still lands, and says so');
});
test('the bumper lands on the message item too, by name', () => {
const hit = place('Message Bumper', NA);
assert.strictEqual(titleOf(hit), 'Message');
assert.strictEqual(hit.via, 'name');
});
test('a song called Faith does not catch the sermon', () => {
const trap = [...NA.slice(0, 11), item('f', 'Faith', 'song', 'Faith'), ...NA.slice(11)];
assert.strictEqual(titleOf(place('Faith - [ Full ]', trap)), 'Faith', 'the song itself still lands');
assert.strictEqual(titleOf(place(SERMON, trap)), 'Message', 'dated: the message wins outright');
assert.strictEqual(titleOf(place('Where is Your Faith? - Part 6', trap)), 'Message', 'undated: it reads better than the song');
});
test('an item titled exactly like the document wins over the message slot', () => {
const titled = [...NA.slice(0, 12), item('s', 'Where is Your Faith? - Part 6'), ...NA.slice(12)];
assert.strictEqual(place(SERMON, titled).item.id, 's');
});
test('a plan without a message slot leaves the sermon document unplaced', () => {
const noSlot = NA.filter((it) => it.id !== '12' && it.id !== 'h11');
assert.strictEqual(place(SERMON, noSlot), null);
});
test("an unplanned document, or last week's sermon, lands nowhere", () => {
assert.strictEqual(place('Offering Slide', NA), null);
assert.strictEqual(place('260920 Where is Your Faith? - Part 5', NA), null);
});
test('nothing to place on an empty plan', () => {
assert.strictEqual(place(SERMON, []), null);
assert.strictEqual(place(SERMON, [header('h', 'Message')]), null);
});
// The same song twice: a reprise after "What a God".
const REPRISE = [...NA.slice(0, 8), item('6b', 'Alleluia', 'song', 'Alleluia'), ...NA.slice(8)];
const REPRISE_PP = [...NA_PP.slice(0, 8), pp('Alleluia - [ Reprise ]'), ...NA_PP.slice(8)];
test('a tie between equal names goes to the one ahead of the current item', () => {
assert.strictEqual(place('Alleluia - [ Full ]', REPRISE).item.id, '6', 'nothing current yet: the first');
assert.strictEqual(place('Alleluia - [ Full ]', REPRISE, { currentItemId: '7' }).item.id, '6b', 'after What a God: the reprise');
assert.strictEqual(place('Alleluia - [ Full ]', REPRISE, { currentItemId: '6b' }).item.id, '6b', 'the current one keeps a tie');
});
test('position breaks a tie only while the playlist mirrors the plan', () => {
const mirror = playlistMirrorsPlan(REPRISE_PP, REPRISE);
assert.strictEqual(mirror, true);
assert.strictEqual(place('Alleluia - [ Reprise ]', REPRISE, { hint: { index: 8, mirror } }).item.id, '6b');
assert.strictEqual(place('Alleluia - [ Full ]', REPRISE, { hint: { index: 6, mirror } }).item.id, '6');
assert.strictEqual(place('Alleluia - [ Full ]', REPRISE, { currentItemId: '7', hint: { index: 6, mirror } }).item.id, '6', 'position wins the tie over "ahead"');
assert.strictEqual(place('Alleluia - [ Reprise ]', REPRISE, { hint: { index: 8, mirror: false } }).item.id, '6', 'no mirror: back to "ahead"');
});
test('position never places a document on its own', () => {
const mirror = playlistMirrorsPlan(NA_PP, NA);
assert.strictEqual(place('Offering Slide', NA, { hint: { index: 8, mirror } }), null);
assert.strictEqual(titleOf(place('What a God - [ Full ]', NA, { hint: { index: 12, mirror } })), 'What a God', 'a wrong position cannot move a clear name');
});
console.log(`\n${passed} tests passed`);
+486 -51
View File
@@ -1,15 +1,23 @@
{
"id": "pco-plan",
"name": "PCO Plan",
"version": "1.4.0",
"version": "1.8.0",
"proddash": ">=1.4.0",
"description": "Order of service from Planning Center Services",
"provides": ["timers"],
"description": "Order of service and team assignments from Planning Center Services",
"provides": [
"timers"
],
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": { "w": 3, "h": 3 },
"defaultSize": { "w": 5, "h": 6 },
"minSize": {
"w": 3,
"h": 3
},
"defaultSize": {
"w": 5,
"h": 6
},
"configGroups": {
"Planning Center credentials": {
"collapsed": "whenSet",
@@ -48,7 +56,12 @@
"type": "select",
"label": "Plan",
"default": "",
"options": [{ "value": "", "label": "Automatic — today's plan, else the next upcoming" }],
"options": [
{
"value": "",
"label": "Automatic — today's plan, else the next upcoming"
}
],
"optionsRoute": "/plans",
"optionsDependsOn": "serviceTypeId"
},
@@ -82,8 +95,14 @@
"group": "Service timing",
"showWhen": "useDocumentTriggers",
"options": [
{ "value": "schedule", "label": "Scheduled service time" },
{ "value": "document", "label": "ProPresenter document" }
{
"value": "schedule",
"label": "Scheduled service time"
},
{
"value": "document",
"label": "ProPresenter document"
}
]
},
"serviceStartDocument": {
@@ -124,37 +143,94 @@
"Item notes": {
"toggle": "showNotes"
},
"Show / hide": {
"Show": {
"collapsed": true,
"columns": 3,
"help": "Switch off anything this tile should not show."
"columns": 2
}
},
"instanceSchema": {
"autoScroll": { "type": "boolean", "label": "Keep the current item in view", "default": true },
"autoScroll": {
"type": "boolean",
"label": "Auto-scroll",
"default": true
},
"headerTemplate": {
"type": "template",
"label": "Top bar text",
"default": "{series} • {part} | {serviceType} • {date}",
"group": "Top bar",
"variables": [
{ "value": "{series}", "label": "Series" },
{ "value": "{part}", "label": "Part / plan title" },
{ "value": "{serviceType}", "label": "Service type" },
{ "value": "{date}", "label": "Date" },
{ "value": "{shortDate}", "label": "Short date" },
{ "value": "{time}", "label": "Service time" },
{ "value": "{length}", "label": "Planned length" },
{ "value": "{items}", "label": "Item count" }
{
"value": "{series}",
"label": "Series"
},
{
"value": "{part}",
"label": "Part / plan title"
},
{
"value": "{serviceType}",
"label": "Service type"
},
{
"value": "{date}",
"label": "Date"
},
{
"value": "{shortDate}",
"label": "Short date"
},
{
"value": "{time}",
"label": "Service time"
},
{
"value": "{length}",
"label": "Planned length"
},
{
"value": "{items}",
"label": "Item count"
}
],
"help": "Use • between items and | to start a second line."
},
"keyColor": { "type": "color", "label": "Song key", "default": "#4ea1ff", "group": "Colors" },
"headerColor": { "type": "color", "label": "Section headers", "default": "#2ee59a", "group": "Colors" },
"currentColor": { "type": "color", "label": "Current item", "default": "#2ee59a", "group": "Colors" },
"headerGradient": { "type": "boolean", "label": "Fade header color to the right", "default": true, "group": "Colors" },
"tintByType": { "type": "boolean", "label": "Tint items by type (song / media / other)", "default": false, "group": "Colors" },
"showNotes": { "type": "switch", "label": "Item notes", "default": true, "group": "Item notes" },
"keyColor": {
"type": "color",
"label": "Song key",
"default": "#4ea1ff",
"group": "Colors"
},
"headerColor": {
"type": "color",
"label": "Section headers",
"default": "#2ee59a",
"group": "Colors"
},
"currentColor": {
"type": "color",
"label": "Current item",
"default": "#2ee59a",
"group": "Colors"
},
"headerGradient": {
"type": "boolean",
"label": "Header fade",
"default": true,
"group": "Colors"
},
"tintByType": {
"type": "boolean",
"label": "Tint by type",
"default": false,
"group": "Colors"
},
"showNotes": {
"type": "switch",
"label": "Item notes",
"default": true,
"group": "Item notes"
},
"noteCategories": {
"type": "multiselect",
"label": "Categories",
@@ -163,29 +239,388 @@
"columns": 3,
"allByDefault": true
},
"showTopBar": { "type": "boolean", "label": "Top bar", "default": true, "group": "Show / hide" },
"showSeries": { "type": "boolean", "label": "Series name", "default": true, "group": "Show / hide" },
"showPart": { "type": "boolean", "label": "Part # / plan title", "default": true, "group": "Show / hide" },
"showServiceType": { "type": "boolean", "label": "Service type", "default": true, "group": "Show / hide" },
"showDate": { "type": "boolean", "label": "Plan date", "default": true, "group": "Show / hide" },
"showServiceTime": { "type": "boolean", "label": "Service time", "default": true, "group": "Show / hide" },
"showTotalLength": { "type": "boolean", "label": "Planned total length", "default": true, "group": "Show / hide" },
"showRunningClock": { "type": "boolean", "label": "Running clock (ahead / behind)", "default": true, "group": "Show / hide" },
"showCountdown": { "type": "boolean", "label": "Countdown to service start", "default": true, "group": "Show / hide" },
"showHeaders": { "type": "boolean", "label": "Section headers", "default": true, "group": "Show / hide" },
"showItemNumbers": { "type": "boolean", "label": "Item numbers", "default": false, "group": "Show / hide" },
"showStartTimes": { "type": "boolean", "label": "Scheduled start times", "default": true, "group": "Show / hide" },
"showLength": { "type": "boolean", "label": "Item length", "default": true, "group": "Show / hide" },
"showItemType": { "type": "boolean", "label": "Item type badge", "default": true, "group": "Show / hide" },
"showKey": { "type": "boolean", "label": "Song key", "default": true, "group": "Show / hide" },
"showArrangement": { "type": "boolean", "label": "Song arrangement", "default": false, "group": "Show / hide" },
"showSongAuthor": { "type": "boolean", "label": "Song author / CCLI", "default": false, "group": "Show / hide" },
"showDescription": { "type": "boolean", "label": "Item description", "default": true, "group": "Show / hide" },
"showPreService": { "type": "boolean", "label": "Pre-service items", "default": true, "group": "Show / hide" },
"showPostService": { "type": "boolean", "label": "Post-service items", "default": true, "group": "Show / hide" },
"showNowIndicator": { "type": "boolean", "label": "Now indicator", "default": true, "group": "Show / hide" },
"showItemRuntime": { "type": "boolean", "label": "Item runtime (elapsed vs planned)", "default": true, "group": "Show / hide" },
"dimCompleted": { "type": "boolean", "label": "Dim completed items", "default": true, "group": "Show / hide" },
"showLiveFooter": { "type": "boolean", "label": "ProPresenter match line", "default": true, "group": "Show / hide" }
}
"showTopBar": {
"type": "boolean",
"label": "Top bar",
"default": true,
"group": "Show"
},
"showSeries": {
"type": "boolean",
"label": "Series name",
"default": true,
"group": "Show"
},
"showPart": {
"type": "boolean",
"label": "Part / title",
"default": true,
"group": "Show"
},
"showServiceType": {
"type": "boolean",
"label": "Service type",
"default": true,
"group": "Show"
},
"showDate": {
"type": "boolean",
"label": "Plan date",
"default": true,
"group": "Show"
},
"showServiceTime": {
"type": "boolean",
"label": "Service time",
"default": true,
"group": "Show"
},
"showTotalLength": {
"type": "boolean",
"label": "Total length",
"default": true,
"group": "Show"
},
"showRunningClock": {
"type": "boolean",
"label": "Running clock",
"default": true,
"group": "Show"
},
"showCountdown": {
"type": "boolean",
"label": "Countdown",
"default": true,
"group": "Show"
},
"showHeaders": {
"type": "boolean",
"label": "Section headers",
"default": true,
"group": "Show"
},
"showItemNumbers": {
"type": "boolean",
"label": "Item numbers",
"default": false,
"group": "Show"
},
"showStartTimes": {
"type": "boolean",
"label": "Start times",
"default": true,
"group": "Show"
},
"showLength": {
"type": "boolean",
"label": "Item length",
"default": true,
"group": "Show"
},
"showItemType": {
"type": "boolean",
"label": "Type badge",
"default": true,
"group": "Show"
},
"showKey": {
"type": "boolean",
"label": "Song key",
"default": true,
"group": "Show"
},
"showArrangement": {
"type": "boolean",
"label": "Arrangement",
"default": false,
"group": "Show"
},
"showSongAuthor": {
"type": "boolean",
"label": "Author / CCLI",
"default": false,
"group": "Show"
},
"showDescription": {
"type": "boolean",
"label": "Item description",
"default": true,
"group": "Show"
},
"showPreService": {
"type": "boolean",
"label": "Pre-service",
"default": true,
"group": "Show"
},
"showPostService": {
"type": "boolean",
"label": "Post-service",
"default": true,
"group": "Show"
},
"showNowIndicator": {
"type": "boolean",
"label": "Now indicator",
"default": true,
"group": "Show"
},
"showItemRuntime": {
"type": "boolean",
"label": "Item runtime",
"default": true,
"group": "Show"
},
"dimCompleted": {
"type": "boolean",
"label": "Dim completed",
"default": true,
"group": "Show"
},
"showLiveFooter": {
"type": "boolean",
"label": "Match line",
"default": true,
"group": "Show"
},
"absProgress": {
"type": "boolean",
"label": "Song progress",
"default": true,
"group": "Show"
},
"absSections": {
"type": "boolean",
"label": "Song sections",
"default": true,
"group": "Show"
}
},
"tiles": [
{
"id": "plan",
"name": "Plan",
"description": "The order of service, item by item",
"defaultSize": {
"w": 5,
"h": 6
},
"minSize": {
"w": 3,
"h": 3
}
},
{
"id": "teams",
"name": "Teams",
"description": "Who is scheduled, by team and position",
"defaultSize": {
"w": 4,
"h": 6
},
"minSize": {
"w": 2,
"h": 2
},
"instanceSchema": {
"columns": {
"type": "select",
"label": "Columns",
"default": "auto",
"options": [
{
"value": "auto",
"label": "Fit the tile"
},
{
"value": "1",
"label": "One"
},
{
"value": "2",
"label": "Two"
},
{
"value": "3",
"label": "Three"
}
]
},
"teams": {
"type": "multiselect",
"label": "Teams",
"columns": 2,
"allByDefault": true,
"optionsRoute": "/teams"
},
"headerTemplate": {
"type": "template",
"label": "Top bar text",
"default": "{serviceType} • {date} | {people} on {teams}",
"group": "Top bar",
"variables": [
{
"value": "{series}",
"label": "Series"
},
{
"value": "{part}",
"label": "Part / plan title"
},
{
"value": "{serviceType}",
"label": "Service type"
},
{
"value": "{date}",
"label": "Date"
},
{
"value": "{shortDate}",
"label": "Short date"
},
{
"value": "{time}",
"label": "Service time"
},
{
"value": "{people}",
"label": "People count"
},
{
"value": "{teams}",
"label": "Team count"
},
{
"value": "{confirmed}",
"label": "Confirmed count"
}
],
"help": "Use • between items and | to start a second line."
},
"teamColor": {
"type": "color",
"label": "Team headers",
"default": "#2ee59a",
"group": "Colors"
},
"tintTeams": {
"type": "boolean",
"label": "Tint teams",
"default": false,
"group": "Colors"
},
"tintRows": {
"type": "boolean",
"label": "Tint rows too",
"default": false,
"group": "Colors",
"showWhen": "tintTeams"
},
"headerGradient": {
"type": "boolean",
"label": "Header fade",
"default": true,
"group": "Colors"
},
"confirmedColor": {
"type": "color",
"label": "Confirmed",
"default": "#2ee59a",
"group": "Colors"
},
"unconfirmedColor": {
"type": "color",
"label": "Unconfirmed",
"default": "#f0b429",
"group": "Colors"
},
"declinedColor": {
"type": "color",
"label": "Declined",
"default": "#f4433c",
"group": "Colors"
},
"showTopBar": {
"type": "boolean",
"label": "Top bar",
"default": true,
"group": "Show"
},
"showTeamHeaders": {
"type": "boolean",
"label": "Team headers",
"default": true,
"group": "Show"
},
"showTeamCounts": {
"type": "boolean",
"label": "Team counts",
"default": true,
"group": "Show"
},
"showAvatars": {
"type": "boolean",
"label": "Avatars",
"default": true,
"group": "Show"
},
"showPosition": {
"type": "boolean",
"label": "Positions",
"default": true,
"group": "Show"
},
"groupByPosition": {
"type": "boolean",
"label": "Group by position",
"default": false,
"group": "Show"
},
"showStatus": {
"type": "boolean",
"label": "Status",
"default": true,
"group": "Show"
},
"showNotes": {
"type": "boolean",
"label": "Person notes",
"default": false,
"group": "Show"
},
"showDeclined": {
"type": "boolean",
"label": "Declined people",
"default": true,
"group": "Show"
},
"showUnconfirmed": {
"type": "boolean",
"label": "Unconfirmed people",
"default": true,
"group": "Show"
},
"showEmptyTeams": {
"type": "boolean",
"label": "Teams with nobody",
"default": false,
"group": "Show"
}
},
"instanceGroups": {
"Top bar": {
"collapsed": false
},
"Colors": {
"collapsed": false,
"columns": 2
},
"Show": {
"collapsed": true,
"columns": 2
}
}
}
]
}
+589 -35
View File
@@ -9,6 +9,10 @@
*
* GET /state → { state, now } (instant paint for new tiles)
* GET /stream → SSE, `state` events (change-detected, heartbeated)
* plus `ableset` events: the song AbleSet is playing, its
* sections and playhead, when there is an AbleSet module
* to follow (see below). Its own event so the playhead
* never drags the plan onto the wire with it.
* POST /refresh → re-read the plan now
* GET /service-types → { options } for the admin "Service type" select,
* grouped by Planning Center folder path
@@ -17,6 +21,8 @@
* (documents ProPresenter has shown or lists — see below)
* GET /note-categories → { options } for a tile's "Item notes" categories:
* the service type's item note categories, by name
* GET /teams → { options } for a Teams tile's "Teams" switches
* GET /team-avatar/<planPersonId> → that person's photo, proxied + cached
* GET /timers → snapshot for the Timers module (guide: "Offering
* GET /timers/stream → SSE, `timers` events timers to the Timers module")
*
@@ -29,12 +35,24 @@
* GET …/plans/{id}/plan_times (service start times)
* GET …/plans/{id}/items?include=song,arrangement,item_notes
* GET /service_types/{st}/item_note_categories (note category names)
* GET …/plans/{id}/team_members?include=team,person (who is scheduled)
*
* Following AbleSet: the same loopback trick, entirely optional. When this
* ProdDash has an AbleSet module that is configured and answering, its song,
* sections and playhead are passed to the tiles, and the song is matched to a
* plan item by name so a tile can fill that item as the song plays. With no
* such module — not installed, disabled, no host — tiles are told
* `available: false` and draw none of it.
*
* Following ProPresenter: instead of talking to ProPresenter a second time,
* this module reads the propresenter-now-next module's own SSE feed over
* loopback (/api/modules/propresenter-now-next/stream, on shell.port) and
* matches the live presentation name to a plan item. Item start/end
* timestamps are tracked here, once, so every tile agrees on the runtime.
* places the live document on a plan item (matching.js placeDocument): by
* name, or — for the sermon, whose document is named after the sermon and
* never after its plan item — by reading like the plan itself ("YYMMDD
* Series Title - Part #"), which lands it on the plan's message item. Item
* start/end timestamps are tracked here, once, so every tile agrees on the
* runtime.
*
* Service timing: a plan's services (9:00, 11:00…) take turns owning the
* service clock — the rules live in service-timing.js. A service starts at
@@ -52,7 +70,7 @@ const http = require('http');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { MATCH_THRESHOLD, similarity } = require('./matching');
const { placeDocument, messageItemOf, playlistMirrorsPlan, similarity, MATCH_THRESHOLD } = require('./matching');
const {
MINUTE,
serviceTimes,
@@ -78,9 +96,28 @@ const HEARTBEAT_MS = 15000;
/** The Now/Next module whose feed we follow. */
const NOW_NEXT_ID = 'propresenter-now-next';
const NOW_NEXT_RETRY_MS = 3000;
/** The AbleSet module, followed the same way — entirely optional (see below). */
const ABLESET_ID = 'ableset';
const ABLESET_RETRY_MS = 3000;
const ABLESET_MISSING_RETRY_MS = 15000;
/** Fastest the playhead is passed on; AbleSet offers more than a tile can draw. */
const ABLESET_POS_MS = 200;
const NOW_NEXT_MISSING_RETRY_MS = 15000;
/** How many distinct documents seen live are remembered for the admin selects. */
const SEEN_DOCUMENTS_MAX = 200;
/**
* Team assignments change far more slowly than the plan itself (someone
* confirms, a position is filled), so they ride a slow lane: re-read when the
* plan changes, and otherwise no more often than this.
*/
const TEAMS_MIN_MS = 60 * 1000;
/** How long the service type's own team list is believed. */
const SERVICE_TEAMS_TTL_MS = 10 * MINUTE;
/** Avatars live on Planning Center's CDN; browsers only talk to ProdDash. */
const AVATAR_CACHE_MAX = 300;
const AVATAR_TTL_MS = 6 * 60 * 60 * 1000;
const AVATAR_MAX_BYTES = 2 * 1024 * 1024;
/** How long a service type's item note categories are believed before Planning Center is asked again. */
const NOTE_CATEGORIES_TTL_MS = 10 * MINUTE;
/**
@@ -108,6 +145,8 @@ function clearedState() {
serviceType: { id: '', name: '' },
plan: null,
items: [],
teams: [], // who is scheduled, by team (the Teams tile)
teamsError: '', // why the last team read failed, if it did
live: clearedLive(),
service: clearedService(),
timing: null, // the admin's service-timing choices (no secrets)
@@ -131,6 +170,28 @@ function clearedLive() {
};
}
/**
* What tiles are told about AbleSet. `available` false covers every way there
* may be nothing to draw — no module installed, disabled, or not answering —
* and the tiles then show none of it at all.
*/
function clearedAbleSet() {
return {
available: false,
configured: false,
reachable: false,
reason: '',
playing: false,
tempo: null,
song: null,
section: null,
sections: [],
beats: null,
itemId: '',
at: 0,
};
}
/** The service that owns the clock, as tiles and the timers see it. */
function clearedService() {
return {
@@ -368,6 +429,168 @@ function shapePlan(planRec, serviceTypeId, planTimes) {
};
}
/* ── team assignments (the Teams tile) ──────────────────────────────── */
/**
* Planning Center's scheduling status letters. The API answers "C", "U" or
* "D"; some accounts and older records spell the word out, so match on the
* first letter and treat anything unknown as not yet confirmed — the state a
* booth should chase.
*/
function teamStatusOf(raw) {
const s = String(raw || '').trim().toUpperCase();
if (s.startsWith('C')) return 'confirmed';
if (s.startsWith('D')) return 'declined';
return 'unconfirmed';
}
/**
* The person's photo. A PlanPerson usually carries `photo_thumbnail`; when a
* plan is read with `include=person` the Person record carries the fuller set
* of names Planning Center has used for the same thing over the years. Take
* the first that looks like a URL — a missing photo is normal and the tile
* draws initials instead.
*/
function teamPhotoOf(attrs, person) {
const candidates = [
attrs?.photo_thumbnail,
attrs?.photo_url,
person?.attributes?.avatar,
person?.attributes?.photo_thumbnail_url,
person?.attributes?.photo_url,
person?.attributes?.thumbnail_url,
];
for (const c of candidates) {
const url = String(c || '').trim();
if (/^https?:\/\//i.test(url)) return url;
}
return '';
}
/**
* `/plans/{id}/team_members?include=team,person` → the teams a tile draws,
* each with its people. Teams keep Planning Center's own order (a Team's
* `sequence`, then name); people sort by position, then by name, so a tile
* reads the way the schedule page does.
*
* Everyone scheduled belongs to a team, but a record whose team relationship
* is missing (a deleted team, a partial response) is not dropped on the
* floor — it lands under "Unassigned" where somebody will notice it.
*
* `allTeams` is the service type's own team list. Planning Center only
* returns a team here once somebody is scheduled on it, so without that list
* a team nobody has signed up for is invisible — which is the one a booth
* most wants to see. It also carries the authoritative name and order.
*/
function shapeTeams(body, allTeams) {
const included = new Map();
for (const rec of body.included || []) included.set(`${rec.type}/${rec.id}`, rec);
const teams = new Map();
for (const pp of body.data || []) {
const a = pp.attributes || {};
const teamRef = pp.relationships?.team?.data;
const teamRec = teamRef ? included.get(`Team/${teamRef.id}`) : null;
const teamId = teamRef?.id ? String(teamRef.id) : 'unassigned';
if (!teams.has(teamId)) {
teams.set(teamId, {
id: teamId,
name: String(teamRec?.attributes?.name || '').trim() || (teamRef?.id ? `Team ${teamId}` : 'Unassigned'),
sequence: Number(teamRec?.attributes?.sequence) || 0,
members: [],
});
}
const personRef = pp.relationships?.person?.data;
const personRec = personRef ? included.get(`Person/${personRef.id}`) : null;
teams.get(teamId).members.push({
id: String(pp.id),
personId: personRef?.id ? String(personRef.id) : '',
name: String(a.name || personRec?.attributes?.name || '').trim() || 'Unnamed',
position: String(a.team_position_name || '').trim(),
status: teamStatusOf(a.status),
declineReason: String(a.decline_reason || '').trim(),
notes: String(a.notes || '').trim(),
// The URL itself stays on the server; the tile asks for /team-avatar/<id>.
hasPhoto: Boolean(teamPhotoOf(a, personRec)),
});
}
// Teams nobody is scheduled on yet, and the real name/order for the rest.
for (const t of allTeams || []) {
const known = teams.get(t.id);
if (known) {
if (t.name) known.name = t.name;
known.sequence = t.sequence;
} else {
teams.set(t.id, { id: t.id, name: t.name, sequence: t.sequence, members: [] });
}
}
const out = [...teams.values()];
out.sort((x, y) => x.sequence - y.sequence || x.name.localeCompare(y.name));
for (const team of out) {
team.members.sort((x, y) => x.position.localeCompare(y.position) || x.name.localeCompare(y.name));
team.counts = {
total: team.members.length,
confirmed: team.members.filter((m) => m.status === 'confirmed').length,
unconfirmed: team.members.filter((m) => m.status === 'unconfirmed').length,
declined: team.members.filter((m) => m.status === 'declined').length,
};
}
return out;
}
/* Avatars: fetched once, kept a while, and served from ProdDash so no browser
ever talks to Planning Center (same reasoning as every other upstream). */
const avatarCache = new Map(); // url → { buf, type, at } — survives a re-init
const avatarInFlight = new Map();
function fetchAvatar(url) {
const hit = avatarCache.get(url);
if (hit && Date.now() - hit.at < AVATAR_TTL_MS) return Promise.resolve(hit);
if (avatarInFlight.has(url)) return avatarInFlight.get(url);
const p = (async () => {
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), redirect: 'follow' });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const type = String(response.headers.get('content-type') || 'image/jpeg').split(';')[0].trim();
if (!type.startsWith('image/')) throw new Error(`not an image (${type})`);
const buf = Buffer.from(await response.arrayBuffer());
if (buf.length > AVATAR_MAX_BYTES) throw new Error('too large');
if (avatarCache.size >= AVATAR_CACHE_MAX) avatarCache.delete(avatarCache.keys().next().value);
const entry = { buf, type, at: Date.now() };
avatarCache.set(url, entry);
return entry;
})().finally(() => avatarInFlight.delete(url));
avatarInFlight.set(url, p);
return p;
}
/** https anywhere, or plain http on this machine — which is the mock, nothing else. */
function avatarUrlAllowed(url) {
try {
const u = new URL(String(url || ''));
return u.protocol === 'https:' || (u.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname));
} catch {
return false;
}
}
/** Answer with the photo at `url`; a failure is a 404/502 and the tile draws initials. */
async function serveAvatar(res, url) {
if (!avatarUrlAllowed(url)) {
res.writeHead(404, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' });
return void res.end('No photo');
}
try {
const img = await fetchAvatar(url);
res.writeHead(200, { 'Content-Type': img.type, 'Content-Length': img.buf.length, 'Cache-Control': 'private, max-age=3600' });
res.end(img.buf);
} catch {
res.writeHead(502, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' });
res.end('Photo unavailable');
}
}
/** "9:00 service" / "9:00 First Service" — how a service is named in details and logs. */
function serviceLabel(win) {
if (!win || !win.startsAt) return '';
@@ -434,6 +657,8 @@ module.exports = {
let inFlight = null;
let lastFrame = '';
let lastTimersSig = '';
let lastMessageItemId = null;
let lastMatchError = '';
/* — broadcasting — */
@@ -543,6 +768,98 @@ module.exports = {
}
}
/* — team assignments (the Teams tile) — */
/**
* The service type's teams, cached: they change when somebody edits the
* service type, not during a service. A failed read is not fatal — the
* plan's own teams still draw, just without the empty ones.
*/
let serviceTeams = { at: 0, list: [] };
async function readServiceTeams() {
if (Date.now() - serviceTeams.at < SERVICE_TEAMS_TTL_MS) return serviceTeams.list;
try {
const body = await pco.getAll(`${SERVICES}/service_types/${encodeURIComponent(serviceTypeId)}/teams`);
const list = (body.data || []).map((t, i) => ({
id: String(t.id),
name: String(t.attributes?.name || '').trim() || `Team ${t.id}`,
sequence: Number(t.attributes?.sequence) || i + 1,
}));
serviceTeams = { at: Date.now(), list };
} catch (err) {
log(`service type team list read failed: ${err?.message || err}`);
serviceTeams.at = Date.now(); // don't retry every poll
}
return serviceTeams.list;
}
/** planPersonId → photo URL, so a browser never learns the CDN address. */
let teamPhotos = new Map();
let teamsReadAt = 0;
/**
* Who is scheduled on this plan. Asked for with `include=team,person` and
* read again defensively without the includes when an account refuses
* them, exactly as the items read does: a tile that can name people
* without photos is far better than a tile that shows nothing.
*/
async function readTeams(planId) {
const target = `${planPath(planId)}/team_members`;
let body;
try {
body = await pco.getAll(target, { include: 'team,person' });
} catch (err) {
if (err.status && err.status >= 400 && err.status < 500 && err.status !== 401 && err.status !== 429) {
log(`team include rejected (${err.message}) — reading team members without includes`);
body = await pco.getAll(target);
} else {
throw err;
}
}
const teams = shapeTeams(body, await readServiceTeams());
const photos = new Map();
const included = new Map();
for (const rec of body.included || []) included.set(`${rec.type}/${rec.id}`, rec);
for (const pp of body.data || []) {
const personRef = pp.relationships?.person?.data;
const url = teamPhotoOf(pp.attributes, personRef ? included.get(`Person/${personRef.id}`) : null);
if (url) photos.set(String(pp.id), url);
}
teamPhotos = photos;
teamsReadAt = Date.now();
return teams;
}
/**
* Refresh the team list when it is worth it: a new plan, or the slow lane
* coming round. A failure keeps the last good list and says so in the
* state — the plan itself is what the booth needs, and losing the roster
* must never cost them the running order.
*/
async function refreshTeams(planId, force) {
if (!force && Date.now() - teamsReadAt < TEAMS_MIN_MS) return;
try {
const teams = await readTeams(planId);
const before = state.teams.reduce((n, t) => n + t.members.length, 0);
const after = teams.reduce((n, t) => n + t.members.length, 0);
state.teams = teams;
state.teamsError = '';
if (force || before !== after) {
log(`teams: ${after} scheduled across ${teams.length} team${teams.length === 1 ? '' : 's'}`);
}
} catch (err) {
state.teamsError = err?.message || String(err);
log(`team read failed: ${state.teamsError}`);
}
}
/** Options for a Teams tile's "Teams" switches — the plan's own teams, in its order. */
function teamOptions() {
return { options: state.teams.map((t) => ({ value: t.id, label: t.name })) };
}
async function readPlan() {
if (!pco.configured || !serviceTypeId) return;
let planRec = null;
@@ -567,6 +884,8 @@ module.exports = {
if (state.plan) log('no plan found any more — service timing reset');
state.plan = null;
state.items = [];
state.teams = [];
state.teamsError = "";
state.reachable = true;
state.lastError = '';
state.lastFetched = Date.now();
@@ -582,6 +901,9 @@ module.exports = {
}
state.plan = plan;
state.items = items;
noteMessageItem(items);
// The roster rides its own slow lane and never fails the plan read.
await refreshTeams(plan.id, planChanged);
state.reachable = true;
state.lastError = '';
state.lastFetched = Date.now();
@@ -596,6 +918,17 @@ module.exports = {
syncServiceSafe(Date.now(), null);
}
/** Say, once per plan, which item a document named like the plan will land on. */
function noteMessageItem(items) {
const msg = messageItemOf(items);
const id = msg ? msg.id : '';
if (id === lastMessageItemId) return;
lastMessageItemId = id;
log(msg
? `message item: "${msg.title}" — a live document named like this plan (its date, series and part) lands here`
: 'no message item in this plan — a document named like the plan has nowhere to land');
}
/* — item note categories (a tile's "Item notes" → Categories switches) — */
let noteCategories = { at: 0, options: [] }; // the last good answer from Planning Center
@@ -964,6 +1297,170 @@ module.exports = {
const badPorts = new Set();
/** Fallback only: a browser reached us on this Host — normally the shell's real port. */
/* — AbleSet, over loopback like the ProPresenter feed above — */
/**
* The AbleSet module, if this ProdDash has one. Nothing here is required:
* a dashboard with no AbleSet module, a disabled one, or one with no host
* configured simply reports `available: false` and the tiles draw none of
* it. Installing AbleSet later lights it up without a restart, because a
* 404 is retried on the slow timer like any other missing feed.
*
* What tiles get is deliberately small — the song, its sections, and the
* playhead in beats with a stamp — because it moves five times a second
* and must never drag the plan (items, teams) onto the wire with it. It
* rides its own `ableset` event on the module's one stream.
*/
let absRequest = null;
let absRetryTimer = null;
let absPosTimer = null;
let absLastSent = 0;
let absLastStill = '';
let abs = clearedAbleSet();
function absPart(p) {
if (!p || typeof p !== 'object') return null;
const name = String(p.name || '').trim();
if (!name) return null;
const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
return { name, index: n(p.index), start: n(p.start), end: n(p.end) };
}
/**
* Which plan item AbleSet's song is, by the same name matching the live
* ProPresenter document uses. Without this a progress bar would happily
* fill the sermon while the band rehearses the next song: the tile only
* draws progress when the song AbleSet is playing IS the item on screen.
*/
function absItemFor(songName) {
if (!songName) return '';
let best = null;
for (const item of state.items) {
if (item.itemType === 'header') continue;
const score = Math.max(
similarity(songName, item.title),
item.song ? similarity(songName, item.song.title) : 0
);
if (score >= MATCH_THRESHOLD && (!best || score > best.score)) best = { id: item.id, score };
}
return best ? best.id : '';
}
function applyAbleSet(view) {
const song = absPart(view?.song);
abs = {
available: true,
configured: Boolean(view?.configured),
reachable: Boolean(view?.reachable),
playing: Boolean(view?.playing),
tempo: Number.isFinite(Number(view?.tempo)) ? Number(view.tempo) : null,
song,
section: absPart(view?.section),
sections: Array.isArray(view?.sections)
? view.sections.slice(0, 60).map((s) => ({ name: String(s?.name || ''), color: s?.color || null }))
: [],
beats: Number.isFinite(Number(view?.pos?.beats)) ? Number(view.pos.beats) : null,
itemId: song ? absItemFor(song.name) : '',
at: Date.now(),
};
broadcastAbleSet();
}
/** Only the playhead moved: keep everything else and restamp. */
function applyAbleSetPos(pos) {
if (!abs.available) return;
abs = {
...abs,
beats: Number.isFinite(Number(pos?.beats)) ? Number(pos.beats) : abs.beats,
at: Date.now(),
};
broadcastAbleSet();
}
/**
* Fan the slice out. A change in anything but the playhead goes at once;
* the playhead itself is throttled, since AbleSet offers more packets
* than any tile can draw.
*/
function broadcastAbleSet(force) {
const { beats, at, ...still } = abs;
const frame = JSON.stringify(still);
const changed = frame !== absLastStill;
absLastStill = frame;
const now = Date.now();
if (!force && !changed && now - absLastSent < ABLESET_POS_MS) {
// Due soon anyway — make sure the last packet of a burst still lands.
if (!absPosTimer) {
absPosTimer = setTimeout(() => { absPosTimer = null; broadcastAbleSet(true); }, ABLESET_POS_MS);
absPosTimer.unref?.();
}
return;
}
clearTimeout(absPosTimer);
absPosTimer = null;
absLastSent = now;
if (!streams.size) return;
writeAll(streams, `event: ableset\ndata: ${JSON.stringify(abs)}\n\n`);
}
function absUnavailable(reason, retryMs) {
if (abs.available || abs.reason !== reason) {
abs = { ...clearedAbleSet(), reason };
broadcastAbleSet(true);
}
if (stopped) return;
clearTimeout(absRetryTimer);
absRetryTimer = setTimeout(connectAbleSet, retryMs);
absRetryTimer.unref?.();
}
function connectAbleSet() {
if (stopped) return;
const port = nnPort;
const req = http.get(
{ host: '127.0.0.1', port, path: `/api/modules/${ABLESET_ID}/stream`, headers: { Accept: 'text/event-stream' } },
(res) => {
if (res.statusCode !== 200) {
res.resume();
return absUnavailable(
res.statusCode === 404 ? 'no AbleSet module here' : `AbleSet module feed answered ${res.statusCode}`,
ABLESET_MISSING_RETRY_MS
);
}
res.setEncoding('utf8');
let buffer = '';
res.on('data', (chunk) => {
buffer += chunk;
let idx;
while ((idx = buffer.indexOf('\n\n')) >= 0) {
const block = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
let event = 'message';
let data = '';
for (const line of block.split('\n')) {
if (line.startsWith('event:')) event = line.slice(6).trim();
else if (line.startsWith('data:')) data += line.slice(5).trim();
}
if (!data) continue;
try {
if (event === 'state') applyAbleSet(JSON.parse(data).state ?? JSON.parse(data));
else if (event === 'pos') applyAbleSetPos(JSON.parse(data));
} catch { /* a bad frame is not fatal */ }
}
});
res.on('end', () => absUnavailable('AbleSet module feed ended', ABLESET_RETRY_MS));
res.on('error', () => absUnavailable('AbleSet module feed dropped', ABLESET_RETRY_MS));
}
);
req.on('error', (err) => {
if (req !== absRequest) return; // superseded by a reconnect on the learned port
absUnavailable(`ProdDash loopback failed: ${err.message}`, ABLESET_RETRY_MS);
});
req.setTimeout(45000, () => req.destroy(new Error('feed went silent')));
absRequest = req;
}
function learnPort(hostHeader) {
if (shellPort) return; // the shell told us; nothing to learn
const port = portFromHost(hostHeader);
@@ -975,6 +1472,10 @@ module.exports = {
try { nnRequest?.destroy(); } catch { /* gone */ }
nnRequest = null;
connectNowNext();
clearTimeout(absRetryTimer);
try { absRequest?.destroy(); } catch { /* gone */ }
absRequest = null;
connectAbleSet();
}
/**
@@ -996,36 +1497,29 @@ module.exports = {
};
lastLiveName = keep.activeName || '';
if (follow && keep.activeName) {
const hit = matchItem(keep.activeName);
const hit = matchItem(keep.activeName, hintFrom(lastView));
state.live.matched = Boolean(hit);
if (hit) {
state.live.currentScore = hit.score;
startItem(hit.item.id);
startItem(hit.item.id, keep.activeName, hit);
}
}
}
/** Best plan item for a live presentation name, preferring the ones ahead of us. */
function matchItem(name) {
const items = state.items.filter((it) => it.itemType !== 'header');
if (!items.length) return null;
const currentIdx = items.findIndex((it) => it.id === state.live.currentItemId);
let best = null;
for (let i = 0; i < items.length; i += 1) {
const item = items[i];
const score = Math.max(similarity(name, item.title), item.song ? similarity(name, item.song.title) : 0);
if (score < MATCH_THRESHOLD) continue;
// Distance ahead of the current item (wrapping so items behind rank last).
const dist = currentIdx < 0 ? i : (i - currentIdx + items.length) % items.length;
if (
!best
|| score > best.score + 0.001
|| (Math.abs(score - best.score) <= 0.001 && dist < best.dist)
) {
best = { item, score, dist };
}
}
return best;
/**
* The plan item a live document stands for — { item, score, via } or
* null. The rules live in matching.js (placeDocument): by name, then the
* message rule for a document named like the plan itself; the playlist
* position only breaks ties, and only while the playlist mirrors the plan.
*/
function matchItem(name, hint) {
return placeDocument(name, { items: state.items, plan: state.plan, currentItemId: state.live.currentItemId, hint });
}
/** The live item's place in ProPresenter's playlist, and whether that playlist mirrors the plan. */
function hintFrom(view) {
const index = Number.isInteger(view?.activeIndex) ? view.activeIndex : -1;
return { index, mirror: index >= 0 && playlistMirrorsPlan(view?.items, state.items) };
}
/** Remember a document ProPresenter put live, most recent first, for the admin selects. */
@@ -1077,6 +1571,7 @@ module.exports = {
function applyLiveView(view) {
lastView = view && typeof view === 'object' ? view : null;
const live = state.live;
if (!live.available) log('following the ProPresenter module feed');
live.available = true;
live.reason = '';
live.ppEnabled = Boolean(view?.enabled);
@@ -1095,23 +1590,40 @@ module.exports = {
broadcast(); // reachability may have changed; the frame check keeps it quiet otherwise
return;
}
lastLiveName = name;
rememberDocument(name);
if (follow) {
const hit = matchItem(name);
live.matched = Boolean(hit);
if (hit) {
live.currentScore = hit.score;
if (hit.item.id !== live.currentItemId) startItem(hit.item.id);
try {
const hit = matchItem(name, hintFrom(view));
live.matched = Boolean(hit);
if (hit) {
live.currentScore = hit.score;
if (hit.item.id !== live.currentItemId) startItem(hit.item.id, name, hit);
} else {
// Said in the log, because on the wall it looks like the plan
// stopped following: the highlight stays where it was.
const staying = state.items.find((it) => it.id === live.currentItemId);
log(`live document "${name}" is not in the plan — ${staying ? `"${staying.title}" stays current` : 'no current item'}`);
}
lastMatchError = '';
} catch (err) {
// Never silent: a matcher that throws would otherwise leave the
// highlight stuck with nothing in the log to say why.
const msg = err?.message || String(err);
if (msg !== lastMatchError) {
lastMatchError = msg;
log(`matching "${name}" failed: ${msg}`);
}
}
}
lastLiveName = name;
// The same document is also a possible service start / end cue.
syncServiceSafe(Date.now(), name);
broadcast();
broadcastTimers();
}
function startItem(itemId) {
/** Make an item current; `liveName` and `hit` say what placed it, for the log. */
function startItem(itemId, liveName, hit) {
const live = state.live;
const now = Date.now();
if (live.currentItemId && live.history[live.currentItemId] && !live.history[live.currentItemId].endedAt) {
@@ -1120,12 +1632,18 @@ module.exports = {
live.currentItemId = itemId;
live.history[itemId] = { startedAt: now, endedAt: 0 };
const item = state.items.find((it) => it.id === itemId);
log(`live item → ${item?.title || itemId}`);
const how = hit
? ` (${hit.via}${hit.via === 'name' ? ` ${Number(hit.score).toFixed(2)}` : ''}${liveName ? `: "${liveName}"` : ''})`
: '';
log(`live item → ${item?.title || itemId}${how}`);
}
function nowNextUnavailable(reason, retryMs) {
const live = state.live;
if (live.available || live.reason !== reason) {
// Every drop is in the log: a highlight that stopped moving is
// otherwise indistinguishable from a feed that went away.
log(`ProPresenter module feed unavailable — ${reason}`);
live.available = false;
live.reason = reason;
live.ppReachable = false;
@@ -1216,6 +1734,9 @@ module.exports = {
state.live.reason = 'Connecting to the ProPresenter module feed';
connectNowNext();
}
// Always: whether there is an AbleSet module to follow is its answer, not
// an admin setting here.
connectAbleSet();
mirrorService();
const heartbeat = setInterval(() => {
@@ -1248,6 +1769,7 @@ module.exports = {
timerStreams,
pco,
getState: () => state,
getAbleSet: () => abs,
learnPort,
refresh() {
clearTimeout(pollTimer);
@@ -1258,6 +1780,8 @@ module.exports = {
timersSnapshot,
documentOptions,
noteCategoryOptions,
teamOptions,
avatarUrlFor: (id) => teamPhotos.get(String(id)) || "",
};
return {
@@ -1267,7 +1791,10 @@ module.exports = {
clearInterval(ticker);
clearTimeout(pollTimer);
clearTimeout(nnRetryTimer);
clearTimeout(absRetryTimer);
clearTimeout(absPosTimer);
try { nnRequest?.destroy(); } catch { /* gone */ }
try { absRequest?.destroy(); } catch { /* gone */ }
for (const set of [streams, timerStreams]) {
for (const res of set) {
try { res.end(); } catch { /* already gone */ }
@@ -1309,7 +1836,11 @@ module.exports = {
return {
'GET /state': (req, res) => {
current?.learnPort(req.headers.host);
json(res, 200, { state: current ? current.getState() : clearedState(), now: Date.now() });
json(res, 200, {
state: current ? current.getState() : clearedState(),
ableset: current ? current.getAbleSet() : clearedAbleSet(),
now: Date.now(),
});
},
'GET /stream': (req, res) => {
@@ -1317,6 +1848,7 @@ module.exports = {
sseHead(res);
const state = current ? current.getState() : clearedState();
res.write(`event: state\ndata: ${JSON.stringify({ state, now: Date.now() })}\n\n`);
res.write(`event: ableset\ndata: ${JSON.stringify(current ? current.getAbleSet() : clearedAbleSet())}\n\n`);
if (!current) return void res.end();
const { streams } = current;
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
@@ -1350,6 +1882,28 @@ module.exports = {
req.on('close', () => timerStreams.delete(res));
},
/**
* Options for a Teams tile's "Teams" switches. Like the note
* categories, always a 200 with a list: an empty one simply means there
* is nothing scheduled to choose from yet, which the gear window says
* plainly.
*/
'GET /teams': (req, res) => {
json(res, 200, current ? current.teamOptions() : { options: [] });
},
/**
* A scheduled person's photo, proxied from Planning Center and cached.
* The tile asks by plan-person id and never sees the CDN URL; an id the
* module does not know (an old tile, a person since unscheduled) is a
* 404 and the tile falls back to initials.
*/
'GET /team-avatar/*': (req, res) => {
const id = String(req.wildcard || '').replace(/^\/+/, '');
const url = current ? current.avatarUrlFor(id) : '';
serveAvatar(res, url);
},
/** Options for the admin "Start document" / "End document" selects. */
'GET /documents': (req, res) => {
if (!current) return json(res, 200, { options: [{ value: '', label: 'None' }], note: 'Module not running.' });
+292
View File
@@ -86,6 +86,7 @@
}
[data-module="pco-plan"] .pp-row {
position: relative;
display: flex;
align-items: flex-start;
gap: 0.6em;
@@ -365,3 +366,294 @@
[data-module="pco-plan"] .pp-foot.is-unmatched::before { background: var(--warn); }
[data-module="pco-plan"] .pp-foot.is-down { color: var(--danger); }
[data-module="pco-plan"] .pp-foot.is-down::before { background: var(--danger); }
/* ── the Teams tile ───────────────────────────────────────────────────
Who is scheduled, by team. Sizes hang off --pp-size like the Plan tile;
colours come from the tile's own settings (--tm-team per section,
--tm-status per person) over the shell's palette. */
[data-module="pco-plan"] .tm-wrap {
--pp-size: 14px;
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
font-size: var(--pp-size);
color: var(--text);
}
[data-module="pco-plan"] .tm-head {
flex: none;
padding: 0.6em 0.85em 0.5em;
border-bottom: 1px solid var(--border);
background: color-mix(in srgb, var(--accent) 6%, transparent);
}
[data-module="pco-plan"] .tm-head[hidden] { display: none; }
[data-module="pco-plan"] .tm-title {
font-size: 1.1em;
font-weight: 700;
line-height: 1.25;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .tm-sub {
margin-top: 0.15em;
font-size: 0.82em;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .tm-sub[hidden] { display: none; }
[data-module="pco-plan"] .tm-body {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
padding: 0 0 0.6em;
overscroll-behavior: contain;
}
/* ── a team ── */
[data-module="pco-plan"] .tm-team { --tm-team: var(--accent); }
/* The header band runs edge to edge, like the Plan tile's section headers. */
[data-module="pco-plan"] .tm-team-head {
display: flex;
align-items: center;
gap: 0.6em;
padding: 0.45em 0.9em 0.4em;
margin-top: 0.7em;
background: color-mix(in srgb, var(--tm-team) 22%, transparent);
}
[data-module="pco-plan"] .tm-team:first-child .tm-team-head { margin-top: 0; }
[data-module="pco-plan"] .header-gradient .tm-team-head {
background: linear-gradient(90deg,
color-mix(in srgb, var(--tm-team) 30%, transparent),
color-mix(in srgb, var(--tm-team) 6%, transparent) 70%,
transparent);
}
[data-module="pco-plan"] .tm-team-name {
flex: 1;
min-width: 0;
font-size: 0.85em;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .tm-team-count {
flex: none;
font-size: 0.78em;
font-weight: 700;
font-variant-numeric: tabular-nums;
color: var(--muted);
}
[data-module="pco-plan"] .tm-people {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(11em, 1fr));
gap: 0.15em 0.5em;
padding: 0.35em 0.6em 0.2em;
}
[data-module="pco-plan"] .tm-people.is-fixed-cols {
grid-template-columns: repeat(var(--tm-cols, 1), minmax(0, 1fr));
}
[data-module="pco-plan"] .tm-people.is-sub { padding-top: 0.1em; padding-bottom: 0.1em; }
/* Grouped by position: headings span, each position's people form their own grid. */
[data-module="pco-plan"] .tm-groups { padding-bottom: 0.2em; }
[data-module="pco-plan"] .tm-position-head {
padding: 0.4em 0.9em 0;
font-size: 0.72em;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--muted);
}
[data-module="pco-plan"] .tm-team-empty {
grid-column: 1 / -1;
padding: 0.2em 0.3em 0.4em;
font-size: 0.85em;
font-style: italic;
color: var(--muted);
}
/* ── one person ── */
[data-module="pco-plan"] .tm-person {
display: flex;
align-items: center;
gap: 0.55em;
min-width: 0;
padding: 0.3em 0.4em;
border-radius: 0.45em;
}
[data-module="pco-plan"] .tm-person:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
[data-module="pco-plan"] .tint-rows .tm-person { background: color-mix(in srgb, var(--tm-team) 8%, transparent); }
[data-module="pco-plan"] .tint-rows .tm-person:hover { background: color-mix(in srgb, var(--tm-team) 16%, transparent); }
[data-module="pco-plan"] .tm-person.is-declined { opacity: 0.55; }
[data-module="pco-plan"] .tm-avatar {
position: relative;
flex: none;
width: 2.1em;
height: 2.1em;
border-radius: 999px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--tm-team) 28%, var(--panel));
color: var(--text);
font-size: 0.78em;
font-weight: 800;
letter-spacing: 0.02em;
user-select: none;
}
/* The photo covers the initials; if it fails to load the script drops it. */
[data-module="pco-plan"] .tm-avatar img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
background: var(--panel);
}
[data-module="pco-plan"] .tm-person-main { flex: 1; min-width: 0; }
[data-module="pco-plan"] .tm-name {
font-weight: 600;
line-height: 1.25;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .tm-person.is-declined .tm-name { text-decoration: line-through; }
[data-module="pco-plan"] .tm-position {
font-size: 0.8em;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .tm-note {
margin-top: 0.1em;
font-size: 0.78em;
line-height: 1.3;
color: color-mix(in srgb, var(--text) 75%, var(--muted));
overflow-wrap: anywhere;
}
[data-module="pco-plan"] .tm-status {
flex: none;
width: 0.55em;
height: 0.55em;
border-radius: 999px;
background: var(--tm-status, var(--muted));
box-shadow: 0 0 0 0.18em color-mix(in srgb, var(--tm-status, var(--muted)) 18%, transparent);
}
/* ── empty / degraded ── */
[data-module="pco-plan"] .tm-empty {
padding: 12% 1.2em 1em;
text-align: center;
color: var(--muted);
}
[data-module="pco-plan"] .tm-empty-title { font-size: 1.1em; font-weight: 700; color: var(--text); }
[data-module="pco-plan"] .tm-empty-hint { margin-top: 0.4em; font-size: 0.9em; line-height: 1.4; }
[data-module="pco-plan"] .tm-empty-link {
display: inline-block;
margin-top: 0.9em;
padding: 0.35em 0.9em;
border: 1px solid color-mix(in srgb, var(--accent) 50%, transparent);
border-radius: 999px;
color: var(--accent);
font-weight: 600;
text-decoration: none;
}
[data-module="pco-plan"] .tm-empty-link:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); }
[data-module="pco-plan"] .tm-wrap.is-offline .tm-head { border-bottom-color: color-mix(in srgb, var(--danger) 50%, transparent); }
[data-module="pco-plan"] .tm-wrap.is-offline .tm-body { opacity: 0.6; }
/* ── AbleSet under the current item ───────────────────────────────────
Drawn only while an AbleSet module is configured, reachable, and playing
the song this item is. The fill is a layer behind the row's own content;
everything else in the row is lifted over it. */
[data-module="pco-plan"] .pp-fill {
position: absolute;
top: 0;
bottom: 0;
left: 0;
z-index: 0;
width: 0;
border-radius: 0.5em 0 0 0.5em;
background: color-mix(in srgb, var(--pp-current) 26%, transparent);
/* Packets arrive about five times a second; the glide covers the gaps. */
transition: width 0.22s linear;
pointer-events: none;
}
[data-module="pco-plan"] .pp-row > *:not(.pp-fill) { position: relative; z-index: 1; }
/* The sections strip, bottom right of the current item. */
[data-module="pco-plan"] .pp-abs-sections {
display: flex;
gap: 0.3em;
/* Bottom right of the item: hug the content and sit against the right edge
until there are more sections than fit, when it fills the width and
scrolls instead. */
width: fit-content;
max-width: 100%;
margin-top: 0.35em;
margin-left: auto;
padding-bottom: 0.1em;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
overscroll-behavior: contain;
-webkit-mask-image: linear-gradient(90deg, transparent, #000 1.2em, #000 calc(100% - 1.2em), transparent);
mask-image: linear-gradient(90deg, transparent, #000 1.2em, #000 calc(100% - 1.2em), transparent);
}
[data-module="pco-plan"] .pp-abs-sections::-webkit-scrollbar { display: none; }
[data-module="pco-plan"] .pp-abs-sec {
flex: none;
padding: 0.1em 0.5em;
border-radius: 999px;
border: 1px solid var(--border);
font-size: 0.72em;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
white-space: nowrap;
color: var(--muted);
transition: color 0.2s ease, border-color 0.2s ease;
}
[data-module="pco-plan"] .pp-abs-sec.is-done { opacity: 0.45; }
/* The section now playing fills left to right as it goes, like the row. */
[data-module="pco-plan"] .pp-abs-sec.is-now {
color: var(--text);
border-color: color-mix(in srgb, var(--pp-current) 60%, transparent);
background:
linear-gradient(90deg,
color-mix(in srgb, var(--pp-current) 40%, transparent) var(--pp-sec-fill, 0%),
transparent var(--pp-sec-fill, 0%));
}
+435
View File
@@ -0,0 +1,435 @@
/* PCO Plan — the Teams tile.
Who is scheduled on the current plan, by team and position, from the same
server state the Plan tile draws (state.teams). Everything shown is this
tile's own choice (gear menu): which teams and positions, what each row
carries, and the colours. Photos come from ProdDash's own avatar route —
the browser never talks to Planning Center. */
const REFRESH_SVG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
const DEFAULT_TEMPLATE = '{serviceType} • {date} | {people} on {teams}';
/** Colours for "Tint teams", walked in order so neighbouring teams differ. */
const TEAM_HUES = [152, 205, 32, 275, 12, 180, 320, 95, 240, 50];
export default function createTeams({ root, moduleApi }) {
let state = null;
let feedOffline = false;
let stream = null;
let lastKey = '';
root.innerHTML = `
<div class="tm-wrap">
<header class="tm-head">
<div class="tm-title"></div>
<div class="tm-sub"></div>
</header>
<div class="tm-body"></div>
</div>`;
const wrap = root.querySelector('.tm-wrap');
const headEl = root.querySelector('.tm-head');
const titleEl = root.querySelector('.tm-title');
const subEl = root.querySelector('.tm-sub');
const bodyEl = root.querySelector('.tm-body');
const cfg = () => moduleApi.instanceSettings || {};
const on = (key) => cfg()[key] !== false; // unset = shown
/* ── title-bar controls ─────────────────────────────────────────── */
const refreshBtn = moduleApi.header.addButton({
icon: REFRESH_SVG,
title: 'Re-read from Planning Center',
onClick() {
refreshBtn.classList.add('active');
moduleApi.fetch('/refresh', { method: 'POST' })
.catch(() => { /* the stream reports the outcome */ })
.finally(() => refreshBtn.classList.remove('active'));
},
});
/* ── helpers ────────────────────────────────────────────────────── */
function colorOf(value, fallback) {
const s = String(value || '').trim();
return /^#[0-9a-fA-F]{3,8}$/.test(s) ? s : fallback;
}
/**
* A team's colour when "Tint teams" is on. Taken from the team's position
* in the plan, not a hash of its name: neighbouring teams then always look
* different, which is the whole point of tinting them.
*/
function teamColor(index) {
if (!cfg().tintTeams) return colorOf(cfg().teamColor, '#2ee59a');
return `hsl(${TEAM_HUES[index % TEAM_HUES.length]} 70% 55%)`;
}
function statusColor(status) {
if (status === 'confirmed') return colorOf(cfg().confirmedColor, '#2ee59a');
if (status === 'declined') return colorOf(cfg().declinedColor, '#f4433c');
return colorOf(cfg().unconfirmedColor, '#f0b429');
}
const STATUS_LABEL = { confirmed: 'Confirmed', unconfirmed: 'Unconfirmed', declined: 'Declined' };
/** "Sarah Miles" → "SM"; one word → its first two letters. */
function initialsOf(name) {
const words = String(name || '').trim().split(/\s+/).filter(Boolean);
if (!words.length) return '?';
if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}
/** A saved multiselect list, or null when the tile has never chosen (= all). */
function chosen(key) {
const v = cfg()[key];
return Array.isArray(v) ? v : null;
}
/* ── which teams and people to show ─────────────────────────────── */
function visibleTeams() {
const teams = Array.isArray(state?.teams) ? state.teams : [];
const wantTeams = chosen('teams');
const out = [];
for (const team of teams) {
if (wantTeams && !wantTeams.includes(team.id)) continue;
const members = team.members.filter((m) => {
if (m.status === 'declined' && !on('showDeclined')) return false;
if (m.status === 'unconfirmed' && !on('showUnconfirmed')) return false;
return true;
});
if (!members.length && !cfg().showEmptyTeams) continue;
out.push({ ...team, members });
}
return out;
}
/* ── status dot ─────────────────────────────────────────────────── */
function renderStatus() {
if (feedOffline) return moduleApi.setStatus('error', 'ProdDash server unreachable — reconnecting…');
if (!state) return moduleApi.setStatus('connecting', 'Connecting…');
if (!state.configured) return moduleApi.setStatus('error', 'No Planning Center credentials — add them in Admin');
if (!state.serviceTypeSet) return moduleApi.setStatus('error', 'No service type selected — pick one in Admin');
if (!state.reachable) {
return moduleApi.setStatus(state.lastFetched ? 'error' : 'connecting', state.lastError || 'Reading the plan…');
}
if (state.teamsError) return moduleApi.setStatus('error', `Team list: ${state.teamsError}`);
const people = (state.teams || []).reduce((n, t) => n + t.members.length, 0);
moduleApi.setStatus('ok', `${people} scheduled · read ${new Date(state.lastFetched).toLocaleTimeString()}`);
}
/* ── top bar ────────────────────────────────────────────────────── */
/** The counts describe what this tile shows, not what the plan holds. */
function templateValues() {
const plan = state?.plan || {};
const teams = visibleTeams();
const people = teams.reduce((n, t) => n + t.members.length, 0);
const confirmed = teams.reduce((n, t) => n + t.counts.confirmed, 0);
return {
series: plan.seriesTitle || '',
part: plan.title || '',
servicetype: state?.serviceType?.name || '',
date: plan.dates || '',
shortdate: plan.shortDates || plan.dates || '',
time: plan.serviceStartsAt
? new Date(plan.serviceStartsAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })
: '',
people: people ? `${people} ${people === 1 ? 'person' : 'people'}` : '',
teams: teams.length ? `${teams.length} ${teams.length === 1 ? 'team' : 'teams'}` : '',
confirmed: confirmed ? `${confirmed} confirmed` : '',
};
}
/**
* "{serviceType} • {date} | {people} on {teams}" → up to two lines. Within
* a line • separates segments and a segment whose placeholders all came out
* empty is dropped, so a plan with no series never leaves a stray bullet.
*/
function renderTemplate(template, values) {
return String(template || DEFAULT_TEMPLATE).split('|').slice(0, 2).map((line) => {
const kept = [];
for (const seg of line.split(/\s*[•·]\s*/)) {
let sawVar = false;
let allEmpty = true;
const text = seg.replace(/\{([a-zA-Z]+)\}/g, (m, name) => {
sawVar = true;
const v = values[name.toLowerCase()];
if (v) allEmpty = false;
return v || '';
}).trim();
if (sawVar && allEmpty) continue;
if (text) kept.push(text);
}
return kept.join(' • ');
});
}
function renderHead() {
const show = on('showTopBar') && state?.plan;
headEl.hidden = !show;
if (!show) return;
const [line1, line2] = renderTemplate(cfg().headerTemplate, templateValues());
titleEl.textContent = line1 || line2 || state.serviceType?.name || 'Teams';
subEl.textContent = line1 ? line2 || '' : '';
subEl.hidden = !subEl.textContent;
}
/* ── the list ───────────────────────────────────────────────────── */
function emptyMessage() {
if (feedOffline && !state) return { title: 'Feed offline', hint: 'Not receiving updates from the ProdDash server.' };
if (!state) return { title: 'Connecting…', hint: '' };
if (!state.configured) {
return {
title: 'Planning Center not connected',
hint: 'Enter the Planning Center credentials under PCO Plan in Admin.',
link: { href: '/admin', text: 'Open Admin' },
};
}
if (!state.serviceTypeSet) {
return {
title: 'No service type selected',
hint: 'Pick the service type to follow under PCO Plan in Admin.',
link: { href: '/admin', text: 'Open Admin' },
};
}
if (!state.reachable && !state.plan) {
return { title: state.lastFetched ? 'Planning Center unavailable' : 'Reading the plan…', hint: state.lastError || '' };
}
if (!state.plan) {
return {
title: 'No plan found',
hint: `${state.serviceType?.name || 'This service type'} has no upcoming or recent plans.`,
};
}
if (!(state.teams || []).length) {
return {
title: 'Nobody scheduled yet',
hint: state.teamsError || 'This plan has no team members in Planning Center.',
};
}
if (!visibleTeams().length) {
return { title: 'Nothing to show', hint: 'Every team is hidden by this tile’s settings (gear menu).' };
}
return null;
}
function buildMember(member) {
const row = document.createElement('div');
row.className = `tm-person is-${member.status}`;
if (on('showAvatars')) {
const avatar = document.createElement('div');
avatar.className = 'tm-avatar';
avatar.textContent = initialsOf(member.name);
if (member.hasPhoto) {
const img = document.createElement('img');
img.loading = 'lazy';
img.alt = '';
img.src = `/api/modules/${moduleApi.id}/team-avatar/${encodeURIComponent(member.id)}`;
// No photo, or the CDN is unreachable: the initials underneath stand.
img.addEventListener('error', () => img.remove());
avatar.appendChild(img);
}
row.appendChild(avatar);
}
const main = document.createElement('div');
main.className = 'tm-person-main';
const nameEl = document.createElement('div');
nameEl.className = 'tm-name';
nameEl.textContent = member.name;
main.appendChild(nameEl);
if (on('showPosition') && member.position && !cfg().groupByPosition) {
const pos = document.createElement('div');
pos.className = 'tm-position';
pos.textContent = member.position;
main.appendChild(pos);
}
if (cfg().showNotes && (member.notes || member.declineReason)) {
const note = document.createElement('div');
note.className = 'tm-note';
note.textContent = member.declineReason ? `Declined: ${member.declineReason}` : member.notes;
main.appendChild(note);
}
row.appendChild(main);
if (on('showStatus')) {
const status = document.createElement('div');
status.className = 'tm-status';
status.style.setProperty('--tm-status', statusColor(member.status));
status.title = STATUS_LABEL[member.status] || member.status;
row.appendChild(status);
}
return row;
}
/** One team: its header band, then its people (optionally under position sub-headings). */
function buildTeam(team, index) {
const section = document.createElement('section');
section.className = 'tm-team';
section.style.setProperty('--tm-team', teamColor(index));
if (on('showTeamHeaders')) {
const header = document.createElement('div');
header.className = 'tm-team-head';
const name = document.createElement('span');
name.className = 'tm-team-name';
name.textContent = team.name;
header.appendChild(name);
if (on('showTeamCounts')) {
const counts = document.createElement('span');
counts.className = 'tm-team-count';
const pending = team.counts.unconfirmed;
counts.textContent = pending ? `${team.members.length} · ${pending} pending` : String(team.members.length);
header.appendChild(counts);
}
section.appendChild(header);
}
const columns = String(cfg().columns || 'auto');
const grouping = Boolean(cfg().groupByPosition) && on('showPosition');
// Grouped, the container is a plain block so each position heading spans
// the width and only its own people form a grid.
const list = document.createElement('div');
list.className = grouping ? 'tm-groups' : 'tm-people';
if (!grouping && columns !== 'auto') {
list.style.setProperty('--tm-cols', columns);
list.classList.add('is-fixed-cols');
}
if (grouping) {
// Positions keep the order the members already sort in.
const groups = new Map();
for (const m of team.members) {
const key = m.position || '(no position)';
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(m);
}
for (const [position, members] of groups) {
const label = document.createElement('div');
label.className = 'tm-position-head';
label.textContent = position;
list.appendChild(label);
const sub = document.createElement('div');
sub.className = 'tm-people is-sub';
if (columns !== 'auto') sub.style.setProperty('--tm-cols', columns);
sub.classList.toggle('is-fixed-cols', columns !== 'auto');
for (const m of members) sub.appendChild(buildMember(m));
list.appendChild(sub);
}
} else {
for (const m of team.members) list.appendChild(buildMember(m));
}
if (!team.members.length) {
const none = document.createElement('div');
none.className = 'tm-team-empty';
none.textContent = 'Nobody scheduled';
list.appendChild(none);
}
section.appendChild(list);
return section;
}
function renderBody() {
const empty = emptyMessage();
if (empty) {
lastKey = '';
bodyEl.innerHTML = '';
const box = document.createElement('div');
box.className = 'tm-empty';
const t = document.createElement('div');
t.className = 'tm-empty-title';
t.textContent = empty.title;
box.appendChild(t);
if (empty.hint) {
const h = document.createElement('div');
h.className = 'tm-empty-hint';
h.textContent = empty.hint;
box.appendChild(h);
}
if (empty.link) {
const a = document.createElement('a');
a.className = 'tm-empty-link';
a.href = empty.link.href;
a.target = '_blank';
a.rel = 'noopener';
a.textContent = empty.link.text;
box.appendChild(a);
}
bodyEl.appendChild(box);
return;
}
// Rebuild only when the roster or the settings actually changed: the
// avatars are <img>s and a needless rebuild makes them flicker.
const teams = visibleTeams();
const key = JSON.stringify([teams, cfg()]);
if (key === lastKey) return;
lastKey = key;
bodyEl.innerHTML = '';
teams.forEach((team, i) => bodyEl.appendChild(buildTeam(team, i)));
}
function render() {
wrap.classList.toggle('is-offline', feedOffline);
wrap.classList.toggle('tint-rows', Boolean(cfg().tintTeams && cfg().tintRows));
wrap.classList.toggle('header-gradient', on('headerGradient'));
renderStatus();
renderHead();
renderBody();
}
/* ── live feed ──────────────────────────────────────────────────── */
function accept(payload) {
if (!payload || typeof payload !== 'object' || !payload.state) return;
state = payload.state;
feedOffline = false;
render();
}
function connect() {
stream = moduleApi.sse('/stream', {
open() { feedOffline = false; render(); },
error() { feedOffline = true; render(); },
events: {
state(ev) {
try {
accept(JSON.parse(ev.data));
} catch { /* a bad frame is not fatal */ }
},
},
});
}
/* ── lifecycle ──────────────────────────────────────────────────── */
return {
start() {
moduleApi.setStatus('connecting', 'Connecting…');
moduleApi.fetch('/state')
.then((res) => (res.ok ? res.json() : null))
.then((body) => { if (body && !state) accept(body); })
.catch(() => { /* the stream will cover it */ });
connect();
render();
},
stop() {
stream?.close();
stream = null;
root.innerHTML = '';
},
onConfigChange() {
// Admin holds the connection only; the server re-inits and re-sends.
},
};
}
+2 -2
View File
@@ -1,7 +1,7 @@
{
"id": "prodcom-transcript",
"name": "ProdCom",
"version": "1.3.1",
"version": "1.3.2",
"proddash": ">=1.1.0",
"description": "Live ProdCom transcript",
"permissions": [
@@ -40,7 +40,7 @@
"instanceSchema": {
"showAvatars": {
"type": "boolean",
"label": "Show channel icons",
"label": "Channel icons",
"default": true
}
}
+39 -9
View File
@@ -6,6 +6,12 @@
in /admin; the tile only renders. */
export default function create({ root, moduleApi }) {
/* "now" is the live item on its own, filling the tile; "full" is that plus
the rest of the playlist. The picker presets `view`; a tile placed before
this module had a picker has neither, and gets the full card. */
const view = String(moduleApi.instanceSettings.view || moduleApi.variant || 'full');
const nowOnly = view === 'now';
let state = null;
let feedOffline = false;
let stream = null;
@@ -33,11 +39,13 @@ export default function create({ root, moduleApi }) {
</div>`;
const screenEl = root.querySelector('.nn-screen');
if (nowOnly) screenEl.classList.add('nn-only-now');
const topRow = root.querySelector('.nn-top');
const playlistNameEl = root.querySelector('.nn-playlist');
const liveEl = root.querySelector('.nn-live');
const liveTextEl = root.querySelector('.nn-live-text');
const nowEl = root.querySelector('.nn-now');
const nowLabelEl = root.querySelector('.nn-label');
const nowTitleBox = root.querySelector('.nn-title-box');
let nowTitleEl = root.querySelector('.nn-title');
const nowMetaEl = root.querySelector('.nn-meta');
@@ -47,9 +55,11 @@ export default function create({ root, moduleApi }) {
const nextListEl = root.querySelector('.nn-next-list');
const nextMoreEl = root.querySelector('.nn-next-more');
/** A setting, defaulting to on — a Now tile's schema omits the Next ones. */
function prefs() {
return moduleApi.instanceSettings; // showPlaylist / showProgress / cleanTitles
return moduleApi.instanceSettings;
}
const on = (key) => prefs()[key] !== false;
/* ── title tidying (same rule as propresenter-core.cleanItemName) ─ */
@@ -65,7 +75,7 @@ export default function create({ root, moduleApi }) {
}
function displayName(raw) {
return prefs().cleanTitles ? cleanItemName(raw) : String(raw || '').trim();
return on('cleanTitles') ? cleanItemName(raw) : String(raw || '').trim();
}
function itemTypeTag(type) {
@@ -307,7 +317,9 @@ export default function create({ root, moduleApi }) {
const total = state.currentSlideTotal || activeItem?.slideCount || 0;
const current = state.currentSlide || 0;
if (total > 0 && current > 0) {
if (!on('showSlideCount')) {
nowMetaEl.textContent = '';
} else if (total > 0 && current > 0) {
const remaining = Math.max(0, total - current);
nowMetaEl.textContent = `Slide ${current} / ${total} · ${remaining} left`;
} else if (total > 0) {
@@ -318,7 +330,7 @@ export default function create({ root, moduleApi }) {
nowMetaEl.textContent = '';
}
if (prefs().showProgress && total > 0) {
if (on('showProgress') && total > 0) {
progressEl.hidden = false;
const pct = current > 0 ? Math.max(0, Math.min(100, (current / total) * 100)) : 0;
progressFillEl.style.width = `${pct}%`;
@@ -349,6 +361,10 @@ export default function create({ root, moduleApi }) {
nameEl.textContent = displayName(item.name) || '(untitled)';
row.appendChild(nameEl);
if (!on('showTags')) {
nextListEl.appendChild(row);
continue;
}
if (item.type === 'presentation' && Number.isInteger(item.slideCount)) {
const chip = document.createElement('div');
chip.className = 'nn-count-chip';
@@ -366,7 +382,7 @@ export default function create({ root, moduleApi }) {
nextListEl.appendChild(row);
}
nextLabelEl.hidden = upcoming.length === 0;
nextLabelEl.hidden = upcoming.length === 0 || !on('showNextLabel');
nextMoreEl.hidden = true;
markNextOverflow();
requestAnimationFrame(markNextOverflow);
@@ -374,12 +390,22 @@ export default function create({ root, moduleApi }) {
function render() {
screenEl.classList.toggle('is-offline', feedOffline);
const showTop = prefs().showPlaylist || feedOffline || !state?.reachable || !state?.enabled;
topRow.classList.toggle('hidden-row', !showTop);
playlistNameEl.textContent = prefs().showPlaylist ? state?.playlistName || '' : '';
// Trouble always shows, whatever is switched off: a tile that has stopped
// updating must never look like one with nothing live.
const trouble = feedOffline || !state?.reachable || !state?.enabled;
const wantPlaylist = on('showPlaylist');
const wantLive = on('showLive') || trouble;
topRow.classList.toggle('hidden-row', !wantPlaylist && !wantLive);
liveEl.hidden = !wantLive;
// Hidden, not just emptied: it is flex:1, so an emptied one still holds
// the row open and pushes the live dot off the right edge.
playlistNameEl.hidden = !wantPlaylist;
playlistNameEl.textContent = state?.playlistName || '';
nowLabelEl.hidden = !on('showNowLabel');
screenEl.classList.toggle('nn-no-next', nowOnly || !on('showNext'));
renderLive();
renderNow();
renderNext();
if (!nowOnly && on('showNext')) renderNext();
}
/* ── sizing: --unit scales the whole card to the tile ───────────── */
@@ -387,6 +413,10 @@ export default function create({ root, moduleApi }) {
function applyUnit() {
const unit = Math.max(6.5, Math.min(20, root.clientHeight * 0.032));
screenEl.style.setProperty('--unit', unit.toFixed(2) + 'px');
// On a Now tile the top row floats over the gradient, so at the shortest
// sizes it would sit on the title. Below the height it needs, it goes —
// the header dot and the title itself still report trouble.
screenEl.classList.toggle('nn-tight', nowOnly && root.clientHeight < unit * 9);
}
/* ── live feed ──────────────────────────────────────────────────── */
+78 -10
View File
@@ -1,32 +1,100 @@
{
"id": "propresenter-now-next",
"name": "ProPresenter",
"version": "1.0.1",
"proddash": ">=1.1.0",
"version": "1.1.1",
"proddash": ">=1.5.0",
"description": "What is live in ProPresenter and what comes next",
"permissions": [
{ "kind": "local-network", "reason": "Reaching ProPresenter on this network" }
{
"kind": "local-network",
"reason": "Reaching ProPresenter on this network"
}
],
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": { "w": 3, "h": 3 },
"defaultSize": { "w": 4, "h": 5 },
"minSize": {
"w": 3,
"h": 3
},
"defaultSize": {
"w": 4,
"h": 5
},
"configSchema": {
"propresenter": {
"type": "endpoint",
"label": "ProPresenter",
"default": { "host": "", "port": 1025 }
"default": {
"host": "",
"port": 1025
}
},
"password": {
"type": "password",
"label": "API password (only if set in ProPresenter)",
"label": "Password",
"default": ""
}
},
"instanceSchema": {
"showPlaylist": { "type": "boolean", "label": "Show the playlist name", "default": true },
"showProgress": { "type": "boolean", "label": "Show the slide progress bar", "default": true },
"cleanTitles": { "type": "boolean", "label": "Tidy titles (hide [ Full ] tags and date codes)", "default": true }
"cleanTitles": {
"type": "switch",
"label": "Tidy titles",
"default": true
},
"showPlaylist": {
"type": "switch",
"label": "Playlist",
"default": true,
"group": "Show"
},
"showLive": {
"type": "switch",
"label": "Live status",
"default": true,
"group": "Show"
},
"showNowLabel": {
"type": "switch",
"label": "Now label",
"default": true,
"group": "Show"
},
"showSlideCount": {
"type": "switch",
"label": "Slide count",
"default": true,
"group": "Show"
},
"showProgress": {
"type": "switch",
"label": "Progress bar",
"default": true,
"group": "Show"
},
"showNext": {
"type": "switch",
"label": "Next list",
"default": true,
"group": "Show"
},
"showNextLabel": {
"type": "switch",
"label": "Next label",
"default": true,
"group": "Show"
},
"showTags": {
"type": "switch",
"label": "Item tags",
"default": true,
"group": "Show"
}
},
"instanceGroups": {
"Show": {
"collapsed": true,
"columns": 2
}
}
}
+37
View File
@@ -108,6 +108,43 @@ module.exports = {
};
},
/**
* Two ways to place this module. "Now / Next" is the full card — what is
* live, then the rest of the playlist. "Now" is the same live item alone,
* edge to edge with the gradient filling the tile: a wall display that says
* one thing. The Now entry offers only the settings it can act on, so its
* gear carries no Next switches.
*/
tiles() {
return [
{
id: 'full',
name: 'Now / Next',
description: 'What is live, and the rest of the playlist',
defaultSize: { w: 4, h: 5 },
minSize: { w: 3, h: 3 },
settings: { view: 'full' },
},
{
id: 'now',
name: 'Now',
description: 'Only what is live, filling the tile',
defaultSize: { w: 4, h: 2 },
minSize: { w: 2, h: 1 },
settings: { view: 'now' },
instanceSchema: {
cleanTitles: { type: 'switch', label: 'Tidy titles', default: true },
showPlaylist: { type: 'switch', label: 'Playlist', default: true, group: 'Show' },
showLive: { type: 'switch', label: 'Live status', default: true, group: 'Show' },
showNowLabel: { type: 'switch', label: 'Now label', default: true, group: 'Show' },
showSlideCount: { type: 'switch', label: 'Slide count', default: true, group: 'Show' },
showProgress: { type: 'switch', label: 'Progress bar', default: true, group: 'Show' },
},
instanceGroups: { Show: { collapsed: true, columns: 2 } },
},
];
},
routes() {
return {
'GET /state': (req, res) => {
+48
View File
@@ -21,6 +21,51 @@
justify-content: center;
}
/* NEXT switched off, or a Now tile: the list goes and the card takes the room. */
[data-module="propresenter-now-next"] .nn-screen.nn-no-next .nn-next-wrap { display: none; }
[data-module="propresenter-now-next"] .nn-screen.nn-no-next { justify-content: center; }
/* ── the "Now" tile ──
Only what is live, edge to edge: the gradient moves off the card and onto
the whole tile, the card loses its border, radius and box, and the title
sits in the middle of everything. Nothing is inset, so a wall of these
reads as panels of colour rather than cards on a background. */
[data-module="propresenter-now-next"] .nn-screen.nn-only-now {
gap: 0;
background: linear-gradient(
160deg,
color-mix(in srgb, var(--accent) 14%, transparent),
color-mix(in srgb, var(--bg) 70%, transparent)
);
}
[data-module="propresenter-now-next"] .nn-only-now .nn-now {
flex: 1;
height: auto;
min-height: 0;
justify-content: center;
border: none;
border-radius: 0;
background: none;
padding: 0;
}
/* The live dot and playlist ride over the gradient rather than above it. */
[data-module="propresenter-now-next"] .nn-only-now .nn-top {
position: absolute;
inset: var(--nn-pad) var(--nn-pad) auto;
pointer-events: none;
}
[data-module="propresenter-now-next"] .nn-only-now .nn-title-box { margin-top: 0; }
/* The overlay floats, so it takes no room — this keeps the title clear of it
and still centred, by holding back as much at the bottom as at the top. */
[data-module="propresenter-now-next"] .nn-only-now:not(.nn-tight) .nn-now {
padding: calc(var(--unit) * 1.4) 0;
}
/* Too short for the overlay: the title gets the whole panel to itself. */
[data-module="propresenter-now-next"] .nn-only-now.nn-tight .nn-top,
[data-module="propresenter-now-next"] .nn-only-now.nn-tight.is-offline .nn-top {
display: none !important;
}
/* ── top row ── */
[data-module="propresenter-now-next"] .nn-top {
@@ -59,6 +104,7 @@
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="propresenter-now-next"] .nn-playlist[hidden] { display: none; }
[data-module="propresenter-now-next"] .nn-live {
display: flex;
@@ -71,6 +117,7 @@
text-transform: uppercase;
color: var(--muted);
}
[data-module="propresenter-now-next"] .nn-live[hidden] { display: none; }
[data-module="propresenter-now-next"] .nn-live-dot {
width: calc(var(--unit) * 0.6);
@@ -122,6 +169,7 @@
text-transform: uppercase;
color: var(--accent);
}
[data-module="propresenter-now-next"] .nn-label[hidden] { display: none; }
[data-module="propresenter-now-next"] .nn-title-box {
flex: 1;
+48 -41
View File
@@ -15,7 +15,7 @@
Per-tile choices: the gear popover's static switches (whole sources,
headings, status lines, the clock's format, the state colours) and the
"Timers ▾" header menu, which hides any single timer — keyed `source:id`
timers header menu, which hides any single timer — keyed `source:id`
and saved with the layout via saveInstanceSettings. The header can be
hidden by the user, so the static switches stay the primary controls.
A solo tile's gear carries only the settings its one card can use (the
@@ -123,10 +123,13 @@ export function framesToTc(n, nominal, df) {
* elapsed ms otherwise, or null when the snapshot can't say. The values as
* of the snapshot (`elapsedMs` / `remainingMs`) are preferred and carried
* forward while running; `startedAt` is the fallback when they are absent.
* A timer measured at its own instant carries `asOf` (a phase-locked
* ProPresenter value — see the server's phase.js) which beats the source's
* snapshot time.
*/
export function valueAt(timer, sourceUpdatedAt, now) {
const running = timer.state === 'running';
const at = Number(sourceUpdatedAt) || now;
const at = Number(timer.asOf) || Number(sourceUpdatedAt) || now;
const dt = running ? Math.max(0, now - at) : 0;
const has = (v) => v !== null && v !== undefined && Number.isFinite(v);
if (timer.kind === 'countdown') {
@@ -196,6 +199,10 @@ function defaultStatus(timer, value, tone) {
/* ── the tile ─────────────────────────────────────────────────────────── */
/* The header menu's icon: a stopwatch, for the list of timers behind it.
Title-bar controls carry no words (module guide, rule 9). */
const TIMERS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 2h4"/><path d="M12 14V9"/><circle cx="12" cy="14" r="8"/></svg>';
export default function create({ root, moduleApi }) {
let state = null;
let feedOffline = false;
@@ -227,7 +234,7 @@ export default function create({ root, moduleApi }) {
}
/* Which picker entry this tile was added as (the module's tiles() list):
'' or 'all' = every timer, selectable via the Timers ▾ menu;
'' or 'all' = every timer, selectable via the timers menu;
'solo:<source>:<id>' = exactly one card, no menu, no headings. The
earlier entries 'timer:<uuid>' and 'ltc' map onto the new keys. */
const variant = String(moduleApi.variant || '');
@@ -235,8 +242,6 @@ export default function create({ root, moduleApi }) {
: variant.startsWith('timer:') ? `propresenter:${variant.slice('timer:'.length)}`
: variant.startsWith('solo:') ? variant.slice('solo:'.length)
: '';
/** Last label seen for a solo timer, so its card stays labeled if the timer is later deleted upstream. */
let lastSoloLabel = '';
/* ── DOM skeleton ───────────────────────────────────────────────── */
@@ -283,8 +288,8 @@ export default function create({ root, moduleApi }) {
let menuEl = null; // the open menu's element (filled on each open)
const itemsMenu = solo ? null : moduleApi.header.addMenu({
label: 'Timers ▾',
title: 'Choose timers',
icon: TIMERS_SVG,
title: 'Timers',
build(menu) {
// the shell hands over an emptied element on every open
menu.classList.add('tm-menu');
@@ -292,6 +297,12 @@ export default function create({ root, moduleApi }) {
rebuildMenu(true);
},
});
// The icon carries the name; a count rides alongside it while some timers
// are hidden, so the bar says "filtered" without saying it in words.
const itemsCountEl = document.createElement('span');
itemsCountEl.className = 'tm-count';
itemsCountEl.hidden = true;
if (itemsMenu) itemsMenu.button.appendChild(itemsCountEl);
function menuRows() {
const rows = [];
@@ -319,7 +330,9 @@ export default function create({ root, moduleApi }) {
if (!itemsMenu) return;
const rows = menuRows();
const visible = rows.filter((r) => !hidden.has(r.key)).length;
itemsMenu.setLabel(visible === rows.length ? 'Timers ▾' : `Timers (${visible}/${rows.length}) ▾`);
const filtering = visible !== rows.length;
itemsCountEl.textContent = filtering ? `${visible}/${rows.length}` : '';
itemsCountEl.hidden = !filtering;
}
let menuSignature = '';
@@ -364,22 +377,21 @@ export default function create({ root, moduleApi }) {
/* ── state → what this tile shows ───────────────────────────────── */
/** [{ id, source, items: [{ key, source, timer } | { key, missing }] }] */
/** [{ id, source, items: [{ key, source, timer }] }] */
function visibleGroups() {
if (!state) return [];
if (solo) {
for (const source of state.sources) {
for (const timer of source.timers) {
if (keyOf(source, timer) !== solo) continue;
lastSoloLabel = timer.label;
return [{ id: source.id, source, items: [{ key: solo, source, timer }] }];
}
}
// The timer this tile was added for isn't offered (yet, or any more) —
// keep a clearly-labeled card up rather than erroring.
const sourceId = solo.slice(0, solo.indexOf(':'));
const source = state.sources.find((s) => s.id === sourceId) || null;
return [{ id: 'missing', source, items: [{ key: solo, missing: true, source }] }];
// The timer this tile was added for is not offered right now. Nothing is
// drawn for it — no placeholder that reads like a timer, and never the
// full list in its place. The shell folds the tile away on its next
// registry refresh (module guide, Presenting multiple tiles).
return [];
}
const groups = [];
for (const source of state.sources) {
@@ -439,7 +451,7 @@ export default function create({ root, moduleApi }) {
/** The parts of a card that only change with the snapshot (label, kind). */
function updateCard(card, item) {
card.item = item;
card.isClock = !item.missing && item.source?.kind === 'clock';
card.isClock = item.source?.kind === 'clock';
const isLtc = item.source?.kind === 'ltc';
const badge = card.nameEl.querySelector('.tm-ltc-badge');
if (isLtc && !badge) {
@@ -450,29 +462,13 @@ export default function create({ root, moduleApi }) {
} else if (!isLtc && badge) {
badge.remove();
}
const label = item.missing ? (lastSoloLabel || 'Timer') : card.isClock ? '' : item.timer.label;
const label = card.isClock ? '' : item.timer.label;
if (card.labelEl.textContent !== label) {
setText(card.labelEl, label);
needFit = true; // the title's size follows its length
}
}
function updateMissingCard(card) {
const source = card.item.source;
setText(card.timeEl, '—');
card.chars = 5;
let note;
if (!source) note = 'Source not available — check Admin';
else if (source.status === 'ok') note = `Not offered by ${source.label}`;
else note = '—';
setText(card.statusEl, note);
card.statusEl.hidden = false;
card.statusEl.className = 'tm-status is-note';
card.statusEl.dataset.tone = source && source.status === 'ok' ? 'warn' : 'muted';
card.detailEl.hidden = true;
setCardClass(card, 'tm-card is-muted is-missing');
}
/* ── clocks ─────────────────────────────────────────────────────── */
function clockOptions() {
@@ -621,10 +617,6 @@ export default function create({ root, moduleApi }) {
let charsChanged = false;
for (const card of cards.values()) {
const { item } = card;
if (item.missing) {
updateMissingCard(card);
continue;
}
const { source, timer } = item;
let text;
let tone;
@@ -658,7 +650,21 @@ export default function create({ root, moduleApi }) {
statusTone = timer.status?.tone || 'muted';
}
} else {
const value = valueAt(timer, source.updatedAt, now);
let value = valueAt(timer, source.updatedAt, now);
// A running card must never tick backwards: an anchor correction or
// clock-offset wobble can re-place a second boundary by a few
// hundred ms, and a digit that regresses reads as broken. A small
// step against the direction of travel holds the shown value (time
// re-passes it within the jitter bound); a big one is a real
// reset/seek and snaps.
if (timer.state === 'running' && value !== null) {
const dir = timer.kind === 'countdown' ? -1 : 1;
const prev = card.mono;
if (prev && (value - prev) * dir < 0 && Math.abs(value - prev) < 1500) value = prev;
card.mono = value;
} else {
card.mono = null;
}
text = value === null ? '—' : fmtDuration(value, { ...digits, up: timer.kind === 'countdown' });
tone = toneFor(timer, value);
statusText = timer.status?.text || defaultStatus(timer, value, tone);
@@ -723,8 +729,9 @@ export default function create({ root, moduleApi }) {
moduleApi.setStatus('connecting', say(waiting));
return;
}
const n = groups.reduce((a, g) => a + g.items.filter((i) => !i.missing).length, 0);
moduleApi.setStatus('ok', `${n} timer${n === 1 ? '' : 's'} from ${shown.length} source${shown.length === 1 ? '' : 's'}`);
const n = groups.reduce((a, g) => a + g.items.length, 0);
if (solo && n === 0) moduleApi.setStatus('connecting', 'Not offered right now');
else moduleApi.setStatus('ok', `${n} timer${n === 1 ? '' : 's'} from ${shown.length} source${shown.length === 1 ? '' : 's'}`);
}
/* ── main render: diff groups and cards, update in place ────────── */
@@ -779,7 +786,7 @@ export default function create({ root, moduleApi }) {
let hint = '';
const groups = visibleGroups();
if (state && !state.sources.length) hint = 'Every source is switched off — turn one on in Admin.';
else if (state && !groups.length) hint = 'Nothing selected — switch a source on in this tile’s settings, or pick timers in the Timers ▾ menu.';
else if (state && !groups.length && !solo) hint = 'Nothing selected — switch a source on in this tile’s settings, or pick timers in the title bar’s timers menu.';
hintEl.hidden = !hint;
hintEl.textContent = hint;
groupsEl.hidden = Boolean(hint);
+3 -4
View File
@@ -1,7 +1,7 @@
{
"id": "propresenter-timers",
"name": "Timers",
"version": "1.3.0",
"version": "1.4.2",
"proddash": ">=1.4.0",
"description": "Timers, Clocks, and LTC From configured Modules",
"provides": [
@@ -112,7 +112,7 @@
},
"instanceGroups": {
"Show": {
"collapsed": false,
"collapsed": true,
"columns": 2
},
"Clock": {
@@ -121,8 +121,7 @@
},
"Colours": {
"collapsed": true,
"columns": 2,
"help": "The time's colour per state. Left at the default, a colour follows the dashboard theme; one you change here wins over it."
"columns": 2
}
},
"instanceSchema": {
+113
View File
@@ -0,0 +1,113 @@
'use strict';
/**
* Phase lock for whole-second timer reports (the ProPresenter poller).
*
* ProPresenter reports a running timer as whole seconds — trunc(value):
* "12:34" means the true remaining time is anywhere in [754 s, 755 s). The
* old poller re-anchored a tile's local count at the bottom of that interval
* on every poll, so the displayed digit ran up to a second ahead and then
* got yanked back a step whenever a fresh poll happened to sample the next
* flip later than the last one did — the poll clock and ProPresenter's
* second boundaries drift through each other, so tiles flickered
* "…12:33 → 12:34 → 12:33…" about once a second.
*
* This tracker turns the quantized reports into ONE stable anchor
* { valueMs, at } — the continuous value at a fixed instant — which the
* client extrapolates from. Rules:
*
* - The only real information in a poll is a FLIP: the report stepping one
* second in the direction of travel. At the flip instant the true value
* equals the interval boundary just crossed, and the flip happened between
* the last two polls, so their midpoint dates it to within half a poll.
* - While a poll's report matches what the anchor predicts (within TOL_MS
* around the reported second's interval), the anchor HOLDS — the same
* numbers are republished, so consumers count along one steady clock
* instead of a freshly re-phased one per sample.
* - A report the anchor can't explain re-anchors: at the flip boundary when
* this poll saw a clean one-second flip, else mid-interval (first sight,
* an operator reset/seek, a resume, or clock drift past TOL_MS).
* - Before the first flip the anchor sits mid-interval: at most ±½ s off,
* and the first flip (≤1 s away) locks it — instead of the old guaranteed
* whole-second bias one way.
*
* trunc() semantics also cover overrun: a countdown at −12.4 s reports
* "-12", so a negative countdown's interval is (W−1 s, W] and its flip
* boundary is W itself, where a positive countdown's are [W, W+1 s) and
* W+1 s. Around zero ("00:00:00" covers (−1 s, 1 s)) the flip in from above
* crosses +1 s.
*/
/** How far a report may sit outside the anchor's prediction before it means
something real. A flip is dated to the midpoint of two polls, so its own
error bound is ±½ poll (~±300 ms at the 500 ms cadence, more when a poll
runs long); the tolerance must sit ABOVE that or consecutive flips
re-anchor each other forever, and safely below a full second so a real
one-second seek still registers. */
const TOL_MS = 450;
/** The continuous-value interval implied by a whole-second report. */
function intervalFor(kind, wholeMs) {
if (kind === 'countdown') {
if (wholeMs === 0) return { lo: -1000, hi: 1000 };
if (wholeMs < 0) return { lo: wholeMs - 1000, hi: wholeMs };
}
return { lo: wholeMs, hi: wholeMs + 1000 };
}
/** The continuous value at the instant a running timer's report flips TO wholeMs. */
function boundaryFor(kind, wholeMs) {
if (kind === 'countdown') return wholeMs <= 0 ? intervalFor(kind, wholeMs).hi : wholeMs + 1000;
return wholeMs;
}
/**
* One tracker per timer. Feed one observation per poll; get back what to
* publish: `{ valueMs, asOf }` — a continuous value at a fixed instant,
* stable across polls while the reports stay consistent with it. Not
* running (or no value): the report is returned verbatim, dated at the poll.
*/
function createTimerPhase() {
let anchor = null; // { valueMs, at }
let kind = '';
let lastWhole = null;
let lastAt = 0;
let wasRunning = false;
function observe({ kind: rawKind, running, wholeMs, pollAt }) {
const k = rawKind === 'countdown' ? 'countdown' : 'elapsed';
const dir = k === 'countdown' ? -1 : 1;
const flip = Boolean(running) && wasRunning && k === kind && lastAt > 0
&& lastWhole !== null && wholeMs !== null
&& wholeMs - lastWhole === dir * 1000;
const prevAt = lastAt;
lastWhole = wholeMs;
lastAt = pollAt;
wasRunning = Boolean(running);
if (k !== kind) anchor = null;
kind = k;
if (!running || wholeMs === null) {
anchor = null;
return { valueMs: wholeMs, asOf: pollAt };
}
const { lo, hi } = intervalFor(k, wholeMs);
// A mid-interval anchor is provisional — a guess up to ±½ s off that the
// tolerance check may fail to catch for a long time (its error only
// shows at a poll landing more than TOL_MS past a flip). The first
// clean flip is strictly better evidence (±½ poll), so it always wins.
if (anchor && !(anchor.provisional && flip)) {
const predicted = anchor.valueMs + dir * (pollAt - anchor.at);
if (predicted >= lo - TOL_MS && predicted <= hi + TOL_MS) {
return { valueMs: anchor.valueMs, asOf: anchor.at };
}
}
anchor = flip
? { valueMs: boundaryFor(k, wholeMs), at: (prevAt + pollAt) / 2, provisional: false }
: { valueMs: (lo + hi) / 2, at: pollAt, provisional: true };
return { valueMs: anchor.valueMs, asOf: anchor.at };
}
return { observe };
}
module.exports = { createTimerPhase, TOL_MS };
@@ -0,0 +1,205 @@
'use strict';
/**
* Self-test for phase.js — the whole-second phase lock — plus the client's
* never-tick-backwards guard, driven by a simulated ProPresenter:
*
* node modules/propresenter-timers/phase.selftest.js
*
* The simulation runs a true continuous timer, reports it the way
* ProPresenter does (truncated whole seconds, sampled every ~500 ms with
* jitter), feeds the reports through createTimerPhase(), then renders the
* displayed value at 25 ms steps exactly the way client.js does (extrapolate
* from { valueMs, asOf }, clamp regressions under 1.5 s). Asserts:
*
* - the displayed digits NEVER step against the direction of travel
* (the reported bug: countdown tiles flicking back to the previous
* second about once a second),
* - each displayed second dwells ~1 s,
* - the published anchor stays within tolerance of the true value,
* - operator resets/seeks snap within a poll or two,
* - pause → resume re-locks,
* - a ProPresenter whose clock drifts against the server's stays locked.
*/
const { createTimerPhase, TOL_MS } = require('./phase');
let checks = 0;
let failures = 0;
function ok(name, cond, detail) {
checks += 1;
if (!cond) {
failures += 1;
console.error(`FAIL ${name}${detail ? ` — ${detail}` : ''}`);
}
}
/** Deterministic pseudo-random (so a failure reproduces). */
function makeRand(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 2 ** 32;
};
}
/** ProPresenter's report: whole seconds, truncated toward zero. */
const trunc = (ms) => Math.trunc(ms / 1000) * 1000;
/**
* Run one scenario. `trueValueAt(t)` is the continuous value (countdown
* remaining or elapsed) on the SERVER's clock; null = not reported (paused
* timers report a frozen value via `frozen`).
*/
function simulate({ name, kind, seed, durationMs, trueValueAt, runningAt = () => true, pollMs = 500, jitterMs = 120 }) {
const rand = makeRand(seed);
const phase = createTimerPhase();
const dir = kind === 'countdown' ? -1 : 1;
const polls = [];
for (let t = 0; t <= durationMs;) {
const running = runningAt(t);
const value = trueValueAt(t);
polls.push({ t, out: phase.observe({ kind, running, wholeMs: value === null ? null : trunc(value), pollAt: t }), running });
t += pollMs + Math.floor(rand() * jitterMs);
}
// Render like client.js: between polls, extrapolate from the latest
// anchor; clamp sub-1.5 s regressions while running.
const shown = []; // { t, sec, err }
let mono = null;
let p = 0;
for (let t = polls[0].t; t <= durationMs; t += 25) {
while (p + 1 < polls.length && polls[p + 1].t <= t) p += 1;
const { out, running } = polls[p];
if (!running || out.valueMs === null) {
mono = null;
continue;
}
let value = out.valueMs + dir * (t - out.asOf);
if (mono !== null && (value - mono) * dir < 0 && Math.abs(value - mono) < 1500) value = mono;
mono = value;
const truth = trueValueAt(t);
shown.push({ t, sec: Math.trunc(value / 1000), value, err: truth === null ? 0 : value - truth });
}
return { name, dir, shown };
}
/** Assertions shared by the steady scenarios. `allowOdd` admits dwell pairs
from legitimate corrections (absorbing clock drift re-places a boundary
by up to TOL_MS once in a while). */
function assertSteady({ name, dir, shown }, { settleMs = 1600, maxErr = 700, allowOdd = 0 } = {}) {
let regressions = 0;
let maxAbsErr = 0;
const changes = [];
for (let i = 1; i < shown.length; i += 1) {
const step = shown[i].sec - shown[i - 1].sec;
if (step !== 0 && Math.sign(step) !== dir) regressions += 1;
if (step !== 0) changes.push(shown[i].t);
if (shown[i].t - shown[0].t > settleMs) maxAbsErr = Math.max(maxAbsErr, Math.abs(shown[i].err));
}
// Whole dwells only (drop the partial first and trailing segments), after
// the lock settles — the first observed flip corrects the provisional
// mid-interval anchor once, stretching or squeezing a boundary in the
// timer's first moments, which no one can see on a wall. A countdown
// crossing zero legitimately shows "0" for ~2 s — trunc keeps the digit
// for the whole (−1 s, +1 s) span, like ProPresenter's own display — so
// allow one ~2 s dwell; everything else must be ~1 s.
const settled = shown.length ? shown[0].t + 2500 : 0;
const dwells = changes.slice(1).map((t, i) => t - changes[i]).filter((d, i) => changes[i + 1] > settled + d);
const near = (d, target) => Math.abs(d - target) <= 200;
const long = dwells.filter((d) => near(d, 2000)).length;
const bad = dwells.filter((d) => !near(d, 1000) && !near(d, 2000)).length;
ok(`${name}: no digit ever steps backwards`, regressions === 0, `${regressions} regressions`);
ok(`${name}: seconds dwell ~1 s (${dwells.length} sampled)`, dwells.length > 5 && bad <= allowOdd && long <= 1,
`${bad} odd dwells, ${long} ~2 s dwells [${dwells.join(',')}]`);
ok(`${name}: locked within ${maxErr} ms of the true value`, maxAbsErr <= maxErr, `max ${Math.round(maxAbsErr)} ms`);
}
/* 1. Plain countdown, many sub-second phases and poll seeds. */
for (let i = 0; i < 12; i += 1) {
const phase0 = (i * 83) % 1000;
const run = simulate({
name: `countdown q=${phase0}ms seed=${i}`,
kind: 'countdown',
seed: 1000 + i,
durationMs: 30000,
trueValueAt: (t) => 20000 + phase0 - t, // runs through zero into overrun
});
assertSteady(run);
}
/* 2. Elapsed timer (counts up). */
for (let i = 0; i < 6; i += 1) {
const run = simulate({
name: `elapsed seed=${i}`,
kind: 'elapsed',
seed: 2000 + i,
durationMs: 25000,
trueValueAt: (t) => 400 + i * 137 + t,
});
assertSteady(run);
}
/* 3. Operator reset mid-run: value jumps back up to full length. */
{
const run = simulate({
name: 'reset',
kind: 'countdown',
seed: 7,
durationMs: 24000,
trueValueAt: (t) => (t < 12000 ? 15000 - t : 60000 - (t - 12000)),
});
// After the reset the shown value must reach the new region within ~2 polls.
const after = run.shown.filter((s) => s.t >= 13400);
ok('reset: snaps to the new value', after.length && after.every((s) => Math.abs(s.err) <= 1300), after.length ? `err ${Math.round(Math.max(...after.map((s) => Math.abs(s.err))))} ms` : 'no samples');
// Before and after the jump, digits stay monotonic within each phase.
const pre = { ...run, shown: run.shown.filter((s) => s.t < 12000) };
assertSteady(pre, { maxErr: 700 });
}
/* 4. Pause, then resume: no stale-anchor explosion. */
{
const frozen = 8000;
const run = simulate({
name: 'pause/resume',
kind: 'countdown',
seed: 11,
durationMs: 26000,
trueValueAt: (t) => (t < 6000 ? 14000 - t : t < 14000 ? frozen : frozen - (t - 14000)),
runningAt: (t) => t < 6000 || t >= 14000,
});
const resumed = { ...run, shown: run.shown.filter((s) => s.t >= 14000) };
assertSteady(resumed);
}
/* 5. ProPresenter's clock drifts 0.2% against the server's: the anchor
re-locks over time instead of accumulating a visible error. */
{
const run = simulate({
name: 'clock drift',
kind: 'countdown',
seed: 13,
durationMs: 120000,
trueValueAt: (t) => 130000 - t * 1.002,
});
// Drift accumulates ~2 ms/s; every ~4 min the anchor re-places a boundary
// by up to TOL_MS to absorb it — a slightly long/short dwell pair, never
// a backwards step (the separate regression check still demands zero).
assertSteady(run, { maxErr: 700 + TOL_MS, allowOdd: 2 });
}
/* 6. Idle timers pass through untouched. */
{
const phase = createTimerPhase();
const a = phase.observe({ kind: 'countdown', running: false, wholeMs: 300000, pollAt: 1000 });
ok('idle passes through', a.valueMs === 300000 && a.asOf === 1000);
const b = phase.observe({ kind: 'countdown', running: false, wholeMs: null, pollAt: 1500 });
ok('missing value passes through', b.valueMs === null && b.asOf === 1500);
}
if (failures) {
console.error(`\n${failures} of ${checks} checks FAILED`);
process.exit(1);
}
console.log(`phase.selftest: all ${checks} checks passed`);
+30 -5
View File
@@ -82,6 +82,7 @@ const http = require('http');
const path = require('path');
const { spawn } = require('child_process');
const { createLtcListener } = require('./ltc-listener');
const { createTimerPhase } = require('./phase');
const manifest = require('./module.json');
/** This module's id — left out of provider discovery (we don't consume ourselves). */
@@ -209,6 +210,7 @@ function sanitizeTimer(t) {
label: String(t.label || id).slice(0, 120),
kind: KINDS.has(t.kind) ? t.kind : 'elapsed',
state: STATES.has(t.state) ? t.state : 'stopped',
asOf: numOrNull(t.asOf),
startedAt: numOrNull(t.startedAt),
elapsedMs: numOrNull(t.elapsedMs),
remainingMs: numOrNull(t.remainingMs),
@@ -250,6 +252,8 @@ function createProPresenterSource({ config, log }) {
let updatedAt = 0;
/** uuid → { name, index, type, allowsOverrun, targetMs, detail } from /v1/timers, in list order. */
let timerConfigs = new Map();
/** uuid → phase tracker: whole-second reports → one stable anchor (see phase.js). */
const phases = new Map();
function url(target) {
const built = new URL(`http://${host}:${port}${target}`);
@@ -325,9 +329,21 @@ function createProPresenterSource({ config, log }) {
const atStart = value === null || (kind === 'countdown' ? targetMs !== null && value === targetMs : value === 0);
state = atStart ? 'idle' : 'paused';
}
const elapsedMs = kind === 'elapsed' ? value : targetMs !== null && value !== null ? targetMs - value : null;
const remainingMs = kind === 'countdown' ? value : targetMs !== null && value !== null ? targetMs - value : null;
const startedAt = state === 'running' && elapsedMs !== null ? now - elapsedMs : null;
// ProPresenter reports whole (truncated) seconds. Re-anchoring the tiles'
// local count at the bottom of that second every poll made the digits run
// ahead and flick back a step about once a second — phase.js turns the
// reports into one stable anchor { valueMs, asOf } the tiles count from.
let phase = phases.get(uuid);
if (!phase) {
phase = createTimerPhase();
phases.set(uuid, phase);
}
const anchored = phase.observe({ kind, running: state === 'running', wholeMs: value, pollAt: now });
const v = anchored.valueMs;
const asOf = anchored.asOf;
const elapsedMs = kind === 'elapsed' ? v : targetMs !== null && v !== null ? targetMs - v : null;
const remainingMs = kind === 'countdown' ? v : targetMs !== null && v !== null ? targetMs - v : null;
const startedAt = state === 'running' && elapsedMs !== null ? asOf - elapsedMs : null;
const text = !live ? '—' : overrun ? 'Overrun' : rawState === 'running' ? 'Running' : rawState === 'complete' ? 'Complete' : 'Stopped';
const tone = overrun ? 'danger' : rawState === 'running' ? 'ok' : rawState === 'complete' ? 'warn' : 'muted';
return {
@@ -335,6 +351,7 @@ function createProPresenterSource({ config, log }) {
label: (live && live.name) || (cfg && cfg.name) || 'Timer',
kind,
state,
asOf,
startedAt,
elapsedMs,
remainingMs,
@@ -367,6 +384,9 @@ function createProPresenterSource({ config, log }) {
// Timers reported live but missing from the (possibly stale) config
// list still deserve a card — type unknown until the slow lane catches up.
for (const [uuid, now_] of live) out.push(toTimer(uuid, null, now_, now));
for (const uuid of phases.keys()) {
if (!out.some((t) => t.id === uuid)) phases.delete(uuid); // timer deleted in ProPresenter
}
return out;
}
@@ -992,12 +1012,17 @@ module.exports = {
for (const t of v.timers) {
const out = { ...t, id: `${v.id}:${t.id}`, group: v.label };
if (v.id === 'clock') out.status = { text: new Date(now).toISOString(), tone: 'ok' };
if (t.state === 'running' && v.updatedAt > 0) {
const dt = Math.max(0, now - v.updatedAt);
// A timer measured at its own instant (asOf — a phase-locked
// ProPresenter value) re-anchors from there; the rest from the
// source snapshot. Consumers see plain contract values as of `now`.
const at = Number(out.asOf) || v.updatedAt;
if (t.state === 'running' && at > 0) {
const dt = Math.max(0, now - at);
if (out.elapsedMs !== null && out.elapsedMs !== undefined) out.elapsedMs += dt;
if (out.remainingMs !== null && out.remainingMs !== undefined) out.remainingMs -= dt;
if (out.ltc && Number.isFinite(out.ltc.ageMs)) out.ltc = { ...out.ltc, ageMs: out.ltc.ageMs + dt };
}
delete out.asOf;
timers.push(out);
}
}
+9 -2
View File
@@ -295,7 +295,6 @@
}
/* A solo tile whose timer is no longer offered. */
[data-module="propresenter-timers"] .tm-card.is-missing { border-style: dashed; }
/* ── the LTC card: visually its own thing ── */
@@ -321,7 +320,7 @@
@keyframes tm-nosignal-blink { 50% { opacity: 0.35; } }
/* ── the "Timers ▾" menu (container styled/positioned by the shell) ── */
/* ── the timers menu (container styled/positioned by the shell) ── */
[data-module="propresenter-timers"] .tm-menu-item {
display: flex;
@@ -383,3 +382,11 @@
font-size: 12px;
white-space: nowrap;
}
/* the count beside the title-bar timers icon, while some are hidden */
[data-module="propresenter-timers"] .tm-count {
font-size: 10px;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
[data-module="propresenter-timers"] .tm-count[hidden] { display: none; }
+138
View File
@@ -0,0 +1,138 @@
/* Resi Cues — the tile.
*
* One number matters: how long until the next cue. It is drawn as large as the
* tile allows, with the cue's name above it, because on a wall the operator reads
* it from across the booth.
*
* The countdown ticks locally. The server sends the playhead with the instant it
* was true (`estMs` at `estAt`) and whether playback is running; this adds the
* elapsed time since. That is what keeps the digits moving every second while
* Resi itself only reports every few seconds, and it means a slow poll never
* shows as a stalled clock.
*/
const TICK_MS = 250; // redraw faster than a second so the digit turns on time
export default function create({ root, moduleApi }) {
let stream = null;
let ticker = null;
let state = null;
const settings = () => moduleApi.instanceSettings;
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function hms(ms) {
const total = Math.max(0, Math.round(ms / 1000));
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
const pad = (n) => String(n).padStart(2, '0');
return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
}
/** Where the playhead is right now, extrapolated from the last server word. */
function playheadMs() {
if (!state || state.estMs === null || state.estMs === undefined) return null;
return state.estMs + (state.playing ? Date.now() - state.estAt : 0);
}
function render() {
root.textContent = '';
const set = settings();
if (!state || state.status === 'error') {
const box = el('div', 'resi-empty');
box.append(el('div', 'resi-empty-line', (state && state.message) || 'Not connected'));
root.append(box);
return;
}
const here = playheadMs();
const wrap = el('div', 'resi-wrap');
if (state.next) {
if (set.showCueName !== false) wrap.append(el('div', 'resi-label', 'NEXT'));
if (set.showCueName !== false) wrap.append(el('div', 'resi-cue', state.next.name || 'Next cue'));
const remaining = here === null ? null : state.next.ms - here;
const count = el('div', 'resi-count', remaining === null ? '—' : hms(remaining));
if (remaining !== null && remaining <= 30000) count.classList.add('is-soon');
if (!state.playing) count.classList.add('is-held');
wrap.append(count);
} else {
wrap.append(el('div', 'resi-label', state.event ? 'NO CUES LEFT' : 'NOTHING PLAYING'));
wrap.append(el('div', 'resi-cue', state.event || state.decoder || ''));
}
const foot = el('div', 'resi-foot');
if (set.showPrevious !== false && state.prev) {
foot.append(el('span', 'resi-foot-item',
`after ${state.prev.name}${here === null ? '' : ` · ${hms(here - state.prev.ms)} ago`}`));
}
if (set.showPosition !== false && here !== null) {
foot.append(el('span', 'resi-foot-item', `playhead ${hms(here)}`));
}
if (!state.playing && state.estMs !== null) foot.append(el('span', 'resi-foot-item is-held', 'paused'));
if (foot.childElementCount) wrap.append(foot);
if (set.showCueList && state.cues && state.cues.length) {
const list = el('ul', 'resi-list');
for (const cue of state.cues) {
const row = el('li', 'resi-list-row');
if (here !== null && cue.ms <= here) row.classList.add('is-past');
if (state.next && cue.ms === state.next.ms) row.classList.add('is-next');
row.append(el('span', 'resi-list-name', cue.name));
row.append(el('span', 'resi-list-at', hms(cue.ms)));
list.append(row);
}
wrap.append(list);
}
root.append(wrap);
}
function applyStatus() {
if (!state) return moduleApi.setStatus('connecting', 'Waiting for the server');
if (state.status !== 'ok') return moduleApi.setStatus('error', state.message || 'Not connected');
if (!state.playing) return moduleApi.setStatus('connecting', `Playback stopped — ${state.decoder}`);
const cadence = state.cadenceMs ? ` · Resi updates every ${Math.round(state.cadenceMs / 1000)}s` : '';
return moduleApi.setStatus('ok', `${state.decoder}${cadence}`);
}
return {
start() {
moduleApi.setStatus('connecting', 'Connecting');
stream = moduleApi.sse('/stream', {
state: (data) => {
try {
state = JSON.parse(data);
} catch {
return;
}
applyStatus();
render();
},
error: () => moduleApi.setStatus('error', 'Lost the connection to ProdDash'),
});
ticker = setInterval(render, TICK_MS);
render();
},
stop() {
if (stream) stream.close();
if (ticker) clearInterval(ticker);
stream = null;
ticker = null;
root.textContent = '';
},
onConfigChange() {
render();
},
};
}
+91
View File
@@ -0,0 +1,91 @@
{
"id": "resi-cues",
"name": "Resi Cues",
"version": "1.0.0",
"proddash": ">=1.4.0",
"description": "Time until the next Resi cue point, on the board and as a timer",
"provides": ["timers"],
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": { "w": 2, "h": 1 },
"defaultSize": { "w": 4, "h": 3 },
"configGroups": {
"Resi account": {
"help": "The Resi Studio login the board reads with. Cue points and the decoder's playhead both come from Resi's cloud, so nothing is installed at the decoder. Worth using a dedicated low-privilege Resi user rather than a personal one."
},
"Decoder": {
"help": "Which decoder to follow. The list is read from the account once the login above is saved."
},
"Timing": {
"collapsed": true,
"help": "Resi refreshes a decoder's position only every few seconds, on an irregular cadence, and each reading is already slightly stale. The board estimates between readings rather than repeating them, so these only change how often it asks — not how accurate it is."
}
},
"configSchema": {
"username": {
"type": "string",
"label": "Resi login",
"group": "Resi account",
"default": "",
"help": "The email address used to sign in to studio.resi.io."
},
"password": {
"type": "password",
"label": "Password",
"group": "Resi account",
"default": ""
},
"player": {
"type": "select",
"label": "Decoder",
"group": "Decoder",
"default": "",
"optionsRoute": "/decoders",
"help": "Leave unset to follow the only decoder on the account."
},
"pollSeconds": {
"type": "number",
"label": "Position poll (s)",
"group": "Timing",
"default": 1,
"help": "How often Resi is asked where the playhead is. A faster poll notices a fired cue sooner; it does not make the countdown smoother, which is handled by estimating between readings."
},
"cueRefreshSeconds": {
"type": "number",
"label": "Cue list refresh (s)",
"group": "Timing",
"default": 5,
"help": "How often the cue list is re-read. It is also re-read immediately whenever the playhead jumps, so a cue fired at the host shows up without waiting for this."
},
"positionTrimMs": {
"type": "number",
"label": "Position trim (ms)",
"group": "Timing",
"default": 0,
"help": "Leave at zero. Only needed if the whole chain reads consistently behind; a positive value pushes the estimate forward."
}
},
"instanceSchema": {
"showCueName": {
"type": "switch",
"label": "Cue name",
"default": true
},
"showPrevious": {
"type": "switch",
"label": "Previous cue",
"default": true
},
"showPosition": {
"type": "switch",
"label": "Playhead",
"default": true
},
"showCueList": {
"type": "switch",
"label": "Cue list",
"default": false
}
}
}
+263
View File
@@ -0,0 +1,263 @@
/* Resi Cues — talking to Resi, and working out where the decoder actually is.
*
* Two things live here, both free of the shell so they can be tested on their own
* (`resi.test.js`): a thin client for the Resi Central API, and the playhead
* estimator that turns its coarse, late readings into a usable position.
*
* The API is the undocumented one behind studio.resi.io. It is not supported by
* Resi and can change without notice; that is the price of there being no public
* way to read cue points at all.
*/
'use strict';
const RESI = 'https://central.resi.io';
/* ── time ──────────────────────────────────────────────────────────────── */
/** '01:02:03.500' → milliseconds, or null when it is not a position at all. */
function positionToMs(position) {
if (typeof position !== 'string') return null;
const parts = position.split(':');
if (parts.length !== 3) return null;
const hh = Number(parts[0]);
const mm = Number(parts[1]);
const ss = Number(parts[2]);
if (!Number.isFinite(hh) || !Number.isFinite(mm) || !Number.isFinite(ss)) return null;
return Math.round((hh * 3600 + mm * 60 + ss) * 1000);
}
/** milliseconds → 'HH:MM:SS.mmm', the shape Resi's own cue positions use. */
function msToPosition(total) {
const t = Math.max(0, Math.floor(total));
const pad = (n, w) => String(n).padStart(w, '0');
return `${pad(Math.floor(t / 3600000), 2)}:${pad(Math.floor((t % 3600000) / 60000), 2)}`
+ `:${pad(Math.floor((t % 60000) / 1000), 2)}.${pad(t % 1000, 3)}`;
}
/* ── the playhead estimator ────────────────────────────────────────────── */
const WINDOW_MS = 120000; // how long a reading stays useful
const JUMP_FLOOR_MS = 5000; // the smallest move ever treated as a seek
/**
* Resi republishes a decoder's `position` only every few seconds, on an irregular
* cadence, and each reading is already a little stale when it appears. Shown raw,
* a countdown built on it sits seconds behind and moves in lurches.
*
* So every reading is kept as *media time minus wall time*. While playback runs at
* 1x that difference is constant, and the LARGEST recent value is the reading that
* reached us with the least delay — the one to trust. The estimate is then simply
* "now plus that offset", which advances smoothly by itself and cannot be dragged
* backwards by a slow round trip.
*
* `now` is injected so the tests can drive a fake clock.
*/
function createPlayhead(options) {
const opts = options || {};
const trimMs = Number(opts.trimMs) || 0;
const now = typeof opts.now === 'function' ? opts.now : () => Date.now();
let offsets = []; // { at, off } — off is mediaMs - wall time it was read
let spreads = []; // how far apart honest readings sit: this link's noise
let gaps = []; // how long between the playhead actually moving
let base; // the trusted offset
let lastMedia;
let lastNewAt;
let lastEst;
let seeked = false;
function note(mediaMs) {
if (!Number.isFinite(mediaMs)) return;
const t = now();
if (mediaMs !== lastMedia) {
const off = mediaMs - t;
// Anything inside the measured noise floor is noise; only a move clearly
// beyond it is a real seek. Measured rather than assumed, and remembered
// across a reset so the first reading after one is not judged blind.
const noise = spreads.length ? Math.max.apply(null, spreads) : 0;
const threshold = Math.max(JUMP_FLOOR_MS, noise * 1.5 + 4000);
if (base !== undefined) {
const delta = off - base;
if (Math.abs(delta) > threshold) {
offsets = []; // the window describes where we used to be
seeked = true;
// Only abandon the no-going-backwards guard for a move big enough that
// snapping is obviously right; a marginal call must not make the
// displayed playhead lurch backwards.
if (Math.abs(delta) > 10000) lastEst = undefined;
} else if (delta < 0) {
spreads = spreads.concat(-delta).slice(-20);
}
}
if (lastNewAt !== undefined) {
const gap = t - lastNewAt;
// The gap either side of a pause is not Resi's cadence — recording it
// would inflate the estimate and make the next pause slow to notice.
const worst = gaps.length ? Math.max.apply(null, gaps) : 0;
if (gap > 0 && gap < 60000 && (!worst || gap <= worst * 3)) {
gaps = gaps.concat(gap).slice(-8);
}
}
offsets = offsets.concat({ at: t, off });
lastMedia = mediaMs;
lastNewAt = t;
}
const kept = offsets.filter((o) => t - o.at <= WINDOW_MS);
// Always keep the newest reading even once it ages out. If the window empties
// during a long pause there is nothing left to compare against, and the resume
// reads as an ordinary reading instead of the discontinuity it is.
offsets = kept.length ? kept : offsets.slice(-1);
base = offsets.length ? offsets.reduce((m, o) => (o.off > m ? o.off : m), -Infinity) : undefined;
}
function read() {
if (lastNewAt === undefined) return { estMs: null, playing: false, cadenceMs: 0 };
const t = now();
const cadenceMs = gaps.length ? Math.max.apply(null, gaps) : 0;
// Only call it paused once the playhead has been still for clearly longer than
// Resi's own cadence. A fixed timeout mistakes a slow update for a stop, and a
// countdown that freezes mid-service is the worse failure of the two.
const pauseAfter = Math.max(15000, Math.min(45000, cadenceMs * 2.5 + 6000));
const playing = base !== undefined && t - lastNewAt < pauseAfter;
if (!playing) {
return { estMs: lastEst !== undefined ? lastEst : lastMedia, playing: false, cadenceMs };
}
let est = t + base + trimMs;
if (lastEst !== undefined && est < lastEst) est = lastEst; // the base is a max
lastEst = est;
return { estMs: est, playing: true, cadenceMs };
}
/** True once per detected discontinuity — the caller re-reads the cue list. */
function takeSeek() {
const was = seeked;
seeked = false;
return was;
}
return { note, read, takeSeek };
}
/* ── the Resi Central API ──────────────────────────────────────────────── */
/**
* Login sets a `livingas1` cookie which doubles as the bearer token, sent as
* `Authorization: X-Bearer <cookie>`. Everything else is a plain GET.
*/
function createResiClient(options) {
const opts = options || {};
const doFetch = opts.fetch || globalThis.fetch;
let cookieHeader = '';
let token = '';
let loggedInAt = 0;
let customerId = '';
let cacheBust = true;
function headers() {
const h = { Accept: 'application/json' };
if (cookieHeader) h.Cookie = cookieHeader;
if (token) h.Authorization = `X-Bearer ${token}`;
return h;
}
async function login() {
const res = await doFetch(`${RESI}/api/v3/login?newToken=true`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ userName: opts.username, password: opts.password }),
});
if (!res.ok) throw new Error(`Resi login failed (${res.status})`);
const setCookies = (res.headers.getSetCookie && res.headers.getSetCookie())
|| (res.headers.get('set-cookie') ? [res.headers.get('set-cookie')] : []);
const jar = {};
for (const raw of setCookies) {
const first = String(raw).split(';')[0];
const eq = first.indexOf('=');
if (eq > 0) jar[first.slice(0, eq)] = first.slice(eq + 1);
}
token = jar.livingas1 || '';
if (!token) throw new Error('Resi login returned no session cookie');
cookieHeader = Object.keys(jar).map((k) => `${k}=${jar[k]}`).join('; ');
loggedInAt = Date.now();
const me = await get('/api_v2.svc/users/me');
customerId = (me && me.customerId) || '';
if (!customerId) throw new Error('This Resi account has no customerId');
return me;
}
async function ensureSession() {
if (!token || Date.now() - loggedInAt > 50 * 60 * 1000) await login();
}
async function get(path) {
const res = await doFetch(RESI + path, { method: 'GET', headers: headers() });
if (res.status === 401 || res.status === 403) {
await login();
const retry = await doFetch(RESI + path, { method: 'GET', headers: headers() });
if (!retry.ok) throw new Error(`Resi ${path} failed (${retry.status})`);
return retry.json();
}
if (!res.ok) throw new Error(`Resi ${path} failed (${res.status})`);
return res.json();
}
async function venues() {
await ensureSession();
return (await get(`/api/v3/customers/${customerId}/venues`)) || [];
}
/** A stale cached reading looks exactly like a laggy playhead, so ask for a fresh
* one — and if the service objects to the parameter, stop sending it. */
async function players(venueUuid) {
await ensureSession();
const path = `/api_v2.svc/users/${venueUuid}/players`;
if (cacheBust) {
try {
return (await get(`${path}?_=${Date.now()}`)) || [];
} catch (err) {
if (!/\((4\d\d)\)/.test(String(err.message))) throw err;
cacheBust = false;
}
}
return (await get(path)) || [];
}
async function event(eventId) {
await ensureSession();
return get(`/api/v3/customers/${customerId}/events/${eventId}`);
}
async function cues(profileId, eventId) {
await ensureSession();
const raw = (await get(
`/api_v2.svc/streamprofiles/${profileId}/events/${eventId}/cues?canISetCues=1`)) || [];
return raw
.map((c) => ({ name: String(c.name || ''), ms: positionToMs(c.position) }))
.filter((c) => c.ms !== null)
.sort((a, b) => a.ms - b.ms);
}
return {
login,
ensureSession,
venues,
players,
event,
cues,
get customerId() { return customerId; },
};
}
/** The cue after `estMs`, and the one before it. */
function surroundingCues(cues, estMs) {
let prev = null;
let next = null;
for (const c of cues || []) {
if (c.ms > estMs) { next = c; break; }
prev = c;
}
return { prev, next };
}
module.exports = { positionToMs, msToPosition, createPlayhead, createResiClient, surroundingCues, RESI };
+210
View File
@@ -0,0 +1,210 @@
'use strict';
/**
* Unit tests for the Resi playhead estimator.
*
* node modules/resi-cues/resi.test.js
* node modules/resi-cues/resi.test.js 7000 1000 4000 2000 # one profile
*
* Plain Node, no dependencies; exits non-zero on the first failure.
*
* The estimator's whole job is to be right about a feed that is coarse, late and
* irregular, so the fixture is a simulated Resi rather than a list of values: a
* decoder playing at 1x, and an API that republishes its position every so often,
* already stale, over a round trip that varies. Nine profiles span what the real
* one has been seen to do. Feeding it a kind, punctual API proves nothing —
* against one, three separate breakages of this code go unnoticed.
*/
const assert = require('assert');
const { createPlayhead, surroundingCues, positionToMs, msToPosition } = require('./resi');
let passed = 0;
function test(name, fn) {
fn();
passed++;
console.log(` ok ${name}`);
}
/* ── the simulated world ───────────────────────────────────────────────── */
function makeWorld({ cadence, lag, jitter, net }) {
let seed = 12345;
const rnd = () => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed / 0x7fffffff;
};
const w = {
t: 1700000000000,
media: 8 * 60000 + 48000,
playing: true,
published: 0,
lastPublish: 0,
nextCadence: cadence,
};
w.published = w.media - lag;
w.lastPublish = w.t;
w.advance = (ms) => {
for (let i = 0; i < ms; i += 100) {
w.t += 100;
if (w.playing) w.media += 100;
if (w.t - w.lastPublish >= w.nextCadence) {
w.lastPublish = w.t;
w.published = w.media - lag;
w.nextCadence = Math.max(500, cadence + Math.round((rnd() - 0.5) * 2 * jitter));
}
}
};
// A poll reads what Resi had when the request left, and the round trip costs time.
w.poll = () => {
const body = w.published;
if (net) w.advance(100 + Math.round(rnd() * net));
return body;
};
return w;
}
const CUES = [
{ name: 'Welcome', ms: 5 * 60000 },
{ name: 'Campus Host', ms: 12 * 60000 + 30000 },
{ name: 'Message', ms: 41 * 60000 },
{ name: 'Closing', ms: 45 * 60000 },
];
function runProfile(cadence, lag, jitter, net) {
const w = makeWorld({ cadence, lag, jitter, net });
const head = createPlayhead({ now: () => w.t });
const tol = lag + 1200 + jitter + net * 0.35;
const label = `cadence ${cadence} lag ${lag} jitter ${jitter} net ${net}`;
const second = () => { w.advance(1000); head.note(w.poll()); return head.read(); };
const seconds = (n) => { let r; for (let i = 0; i < n; i++) r = second(); return r; };
test(`${label}: locks on, and beats the raw reading it is built from`, () => {
seconds(40);
let worstEst = 0;
let worstRaw = 0;
for (let i = 0; i < 30; i++) {
const { estMs } = second();
worstEst = Math.max(worstEst, w.media - estMs);
worstRaw = Math.max(worstRaw, w.media - w.published);
}
assert.ok(worstEst <= tol, `estimate drifted ${Math.round(worstEst)}ms (allowed ${Math.round(tol)})`);
if (cadence >= 2000) {
assert.ok(worstRaw >= cadence * 0.4,
`fixture is too kind: the raw value only went ${Math.round(worstRaw)}ms stale`);
}
assert.ok(head.read().playing, 'should read as playing');
});
test(`${label}: ticks every second and never runs backwards`, () => {
let prev = head.read().estMs;
let stalls = 0;
let backwards = 0;
for (let i = 0; i < 200; i++) {
const { estMs } = second();
if (estMs === prev) stalls++;
if (estMs < prev) backwards++;
prev = estMs;
}
assert.strictEqual(stalls, 0, 'the playhead stalled');
assert.strictEqual(backwards, 0, 'the playhead went backwards');
});
test(`${label}: follows a fired cue, and rolls over the one it passes`, () => {
w.media = 40 * 60000 + 50000; // decoder jumps; Resi says nothing yet
let reported = false;
for (let i = 0; i < 60 && !reported; i++) {
second();
reported = Math.abs((head.read().estMs || 0) - w.media) < 8000;
}
assert.ok(reported, 'the jump was never picked up');
assert.ok(head.takeSeek(), 'the jump was not flagged as a seek');
const { estMs } = head.read();
assert.ok(Math.abs(estMs - w.media) <= tol + cadence / 2,
`resynced ${Math.round(w.media - estMs)}ms off`);
assert.ok(w.media - estMs >= -400, 'overshot the new playhead');
assert.strictEqual(surroundingCues(CUES, estMs).next.name, 'Message');
const after = seconds(15);
assert.strictEqual(surroundingCues(CUES, after.estMs).next.name, 'Closing');
assert.strictEqual(surroundingCues(CUES, after.estMs).prev.name, 'Message');
});
test(`${label}: follows a seek backwards`, () => {
w.media = 6 * 60000;
for (let i = 0; i < 60 && Math.abs((head.read().estMs || 0) - w.media) > 8000; i++) second();
const { estMs } = head.read();
assert.ok(Math.abs(estMs - w.media) <= tol + cadence / 2, 'did not follow the seek back');
assert.strictEqual(surroundingCues(CUES, estMs).next.name, 'Campus Host');
});
test(`${label}: freezes on a real pause and re-locks on resume`, () => {
w.playing = false;
const stoppedAt = w.media;
const wait = Math.ceil((Math.max(15000, Math.min(45000, (cadence + jitter) * 2.5 + 6000))
+ cadence + jitter + 6000) / 1000);
let r = seconds(wait);
assert.strictEqual(r.playing, false, 'did not notice the pause');
const held = r.estMs;
r = seconds(20);
assert.strictEqual(r.estMs, held, 'kept counting while paused');
w.playing = true;
r = seconds(25);
assert.strictEqual(r.playing, true, 'did not notice the resume');
assert.ok(Math.abs(r.estMs - w.media) <= tol + cadence, 're-locked in the wrong place');
assert.ok(held - stoppedAt <= 45000 + cadence + jitter + 2 * net + 3000,
'the frozen position crept instead of stopping');
});
test(`${label}: survives a pause longer than the offset window`, () => {
w.playing = false;
let r = seconds(150);
assert.strictEqual(r.playing, false, 'should still read as paused');
assert.ok(r.estMs !== null && r.estMs !== undefined, 'lost the position entirely');
w.playing = true;
head.takeSeek();
r = seconds(30);
assert.strictEqual(r.playing, true, 'did not recover');
assert.ok(Math.abs(r.estMs - w.media) <= tol + cadence, 're-locked in the wrong place');
assert.ok(head.takeSeek(), 'a resume after a long pause must flag as a seek');
});
}
/* ── the plain bits ────────────────────────────────────────────────────── */
test('positionToMs reads Resi positions, and rejects anything else', () => {
assert.strictEqual(positionToMs('00:00:00.000'), 0);
assert.strictEqual(positionToMs('01:02:03.500'), 3723500);
assert.strictEqual(positionToMs('00:00:01'), 1000);
assert.strictEqual(positionToMs(''), null);
assert.strictEqual(positionToMs('garbage'), null);
assert.strictEqual(positionToMs(null), null);
assert.strictEqual(positionToMs(undefined), null);
});
test('msToPosition round-trips', () => {
for (const ms of [0, 1500, 3723500, 36000000]) {
assert.strictEqual(positionToMs(msToPosition(ms)), ms);
}
});
test('surroundingCues puts a cue you are exactly on behind you', () => {
assert.strictEqual(surroundingCues(CUES, 12 * 60000 + 30000).next.name, 'Message');
assert.strictEqual(surroundingCues(CUES, 12 * 60000 + 30000).prev.name, 'Campus Host');
assert.strictEqual(surroundingCues(CUES, 0).prev, null);
assert.strictEqual(surroundingCues(CUES, 60 * 60000).next, null);
assert.strictEqual(surroundingCues([], 1000).next, null);
});
/* ── the matrix ────────────────────────────────────────────────────────── */
const argv = process.argv.slice(2).map(Number);
const PROFILES = argv.length >= 4 ? [argv.slice(0, 4)] : [
[5000, 500, 0, 0], [5000, 500, 0, 2500], [2000, 0, 0, 800],
[10000, 3000, 0, 2500], [7000, 1000, 4000, 2000], [3000, 500, 2000, 1000],
[12000, 2000, 6000, 3000], [1000, 0, 0, 0], [8000, 1500, 3000, 4000],
];
for (const [cadence, lag, jitter, net] of PROFILES) runProfile(cadence, lag, jitter, net);
console.log(`\n${passed} tests passed`);
+356
View File
@@ -0,0 +1,356 @@
/* Resi Cues — server entry.
*
* Follows one Resi decoder and works out how long until its next cue point, then
* offers that two ways:
*
* GET /state → snapshot for this module's tile
* GET /stream → SSE, `state` events on every change
* GET /timers → snapshot for the Timers module (guide: "Offering
* GET /timers/stream → SSE, `timers` events timers to the Timers module")
* GET /decoders → optionsRoute for the admin page's decoder picker
*
* Both the cue list and the playhead come from Resi's cloud rather than the
* decoder: the decoder reports its position upstream and central.resi.io hands it
* back. Nothing is installed at the decoder end, and nothing here talks to the
* decoder directly.
*
* Why the playhead is estimated rather than repeated is explained in resi.js.
*/
'use strict';
const { createResiClient, createPlayhead, surroundingCues, positionToMs } = require('./resi');
const HEARTBEAT_MS = 15000;
function json(res, code, body) {
const text = JSON.stringify(body);
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(text);
}
function sseHead(res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
}
function writeAll(set, chunk) {
for (const res of set) {
try {
res.write(chunk);
} catch {
set.delete(res);
}
}
}
/** What the tile and the Timers module see before anything has been configured. */
function emptyState(message) {
return {
status: 'error',
message: message || 'Not configured',
decoder: '',
event: '',
playing: false,
estMs: null,
estAt: Date.now(),
cadenceMs: 0,
next: null,
prev: null,
cues: [],
};
}
function emptyTimers(now) {
return { source: 'resi-cues', label: 'Resi', updatedAt: now, timers: [] };
}
let current = null; // the live handle, shared with routes()
module.exports = {
init({ config, log }) {
const username = String(config.username || '').trim();
const password = String(config.password || '');
const wanted = String(config.player || '').trim();
const pollMs = Math.max(250, Number(config.pollSeconds || 1) * 1000);
const cueRefreshMs = Math.max(1000, Number(config.cueRefreshSeconds || 5) * 1000);
const stateStreams = new Set();
const timerStreams = new Set();
let state = emptyState(username && password ? 'Connecting' : 'Enter the Resi login in admin');
let timer = null;
let heartbeat = null;
let stopped = false;
const resi = createResiClient({ username, password });
const head = createPlayhead({ trimMs: Number(config.positionTrimMs || 0) });
let venueUuid = '';
let hardwareId = '';
let decoderName = '';
let eventId = '';
let profileId = '';
let eventName = '';
let cues = [];
let lastCueLoad = 0;
let inFlight = false;
/* — what the two consumers see — */
function publishState(next) {
const before = JSON.stringify(state);
state = next;
if (JSON.stringify(state) === before) return;
writeAll(stateStreams, `event: state\ndata: ${JSON.stringify(state)}\n\n`);
}
/**
* The Timers module extrapolates from `startedAt` and its own clock, so this
* only has to change when a timer changes *structurally* — a new cue, a pause,
* a seek. Broadcasting every poll would make every dashboard repaint at 1 Hz
* for nothing.
*/
function timersSignature(snap) {
return JSON.stringify(snap.timers.map(
(t) => [t.id, t.label, t.state, t.startedAt, t.targetMs, t.status && t.status.text]));
}
let lastTimerSig = '';
function publishTimers() {
const snap = timersSnapshot(Date.now());
const sig = timersSignature(snap);
if (sig === lastTimerSig) return;
lastTimerSig = sig;
writeAll(timerStreams, `event: timers\ndata: ${JSON.stringify(snap)}\n\n`);
}
function timersSnapshot(now) {
const timers = [];
if (state.estMs !== null && state.estMs !== undefined) {
const est = state.estMs + (state.playing ? now - state.estAt : 0);
if (state.next) {
const remainingMs = Math.max(0, state.next.ms - est);
// The countdown "runs" from the cue before it, which is what gives the
// consumer something to colour progress against.
const from = state.prev ? state.prev.ms : 0;
timers.push({
id: 'next-cue',
label: state.next.name || 'Next cue',
kind: 'countdown',
state: state.playing ? 'running' : 'paused',
startedAt: now - Math.max(0, est - from),
elapsedMs: null,
remainingMs,
targetMs: Math.max(1000, state.next.ms - from),
status: { text: state.next.name || 'Next cue', tone: state.playing ? 'ok' : 'warn' },
detail: state.event || '',
});
}
timers.push({
id: 'playhead',
label: 'Playhead',
kind: 'elapsed',
state: state.playing ? 'running' : 'paused',
startedAt: now - Math.max(0, est),
elapsedMs: Math.max(0, est),
remainingMs: null,
targetMs: null,
status: { text: state.decoder || '', tone: state.playing ? 'ok' : 'muted' },
detail: state.prev ? `After ${state.prev.name}` : '',
});
}
return { source: 'resi-cues', label: 'Resi', updatedAt: now, timers };
}
/* — finding the decoder — */
async function locate() {
const venues = await resi.venues();
for (const v of venues) {
const players = await resi.players(v.uuid);
for (const p of players) {
if (wanted ? p.playerHardwareId === wanted : true) {
venueUuid = v.uuid;
hardwareId = p.playerHardwareId;
decoderName = `${v.userName || v.name || 'Venue'} — ${p.userName || hardwareId}`;
return true;
}
}
}
return false;
}
/* — the loop — */
async function tick() {
if (inFlight || stopped) return;
inFlight = true;
try {
if (!hardwareId && !(await locate())) {
publishState(emptyState(wanted ? 'That decoder is not on this account' : 'No decoders found'));
return;
}
const players = await resi.players(venueUuid);
const me = players.find((p) => p.playerHardwareId === hardwareId);
if (!me) {
publishState({ ...emptyState('Decoder not listed'), decoder: decoderName });
return;
}
head.note(positionToMs(me.position));
if (me.eventId && me.eventId !== eventId) {
eventId = me.eventId;
const ev = (await resi.event(eventId)) || {};
profileId = ev.eventProfileId || '';
eventName = ev.name || '';
cues = profileId ? await resi.cues(profileId, eventId) : [];
lastCueLoad = Date.now();
log(`event ${eventName || eventId} — ${cues.length} cue(s)`);
} else if (!me.eventId) {
eventId = '';
profileId = '';
eventName = '';
cues = [];
}
const seeked = head.takeSeek();
if (profileId && eventId && (seeked || Date.now() - lastCueLoad >= cueRefreshMs)) {
lastCueLoad = Date.now();
const fresh = await resi.cues(profileId, eventId);
if (JSON.stringify(fresh) !== JSON.stringify(cues)) {
log(`cue list changed — ${fresh.length} cue(s)`);
cues = fresh;
}
}
const { estMs, playing, cadenceMs } = head.read();
const { prev, next } = surroundingCues(cues, estMs === null ? -1 : estMs);
publishState({
status: 'ok',
message: '',
decoder: decoderName,
event: eventName,
playing,
estMs,
estAt: Date.now(),
cadenceMs,
next,
prev,
cues,
});
} catch (err) {
const message = (err && err.message) || String(err);
log(`poll failed: ${message}`);
publishState({ ...state, status: 'error', message });
} finally {
inFlight = false;
publishTimers();
}
}
if (username && password) {
timer = setInterval(() => { void tick(); }, pollMs);
void tick();
} else {
log('no Resi login configured — idle');
}
heartbeat = setInterval(() => {
writeAll(stateStreams, ': ping\n\n');
writeAll(timerStreams, ': ping\n\n');
}, HEARTBEAT_MS);
current = {
get state() { return state; },
timersSnapshot,
stateStreams,
timerStreams,
resi,
configured: Boolean(username && password),
stop() {
stopped = true;
if (timer) clearInterval(timer);
if (heartbeat) clearInterval(heartbeat);
for (const res of [...stateStreams, ...timerStreams]) {
try { res.end(); } catch { /* already gone */ }
}
stateStreams.clear();
timerStreams.clear();
if (current && current.stop === this.stop) current = null;
},
health() {
if (!username || !password) return { status: 'error', message: 'Enter the Resi login in admin' };
if (state.status === 'ok') {
return { status: 'ok', message: state.playing ? `Playing — ${state.decoder}` : `Paused — ${state.decoder}` };
}
if (state.status === 'error') return { status: 'error', message: state.message };
return { status: 'connecting', message: state.message };
},
};
return current;
},
routes({ config, log }) {
return {
'GET /state': (req, res) => {
json(res, 200, current ? current.state : emptyState('Module restarting'));
},
'GET /stream': (req, res) => {
sseHead(res);
const snap = current ? current.state : emptyState('Module restarting');
res.write(`event: state\ndata: ${JSON.stringify(snap)}\n\n`);
if (!current) return res.end();
current.stateStreams.add(res);
req.on('close', () => current && current.stateStreams.delete(res));
},
'GET /timers': (req, res) => {
const now = Date.now();
json(res, 200, current ? current.timersSnapshot(now) : emptyTimers(now));
},
'GET /timers/stream': (req, res) => {
sseHead(res);
const now = Date.now();
const snap = current ? current.timersSnapshot(now) : emptyTimers(now);
res.write(`event: timers\ndata: ${JSON.stringify(snap)}\n\n`);
if (!current) return res.end();
current.timerStreams.add(res);
req.on('close', () => current && current.timerStreams.delete(res));
},
// The admin page's decoder picker. A live call, because it is how the decoder
// gets chosen in the first place — there is nothing cached to answer from.
'GET /decoders': async (req, res) => {
if (!config.username || !config.password) {
return json(res, 200, { options: [], note: 'Enter the Resi login first' });
}
try {
const client = createResiClient({
username: String(config.username), password: String(config.password),
});
const options = [];
for (const v of await client.venues()) {
for (const p of await client.players(v.uuid)) {
options.push({
value: p.playerHardwareId,
label: `${p.userName || p.playerHardwareId}`,
group: v.userName || v.name || 'Venue',
});
}
}
json(res, 200, { options });
} catch (err) {
log(`decoder list failed: ${(err && err.message) || err}`);
json(res, 502, { options: [], error: (err && err.message) || String(err) });
}
},
};
},
};
+201
View File
@@ -0,0 +1,201 @@
'use strict';
/**
* Server-entry tests for Resi Cues.
*
* node modules/resi-cues/server.test.js
*
* Plain Node, no dependencies; exits non-zero on the first failure. Resi is
* replaced with a canned account — a venue, a decoder on an event, four cue
* points — so this covers the parts `resi.test.js` cannot: signing in, finding
* the decoder, following the event, and the two snapshots other things read
* (`/state` for the tile, `/timers` for the Timers module).
*
* Nothing here reaches the network, and the poll interval is captured rather
* than run, so the test drives the loop a tick at a time.
*/
const assert = require('assert');
let passed = 0;
function test(name, fn) {
fn();
passed++;
console.log(` ok ${name}`);
}
/* ── a canned Resi account ─────────────────────────────────────────────── */
const CUES = [
{ name: 'Welcome', position: '00:05:00.000' },
{ name: 'Campus Host', position: '00:12:30.000' },
{ name: 'Message', position: '00:41:00.000' },
];
const world = { position: '00:08:48.000', eventId: 'EV1', logins: 0, playerCalls: 0 };
function reply(body, extra) {
return Object.assign({
ok: true,
status: 200,
headers: { get: () => null, getSetCookie: () => [] },
json: async () => body,
}, extra || {});
}
globalThis.fetch = async (url) => {
const path = String(url).replace('https://central.resi.io', '').split('?')[0];
if (path === '/api/v3/login') {
world.logins++;
return reply({}, { headers: { get: () => null, getSetCookie: () => ['livingas1=TOKEN; Path=/'] } });
}
if (path === '/api_v2.svc/users/me') return reply({ customerId: 'CUST', userName: 'tester' });
if (path === '/api/v3/customers/CUST/venues') return reply([{ uuid: 'V1', userName: 'Main' }]);
if (path === '/api_v2.svc/users/V1/players') {
world.playerCalls++;
return reply([{ playerHardwareId: 'DEC1', userName: 'Lobby', position: world.position, eventId: world.eventId }]);
}
if (path === '/api/v3/customers/CUST/events/EV1') {
return reply({ name: 'Sunday 9am', eventProfileId: 'P1' });
}
if (path === '/api_v2.svc/streamprofiles/P1/events/EV1/cues') return reply(CUES);
return reply({}, { ok: false, status: 404 });
};
/* ── the shell, as much of it as the module touches ────────────────────── */
const realSetInterval = globalThis.setInterval;
const realClearInterval = globalThis.clearInterval;
let tickFn = null;
globalThis.setInterval = (fn, ms) => {
if (!tickFn) tickFn = fn; // the poll; the heartbeat is the second one
return { fn, ms };
};
globalThis.clearInterval = () => {};
const server = require('./server');
const logged = [];
const handle = server.init({
config: { username: 'a@b.c', password: 'secret', player: 'DEC1', pollSeconds: 1, cueRefreshSeconds: 5 },
log: (m) => logged.push(m),
});
/** Let the poll's promise chain finish; nothing here waits on real time. */
async function settle() {
for (let i = 0; i < 60; i++) await Promise.resolve();
}
function collect(route, req) {
const res = {
code: 0, headers: null, body: '',
writeHead(code, headers) { this.code = code; this.headers = headers; },
write(chunk) { this.body += chunk; },
end(chunk) { if (chunk) this.body += chunk; },
};
route(req || { on() {} }, res);
return res;
}
(async () => {
await settle();
const routes = server.routes({ config: {}, log: (m) => logged.push(m) });
test('signs in once and finds the configured decoder', () => {
assert.strictEqual(world.logins, 1, 'should sign in exactly once');
const state = handle.state;
assert.strictEqual(state.status, 'ok', state.message);
assert.strictEqual(state.decoder, 'Main — Lobby');
assert.strictEqual(state.event, 'Sunday 9am');
assert.strictEqual(state.cues.length, 3);
});
test('works out the cue either side of the playhead', () => {
const state = handle.state;
assert.strictEqual(state.next.name, 'Campus Host');
assert.strictEqual(state.prev.name, 'Welcome');
assert.ok(Math.abs(state.estMs - 528000) < 2000, `playhead was ${state.estMs}`);
});
test('/state answers the same snapshot as the stream', () => {
const res = collect(routes['GET /state']);
assert.strictEqual(res.code, 200);
assert.deepStrictEqual(JSON.parse(res.body), handle.state);
});
test('/stream opens with an event so a new tile paints at once', () => {
const res = collect(routes['GET /stream']);
assert.strictEqual(res.code, 200);
assert.strictEqual(res.headers['Content-Type'], 'text/event-stream; charset=utf-8');
assert.ok(res.body.includes('retry: 3000'), 'should set a retry');
assert.ok(res.body.includes('event: state'), 'should send an initial state event');
});
test('/timers offers the countdown and the playhead, shaped as the guide says', () => {
const snap = JSON.parse(collect(routes['GET /timers']).body);
assert.strictEqual(snap.source, 'resi-cues');
assert.strictEqual(snap.label, 'Resi');
assert.ok(snap.updatedAt > 0);
const [next, playhead] = snap.timers;
assert.strictEqual(next.id, 'next-cue');
assert.strictEqual(next.kind, 'countdown');
assert.strictEqual(next.state, 'running');
assert.strictEqual(next.label, 'Campus Host');
assert.ok(Math.abs(next.remainingMs - 222000) < 2000, `remaining was ${next.remainingMs}`);
// the countdown runs from the cue before it, so a consumer can colour progress
assert.strictEqual(next.targetMs, 450000);
assert.strictEqual(next.status.text, 'Campus Host');
assert.ok(next.startedAt <= snap.updatedAt, 'startedAt must be in the past');
assert.strictEqual(playhead.id, 'playhead');
assert.strictEqual(playhead.kind, 'elapsed');
assert.strictEqual(playhead.remainingMs, null);
assert.ok(Math.abs(playhead.elapsedMs - 528000) < 2000);
});
test('a cue fired at the host moves the countdown on the next poll', async () => {
world.position = '00:12:40.000'; // jumped past Campus Host
tickFn();
await settle();
const state = handle.state;
assert.strictEqual(state.next.name, 'Message');
assert.strictEqual(state.prev.name, 'Campus Host');
const snap = JSON.parse(collect(routes['GET /timers']).body);
assert.strictEqual(snap.timers[0].label, 'Message');
});
test('a decoder with no event reports nothing playing rather than stale cues', async () => {
world.eventId = '';
tickFn();
await settle();
assert.strictEqual(handle.state.next, null);
assert.deepStrictEqual(handle.state.cues, []);
assert.strictEqual(handle.state.event, '');
});
test('health speaks about the upstream, not about itself', () => {
const h = handle.health();
assert.ok(['ok', 'connecting', 'error'].includes(h.status), h.status);
assert.ok(h.message.length > 0, 'health should say something useful');
});
test('an unconfigured module idles instead of hammering Resi', () => {
const before = world.logins;
const idle = server.init({ config: {}, log: () => {} });
assert.strictEqual(world.logins, before, 'must not sign in with no credentials');
assert.strictEqual(idle.health().status, 'error');
assert.ok(/login/i.test(idle.health().message), idle.health().message);
idle.stop();
});
test('stop() leaves nothing running', () => {
handle.stop();
const res = collect(routes['GET /state']);
assert.strictEqual(JSON.parse(res.body).status, 'error');
});
globalThis.setInterval = realSetInterval;
globalThis.clearInterval = realClearInterval;
console.log(`\n${passed} tests passed`);
})();
+113
View File
@@ -0,0 +1,113 @@
/* Resi Cues — scoped under its tile via [data-module="resi-cues"], styled with
the shell's CSS variables only.
The countdown is sized in cqmin so it fills whatever the tile is given: the
same module is a small strip on a busy dashboard and a wall panel on its own. */
[data-module="resi-cues"] {
container-type: size;
}
[data-module="resi-cues"] .resi-wrap {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.35em;
padding: 2%;
text-align: center;
overflow: hidden;
}
[data-module="resi-cues"] .resi-label {
color: var(--muted);
font-size: clamp(0.6rem, 5cqmin, 1rem);
font-weight: 700;
letter-spacing: 0.14em;
line-height: 1;
}
[data-module="resi-cues"] .resi-cue {
color: var(--text);
font-size: clamp(0.85rem, 11cqmin, 2.6rem);
font-weight: 650;
line-height: 1.05;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="resi-cues"] .resi-count {
color: var(--accent);
font-size: clamp(1.4rem, 30cqmin, 9rem);
font-weight: 700;
font-variant-numeric: tabular-nums;
letter-spacing: 0.01em;
line-height: 1;
}
[data-module="resi-cues"] .resi-count.is-soon { color: var(--warn); }
/* Held rather than counting: the digits are still true, they just are not moving. */
[data-module="resi-cues"] .resi-count.is-held,
[data-module="resi-cues"] .resi-foot-item.is-held {
color: var(--muted);
}
[data-module="resi-cues"] .resi-foot {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 0.2em 0.9em;
color: var(--muted);
font-size: clamp(0.6rem, 5cqmin, 0.95rem);
font-variant-numeric: tabular-nums;
}
[data-module="resi-cues"] .resi-list {
list-style: none;
margin: 0.4em 0 0;
padding: 0.4em 0 0;
width: 100%;
max-width: 28em;
border-top: 1px solid var(--border);
overflow-y: auto;
font-size: clamp(0.6rem, 4.5cqmin, 0.95rem);
}
[data-module="resi-cues"] .resi-list-row {
display: flex;
justify-content: space-between;
gap: 1em;
padding: 0.12em 0.2em;
color: var(--text);
}
[data-module="resi-cues"] .resi-list-row.is-past { color: var(--muted); }
[data-module="resi-cues"] .resi-list-row.is-next {
color: var(--accent);
font-weight: 650;
}
[data-module="resi-cues"] .resi-list-at { font-variant-numeric: tabular-nums; }
[data-module="resi-cues"] .resi-list-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="resi-cues"] .resi-empty {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 6%;
color: var(--muted);
text-align: center;
}
+471
View File
@@ -0,0 +1,471 @@
/* Service Times — the board.
*
* One card per campus, one row per service, and a mark on any service that
* production has to treat differently this week. Everything is drawn from the
* server's SSE state so every booth sees the same marks at the same moment;
* nothing here talks to the website.
*
* Marking lives in the tile body, not the title bar, because the bar folds
* away in fullscreen and on an auto-hiding dashboard — a control an operator
* needs mid-service may not disappear with it.
*/
const STATUSES = [
{ value: 'ok', label: 'Clear', short: '' },
{ value: 'issue', label: 'Issue', short: 'Issue' },
{ value: 'replay', label: 'Replay', short: 'Replay' },
{ value: 'skip', label: 'Do not use', short: 'Do not use' },
];
const ICON_REFRESH = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">'
+ '<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>'
+ '<path d="M13.6 1.9v3.2h-3.2" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const ICON_CLEAR = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">'
+ '<path d="M3 4h10M6.5 4V2.8h3V4M4.4 4l.7 8.4a1 1 0 0 0 1 .9h3.8a1 1 0 0 0 1-.9L11.6 4"'
+ ' fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
const ICON_SMALLER = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">'
+ '<path d="M3.5 8h9" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
const ICON_BIGGER = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">'
+ '<path d="M3.5 8h9M8 3.5v9" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
const TEXT_MIN = 0.8;
const TEXT_MAX = 1.8;
const TEXT_STEP = 0.1;
export default function create({ root, moduleApi }) {
let stream = null;
let state = null;
let editing = null; // { campus, service } while the editor is open
let pendingRender = false; // a state arrived while the editor was open
let board = null;
let closeEditor = null;
const settings = () => moduleApi.instanceSettings;
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text != null) node.textContent = text;
return node;
}
/** The campuses this tile is asked to show; no choice made means all of them. */
function visibleCampuses() {
const all = state?.campuses || [];
const chosen = settings().campuses;
if (!Array.isArray(chosen) || !chosen.length) return all;
return all.filter((campus) => chosen.includes(campus.slug));
}
function textScale() {
const saved = Number(settings().textSize);
return Number.isFinite(saved) ? Math.min(TEXT_MAX, Math.max(TEXT_MIN, saved)) : 1;
}
function serviceLabel(service) {
return service.label ? `${service.label} ${service.text}` : service.text;
}
/** Every service of the campus a resi campus takes its feed from. */
function sourceServices(campus) {
if (!campus.source) return [];
const origin = (state?.campuses || []).find((c) => c.slug === campus.source);
return origin ? origin.services : [];
}
/** The mark on the origin service a resi service is taking, if any. */
function upstreamTrouble(campus, service) {
const sourceId = service.mark?.source;
if (!sourceId || !campus.source) return null;
const origin = (state?.campuses || []).find((c) => c.slug === campus.source);
const upstream = origin?.services.find((s) => s.id === sourceId);
if (!upstream?.mark || upstream.mark.status === 'ok') return null;
return { origin, upstream };
}
/** Resi services pointed at this broadcast service. */
function dependentsOf(campus, service) {
if (campus.role !== 'broadcast') return [];
const out = [];
for (const other of state?.campuses || []) {
if (other.source !== campus.slug) continue;
for (const theirs of other.services) {
if (theirs.mark?.source === service.id) out.push({ campus: other, service: theirs });
}
}
return out;
}
/* ── drawing ──────────────────────────────────────────────────────── */
function renderServiceRow(campus, service) {
const opts = settings();
const row = el('button', 'st-row');
row.type = 'button';
const status = service.mark?.status || 'ok';
if (status !== 'ok') row.classList.add(`st-${status}`);
const time = el('span', 'st-time', serviceLabel(service));
row.appendChild(time);
if (opts.showDay && service.day) row.appendChild(el('span', 'st-day', service.day));
const chips = el('span', 'st-chips');
const statusDef = STATUSES.find((s) => s.value === status);
if (statusDef?.short) chips.appendChild(el('span', `st-chip st-chip-${status}`, statusDef.short));
// A resi service says which of the origin's services it is taking…
if (opts.showSource && campus.role === 'resi' && service.mark?.source) {
const origin = (state?.campuses || []).find((c) => c.slug === campus.source);
const upstream = origin?.services.find((s) => s.id === service.mark.source);
if (upstream) chips.appendChild(el('span', 'st-chip st-chip-source', `← ${upstream.text}`));
}
// …and turns red when that service is the one in trouble.
const trouble = upstreamTrouble(campus, service);
if (trouble) {
row.classList.add('st-affected');
const what = STATUSES.find((s) => s.value === trouble.upstream.mark.status)?.short || 'marked';
chips.appendChild(el('span', 'st-chip st-chip-skip', `source ${what.toLowerCase()}`));
}
// A broadcast service says who is riding on it.
if (opts.showDependents && campus.role === 'broadcast') {
const riders = dependentsOf(campus, service);
if (riders.length && status !== 'ok') {
chips.appendChild(el('span', 'st-chip st-chip-warn',
`affects ${riders.map((r) => r.campus.name).join(', ')}`));
} else if (riders.length) {
chips.appendChild(el('span', 'st-chip st-chip-quiet', `→ ${riders.length}`));
}
}
row.appendChild(chips);
if (opts.showNotes && service.mark?.note) {
row.appendChild(el('span', 'st-note', service.mark.note));
}
row.addEventListener('click', (event) => {
event.stopPropagation();
openEditor(campus, service, row);
});
return row;
}
function renderCampus(campus) {
const opts = settings();
const card = el('section', 'st-campus');
if (campus.role === 'broadcast') card.classList.add('st-is-broadcast');
const head = el('header', 'st-campus-head');
head.appendChild(el('h3', 'st-campus-name', campus.name));
if (opts.showRole) {
if (campus.role === 'broadcast') {
head.appendChild(el('span', 'st-role st-role-broadcast', 'Broadcast'));
} else if (campus.source) {
head.appendChild(el('span', 'st-role', campus.sourceMissing
? `resi ← ${campus.sourceName} (not listed)`
: `resi ← ${campus.sourceName}`));
} else {
head.appendChild(el('span', 'st-role st-role-unset', 'no resi source'));
}
}
if (campus.manual) head.appendChild(el('span', 'st-role st-role-manual', 'manual'));
card.appendChild(head);
if (opts.showDependents && campus.role === 'broadcast' && campus.dependents?.length) {
card.appendChild(el('p', 'st-feeds', `feeds ${campus.dependents.map((d) => d.name).join(', ')}`));
}
if (!campus.services.length) {
card.appendChild(el('p', 'st-empty', campus.error || 'No times published'));
return card;
}
const list = el('div', 'st-rows');
for (const service of campus.services) list.appendChild(renderServiceRow(campus, service));
card.appendChild(list);
return card;
}
function render() {
if (closeEditor) closeEditor();
root.innerHTML = '';
board = el('div', 'st-board');
board.style.fontSize = `${textScale()}em`;
root.appendChild(board);
if (!state) {
board.appendChild(el('p', 'st-empty', 'Waiting for the server…'));
return;
}
if (!state.configured) {
board.appendChild(el('p', 'st-empty', 'No website address configured — set one in Admin.'));
return;
}
const campuses = visibleCampuses();
if (!campuses.length) {
board.appendChild(el('p', 'st-empty', state.reachable
? 'No campuses to show. Pick some in Admin, or in this tile’s settings.'
: 'No service times yet.'));
} else {
const grid = el('div', settings().layout === 'list' ? 'st-grid st-grid-list' : 'st-grid');
for (const campus of campuses) grid.appendChild(renderCampus(campus));
board.appendChild(grid);
}
if (!state.reachable && state.lastError) {
board.appendChild(el('p', 'st-warn', `Website unreachable — ${state.lastError}. Showing the last times read.`));
}
if (settings().showUpdated && state.lastFetched) {
board.appendChild(el('p', 'st-updated',
`Times read ${new Date(state.lastFetched).toLocaleString([], { hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' })}`));
}
}
/* ── the mark editor ──────────────────────────────────────────────── */
function openEditor(campus, service, anchor) {
if (closeEditor) closeEditor();
editing = { campus: campus.slug, service: service.id };
const panel = el('div', 'st-editor');
panel.appendChild(el('div', 'st-editor-title', `${campus.name} — ${serviceLabel(service)}`));
const mark = service.mark || { status: 'ok', note: '', source: '' };
let status = mark.status || 'ok';
const row = el('div', 'st-editor-status');
const buttons = new Map();
for (const def of STATUSES) {
const button = el('button', 'st-pick', def.label);
button.type = 'button';
if (def.value === status) button.classList.add('active');
button.addEventListener('click', () => {
status = def.value;
for (const [value, node] of buttons) node.classList.toggle('active', value === status);
});
buttons.set(def.value, button);
row.appendChild(button);
}
panel.appendChild(row);
// Which of the origin's services this one is taking — the answer to
// "which service, and where, can be altered".
let sourceSelect = null;
const origins = campus.role === 'resi' ? sourceServices(campus) : [];
if (origins.length) {
const wrap = el('label', 'st-editor-field');
wrap.appendChild(el('span', 'st-editor-label', `Taking from ${campus.sourceName}`));
sourceSelect = el('select', 'st-editor-input');
const none = el('option', null, '— not set —');
none.value = '';
sourceSelect.appendChild(none);
for (const candidate of origins) {
const option = el('option', null, serviceLabel(candidate));
option.value = candidate.id;
if (candidate.id === mark.source) option.selected = true;
sourceSelect.appendChild(option);
}
wrap.appendChild(sourceSelect);
panel.appendChild(wrap);
}
const noteWrap = el('label', 'st-editor-field');
noteWrap.appendChild(el('span', 'st-editor-label', 'Note'));
const note = el('input', 'st-editor-input');
note.type = 'text';
note.maxLength = 280;
note.value = mark.note || '';
note.placeholder = 'What production needs to know';
noteWrap.appendChild(note);
panel.appendChild(noteWrap);
const actions = el('div', 'st-editor-actions');
const save = el('button', 'st-pick st-save', 'Save');
save.type = 'button';
const cancel = el('button', 'st-pick', 'Cancel');
cancel.type = 'button';
actions.append(save, cancel);
panel.appendChild(actions);
async function commit() {
const body = {
campus: campus.slug,
service: service.id,
status,
note: note.value.trim(),
source: sourceSelect ? sourceSelect.value : (mark.source || ''),
};
close();
try {
const response = await moduleApi.fetch('/mark', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!response.ok) throw new Error(`${response.status}`);
} catch (err) {
moduleApi.setStatus('error', `Could not save the mark: ${err.message || err}`);
}
}
save.addEventListener('click', commit);
cancel.addEventListener('click', () => close());
note.addEventListener('keydown', (event) => {
if (event.key === 'Enter') commit();
if (event.key === 'Escape') close();
});
panel.addEventListener('click', (event) => event.stopPropagation());
function onOutside() { close(); }
function onKey(event) { if (event.key === 'Escape') close(); }
function close() {
if (closeEditor !== close) return;
panel.remove();
anchor?.classList.remove('st-open');
root.removeEventListener('click', onOutside);
document.removeEventListener('keydown', onKey);
closeEditor = null;
editing = null;
if (pendingRender) {
pendingRender = false;
render(); // closeEditor is already null, so this cannot re-enter
}
}
closeEditor = close;
anchor?.classList.add('st-open');
board.appendChild(panel);
root.addEventListener('click', onOutside);
document.addEventListener('keydown', onKey);
note.focus();
note.select();
}
/* ── lifecycle ────────────────────────────────────────────────────── */
function applyState(next) {
state = next;
if (!state) {
moduleApi.setStatus('connecting', 'Waiting for the server');
} else if (!state.configured) {
moduleApi.setStatus('error', 'No website address configured');
} else if (!state.reachable) {
moduleApi.setStatus('error', state.lastError
? `Website unreachable — ${state.lastError}`
: 'Website unreachable');
} else if (state.lastError) {
moduleApi.setStatus('connecting', state.lastError);
} else {
const count = (state.campuses || []).reduce((sum, c) => sum + c.services.length, 0);
moduleApi.setStatus('ok', `${count} service(s) across ${(state.campuses || []).length} campus(es)`);
}
// Re-rendering would close an open editor mid-sentence, so hold the change
// back while someone is typing — and draw it the moment they are done, or
// the board would sit stale until the next change happened to arrive.
if (editing) {
pendingRender = true;
return;
}
render();
}
async function loadState() {
try {
const response = await moduleApi.fetch('/state');
const body = await response.json();
applyState(body.state);
} catch {
/* the stream will bring it */
}
}
function setTextSize(delta) {
const next = Math.min(TEXT_MAX, Math.max(TEXT_MIN, textScale() + delta));
moduleApi.saveInstanceSettings({ textSize: Number(next.toFixed(2)) });
if (board) board.style.fontSize = `${next}em`;
}
return {
start() {
moduleApi.setStatus('connecting', 'Reading service times');
render();
moduleApi.header.addButton({
icon: ICON_REFRESH,
title: 'Refresh times',
onClick: async () => {
moduleApi.setStatus('connecting', 'Re-reading the website');
try {
const response = await moduleApi.fetch('/refresh', { method: 'POST' });
const body = await response.json();
if (body.state) applyState(body.state);
} catch (err) {
moduleApi.setStatus('error', `Refresh failed: ${err.message || err}`);
}
},
});
moduleApi.header.addButton({
icon: ICON_CLEAR,
title: 'Clear marks',
onClick: async () => {
const marked = (state?.campuses || []).reduce(
(sum, campus) => sum + campus.services.filter((s) => s.mark).length, 0
);
if (!marked) return;
// Marks are shared by every campus watching — never wipe them silently.
if (!window.confirm(`Clear ${marked} mark${marked === 1 ? '' : 's'} for every campus?`)) return;
try {
await moduleApi.fetch('/clear', { method: 'POST' });
} catch (err) {
moduleApi.setStatus('error', `Could not clear marks: ${err.message || err}`);
}
},
});
moduleApi.header.addButton({
icon: ICON_SMALLER,
title: 'Smaller text',
onClick: () => setTextSize(-TEXT_STEP),
});
moduleApi.header.addButton({
icon: ICON_BIGGER,
title: 'Larger text',
onClick: () => setTextSize(TEXT_STEP),
});
stream = moduleApi.sse('/stream', {
open() {
// The shared connection was (re)made — we may have missed a change.
loadState();
},
error() {
moduleApi.setStatus('error', 'Lost the connection to ProdDash');
},
events: {
state(event) {
try {
applyState(JSON.parse(event.data));
} catch { /* a truncated frame; the next one will be whole */ }
},
},
});
loadState();
},
stop() {
pendingRender = false; // nothing to catch up on: the tile is going away
if (closeEditor) closeEditor();
stream?.close();
stream = null;
state = null;
editing = null;
board = null;
root.innerHTML = '';
},
};
}
+108
View File
@@ -0,0 +1,108 @@
{
"id": "service-times",
"name": "Service Times",
"version": "1.0.0",
"proddash": ">=1.4.0",
"description": "Sunday service times for every campus, marked up for replays and services production cannot use",
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": { "w": 3, "h": 3 },
"defaultSize": { "w": 6, "h": 5 },
"configGroups": {
"Website": {
"help": "Service times are read from the campus pages at <site>/locations/<campus>/ and refreshed on their own, so the board follows the website whenever the times change. Campuses are discovered from the site's sitemap — tick the ones production is responsible for."
},
"Broadcast": {
"help": "Which campuses originate the Sunday broadcast, and which campus each of the others takes its resi from. This is what lets the board show, when a service is marked unusable, every campus affected by it."
},
"Manual campuses": {
"collapsed": "whenSet",
"help": "A stopgap for a campus the website has not published yet. The website stays the source of truth: as soon as it carries a campus by this name, its times take over and the health line above says the line here can be removed."
},
"Marks": {
"collapsed": true,
"help": "Marks are shared by every tile and every browser, and survive a restart of ProdDash."
}
},
"configSchema": {
"siteUrl": {
"type": "string",
"label": "Website",
"default": "https://waterschurch.org",
"group": "Website",
"help": "The church website's address. Campus pages are read from /locations/ underneath it."
},
"campuses": {
"type": "multiselect",
"label": "Campuses",
"default": ["north-attleboro", "woonsocket", "southcoast", "apollo-beach"],
"group": "Website",
"optionsRoute": "/discovered",
"help": "Leave every campus unticked to follow all of them."
},
"refreshMinutes": {
"type": "number",
"label": "Refresh (min)",
"default": 360,
"group": "Website",
"help": "How often the website is re-read. Times change a few times a year, so this can be slow; a failed read retries every minute and the last good times stay on screen."
},
"broadcast": {
"type": "multiselect",
"label": "Broadcast campuses",
"default": ["north-attleboro", "apollo-beach"],
"group": "Broadcast",
"optionsRoute": "/campuses",
"help": "The campuses the broadcast originates from."
},
"feeds": {
"type": "text",
"label": "Resi sources",
"default": "woonsocket = north-attleboro\nsouthcoast = north-attleboro",
"group": "Broadcast",
"help": "One campus per line: campus = the broadcast campus it takes resi from. Names or slugs both work."
},
"manual": {
"type": "text",
"label": "Campuses and times",
"default": "",
"group": "Manual campuses",
"help": "One campus per line: Name | Day | 9:00a, 11:00a. The day is optional and defaults to Sunday. Lines starting with # are ignored."
},
"retentionHours": {
"type": "number",
"label": "Marks clear after (h)",
"default": 36,
"group": "Marks",
"help": "A mark disappears this long after it was made, so Saturday's and Sunday's notes are gone before the next week. Set 0 to keep marks until they are cleared by hand."
}
},
"instanceGroups": {
"Show": { "collapsed": true, "columns": 2 }
},
"instanceSchema": {
"campuses": {
"type": "multiselect",
"label": "Campuses",
"optionsRoute": "/campuses",
"columns": 2,
"allByDefault": true
},
"layout": {
"type": "select",
"label": "Layout",
"default": "cards",
"options": [
{ "value": "cards", "label": "Cards" },
{ "value": "list", "label": "List" }
]
},
"showDay": { "type": "boolean", "label": "Day", "default": true, "group": "Show" },
"showRole": { "type": "boolean", "label": "Role", "default": true, "group": "Show" },
"showSource": { "type": "boolean", "label": "Resi source", "default": true, "group": "Show" },
"showDependents": { "type": "boolean", "label": "Campuses fed", "default": true, "group": "Show" },
"showNotes": { "type": "boolean", "label": "Notes", "default": true, "group": "Show" },
"showUpdated": { "type": "boolean", "label": "Updated line", "default": false, "group": "Show" }
}
}
+413
View File
@@ -0,0 +1,413 @@
'use strict';
/**
* Service Times — reading the church website.
*
* Pure functions, no I/O, so every shape below can be checked without the
* network (parse.test.js). The server entry does the fetching.
*
* Every campus page is built from the same page-builder blocks: a "Times"
* heading, the day in bold, then the service times under it, ending before
* the "Get Involved" heading. Bounding the slice that way is what keeps the
* footer's main-office hours out of the service list — and some campuses
* (Apollo Beach) carry their own "Office Hours" block inside the Times
* section, which is why STOP_HEADINGS ends the walk early as well.
*
* The four shapes seen in the wild, all handled by walkSection():
*
* Woonsocket / Apollo Beach Sunday → 9:00a, 11:00a
* 9:00a & 11:00a
* North Attleboro Sunday → 7:30a, 9:30a, 11:30a
* 7:30a<br>9:30a<br>11:30a
* Orlando Sundays → Welcome 10:00a,
* Welcome 10:00am Start 10:30a
* Start 10:30am
*/
const WEEKDAYS = [
'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
];
/** Headings that end the service list wherever they turn up in the section. */
const STOP_HEADINGS = /^(office\s*hours?|get\s*involved|location\s*pastor|contact|address|events?)\b/i;
/** A time: "9:00a", "11:30am", "7a", "10:00 a.m." — never "1 person". */
const TIME_RE = /(\d{1,2})(?::(\d{2}))?\s*([ap])\.?\s*(?:m\.?)?(?![a-z])/gi;
/** "9:00a-4:30p" — an hours range, not two services. */
const RANGE_RE = /\d\s*(?::\d{2})?\s*[ap]\.?m?\.?\s*[-–—]\s*\d/i;
const NAMED_ENTITIES = {
amp: '&', nbsp: ' ', quot: '"', apos: "'", lt: '<', gt: '>',
ndash: '–', mdash: '—', hellip: '…', middot: '·', bull: '•',
rsquo: '’', lsquo: '‘', ldquo: '“', rdquo: '”',
};
function fromCodePoint(n) {
try {
return Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '';
} catch {
return '';
}
}
function decodeEntities(input) {
return String(input == null ? '' : input)
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => fromCodePoint(parseInt(dec, 10)))
.replace(/&([a-z]+);/gi, (whole, name) => {
const value = NAMED_ENTITIES[name.toLowerCase()];
return value === undefined ? whole : value;
});
}
/**
* HTML → the lines a reader would see. Block ends and <br> become line
* breaks so "7:30a<br>9:30a" stays two services rather than one run-on.
*/
function htmlToLines(html) {
return String(html == null ? '' : html)
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
.replace(/<!--[\s\S]*?-->/g, ' ')
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/(p|div|li|ul|ol|h[1-6]|td|tr|span|strong|b|em|i|a)\s*>/gi, '\n')
.replace(/<[^>]*>/g, ' ')
.split('\n')
.map((line) => decodeEntities(line).replace(/[   ]/g, ' ').replace(/\s+/g, ' ').trim())
.filter(Boolean);
}
/** Title Case a slug: "north-attleboro" → "North Attleboro". */
function nameFromSlug(slug) {
return String(slug || '')
.split(/[-_/]+/)
.filter(Boolean)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
function slugify(name) {
return String(name == null ? '' : name)
.toLowerCase()
.normalize('NFKD')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/** A weekday heading — "Sunday", "Sundays", "SUNDAY" — and nothing else. */
function dayFromLine(line) {
const cleaned = String(line || '').toLowerCase().replace(/[^a-z]+/g, '');
if (!cleaned) return '';
for (const day of WEEKDAYS) {
if (cleaned === day || cleaned === `${day}s`) {
return day.charAt(0).toUpperCase() + day.slice(1);
}
}
return '';
}
function pad2(n) {
return String(n).padStart(2, '0');
}
/** "9:00a" → { hour24: 9, minute: 0, text: "9:00a" }; 12a/12p handled. */
function toService(hourRaw, minuteRaw, meridiemRaw) {
const hour12 = Number(hourRaw);
const minute = Number(minuteRaw || 0);
const pm = String(meridiemRaw || '').toLowerCase() === 'p';
if (!Number.isFinite(hour12) || hour12 < 1 || hour12 > 12) return null;
if (!Number.isFinite(minute) || minute > 59) return null;
const hour24 = pm ? (hour12 === 12 ? 12 : hour12 + 12) : hour12 === 12 ? 0 : hour12;
return {
hour24,
minute,
minutes: hour24 * 60 + minute,
text: `${hour12}:${pad2(minute)}${pm ? 'p' : 'a'}`,
};
}
/**
* Times on one line, with the words in front of the first one as a label
* ("Welcome 10:00am" → label "Welcome"). A line holding an hours range
* ("9:00a-4:30p") is office hours, not services, and yields nothing.
*/
function timesFromLine(line) {
const text = String(line || '');
if (RANGE_RE.test(text)) return [];
TIME_RE.lastIndex = 0;
const found = [];
let first = -1;
let match = TIME_RE.exec(text);
while (match) {
const service = toService(match[1], match[2], match[3]);
if (service) {
if (first < 0) first = match.index;
found.push(service);
}
match = TIME_RE.exec(text);
}
if (!found.length) return [];
const label = first > 0
? text.slice(0, first).replace(/[\s|,;:&/–—-]+$/, '').trim()
: '';
// A label belongs to a single time ("Start 10:30am"); a list of times on
// one line ("9:00a & 11:00a") shares none.
return found.map((service) => ({ ...service, label: found.length === 1 ? label : '' }));
}
/**
* Walk the lines of a Times section into services, stopping at the first
* stop-heading. Lines before any weekday heading still count — a campus
* that lists bare times under "Times" is read as Sunday.
*/
function walkSection(lines, { defaultDay = 'Sunday' } = {}) {
const services = [];
let day = '';
for (const line of lines) {
if (STOP_HEADINGS.test(line)) break;
const heading = dayFromLine(line);
if (heading) {
day = heading;
continue;
}
for (const service of timesFromLine(line)) {
services.push({ ...service, day: day || defaultDay });
}
}
return services;
}
/** Give every service a stable id — marks are keyed on it, so it must not drift. */
function withIds(services) {
const seen = new Map();
return services.map((service) => {
const base = [
pad2(service.hour24) + pad2(service.minute),
slugify(service.label),
].filter(Boolean).join('-');
const count = (seen.get(base) || 0) + 1;
seen.set(base, count);
return { ...service, id: count === 1 ? base : `${base}-${count}` };
});
}
/** Drop exact duplicates (same day + time + label) while keeping order. */
function dedupe(services) {
const seen = new Set();
return services.filter((service) => {
const key = `${service.day}|${service.minutes}|${service.label.toLowerCase()}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/**
* The slice of a campus page between the "Times" heading and whatever ends
* it. Returns '' when the page has no Times heading, which the caller
* reports rather than guessing at.
*/
function timesSection(html) {
const text = String(html == null ? '' : html);
const start = /<([a-z0-9]+)\b[^>]*>\s*times\s*<\/\1\s*>/i.exec(text)
|| />\s*times\s*</i.exec(text);
if (!start) return '';
const from = start.index + start[0].length;
const rest = text.slice(from);
const end = /<([a-z0-9]+)\b[^>]*>\s*get\s+involved\s*<\/\1\s*>/i.exec(rest)
|| />\s*get\s+involved\s*</i.exec(rest);
return end ? rest.slice(0, end.index) : rest.slice(0, 20000);
}
/**
* One campus page → { slug, name, day, services, error }. `error` is set
* (and services empty) when the page no longer looks the way this parser
* expects, so the admin health line can say the site changed rather than
* quietly showing a campus with no services.
*/
function parseCampusPage(html, { slug = '', name = '' } = {}) {
const campusSlug = slugify(slug);
const campusName = name || nameFromSlug(campusSlug);
const section = timesSection(html);
if (!section) {
return { slug: campusSlug, name: campusName, services: [], error: 'No "Times" section on the page' };
}
const services = withIds(dedupe(walkSection(htmlToLines(section))));
if (!services.length) {
return { slug: campusSlug, name: campusName, services: [], error: 'No service times under "Times"' };
}
return { slug: campusSlug, name: campusName, services, error: '' };
}
/**
* Campus page slugs from a sitemap and/or any page's links. The sitemap is
* the fuller list — it carries campuses the navigation does not link yet.
*/
function discoverCampusSlugs(...sources) {
const slugs = new Set();
for (const source of sources) {
const text = String(source == null ? '' : source);
const re = /\/locations\/([a-z0-9][a-z0-9-]*)\/?/gi;
let match = re.exec(text);
while (match) {
const slug = slugify(match[1]);
if (slug && slug !== 'locations') slugs.add(slug);
match = re.exec(text);
}
}
return [...slugs].sort();
}
/**
* The admin "Manual campuses" text: one campus per line,
*
* Name | Day | 9:00a, 11:00a
*
* Day is optional and defaults to Sunday: "Plymouth | 9:00a & 11:00a".
* A line the parser cannot read is returned in `errors` so the admin page
* can say which line, rather than the campus silently not appearing.
*/
function parseManualCampuses(text) {
const campuses = [];
const errors = [];
const lines = String(text == null ? '' : text).split(/\r?\n/);
lines.forEach((raw, index) => {
const line = raw.trim();
if (!line || line.startsWith('#')) return;
const parts = line.split('|').map((part) => part.trim());
const name = parts.shift() || '';
if (!name) return;
if (!parts.length) {
errors.push(`Line ${index + 1}: "${line}" has no times`);
return;
}
let day = '';
if (parts.length > 1) {
day = dayFromLine(parts[0]) || '';
if (day) parts.shift();
}
const services = withIds(dedupe(
walkSection(parts.join('\n').split('\n'), { defaultDay: day || 'Sunday' })
));
if (!services.length) {
errors.push(`Line ${index + 1}: no times found in "${line}"`);
return;
}
campuses.push({ slug: slugify(name), name, services, manual: true, error: '' });
});
return { campuses, errors };
}
/**
* Website campuses and manual ones into the one list the tiles draw.
*
* The website wins: a manual campus is a stopgap for a site that has not
* caught up, so as soon as the site publishes that campus (same slug) its
* times take over and the manual entry is marked `supersededBy` — the admin
* page says so, and the operator can delete the line.
*/
function mergeCampuses(siteCampuses, manualCampuses) {
const merged = [];
const bySlug = new Map();
for (const campus of siteCampuses || []) {
if (!campus || !campus.slug) continue;
const entry = { ...campus, manual: false, superseded: false };
bySlug.set(campus.slug, entry);
merged.push(entry);
}
for (const campus of manualCampuses || []) {
if (!campus || !campus.slug) continue;
const fromSite = bySlug.get(campus.slug);
if (fromSite) {
// The site has it now — its times are the ones that matter.
if (fromSite.services.length) {
fromSite.supersededManual = true;
continue;
}
// The page exists but gave us nothing usable; the manual line still helps.
fromSite.services = campus.services;
fromSite.manual = true;
fromSite.error = '';
continue;
}
const entry = { ...campus, superseded: false };
bySlug.set(campus.slug, entry);
merged.push(entry);
}
return merged;
}
/**
* The admin "Resi sources" text: one campus per line,
*
* woonsocket = north-attleboro
*
* Names work as well as slugs — both sides are slugified, so an operator can
* write what they say out loud. "->", ":" and "→" read as "=".
*/
function parseFeeds(text) {
const feeds = new Map();
const errors = [];
String(text == null ? '' : text).split(/\r?\n/).forEach((raw, index) => {
const line = raw.trim();
if (!line || line.startsWith('#')) return;
const match = /^(.+?)\s*(?:=|->|:|→)\s*(.+)$/.exec(line);
if (!match) {
errors.push(`Line ${index + 1}: "${line}" is not "campus = broadcast campus"`);
return;
}
const from = slugify(match[1]);
const to = slugify(match[2]);
if (!from || !to) {
errors.push(`Line ${index + 1}: "${line}" is missing a campus`);
return;
}
feeds.set(from, to);
});
return { feeds, errors };
}
/**
* Give every campus its production role: which ones originate the broadcast,
* which one each of the others takes its resi from, and — the question the
* board exists to answer — who is riding on each origin.
*
* A resi campus pointed at a campus that is not on the board keeps the
* pointer and is flagged (`sourceMissing`) rather than quietly reading as
* unassigned: a typo in the admin text has to be visible, not invisible.
*/
function assignRoles(campuses, { broadcast = [], feeds = new Map() } = {}) {
const origins = new Set([...broadcast].map((slug) => slugify(slug)).filter(Boolean));
const shaped = (campuses || []).map((campus) => {
const role = origins.has(campus.slug) ? 'broadcast' : 'resi';
const source = role === 'broadcast' ? '' : feeds.get(campus.slug) || '';
return { ...campus, role, source, sourceName: '', sourceMissing: false, dependents: [] };
});
const bySlug = new Map(shaped.map((campus) => [campus.slug, campus]));
for (const campus of shaped) {
if (!campus.source) continue;
const origin = bySlug.get(campus.source);
campus.sourceName = origin ? origin.name : campus.source;
campus.sourceMissing = !origin;
if (origin) origin.dependents.push({ slug: campus.slug, name: campus.name });
}
return shaped;
}
module.exports = {
WEEKDAYS,
decodeEntities,
htmlToLines,
nameFromSlug,
slugify,
dayFromLine,
timesFromLine,
walkSection,
timesSection,
parseCampusPage,
discoverCampusSlugs,
parseManualCampuses,
mergeCampuses,
parseFeeds,
assignRoles,
};
+313
View File
@@ -0,0 +1,313 @@
'use strict';
/**
* Unit tests for the Service Times parser.
*
* node modules/service-times/parse.test.js
*
* Plain Node, no dependencies; exits non-zero on the first failure. The
* fixtures are trimmed from the real campus pages, so each one stands for a
* shape the website actually publishes — including Apollo Beach's "Office
* Hours" block, which sits inside the Times section and must never be read
* as a service.
*/
const assert = require('assert');
const {
htmlToLines,
slugify,
dayFromLine,
timesFromLine,
timesSection,
parseCampusPage,
discoverCampusSlugs,
parseManualCampuses,
mergeCampuses,
parseFeeds,
assignRoles,
} = require('./parse');
let passed = 0;
function test(name, fn) {
try {
fn();
passed += 1;
console.log(` ok ${name}`);
} catch (err) {
console.error(`FAIL ${name}\n ${err.message}`);
process.exit(1);
}
}
/** The page-builder wrapper every campus's Times block sits in. */
const page = (inner) => `
<div class="wpb_wrapper"><h5 class="q_title">Address</h5><p>1 Example Road</p></div>
<div class="wpb_wrapper"><h5 class="q_title">Times</h5>
${inner}
</div>
<div class="wpb_wrapper"><h5 class="q_title">Get Involved</h5><p>Give now</p></div>
<div class="footer"><p>Mon &#8211; Thu 9a &#8211; 4:30p</p></div>
`;
const WOONSOCKET = page('<p><strong>Sunday</strong></p><p>9:00a &amp; 11:00a</p>');
const NORTH_ATTLEBORO = page('<p><strong>Sunday</strong></p><p>7:30a<br />9:30a<br />11:30a</p>');
const ORLANDO = page('<p><b>Sundays</b></p><p>Welcome 10:00am</p><p>Start 10:30am</p>');
const SOUTHCOAST = page('<p><strong>Sunday</strong></p><p>10:30a</p>');
const APOLLO_BEACH = page(
'<p><strong style="color:#333">Sunday</strong></p>'
+ '<p><span style="color:#333">9:00a &amp; 11:00a</span></p>'
+ '<h5 class="q_title">Office Hours</h5><p>Mon-Wed 9:00a-4:30p</p>'
);
const times = (html, slug) => parseCampusPage(html, { slug }).services.map((s) => s.text);
console.log('campus pages');
test('Woonsocket: two times joined by "&" on one line', () => {
assert.deepStrictEqual(times(WOONSOCKET, 'woonsocket'), ['9:00a', '11:00a']);
});
test('North Attleboro: three times separated by <br>', () => {
assert.deepStrictEqual(times(NORTH_ATTLEBORO, 'north-attleboro'), ['7:30a', '9:30a', '11:30a']);
});
test('Southcoast: a single service', () => {
assert.deepStrictEqual(times(SOUTHCOAST, 'southcoast'), ['10:30a']);
});
test('Orlando: "am" spelling, one labelled time per line', () => {
const services = parseCampusPage(ORLANDO, { slug: 'orlando' }).services;
assert.deepStrictEqual(services.map((s) => s.text), ['10:00a', '10:30a']);
assert.deepStrictEqual(services.map((s) => s.label), ['Welcome', 'Start']);
});
test('Apollo Beach: the Office Hours block inside Times is not a service', () => {
assert.deepStrictEqual(times(APOLLO_BEACH, 'apollo-beach'), ['9:00a', '11:00a']);
});
/* Apollo Beach's real page lists an hours *range* under Office Hours, which the
range guard rejects on its own — so the test above passes even if the
stop-heading breaks. This fixture puts plain times there instead, where only
the stop-heading can keep them out: without it, the 2:00p becomes a service. */
const OFFICE_HOURS_PLAIN = page(
'<p><strong>Sunday</strong></p><p>9:00a &amp; 11:00a</p>'
+ '<h5 class="q_title">Office Hours</h5><p>Mon 9:00a</p><p>Thu 2:00p</p>'
);
test('an Office Hours block ends the service list, range or not', () => {
assert.deepStrictEqual(times(OFFICE_HOURS_PLAIN, 'apollo-beach'), ['9:00a', '11:00a']);
});
test('the footer\'s main-office hours never reach the services', () => {
for (const [html, slug] of [[WOONSOCKET, 'woonsocket'], [SOUTHCOAST, 'southcoast']]) {
assert.ok(!times(html, slug).includes('4:30p'), `${slug} picked up the footer`);
}
});
test('names and days come out as the site writes them', () => {
const campus = parseCampusPage(NORTH_ATTLEBORO, { slug: 'north-attleboro' });
assert.strictEqual(campus.name, 'North Attleboro');
assert.deepStrictEqual([...new Set(campus.services.map((s) => s.day))], ['Sunday']);
});
test('ids are stable and unique — marks are keyed on them', () => {
const first = parseCampusPage(ORLANDO, { slug: 'orlando' }).services.map((s) => s.id);
const again = parseCampusPage(ORLANDO, { slug: 'orlando' }).services.map((s) => s.id);
assert.deepStrictEqual(first, ['1000-welcome', '1030-start']);
assert.deepStrictEqual(first, again);
assert.strictEqual(new Set(first).size, first.length);
});
test('a page that no longer has a Times section reports it', () => {
const campus = parseCampusPage('<h1>Redirected elsewhere</h1>', { slug: 'norwood' });
assert.deepStrictEqual(campus.services, []);
assert.match(campus.error, /Times/);
});
console.log('pieces');
test('24-hour values and sort order', () => {
const [nine] = timesFromLine('9:00a');
const [noon] = timesFromLine('12:00p');
const [midnight] = timesFromLine('12:00a');
const [evening] = timesFromLine('6:30p');
assert.strictEqual(nine.hour24, 9);
assert.strictEqual(noon.hour24, 12);
assert.strictEqual(midnight.hour24, 0);
assert.strictEqual(evening.minutes, 18 * 60 + 30);
});
test('an hours range is not a service list', () => {
assert.deepStrictEqual(timesFromLine('Mon-Wed 9:00a-4:30p'), []);
assert.deepStrictEqual(timesFromLine('9a – 4:30p'), []);
});
test('prose that merely contains a number is not a time', () => {
assert.deepStrictEqual(timesFromLine('1 pastor, 2 people'), []);
assert.deepStrictEqual(timesFromLine('Apollo Beach campus'), []);
});
test('weekday headings, singular or plural, in any case', () => {
assert.strictEqual(dayFromLine('Sunday'), 'Sunday');
assert.strictEqual(dayFromLine('SUNDAYS'), 'Sunday');
assert.strictEqual(dayFromLine(' Saturday '), 'Saturday');
assert.strictEqual(dayFromLine('Sunday 9:00a'), '');
assert.strictEqual(dayFromLine('Get Involved'), '');
});
test('<br> and block ends become line breaks', () => {
assert.deepStrictEqual(htmlToLines('<p>7:30a<br />9:30a</p>'), ['7:30a', '9:30a']);
assert.deepStrictEqual(htmlToLines('<p>9:00a &amp; 11:00a</p>'), ['9:00a & 11:00a']);
});
test('the Times slice stops at Get Involved', () => {
const section = timesSection(WOONSOCKET);
assert.ok(section.includes('9:00a'));
assert.ok(!section.includes('Give now'));
});
test('campus slugs are discovered from a sitemap', () => {
const xml = `<url><loc>https://waterschurch.org/locations/</loc></url>
<url><loc>https://waterschurch.org/locations/north-attleboro/</loc></url>
<url><loc>https://waterschurch.org/locations/norwood/</loc></url>`;
assert.deepStrictEqual(discoverCampusSlugs(xml), ['north-attleboro', 'norwood']);
});
test('slugs survive punctuation and case', () => {
assert.strictEqual(slugify('North Attleboro'), 'north-attleboro');
assert.strictEqual(slugify(' Apollo Beach! '), 'apollo-beach');
});
console.log('manual campuses');
test('name, day and times — day optional', () => {
const { campuses, errors } = parseManualCampuses(
'Plymouth | Sunday | 9:00a, 11:00a\nQuincy | 10:30a\n'
);
assert.deepStrictEqual(errors, []);
assert.deepStrictEqual(campuses.map((c) => c.name), ['Plymouth', 'Quincy']);
assert.deepStrictEqual(campuses[0].services.map((s) => s.text), ['9:00a', '11:00a']);
assert.deepStrictEqual(campuses[1].services.map((s) => s.day), ['Sunday']);
assert.ok(campuses[0].manual);
});
test('blank lines and # comments are skipped; a line with no time is reported', () => {
const { campuses, errors } = parseManualCampuses('\n# not yet on the site\nPlymouth | soon\n');
assert.deepStrictEqual(campuses, []);
assert.strictEqual(errors.length, 1);
assert.match(errors[0], /Line 3/);
});
console.log('merging');
test('the website wins once it publishes a campus the operator added by hand', () => {
const site = [{ slug: 'plymouth', name: 'Plymouth', services: [{ id: '0900', text: '9:00a' }], error: '' }];
const manual = parseManualCampuses('Plymouth | 10:30a').campuses;
const merged = mergeCampuses(site, manual);
assert.strictEqual(merged.length, 1);
assert.deepStrictEqual(merged[0].services.map((s) => s.text), ['9:00a']);
assert.strictEqual(merged[0].manual, false);
assert.ok(merged[0].supersededManual, 'the admin page should be able to say the line can go');
});
test('a manual campus the site does not have yet is kept', () => {
const merged = mergeCampuses([], parseManualCampuses('Plymouth | 10:30a').campuses);
assert.deepStrictEqual(merged.map((c) => c.name), ['Plymouth']);
assert.ok(merged[0].manual);
});
test('a site page that parses to nothing falls back to the manual line', () => {
const site = [{ slug: 'plymouth', name: 'Plymouth', services: [], error: 'No "Times" section on the page' }];
const merged = mergeCampuses(site, parseManualCampuses('Plymouth | 10:30a').campuses);
assert.deepStrictEqual(merged[0].services.map((s) => s.text), ['10:30a']);
assert.strictEqual(merged[0].error, '');
assert.ok(merged[0].manual);
});
console.log('resi sources');
test('campus = broadcast campus, by name or slug, with -> and : accepted', () => {
const { feeds, errors } = parseFeeds(
'Woonsocket = North Attleboro\nsouthcoast -> north-attleboro\n# a comment\n\nOrlando: Apollo Beach'
);
assert.deepStrictEqual(errors, []);
assert.strictEqual(feeds.get('woonsocket'), 'north-attleboro');
assert.strictEqual(feeds.get('southcoast'), 'north-attleboro');
assert.strictEqual(feeds.get('orlando'), 'apollo-beach');
});
test('a line that names no source is reported, not dropped in silence', () => {
const { feeds, errors } = parseFeeds('woonsocket\nsouthcoast = north-attleboro');
assert.strictEqual(feeds.size, 1);
assert.strictEqual(errors.length, 1);
assert.match(errors[0], /Line 1/);
});
console.log('roles and dependents');
/** The four campuses production runs, set up the way the booth runs them. */
const BOARD = [
{ slug: 'north-attleboro', name: 'North Attleboro', services: [{ id: '0730' }, { id: '0930' }, { id: '1130' }] },
{ slug: 'woonsocket', name: 'Woonsocket', services: [{ id: '0900' }, { id: '1100' }] },
{ slug: 'southcoast', name: 'Southcoast', services: [{ id: '1030' }] },
{ slug: 'apollo-beach', name: 'Apollo Beach', services: [{ id: '0900' }, { id: '1100' }] },
];
const SETUP = {
broadcast: ['north-attleboro', 'apollo-beach'],
feeds: parseFeeds('woonsocket = north-attleboro\nsouthcoast = north-attleboro').feeds,
};
const byName = (campuses, name) => campuses.find((c) => c.name === name);
test('the broadcast campuses originate and take resi from nobody', () => {
const roles = assignRoles(BOARD, SETUP);
for (const name of ['North Attleboro', 'Apollo Beach']) {
assert.strictEqual(byName(roles, name).role, 'broadcast', name);
assert.strictEqual(byName(roles, name).source, '', `${name} should have no source`);
}
});
test('every other campus takes resi from the campus it is mapped to', () => {
const roles = assignRoles(BOARD, SETUP);
for (const name of ['Woonsocket', 'Southcoast']) {
const campus = byName(roles, name);
assert.strictEqual(campus.role, 'resi', name);
assert.strictEqual(campus.source, 'north-attleboro', name);
assert.strictEqual(campus.sourceName, 'North Attleboro', name);
assert.strictEqual(campus.sourceMissing, false, name);
}
});
test('an origin lists who is riding on it — the answer the board exists for', () => {
const roles = assignRoles(BOARD, SETUP);
assert.deepStrictEqual(
byName(roles, 'North Attleboro').dependents.map((d) => d.name),
['Woonsocket', 'Southcoast']
);
assert.deepStrictEqual(byName(roles, 'Apollo Beach').dependents, []);
});
test('a source that is not on the board is flagged, not read as unassigned', () => {
const roles = assignRoles(BOARD, {
broadcast: ['north-attleboro'],
feeds: parseFeeds('woonsocket = attleboro-north').feeds, // a typo
});
const woonsocket = byName(roles, 'Woonsocket');
assert.strictEqual(woonsocket.source, 'attleboro-north');
assert.strictEqual(woonsocket.sourceMissing, true);
assert.deepStrictEqual(byName(roles, 'North Attleboro').dependents, []);
});
test('a campus with no mapping reads as having no source at all', () => {
const roles = assignRoles(BOARD, { broadcast: ['north-attleboro'], feeds: new Map() });
assert.strictEqual(byName(roles, 'Southcoast').source, '');
assert.strictEqual(byName(roles, 'Southcoast').sourceMissing, false);
});
test('assignRoles leaves the campuses it was handed alone', () => {
const input = [{ slug: 'woonsocket', name: 'Woonsocket', services: [] }];
assignRoles(input, SETUP);
assert.strictEqual(input[0].role, undefined, 'the caller’s objects must not be rewritten');
});
console.log(`\n${passed} tests passed`);
+570
View File
@@ -0,0 +1,570 @@
'use strict';
/**
* Service Times — server part.
*
* Owns the one connection to the church website, keeps every campus's Sunday
* service times in memory, and fans them — together with the production marks
* an operator puts on a service — out to every tile over SSE. Browsers never
* talk to the website.
*
* GET /state → { state } (instant paint for new tiles)
* GET /stream → SSE, `state` events (change-detected, heartbeated)
* POST /mark → mark one service (replay / do not use / issue)
* POST /clear → drop every mark (a fresh week)
* POST /refresh → re-read the website now
* GET /campuses → { options } — the campuses in play, for the admin
* broadcast picker and a tile's campus list
* GET /discovered → { options } — every campus page the website publishes,
* for the admin "Campuses" picker
*
* Why the marks live here and not in a tile's settings: a mark is the booth's
* shared answer to "is this service usable?", and every campus watching the
* board has to see the same one. Per-tile settings are per browser, so they
* would let two people disagree about whether the 9:30 is going out. Marks
* are written to the ProdDash data directory so a restart mid-morning does
* not lose them, and they expire on their own (admin "Marks") so last week's
* never greet a new Sunday.
*
* The website is the source of truth for times. Manual campuses (admin) are a
* stopgap for a campus the site has not published yet; the moment the site
* carries it, the site's times take over and the admin page says the manual
* line can go.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const {
parseCampusPage,
discoverCampusSlugs,
parseManualCampuses,
mergeCampuses,
parseFeeds,
assignRoles,
slugify,
} = require('./parse');
/** Abort a hung page read well before the refresh cadence. */
const REQUEST_TIMEOUT_MS = 12000;
/** SSE comment ping cadence — keeps idle connections alive through sleepy Wi-Fi. */
const HEARTBEAT_MS = 15000;
/** Fastest allowed re-read: service times change a few times a year. */
const MIN_REFRESH_MINUTES = 5;
/** Backoff after a failed read — keep the last good times on screen meanwhile. */
const RETRY_MS = 60000;
/** Guard against a redirect loop or a runaway campus list. */
const MAX_CAMPUSES = 40;
const BODY_LIMIT_BYTES = 64 * 1024;
const MARK_STATUSES = new Set(['ok', 'issue', 'replay', 'skip']);
const NOTE_LIMIT = 280;
/** Set by init(), read by the routes — both are rebuilt together on remount. */
let current = null;
/* ── small helpers ──────────────────────────────────────────────────── */
function sendJson(res, code, body) {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
}
function readJsonBody(req) {
return new Promise((resolve, reject) => {
let data = '';
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > BODY_LIMIT_BYTES) {
reject(new Error('Request body too large.'));
req.destroy();
return;
}
data += chunk;
});
req.on('end', () => {
if (!data.trim()) return resolve({});
try {
const body = JSON.parse(data);
resolve(body && typeof body === 'object' ? body : {});
} catch {
reject(new Error('Malformed JSON.'));
}
});
req.on('error', reject);
});
}
/** Route handlers are async — the shell only catches synchronous throws. */
function guard(fn) {
return (req, res) => {
Promise.resolve(fn(req, res)).catch((err) => {
try {
sendJson(res, err && err.status ? err.status : 500, { error: err?.message || String(err) });
} catch { /* the client is already gone */ }
});
};
}
/**
* Where ProdDash keeps per-machine state, resolved the way the shell does.
* Never the checkout: the repo folder is replaced on update.
*/
function resolveDataDir() {
const root = path.join(__dirname, '..', '..');
const fromEnv = String(process.env.PRODDASH_DATA_DIR || '').trim();
if (fromEnv) return path.resolve(root, fromEnv);
const home = os.homedir();
if (process.platform === 'win32') {
return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'ProdDash');
}
if (process.platform === 'darwin') {
return path.join(home, 'Library', 'Application Support', 'ProdDash');
}
return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'proddash');
}
const MARKS_FILE = path.join(resolveDataDir(), 'service-times-marks.json');
function markKey(campus, service) {
return `${campus}::${service}`;
}
/* ── admin config shaping ───────────────────────────────────────────── */
function siteBase(config) {
const raw = String(config.siteUrl || '').trim().replace(/\/+$/, '');
if (!raw) return '';
return /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
}
function listSetting(value) {
if (Array.isArray(value)) return value.map((v) => slugify(v)).filter(Boolean);
if (typeof value === 'string') {
return value.split(/[\n,]+/).map((v) => slugify(v)).filter(Boolean);
}
return [];
}
/* ── the website ────────────────────────────────────────────────────── */
async function getText(url) {
const response = await fetch(url, {
redirect: 'follow',
headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
const err = new Error(`${response.status} ${response.statusText || ''}`.trim());
err.status = response.status;
throw err;
}
return response.text();
}
/** Every campus page the site publishes — the sitemap first, the index page as a fallback. */
async function discover(base, log) {
const sources = [];
for (const target of ['/page-sitemap.xml', '/wp-sitemap.xml', '/locations/', '/']) {
try {
sources.push(await getText(base + target));
if (target.includes('sitemap')) break; // a sitemap is the fuller list
} catch (err) {
log(`discovery: ${target} — ${err.message}`);
}
}
if (!sources.length) return [];
return discoverCampusSlugs(...sources).slice(0, MAX_CAMPUSES);
}
async function readCampus(base, slug) {
try {
const html = await getText(`${base}/locations/${slug}/`);
return parseCampusPage(html, { slug });
} catch (err) {
return {
slug,
name: slugify(slug).split('-').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
services: [],
error: `Page unreadable: ${err.message}`,
};
}
}
/* ── module ─────────────────────────────────────────────────────────── */
module.exports = {
init({ config, log }) {
const streams = new Set();
const base = siteBase(config);
const chosen = listSetting(config.campuses);
const broadcast = new Set(listSetting(config.broadcast));
const { feeds, errors: feedErrors } = parseFeeds(config.feeds);
const { campuses: manualCampuses, errors: manualErrors } = parseManualCampuses(config.manual);
const retentionHours = Math.max(0, Number(config.retentionHours) || 0);
const refreshMs = Math.max(MIN_REFRESH_MINUTES, Number(config.refreshMinutes) || 360) * 60000;
let marks = new Map();
let marksWritable = true;
let discovered = [];
let siteCampuses = [];
let reachable = false;
let lastError = base ? '' : 'No website address configured';
let lastFetched = 0;
let timer = null;
let stopped = false;
let lastFrame = '';
/* ── marks: load, save, expire ──────────────────────────────────── */
function loadMarks() {
try {
const saved = JSON.parse(fs.readFileSync(MARKS_FILE, 'utf8'));
for (const [key, value] of Object.entries(saved?.marks || {})) {
if (value && typeof value === 'object') marks.set(key, value);
}
log(`${marks.size} mark(s) restored`);
} catch {
/* no marks yet — the usual case */
}
}
function saveMarks() {
const payload = { marks: Object.fromEntries(marks), savedAt: Date.now() };
try {
fs.mkdirSync(path.dirname(MARKS_FILE), { recursive: true });
const tmp = `${MARKS_FILE}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(payload, null, 2) + '\n');
fs.renameSync(tmp, MARKS_FILE);
marksWritable = true;
} catch (err) {
// Never fall back to writing inside the checkout: the marks stay in
// memory and health() says they will not survive a restart.
if (marksWritable) log(`marks cannot be saved (${err.message}) — keeping them in memory only`);
marksWritable = false;
}
}
/** Drop marks older than the retention window. Returns true if any went. */
function expireMarks() {
if (!retentionHours) return false;
const cutoff = Date.now() - retentionHours * 3600000;
let dropped = false;
for (const [key, mark] of marks) {
if (!(Number(mark?.at) > cutoff)) {
marks.delete(key);
dropped = true;
}
}
if (dropped) saveMarks();
return dropped;
}
/* ── the view every tile draws ──────────────────────────────────── */
function campusList() {
const wanted = chosen.length
? siteCampuses.filter((c) => chosen.includes(c.slug))
: siteCampuses;
const merged = assignRoles(mergeCampuses(wanted, manualCampuses), { broadcast, feeds });
// Marks ride along on the service they belong to.
for (const campus of merged) {
campus.services = campus.services.map((service) => {
const mark = marks.get(markKey(campus.slug, service.id)) || null;
return { ...service, mark };
});
}
return merged;
}
function snapshot() {
return {
configured: Boolean(base),
reachable,
lastError,
lastFetched,
siteUrl: base,
refreshMinutes: refreshMs / 60000,
retentionHours,
marksWritable,
campuses: campusList(),
discovered,
manualErrors,
feedErrors,
now: Date.now(),
};
}
function broadcastState({ force = false } = {}) {
if (!streams.size) return;
const view = snapshot();
let frame;
try {
frame = JSON.stringify(view);
} catch {
return;
}
// `now` changes every call; compare without it so idle tiles stay idle.
const compare = frame.replace(/,"now":\d+/, '');
if (!force && compare === lastFrame) return;
lastFrame = compare;
const payload = `event: state\ndata: ${frame}\n\n`;
for (const res of streams) {
try {
res.write(payload);
} catch {
streams.delete(res);
}
}
}
/* ── the refresh loop ───────────────────────────────────────────── */
async function refresh() {
if (stopped) return;
if (!base) {
reachable = false;
lastError = 'No website address configured';
return;
}
try {
const found = await discover(base, log);
if (found.length) discovered = found;
const slugs = chosen.length ? chosen : discovered;
if (!slugs.length) throw new Error('No campus pages found on the site');
const read = await Promise.all(slugs.slice(0, MAX_CAMPUSES).map((slug) => readCampus(base, slug)));
const usable = read.filter((campus) => campus.services.length);
// A total failure keeps the last good times on screen — a site outage
// must not blank the board in the middle of a service.
if (!usable.length && siteCampuses.length) {
throw new Error(read[0]?.error || 'No service times found on the site');
}
siteCampuses = read;
reachable = true;
lastFetched = Date.now();
const broken = read.filter((campus) => campus.error);
lastError = broken.length ? `${broken.length} campus page(s) unreadable: ${broken[0].error}` : '';
log(`read ${usable.length}/${read.length} campus page(s) from ${base}`);
} catch (err) {
reachable = false;
lastError = err?.message || String(err);
log(`refresh failed: ${lastError}`);
}
}
function schedule(delay) {
clearTimeout(timer);
if (stopped) return;
timer = setTimeout(async () => {
await refresh();
expireMarks();
broadcastState();
schedule(reachable ? refreshMs : RETRY_MS);
}, delay);
timer.unref?.();
}
loadMarks();
expireMarks();
if (base) {
log(`reading service times from ${base} every ${Math.round(refreshMs / 60000)} min`);
} else {
log('no website address configured — set one in /admin');
}
// First read immediately, then on the configured cadence.
schedule(0);
const heartbeat = setInterval(() => {
expireMarks();
broadcastState();
for (const res of streams) {
try {
res.write(': ping\n\n');
} catch {
streams.delete(res);
}
}
}, HEARTBEAT_MS);
heartbeat.unref?.();
current = {
streams,
snapshot,
broadcastState,
refreshNow: async () => {
await refresh();
broadcastState({ force: true });
},
setMark(campusSlug, serviceId, patch) {
const key = markKey(slugify(campusSlug), String(serviceId || ''));
const status = MARK_STATUSES.has(patch.status) ? patch.status : 'ok';
if (status === 'ok' && !patch.note && !patch.source) {
marks.delete(key);
} else {
marks.set(key, {
status,
note: String(patch.note || '').slice(0, NOTE_LIMIT),
source: String(patch.source || '').slice(0, 120),
at: Date.now(),
});
}
saveMarks();
broadcastState({ force: true });
},
clearMarks() {
const had = marks.size;
marks.clear();
saveMarks();
broadcastState({ force: true });
return had;
},
};
return {
stop() {
stopped = true;
clearTimeout(timer);
clearInterval(heartbeat);
for (const res of streams) {
try { res.end(); } catch { /* already gone */ }
}
streams.clear();
if (current && current.streams === streams) current = null;
},
health() {
if (!base) return { status: 'error', message: 'No website address configured' };
const notes = [];
if (!marksWritable) notes.push('marks are memory-only — the data directory is not writable');
if (manualErrors.length) notes.push(manualErrors[0]);
if (feedErrors.length) notes.push(feedErrors[0]);
const superseded = campusList().filter((c) => c.supersededManual).map((c) => c.name);
if (superseded.length) {
notes.push(`the website now publishes ${superseded.join(', ')} — the manual line(s) can be removed`);
}
const suffix = notes.length ? ` — ${notes.join('; ')}` : '';
if (!reachable) {
return { status: 'error', message: `${lastError || 'Website unreachable'}${suffix}` };
}
const count = campusList().reduce((sum, c) => sum + c.services.length, 0);
const warn = lastError || notes.length;
return {
status: warn ? 'connecting' : 'ok',
message: `${count} service(s) across ${campusList().length} campus(es)${lastError ? ` — ${lastError}` : ''}${suffix}`,
};
},
};
},
/**
* The board, plus one entry per campus. A campus booth wants its own times
* and the service it is taking resi from — not the whole network — so those
* entries fix the campus and drop the campus picker from their gear.
*/
tiles() {
const board = {
id: 'board',
name: 'Service Times',
description: 'Every campus, its services, and what is marked for replay or unusable',
defaultSize: { w: 6, h: 5 },
minSize: { w: 3, h: 3 },
settings: {},
};
const campuses = current ? current.snapshot().campuses : [];
return [
board,
...campuses.map((campus) => ({
id: campus.slug,
name: campus.name,
description: `${campus.name} service times`,
defaultSize: { w: 3, h: 4 },
minSize: { w: 2, h: 2 },
settings: { campuses: [campus.slug] },
instanceSchema: {
showDay: { type: 'boolean', label: 'Day', default: true, group: 'Show' },
showRole: { type: 'boolean', label: 'Role', default: true, group: 'Show' },
showSource: { type: 'boolean', label: 'Resi source', default: true, group: 'Show' },
showDependents: { type: 'boolean', label: 'Campuses fed', default: true, group: 'Show' },
showNotes: { type: 'boolean', label: 'Notes', default: true, group: 'Show' },
showUpdated: { type: 'boolean', label: 'Updated line', default: false, group: 'Show' },
},
instanceGroups: { Show: { collapsed: true, columns: 2 } },
})),
];
},
routes() {
return {
'GET /state': (req, res) => {
sendJson(res, 200, { state: current ? current.snapshot() : null });
},
'GET /stream': (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write('retry: 3000\n\n');
res.write(`event: state\ndata: ${JSON.stringify(current ? current.snapshot() : null)}\n\n`);
if (!current) return void res.end();
const { streams } = current;
// A viewer that stops reading (locked tablet, sleeping laptop) must
// not queue frames forever; keepalive probes make the OS notice.
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
streams.add(res);
req.on('close', () => streams.delete(res));
},
'POST /mark': guard(async (req, res) => {
if (!current) return sendJson(res, 503, { error: 'Module is restarting' });
const body = await readJsonBody(req);
const campus = String(body.campus || '').trim();
const service = String(body.service || '').trim();
if (!campus || !service) return sendJson(res, 400, { error: 'campus and service are required' });
current.setMark(campus, service, {
status: body.status,
note: body.note,
source: body.source,
});
sendJson(res, 200, { ok: true });
}),
'POST /clear': guard(async (req, res) => {
if (!current) return sendJson(res, 503, { error: 'Module is restarting' });
sendJson(res, 200, { ok: true, cleared: current.clearMarks() });
}),
'POST /refresh': guard(async (req, res) => {
if (!current) return sendJson(res, 503, { error: 'Module is restarting' });
await current.refreshNow();
sendJson(res, 200, { ok: true, state: current.snapshot() });
}),
'GET /campuses': (req, res) => {
const campuses = current ? current.snapshot().campuses : [];
sendJson(res, 200, {
options: campuses.map((campus) => ({ value: campus.slug, label: campus.name })),
});
},
'GET /discovered': (req, res) => {
const state = current ? current.snapshot() : null;
const names = new Map((state?.campuses || []).map((c) => [c.slug, c.name]));
const slugs = state?.discovered?.length ? state.discovered : [...names.keys()];
sendJson(res, 200, {
options: slugs.map((slug) => ({
value: slug,
label: names.get(slug)
|| slug.split('-').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
})),
});
},
};
},
};
+297
View File
@@ -0,0 +1,297 @@
/* Service Times — scoped under its tiles via [data-module="service-times"],
styled with the shell's CSS variables only so themes reach into it. */
[data-module="service-times"] .st-board {
position: absolute;
inset: 0;
overflow: auto;
padding: 8px;
color: var(--text);
font-size: 1em;
}
[data-module="service-times"] .st-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr));
gap: 8px;
align-items: start;
}
[data-module="service-times"] .st-grid-list {
grid-template-columns: 1fr;
}
/* ── a campus ─────────────────────────────────────────────────────── */
[data-module="service-times"] .st-campus {
border: 1px solid var(--border);
border-radius: 8px;
background: color-mix(in srgb, var(--panel) 92%, var(--text) 8%);
padding: 7px 8px 8px;
min-width: 0;
}
[data-module="service-times"] .st-is-broadcast {
border-color: color-mix(in srgb, var(--accent) 55%, var(--border));
}
[data-module="service-times"] .st-campus-head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 5px;
margin-bottom: 5px;
}
[data-module="service-times"] .st-campus-name {
margin: 0;
font-size: 1.02em;
font-weight: 700;
letter-spacing: 0.01em;
color: var(--text);
}
[data-module="service-times"] .st-role {
font-size: 0.72em;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--muted);
white-space: nowrap;
}
[data-module="service-times"] .st-role-broadcast {
color: var(--accent-text, var(--text));
background: var(--accent);
border-radius: 999px;
padding: 1px 7px;
}
[data-module="service-times"] .st-role-manual {
color: var(--muted);
border: 1px dashed var(--border);
border-radius: 999px;
padding: 0 6px;
}
[data-module="service-times"] .st-role-unset {
color: var(--warn);
}
[data-module="service-times"] .st-feeds {
margin: 0 0 5px;
font-size: 0.76em;
color: var(--muted);
}
/* ── a service ────────────────────────────────────────────────────── */
[data-module="service-times"] .st-rows {
display: flex;
flex-direction: column;
gap: 3px;
}
[data-module="service-times"] .st-row {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
width: 100%;
text-align: left;
font: inherit;
color: var(--text);
background: color-mix(in srgb, var(--text) 5%, transparent);
border: 1px solid transparent;
border-left: 3px solid color-mix(in srgb, var(--text) 22%, transparent);
border-radius: 5px;
padding: 4px 7px;
cursor: pointer;
}
[data-module="service-times"] .st-row:hover,
[data-module="service-times"] .st-row:focus-visible {
border-color: var(--border);
border-left-color: var(--accent);
background: color-mix(in srgb, var(--accent) 12%, transparent);
}
[data-module="service-times"] .st-row.st-open {
border-color: var(--accent);
}
[data-module="service-times"] .st-time {
font-weight: 700;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
[data-module="service-times"] .st-day {
font-size: 0.74em;
color: var(--muted);
}
[data-module="service-times"] .st-chips {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
margin-left: auto;
}
[data-module="service-times"] .st-chip {
font-size: 0.7em;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.03em;
border-radius: 999px;
padding: 1px 7px;
white-space: nowrap;
}
[data-module="service-times"] .st-chip-issue,
[data-module="service-times"] .st-chip-warn {
color: var(--warn);
background: color-mix(in srgb, var(--warn) 18%, transparent);
}
[data-module="service-times"] .st-chip-replay {
color: var(--accent);
background: color-mix(in srgb, var(--accent) 18%, transparent);
}
[data-module="service-times"] .st-chip-skip {
color: var(--danger);
background: color-mix(in srgb, var(--danger) 18%, transparent);
}
[data-module="service-times"] .st-chip-source,
[data-module="service-times"] .st-chip-quiet {
color: var(--muted);
background: color-mix(in srgb, var(--text) 10%, transparent);
text-transform: none;
letter-spacing: 0;
font-weight: 600;
}
/* Marked services read at a glance from across the booth. */
[data-module="service-times"] .st-row.st-issue { border-left-color: var(--warn); }
[data-module="service-times"] .st-row.st-replay { border-left-color: var(--accent); }
[data-module="service-times"] .st-row.st-skip {
border-left-color: var(--danger);
background: color-mix(in srgb, var(--danger) 12%, transparent);
}
[data-module="service-times"] .st-row.st-skip .st-time {
text-decoration: line-through;
text-decoration-thickness: 2px;
}
[data-module="service-times"] .st-row.st-affected {
border-left-color: var(--danger);
border-color: color-mix(in srgb, var(--danger) 45%, transparent);
}
[data-module="service-times"] .st-note {
flex: 1 0 100%;
font-size: 0.8em;
color: var(--muted);
overflow-wrap: anywhere;
}
/* ── messages ─────────────────────────────────────────────────────── */
[data-module="service-times"] .st-empty,
[data-module="service-times"] .st-updated {
margin: 4px 2px 0;
font-size: 0.8em;
color: var(--muted);
}
[data-module="service-times"] .st-warn {
margin: 6px 2px 0;
font-size: 0.8em;
color: var(--warn);
}
/* ── the mark editor ──────────────────────────────────────────────── */
[data-module="service-times"] .st-editor {
position: sticky;
bottom: 0;
margin-top: 8px;
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
border: 1px solid var(--accent);
border-radius: 8px;
background: var(--panel);
box-shadow: 0 6px 20px rgb(0 0 0 / 0.28);
}
[data-module="service-times"] .st-editor-title {
font-weight: 700;
font-size: 0.9em;
}
[data-module="service-times"] .st-editor-status {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
[data-module="service-times"] .st-pick {
font: inherit;
font-size: 0.8em;
font-weight: 600;
color: var(--text);
background: color-mix(in srgb, var(--text) 8%, transparent);
border: 1px solid var(--border);
border-radius: 6px;
padding: 3px 9px;
cursor: pointer;
}
[data-module="service-times"] .st-pick:hover {
border-color: var(--accent);
}
[data-module="service-times"] .st-pick.active,
[data-module="service-times"] .st-save {
color: var(--accent-text, var(--text));
background: var(--accent);
border-color: var(--accent);
}
[data-module="service-times"] .st-editor-field {
display: flex;
flex-direction: column;
gap: 2px;
}
[data-module="service-times"] .st-editor-label {
font-size: 0.72em;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--muted);
}
[data-module="service-times"] .st-editor-input {
font: inherit;
font-size: 0.85em;
color: var(--text);
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
padding: 4px 7px;
min-width: 0;
}
[data-module="service-times"] .st-editor-input:focus {
outline: none;
border-color: var(--accent);
}
[data-module="service-times"] .st-editor-actions {
display: flex;
gap: 5px;
justify-content: flex-end;
}
+23 -12
View File
@@ -141,13 +141,17 @@ const sendTarget = (() => {
/**
* Where a send goes, given the configured channels in admin order: the
* selection while it is still configured and its transcript is on the
* page; otherwise the first configured channel.
* page, else the first configured channel that IS on this page — with one
* transcript up, that one — and only if the page shows none, the first
* configured channel. A send must never quietly go to a channel the
* operator cannot see.
*/
resolve(configured) {
const list = Array.isArray(configured) ? configured : [];
if (!list.length) return '';
if (id && list.includes(id) && this.hasTranscript(id)) return id;
return list[0];
const onPage = list.find((c) => this.hasTranscript(c));
return onPage || list[0];
},
on(fn) {
bus.addEventListener('change', fn);
@@ -1100,7 +1104,7 @@ function createSendTile({ root, moduleApi, mode }) {
if (stopped || !state) return;
if (token) {
if (composeEls) {
composeEls.line.textContent = sendingLine();
if (composeEls.line) composeEls.line.textContent = sendingLine();
if (composeEls.input) composeEls.input.placeholder = placeholder();
}
} else renderGate();
@@ -1177,14 +1181,21 @@ function createSendTile({ root, moduleApi, mode }) {
let composeEls = null;
function buildCompose() {
compose.textContent = '';
const head = el('div', 'sl-compose-head');
const line = el('span', 'sl-sending', sendingLine());
const lockLink = el('button', 'sl-lock-link', 'Lock');
lockLink.type = 'button';
lockLink.title = 'Lock now';
lockLink.addEventListener('click', () => lock('Locked'));
head.append(line, lockLink);
compose.appendChild(head);
// Send message names the channel in the box's own placeholder and locks
// from the title bar, so a line above the field would only say both
// again. Quick replies has no placeholder — there it is the only place
// the target is named, so it stays.
let line = null;
if (mode !== 'send') {
const head = el('div', 'sl-compose-head');
line = el('span', 'sl-sending', sendingLine());
const lockLink = el('button', 'sl-lock-link', 'Lock');
lockLink.type = 'button';
lockLink.title = 'Lock now';
lockLink.addEventListener('click', () => lock('Locked'));
head.append(line, lockLink);
compose.appendChild(head);
}
const foot = el('div', 'sl-compose-foot');
const msg = el('div', 'sl-msg');
@@ -1462,7 +1473,7 @@ function createSendTile({ root, moduleApi, mode }) {
if (!s.sending?.enabled || !s.sending?.pinSet) return void lock('');
if (!composeEls) return void showCompose(); // the page was unlocked before this tile appeared
if (composeEls) {
composeEls.line.textContent = sendingLine();
if (composeEls.line) composeEls.line.textContent = sendingLine();
if (composeEls.input) composeEls.input.placeholder = placeholder();
}
} else renderGate();
+3 -3
View File
@@ -1,7 +1,7 @@
{
"id": "slack",
"name": "Slack",
"version": "1.2.0",
"version": "1.2.1",
"proddash": ">=1.4.0",
"description": "Live transcripts of this location's Slack channels, plus PIN-protected sending as the location",
"client": "client.js",
@@ -21,7 +21,7 @@
"help": "Create a Slack app in the workspace (api.slack.com/apps → Create New App → From scratch) and, under OAuth & Permissions → User Token Scopes, add channels:history, channels:read, groups:history, groups:read, chat:write, users:read, reactions:write (emoji reactions) and emoji:read (the workspace's custom emoji). Sign in to Slack as this location's account — the one named for the campus — open the app's OAuth & Permissions page and press Install to Workspace (or Reinstall to Workspace), then copy the User OAuth Token (xoxp-…) it shows and paste it here: messages from this machine are then literally from the location. A bot token (xoxb-…) works too; it posts as the app, with \"Send as\" naming the location."
},
"Channels": {
"help": "Every channel picked here becomes its own transcript tile in the + picker, titled with the channel's name. The Send message and Quick replies tiles post to whichever transcript was clicked last — its bottom edge lights up in the accent colour — and to the first channel here until one is clicked. Only channels the account has joined are listed; join one in Slack first. Each channel is read on its own schedule, all of them together kept inside Slack's rate limit."
"help": "Every channel picked here becomes its own transcript tile in the + picker, titled with the channel's name. The Send message and Quick replies tiles post to whichever transcript was clicked last — its bottom edge lights up in the accent colour — and until one is clicked, to the first channel here whose transcript is on that dashboard: with a single transcript up, that one. A send never goes to a channel the dashboard is not showing. Only channels the account has joined are listed; join one in Slack first. Each channel is read on its own schedule, all of them together kept inside Slack's rate limit."
},
"Sending": {
"toggle": "sendEnabled",
@@ -49,7 +49,7 @@
"default": [],
"group": "Channels",
"optionsRoute": "/channels",
"help": "One transcript tile per channel; the first one is where sends go until a transcript is clicked. Only channels the account has joined are listed — join one in Slack first."
"help": "One transcript tile per channel; until a transcript is clicked, sends go to the first channel here that the dashboard is actually showing. Only channels the account has joined are listed — join one in Slack first."
},
"pollSeconds": {
"type": "number",
+610
View File
@@ -0,0 +1,610 @@
/**
* SPL Meter tiles.
*
* Four kinds, all fed by one SSE stream from the module's server:
*
* readout the number, big
* bars one level bar per channel, with peak hold
* rta spectrum now, folded to the banding this tile wants
* spectrogram the same bands over time, either axis
*
* Nothing here measures anything. The capture child already sent every
* averaging and the finest banding, and each tile folds that down to the
* view it was configured for. That is the whole design: two dashboards can
* watch one room through different settings without either disturbing the
* measurement or the other dashboard.
*/
const FLOOR = -200;
/**
* A dead input reads as a number, and a number on a wall is believed. Every
* tile therefore refuses to draw a level while the server says the input is
* digitally silent, and says why instead.
*/
function silentFor(payload) {
return payload && payload.silentSec ? payload.silentSec : 0;
}
function silentText(sec) {
if (sec < 90) return `No audio — ${sec} s`;
const m = Math.round(sec / 60);
return m < 90 ? `No audio — ${m} min` : `No audio — ${(m / 60).toFixed(1)} hours`;
}
/** Retention per frame for the RTA's smoothing setting. */
const SMOOTHING = { off: 0, light: 0.45, medium: 0.72, heavy: 0.9 };
export default function create({ root, moduleApi }) {
const variant = moduleApi.variant || 'readout';
let stream = null;
let latest = null;
let raf = 0;
root.classList.add('spl');
root.dataset.variant = variant;
const view = buildView(variant, root, moduleApi);
function onState(payload) {
latest = payload;
if (payload.error) {
moduleApi.setStatus('error', payload.error);
} else if (!payload.frame) {
moduleApi.setStatus('connecting', 'waiting for the first reading');
} else if (silentFor(payload)) {
moduleApi.setStatus('error',
`No audio on the chosen input — digital silence for ${silentText(silentFor(payload)).replace('No audio — ', '')}`);
} else if (!payload.calibrated) {
moduleApi.setStatus('ok', 'Measuring, but uncalibrated — these are dBFS, not dB SPL');
} else {
moduleApi.setStatus('ok', '');
}
// Frames land 20×/s; paint on a frame the browser was going to draw
// anyway rather than fighting it for every one.
if (!raf) raf = requestAnimationFrame(() => { raf = 0; view.render(latest); });
}
return {
start() {
moduleApi.setStatus('connecting', 'connecting');
moduleApi.fetch('/state')
.then((r) => r.json())
.then(onState)
.catch(() => { /* the stream will bring it */ });
// Named events go under `events` — a top-level `state(ev)` is silently
// never registered, and the tile just sits on whatever /state gave it.
stream = moduleApi.sse('/stream', {
events: {
state(ev) {
try { onState(JSON.parse(ev.data)); } catch { /* keep the last good frame */ }
},
},
error() { moduleApi.setStatus('connecting', 'reconnecting'); },
});
},
stop() {
if (stream) { stream.close(); stream = null; }
if (raf) { cancelAnimationFrame(raf); raf = 0; }
view.destroy();
},
onResize() { view.resize(); },
};
}
/* ── shared helpers ─────────────────────────────────────────────────── */
function pickChannel(payload, settings) {
if (!payload || !payload.frame) return null;
const want = Number(settings.channel);
return payload.frame.ch.find((c) => c.i === want) || payload.frame.ch[0] || null;
}
/**
* The level this tile asked for: an averaging, or one of the fixed metrics.
*
* Tiles saved by an earlier version carry metrics that no longer exist —
* "spl" became an averaging, "leq" became Inf. A layout on a wall somewhere
* must not start reading dashes because a setting was renamed, so those map
* forward instead of falling through to undefined.
*/
const LEGACY_METRIC = { spl: 'level', leq: 'level' };
const LEGACY_AVERAGING = { leq: 'inf' };
function readValue(ch, settings) {
const raw = settings.metric || 'level';
const metric = LEGACY_METRIC[raw] || raw;
if (metric !== 'level') {
return metric in ch ? ch[metric] : ch.fast;
}
const avg = LEGACY_AVERAGING[raw] || settings.averaging || 'fast';
return avg in ch ? ch[avg] : ch.fast;
}
function fmt(db) {
if (!Number.isFinite(db) || db <= FLOOR) return '––.–';
return db.toFixed(1);
}
function themeColor(el, name, fallback) {
const v = getComputedStyle(el).getPropertyValue(name).trim();
return v || fallback;
}
function hzLabel(f) {
if (f >= 1000) {
const k = f / 1000;
return (k >= 10 ? Math.round(k) : Math.round(k * 10) / 10) + 'k';
}
return String(f >= 100 ? Math.round(f) : Math.round(f * 10) / 10);
}
/**
* Fold the 1/48-octave bands on the wire down to this tile's banding.
*
* Every banding offered divides 48, so a coarser band is an exact sum of
* finer ones in the power domain — no interpolation, no resampling. Groups
* are keyed on the 1 kHz band (n = 0), which is what keeps folded centres on
* the values an RTA is expected to show.
*
* @returns {{freq:number[], db:number[]}}
*/
function foldBands(bands, bandN0, perOctave, denom) {
const g = Math.max(1, Math.round(perOctave / denom));
const power = new Map();
for (let i = 0; i < bands.length; i++) {
const n = bandN0 + i;
const k = Math.round(n / g);
const p = 10 ** (bands[i] / 10);
power.set(k, (power.get(k) || 0) + p);
}
const keys = [...power.keys()].sort((a, b) => a - b);
return {
freq: keys.map((k) => 1000 * 2 ** ((k * g) / perOctave)),
db: keys.map((k) => 10 * Math.log10(Math.max(power.get(k), 1e-20))),
};
}
/**
* Which frequency labels fit, most important first.
*
* Decades earn their place before octaves, octaves before thirds, and
* anything that would collide with a label already placed is dropped. That
* is what makes the axis thin out as a tile shrinks instead of turning into
* a smear.
*/
const LABEL_TIERS = [
[100, 1000, 10000],
[31.5, 63, 250, 500, 2000, 4000, 8000, 20000],
[20, 40, 50, 80, 125, 160, 200, 315, 400, 630, 800, 1250, 1600, 2500, 3150, 5000, 6300, 12500, 16000],
];
function chooseLabels(freqs, positionOf, extent, minGapPx) {
const placed = [];
for (const tier of LABEL_TIERS) {
for (const f of tier) {
if (f < freqs[0] * 0.92 || f > freqs[freqs.length - 1] * 1.08) continue;
const pos = positionOf(f);
if (pos < 0 || pos > extent) continue;
if (placed.some((p) => Math.abs(p.pos - pos) < minGapPx)) continue;
placed.push({ f, pos });
}
}
return placed.sort((a, b) => a.pos - b.pos);
}
/* ── views ──────────────────────────────────────────────────────────── */
function buildView(variant, root, moduleApi) {
switch (variant) {
case 'bars': return barsView(root, moduleApi);
case 'rta': return spectrumView(root, moduleApi, false);
case 'spectrogram': return spectrumView(root, moduleApi, true);
default: return readoutView(root, moduleApi);
}
}
function readoutView(root, moduleApi) {
root.innerHTML = `
<div class="spl-readout">
<div class="spl-value"><span class="spl-num">––.–</span><span class="spl-unit">dB</span></div>
<div class="spl-sub"></div>
</div>`;
const num = root.querySelector('.spl-num');
const unit = root.querySelector('.spl-unit');
const sub = root.querySelector('.spl-sub');
const box = root.querySelector('.spl-readout');
const value = root.querySelector('.spl-value');
let fitKey = '';
/**
* Grow the number until it fills the tile, measuring the text we actually
* have rather than assuming a digit count.
*
* The CSS can only guess at width — it has to pick a cqw coefficient for
* some number of characters, and then "-100.5" overflows the tile that
* "-45.9" merely filled. Measuring costs one layout read, and only when
* the tile size or the length of the reading changes.
*/
function fit() {
const w = root.clientWidth, h = root.clientHeight;
const key = `${w}x${h}:${num.textContent.length}:${unit.textContent}:${sub.hidden}`;
if (key === fitKey || w < 2 || h < 2) return;
fitKey = key;
const TRIAL = 100;
num.style.fontSize = `${TRIAL}px`;
unit.style.fontSize = `${TRIAL * 0.26}px`;
const natural = value.scrollWidth || 1;
// Leave the caption its room when it is showing, and a little air either
// way so descenders and the tile's padding never clip.
const subH = sub.offsetParent ? sub.getBoundingClientRect().height + 6 : 0;
const byHeight = (h - subH) * 0.92;
const byWidth = ((w - 8) * TRIAL) / natural;
const size = Math.max(12, Math.min(byHeight, byWidth));
num.style.fontSize = `${size}px`;
unit.style.fontSize = `${size * 0.26}px`;
}
return {
render(payload) {
const s = moduleApi.instanceSettings;
const ch = pickChannel(payload, s);
const quiet = silentFor(payload);
if (quiet && ch) {
num.textContent = '––.–';
unit.textContent = '';
sub.hidden = false;
sub.textContent = silentText(quiet);
box.dataset.level = 'dead';
fit();
return;
}
if (!payload || payload.error || !ch) {
num.textContent = '––.–';
sub.textContent = payload && payload.error ? payload.error : '';
box.dataset.level = 'idle';
fit();
return;
}
const value = readValue(ch, s);
num.textContent = fmt(value);
unit.textContent = payload.calibrated ? 'dB' : 'dBFS';
const warn = Number(s.warnAt), alarm = Number(s.alarmAt);
box.dataset.level = !payload.calibrated ? 'idle'
: value >= alarm ? 'alarm' : value >= warn ? 'warn' : 'ok';
const raw = s.metric || 'level';
const metric = LEGACY_METRIC[raw] || raw;
const avg = LEGACY_AVERAGING[raw] || s.averaging || 'fast';
const label = metric === 'level'
? ({ fast: 'Fast', slow: 'Slow', inf: 'Inf', none: 'No avg' }[avg] || 'Fast')
: ({ leq1m: 'Leq 1 min', leq10m: 'Leq 10 min', peakC: 'Peak C' }[metric] || metric);
const parts = [`${payload.weighting || '?'} · ${label}`, `ch ${ch.i}`];
if (ch.clip) parts.push('CLIP');
if (!payload.calibrated) parts.push('uncalibrated');
sub.hidden = s.caption === false;
sub.textContent = parts.join(' · ');
fit();
},
resize() { fitKey = ''; fit(); },
destroy() { root.innerHTML = ''; },
};
}
function barsView(root, moduleApi) {
root.innerHTML = '<div class="spl-bars"></div>';
const host = root.querySelector('.spl-bars');
let built = '';
return {
render(payload) {
if (!payload || !payload.frame) { host.textContent = payload?.error || ''; built = ''; return; }
const chans = payload.frame.ch;
const key = chans.map((c) => c.i).join(',');
if (key !== built) {
built = key;
host.innerHTML = chans.map((c) => `
<div class="spl-bar" data-ch="${c.i}">
<div class="spl-bar-label">${c.i}</div>
<div class="spl-bar-track"><div class="spl-bar-fill"></div><div class="spl-bar-peak"></div></div>
<div class="spl-bar-value">––.–</div>
</div>`).join('');
}
const s = moduleApi.instanceSettings;
const quiet = silentFor(payload);
const warn = Number(s.warnAt), alarm = Number(s.alarmAt);
const showPeak = s.peakHold !== false;
const lo = payload.calibrated ? 40 : -80;
const hi = payload.calibrated ? 110 : 0;
for (const c of chans) {
const el = host.querySelector(`.spl-bar[data-ch="${c.i}"]`);
if (!el) continue;
const value = readValue(c, { averaging: s.averaging });
const pct = (v) => Math.max(0, Math.min(100, ((v - lo) / (hi - lo)) * 100));
el.querySelector('.spl-bar-fill').style.width = quiet ? '0%' : `${pct(value)}%`;
const peak = el.querySelector('.spl-bar-peak');
peak.style.display = showPeak ? '' : 'none';
if (showPeak) peak.style.left = `${pct(c.peakC)}%`;
el.querySelector('.spl-bar-value').textContent = quiet ? '––.–' : fmt(value);
el.dataset.level = quiet ? 'dead' : !payload.calibrated ? 'idle'
: value >= alarm ? 'alarm' : value >= warn ? 'warn' : 'ok';
el.classList.toggle('clip', !!c.clip);
}
},
resize() {},
destroy() { root.innerHTML = ''; },
};
}
/**
* RTA bars, or the same folded bands scrolling as a spectrogram.
*
* Canvas for both, because both redraw wholesale many times a second and a
* few hundred animating DOM nodes is how a dashboard starts dropping frames
* on the machine that is also running the service.
*/
function spectrumView(root, moduleApi, scrolling) {
root.innerHTML = '<canvas class="spl-canvas"></canvas>';
const canvas = root.querySelector('.spl-canvas');
const ctx = canvas.getContext('2d', { alpha: false });
/**
* The spectrogram's scrolling history, on its own surface.
*
* It used to scroll by copying the visible canvas onto itself, which also
* copied whatever had been drawn on top of it — so every frame dragged the
* frequency labels and gridlines one step further along and left a smear.
* Only measured pixels belong on a surface that scrolls; annotations are
* drawn fresh over the top of it, every frame, and never into it.
*/
let history = null;
let historyCtx = null;
let painted = false; // spectrogram: has the history been cleared yet
let smoothed = null; // RTA: displayed values, damped toward the real ones
let smoothedFor = '';
let axisBtn = null;
let axisOverride = null; // set by the title-bar toggle, which never remounts us
function axis() {
return axisOverride || moduleApi.instanceSettings.axis || 'x';
}
if (scrolling) {
// The axis lives here and nowhere else (rule 11): a tile does not offer
// the same action twice. Icon only, tooltip carries the words (rule 9).
// saveInstanceSettings deliberately does not remount us, so the new
// value is held here as well and read back by axis().
const swapIcon = '<svg viewBox="0 0 16 16" width="13" height="13" fill="none" '
+ 'stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">'
+ '<path d="M2 5h9M8.5 2 11.5 5 8.5 8"/><path d="M14 11H5M7.5 8 4.5 11 7.5 14"/></svg>';
const describe = () => (axis() === 'x' ? 'Time left to right' : 'Time top to bottom');
axisBtn = moduleApi.header.addButton({
icon: swapIcon,
title: describe(),
onClick() {
axisOverride = axis() === 'x' ? 'y' : 'x';
moduleApi.saveInstanceSettings({ axis: axisOverride });
painted = false; // the picture means nothing in the other orientation
axisBtn.title = describe();
},
});
}
function sizeCanvas() {
const dpr = window.devicePixelRatio || 1;
const w = Math.max(1, Math.floor(root.clientWidth));
const h = Math.max(1, Math.floor(root.clientHeight));
if (canvas.width === Math.floor(w * dpr) && canvas.height === Math.floor(h * dpr)) return false;
canvas.width = Math.floor(w * dpr);
canvas.height = Math.floor(h * dpr);
canvas.style.width = `${w}px`;
canvas.style.height = `${h}px`;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
painted = false;
return true;
}
sizeCanvas();
function norm(db, calibrated) {
const lo = calibrated ? 30 : -100;
const hi = calibrated ? 110 : -10;
return Math.max(0, Math.min(1, (db - lo) / (hi - lo)));
}
function heat(v) {
const stops = [[10, 12, 20], [30, 90, 150], [90, 180, 140], [230, 190, 80], [220, 80, 60]];
const x = Math.max(0, Math.min(0.999, v)) * (stops.length - 1);
const i = Math.floor(x), t = x - i;
const a = stops[i], b = stops[i + 1] || stops[i];
return `rgb(${Math.round(a[0] + (b[0] - a[0]) * t)},${Math.round(a[1] + (b[1] - a[1]) * t)},${Math.round(a[2] + (b[2] - a[2]) * t)})`;
}
return {
render(payload) {
sizeCanvas();
const w = canvas.clientWidth, h = canvas.clientHeight;
const bg = themeColor(root, '--panel', '#141414');
const muted = themeColor(root, '--muted', '#888');
const border = themeColor(root, '--border', '#333');
const quiet = silentFor(payload);
if (quiet || !payload || !payload.frame || !payload.frame.bands) {
ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h);
ctx.fillStyle = muted; ctx.font = '12px system-ui'; ctx.textAlign = 'center';
ctx.fillText(quiet ? silentText(quiet)
: (payload?.error || 'Spectrum analysis is off'), w / 2, h / 2);
painted = false;
return;
}
const s = moduleApi.instanceSettings;
const want = Number(s.channel);
const idx = Math.max(0, payload.frame.ch.findIndex((c) => c.i === want));
const raw = payload.frame.bands[idx] || payload.frame.bands[0] || [];
if (!raw.length) return;
const denom = Number(s.banding) || 3;
const folded = foldBands(raw, payload.bandN0 || 0, payload.bandsPerOctave || 48, denom);
const freqs = folded.freq;
let values = folded.db;
const grid = s.gridlines === true;
const showLabels = s.labels !== false;
const axisPad = showLabels || grid ? 13 : 0;
if (!scrolling) {
// Damp the bars toward the measurement. Cosmetic: `values` is what
// gets drawn, never what gets reported.
const keep = SMOOTHING[s.smoothing] ?? SMOOTHING.medium;
const key = `${denom}:${values.length}`;
if (smoothedFor !== key || !smoothed || smoothed.length !== values.length) {
smoothed = values.slice();
smoothedFor = key;
} else if (keep > 0) {
for (let i = 0; i < values.length; i++) {
smoothed[i] = smoothed[i] * keep + values[i] * (1 - keep);
}
} else {
smoothed = values.slice();
}
values = smoothed;
ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h);
const plotH = h - axisPad;
const bw = w / values.length;
const xOf = (f) => (Math.log2(f / freqs[0]) / Math.log2(freqs[freqs.length - 1] / freqs[0])) * w;
const labels = chooseLabels(freqs, xOf, w, 34);
if (grid) {
ctx.strokeStyle = border; ctx.lineWidth = 1; ctx.globalAlpha = 0.5;
ctx.beginPath();
for (const l of labels) {
const x = Math.round(l.pos) + 0.5;
ctx.moveTo(x, 0); ctx.lineTo(x, plotH);
}
for (let g = 0.2; g < 1; g += 0.2) {
const y = Math.round(plotH * g) + 0.5;
ctx.moveTo(0, y); ctx.lineTo(w, y);
}
ctx.stroke(); ctx.globalAlpha = 1;
}
for (let i = 0; i < values.length; i++) {
const v = norm(values[i], payload.calibrated);
const bh = v * plotH;
ctx.fillStyle = heat(v);
ctx.fillRect(i * bw, plotH - bh, Math.max(1, bw - (bw > 3 ? 1 : 0)), bh);
}
if (showLabels) {
ctx.fillStyle = muted; ctx.font = '9px system-ui'; ctx.textAlign = 'center';
for (const l of labels) ctx.fillText(hzLabel(l.f), l.pos, h - 3);
}
return;
}
// ── spectrogram ──
const timeX = axis() === 'x';
const colW = 2;
// A label along the bottom needs only its line height; one down the
// side has to fit "12.5k" beside the plot rather than on top of it.
const gutter = (showLabels || grid) ? (timeX ? 30 : axisPad) : 0;
// Labels belong beside the frequency axis: down the left when frequency
// runs vertically, along the bottom when it runs horizontally.
const plotX = timeX ? gutter : 0;
const plotW = timeX ? w - gutter : w;
const plotH = timeX ? h : h - gutter;
const freqExtent = timeX ? plotH : plotW;
const timeExtent = timeX ? plotW : plotH;
if (plotW < 4 || plotH < 4) return;
// The history surface is sized to the plot, in device pixels, and is
// thrown away whenever that geometry changes — a scroll buffer means
// nothing once it is being stretched into a different shape.
const dpr = window.devicePixelRatio || 1;
const needW = Math.max(1, Math.round(plotW * dpr));
const needH = Math.max(1, Math.round(plotH * dpr));
if (!history || history.width !== needW || history.height !== needH) {
history = document.createElement('canvas');
history.width = needW;
history.height = needH;
historyCtx = history.getContext('2d', { alpha: false });
historyCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
painted = false;
}
if (!painted) {
historyCtx.fillStyle = bg;
historyCtx.fillRect(0, 0, plotW, plotH);
painted = true;
}
// Scroll the history, then add the newest column. The source rectangle
// is in device pixels and the destination in CSS pixels, because the
// context carries the dpr transform but the canvas as an image source
// does not.
historyCtx.drawImage(history, 0, 0, history.width, history.height,
timeX ? -colW : 0, timeX ? 0 : -colW, plotW, plotH);
const bandExtent = freqExtent / values.length;
for (let i = 0; i < values.length; i++) {
historyCtx.fillStyle = heat(norm(values[i], payload.calibrated));
if (timeX) {
// Low frequencies at the bottom, as every spectrogram has them.
historyCtx.fillRect(timeExtent - colW, freqExtent - (i + 1) * bandExtent,
colW, Math.ceil(bandExtent) + 1);
} else {
// Low frequencies at the left.
historyCtx.fillRect(i * bandExtent, timeExtent - colW,
Math.ceil(bandExtent) + 1, colW);
}
}
// Repaint the visible canvas from scratch every frame: history first,
// annotations over it. Nothing drawn here can ever reach the scroll.
ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h);
ctx.drawImage(history, 0, 0, history.width, history.height,
plotX, 0, plotW, plotH);
if (!grid && !showLabels) return;
const span = Math.log2(freqs[freqs.length - 1] / freqs[0]);
const posOf = (f) => {
const t = Math.log2(f / freqs[0]) / span;
return timeX ? plotH - t * plotH : plotX + t * plotW;
};
const labels = chooseLabels(freqs, posOf, timeX ? plotH : w, timeX ? 14 : 34);
if (grid) {
ctx.strokeStyle = border; ctx.lineWidth = 1; ctx.globalAlpha = 0.35;
ctx.beginPath();
for (const l of labels) {
if (timeX) {
const y = Math.round(l.pos) + 0.5;
ctx.moveTo(plotX, y); ctx.lineTo(w, y);
} else {
const x = Math.round(l.pos) + 0.5;
ctx.moveTo(x, 0); ctx.lineTo(x, plotH);
}
}
ctx.stroke(); ctx.globalAlpha = 1;
}
if (showLabels) {
ctx.fillStyle = muted; ctx.font = '9px system-ui';
ctx.textAlign = timeX ? 'right' : 'center';
for (const l of labels) {
if (timeX) {
ctx.fillText(hzLabel(l.f), gutter - 2,
Math.max(7, Math.min(h - 2, l.pos + 3)));
} else {
ctx.fillText(hzLabel(l.f), l.pos, h - 3);
}
}
}
},
resize() { sizeCanvas(); },
destroy() { root.innerHTML = ''; },
};
}
+94
View File
@@ -0,0 +1,94 @@
{
"id": "spl-meter",
"name": "SPL Meter",
"version": "0.4.1",
"proddash": ">=1.5.0",
"description": "Calibrated sound level, Leq and RTA from an audio input on this machine",
"permissions": [
{
"kind": "microphone",
"reason": "Measuring sound level from an audio input on this machine"
}
],
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": {
"w": 2,
"h": 1
},
"defaultSize": {
"w": 3,
"h": 2
},
"configGroups": {
"Input": {
"toggle": "enabled"
},
"Measurement": {
"columns": 2
},
"Calibration": {
"collapsed": "whenSet",
"help": "A sound level calibrator fits over the microphone capsule and emits a known level, almost always 94 dB at 1 kHz. Put it on, press Measure beside the channel, and copy the offset it reports into the box. Without this the meter still works, but it reads in dB relative to full scale and every tile says so."
}
},
"configSchema": {
"enabled": {
"type": "switch",
"label": "Sound level measurement",
"group": "Input",
"default": false
},
"device": {
"type": "select",
"label": "Audio device",
"group": "Input",
"showWhen": "enabled",
"default": "",
"optionsRoute": "/devices"
},
"channels": {
"type": "string",
"label": "Channels on that device (1-based, comma separated)",
"group": "Input",
"showWhen": "enabled",
"default": "1",
"help": "One meter per channel — \"1\" for a single measurement mic, \"1,2\" for a stereo pair."
},
"weighting": {
"type": "select",
"label": "Weighting",
"group": "Measurement",
"default": "A",
"options": [
{
"value": "A",
"label": "A — how loud it sounds"
},
{
"value": "C",
"label": "C — keeps the low end"
},
{
"value": "Z",
"label": "Z — no weighting at all"
}
]
},
"bands": {
"type": "switch",
"label": "Spectrum analysis",
"group": "Measurement",
"default": true,
"help": "1/48-octave bands for the RTA and spectrogram tiles, which each fold them to their own banding. Turn it off if you only ever show the number."
},
"calibration": {
"type": "string",
"label": "Offsets in dB, one per channel",
"group": "Calibration",
"default": "",
"help": "Leave empty and every reading is dB relative to full scale, labelled dBFS so nobody mistakes it for real SPL."
}
}
}
+448
View File
@@ -0,0 +1,448 @@
'use strict';
/**
* SPL Meter server entry.
*
* Owns one capture child (spl-listener.js) and fans its frames out to every
* tile over SSE. Browsers never see the audio device, only the numbers.
*
* GET /stream → SSE, `state` events at the capture rate
* GET /state → the latest frame, for an instant first paint
* GET /devices → input devices, for the admin page's picker
* GET /channels → configured channels, for the tile gear picker
* POST /reset → clear Leq and peak hold
* GET /measure → what a calibrator is reading right now, so the
* admin page can tell the operator what to type
*
* Frames arrive 20×/s. That is the right rate for a meter to feel live and
* the wrong rate to re-broadcast blindly, so the SSE fan-out drops a frame
* whose numbers round to what the last one said.
*/
const path = require('path');
const { createSplListener } = require('./spl-listener');
/** Reference level of a sound level calibrator. Effectively always 94 dB. */
const CALIBRATOR_DB = 94;
/** How long /measure averages for. Long enough to ride out a wobble, short
enough that nobody standing at the microphone gets bored. */
const MEASURE_MS = 3000;
/** SSE comment ping — keeps idle connections alive through sleepy Wi-Fi. */
const PING_MS = 15000;
/**
* Below this, unweighted, the input is not quiet — it is not there.
*
* A real input always carries something: a microphone in a silent room still
* reads about -83 dBFS, and even a muted converter dithers around -120. Only
* a stream of actual zeros reaches the capture tool's -200 floor, and that
* means the device handed us nothing at all.
*/
const SILENCE_DBFS = -150;
/** How long that has to hold before saying so, so a gap between buffers or a
device changing sample rate mid-stream doesn't cry wolf. */
const SILENCE_GRACE_MS = 5000;
/** Set by init(), read by routes() — both are rebuilt together on re-init. */
let state = null;
/* ── shared tile settings ───────────────────────────────────────────── */
const CHANNEL_FIELD = {
type: 'select', label: 'Channel', default: '', optionsRoute: '/channels',
};
/**
* Averaging is a view choice, not a measurement one: the capture child
* computes all four every frame and sends all four, so one dashboard on Fast
* and another on Inf are reading the same measurement two ways.
*/
function averagingField() {
return {
type: 'select', label: 'Averaging', default: 'fast',
options: [
{ value: 'fast', label: 'Fast · 125 ms' },
{ value: 'slow', label: 'Slow · 1 s' },
{ value: 'inf', label: 'Inf · since reset' },
{ value: 'none', label: 'None' },
],
};
}
/**
* Banding folds the 1/48-octave bands on the wire down to something
* readable. Coarser is an exact sum of finer, so this costs nothing and
* disturbs no other tile.
*/
const BANDING_FIELD = {
type: 'select', label: 'Banding', default: '3',
options: [
{ value: '3', label: '1/3 octave' },
{ value: '6', label: '1/6 octave' },
{ value: '12', label: '1/12 octave' },
{ value: '24', label: '1/24 octave' },
{ value: '48', label: '1/48 octave' },
],
};
function parseChannels(raw) {
return String(raw || '1')
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => Number.isInteger(n) && n >= 1 && n <= 64);
}
function parseCalibration(raw) {
if (!String(raw || '').trim()) return [];
return String(raw)
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => Number.isFinite(n));
}
module.exports = {
init({ config, log }) {
const channels = parseChannels(config.channels);
const calibration = parseCalibration(config.calibration);
const moduleDir = __dirname;
state = {
channels,
calibrated: calibration.length === channels.length && channels.length > 0,
frame: null,
meta: null,
error: '',
streams: new Set(),
silentSince: null,
listener: null,
lastSent: '',
pinger: null,
};
if (!config.enabled) {
state.error = 'Sound level measurement is off — turn it on in ProdDash settings';
return { stop() { teardown(); }, health: () => ({ status: 'error', message: state.error }) };
}
if (!config.device) {
state.error = 'No audio device chosen yet';
return { stop() { teardown(); }, health: () => ({ status: 'error', message: state.error }) };
}
if (!channels.length) {
state.error = `Cannot read "${config.channels}" as a channel list — try 1, or 1,2`;
return { stop() { teardown(); }, health: () => ({ status: 'error', message: state.error }) };
}
if (calibration.length && calibration.length !== channels.length) {
state.error = `${channels.length} channel(s) but ${calibration.length} calibration offset(s) — `
+ 'give one per channel, or leave the offsets empty';
return { stop() { teardown(); }, health: () => ({ status: 'error', message: state.error }) };
}
state.listener = createSplListener({
device: config.device,
channels,
weighting: config.weighting || 'A',
bands: config.bands !== false,
calibration,
moduleDir,
log,
onUpdate(update) {
if (!state) return; // a frame in flight when the module unmounted
if (update.error) {
if (update.error !== state.error) log(update.error);
state.error = update.error;
state.frame = null;
broadcast();
return;
}
state.error = '';
state.frame = update.frame;
state.meta = update.meta;
// Digital silence on every channel is a dead input, not a reading.
// Saying "ok" through this is what made a stopped Dante device look
// like a frozen module for a day and a half.
const dead = update.frame.ch.every(
(c) => !Number.isFinite(c.dbfs) || c.dbfs <= SILENCE_DBFS);
state.silentSince = dead ? (state.silentSince || Date.now()) : null;
broadcast();
},
});
const mineStreams = state.streams;
state.pinger = setInterval(() => {
for (const res of mineStreams) {
try { res.write(': ping\n\n'); } catch { mineStreams.delete(res); }
}
}, PING_MS);
return {
stop() { teardown(); },
health() {
if (state.error) return { status: 'error', message: state.error };
if (!state.frame) return { status: 'connecting', message: 'waiting for the first reading' };
const quiet = silentMs();
if (quiet > SILENCE_GRACE_MS) {
return { status: 'error',
message: `No audio from ${config.device} — digital silence for ${describe(quiet)}` };
}
const n = state.channels.length;
const what = `${n} channel${n === 1 ? '' : 's'} on ${config.device}`;
return state.calibrated
? { status: 'ok', message: what }
: { status: 'ok', message: `${what} — uncalibrated, reading dBFS` };
},
};
},
/**
* Four tile kinds, each with only the settings that do something to it.
*
* An entry's own instanceSchema replaces the module's, which is the point:
* an RTA has no use for an alarm threshold and a readout has no use for a
* banding, and offering either is how a gear popover stops being read.
*
* Every setting here is a view choice. None of them reach the capture
* child — it already sends every averaging and the finest banding, so two
* dashboards can disagree about how to draw the same room.
*/
tiles() {
return [
{
id: 'readout', name: 'SPL', description: 'The level, big',
defaultSize: { w: 2, h: 1 }, minSize: { w: 1, h: 1 },
instanceGroups: { Thresholds: { columns: 2 } },
instanceSchema: {
channel: CHANNEL_FIELD,
averaging: averagingField(),
metric: {
type: 'select', label: 'Show', default: 'level',
options: [
{ value: 'level', label: 'Level' },
{ value: 'leq1m', label: 'Leq 1 min' },
{ value: 'leq10m', label: 'Leq 10 min' },
{ value: 'peakC', label: 'Peak C' },
],
},
caption: { type: 'switch', label: 'Caption', default: true },
warnAt: { type: 'number', label: 'Amber above', group: 'Thresholds', default: 95 },
alarmAt: { type: 'number', label: 'Red above', group: 'Thresholds', default: 100 },
},
},
{
id: 'bars', name: 'SPL Levels', description: 'One bar per channel, with peak hold',
defaultSize: { w: 3, h: 2 }, minSize: { w: 2, h: 1 },
instanceGroups: { Thresholds: { columns: 2 } },
instanceSchema: {
averaging: averagingField(),
peakHold: { type: 'switch', label: 'Peak hold', default: true },
warnAt: { type: 'number', label: 'Amber above', group: 'Thresholds', default: 95 },
alarmAt: { type: 'number', label: 'Red above', group: 'Thresholds', default: 100 },
},
},
{
id: 'rta', name: 'RTA', description: 'Spectrum now, at your choice of banding',
defaultSize: { w: 5, h: 3 }, minSize: { w: 3, h: 2 },
instanceSchema: {
channel: CHANNEL_FIELD,
averaging: averagingField(),
banding: BANDING_FIELD,
smoothing: {
type: 'select', label: 'Smoothing', default: 'medium',
options: [
{ value: 'off', label: 'Off' },
{ value: 'light', label: 'Light' },
{ value: 'medium', label: 'Medium' },
{ value: 'heavy', label: 'Heavy' },
],
},
labels: { type: 'switch', label: 'Labels', default: true },
gridlines: { type: 'switch', label: 'Gridlines', default: false },
},
},
{
id: 'spectrogram', name: 'Spectrogram', description: 'Spectrum over time',
defaultSize: { w: 5, h: 3 }, minSize: { w: 3, h: 2 },
instanceSchema: {
channel: CHANNEL_FIELD,
banding: BANDING_FIELD,
labels: { type: 'switch', label: 'Labels', default: true },
gridlines: { type: 'switch', label: 'Gridlines', default: false },
},
},
];
},
routes({ config, log }) {
return {
'GET /state': (req, res) => {
json(res, 200, snapshot());
},
'GET /stream': (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n');
try {
res.write(`event: state\ndata: ${JSON.stringify(snapshot())}\n\n`);
} catch { return; }
// Hold this mount's set, not `state`. teardown() nulls `state` and
// then ends every stream, which fires these close handlers — a
// handler that reached through `state` threw on null and took the
// whole server down with it, on any re-init with a browser
// connected. Deleting from a set nobody reads any more is harmless.
const streams = state.streams;
streams.add(res);
req.on('close', () => streams.delete(res));
},
/** Device list for the admin page. Runs the capture tool's --list,
which is the only thing that knows what CoreAudio can see. */
'GET /devices': async (req, res) => {
try {
const devices = await listDevices();
json(res, 200, {
options: devices.map((d) => ({
value: d.name,
label: `${d.name} — ${d.channels} ch @ ${Math.round(d.sampleRate)} Hz`,
})),
});
} catch (err) {
log(`device list failed: ${err.message}`);
json(res, 200, { options: [] }); // the saved value stays selectable
}
},
/** Channel list for a tile's gear popover. */
'GET /channels': (req, res) => {
json(res, 200, {
options: state.channels.map((c) => ({ value: String(c), label: `Channel ${c}` })),
});
},
'POST /reset': (req, res) => {
if (state.listener) state.listener.reset();
json(res, 200, { ok: true });
},
/**
* What the microphone is hearing right now, unweighted and
* uncalibrated, plus the offset that would make it read 94 dB.
*
* The module cannot write its own admin config, so this does not save
* anything — it hands back a number for the operator to paste into the
* Calibration box. Honest, if one step longer than it should be.
*/
'GET /measure': (req, res) => {
if (!state.listener || state.error) {
json(res, 409, { error: state.error || 'not measuring' });
return;
}
const wanted = Number(new URLSearchParams(req.search || '').get('channel'))
|| state.channels[0];
const samples = [];
const started = Date.now();
const tick = setInterval(() => {
if (!state) { clearInterval(tick); return; } // module unmounted mid-measure
const ch = state.frame && state.frame.ch.find((c) => c.i === wanted);
if (ch && Number.isFinite(ch.dbfs) && ch.dbfs > -200) samples.push(ch.dbfs);
if (Date.now() - started < MEASURE_MS) return;
clearInterval(tick);
if (samples.length < 5) {
json(res, 200, {
channel: wanted,
error: 'No steady tone on that channel — check the calibrator is on and seated',
});
return;
}
// Mean of the linear powers, not of the decibels: averaging dB
// would quietly under-read a signal that wobbles at all.
const power = samples.reduce((s, db) => s + 10 ** (db / 10), 0) / samples.length;
const measured = 10 * Math.log10(power);
json(res, 200, {
channel: wanted,
measured: Math.round(measured * 100) / 100,
reference: CALIBRATOR_DB,
offset: Math.round((CALIBRATOR_DB - measured) * 100) / 100,
samples: samples.length,
});
}, 100);
req.on('close', () => clearInterval(tick));
},
};
},
};
/* ── helpers ────────────────────────────────────────────────────────── */
/** How long every channel has been at digital silence, in ms. */
function silentMs() {
return state && state.silentSince ? Date.now() - state.silentSince : 0;
}
function describe(ms) {
const s = Math.round(ms / 1000);
if (s < 90) return `${s} s`;
const m = Math.round(s / 60);
return m < 90 ? `${m} min` : `${(m / 60).toFixed(1)} hours`;
}
function snapshot() {
if (!state) return { error: 'not measuring', calibrated: false, channels: [], frame: null, silentSec: 0 };
// Seconds, not milliseconds: this goes on the wire 20×/s and a value that
// changed every frame would make the fan-out's change check useless.
const quiet = silentMs();
return {
error: state.error,
silentSec: quiet > SILENCE_GRACE_MS ? Math.round(quiet / 1000) : 0,
calibrated: state.calibrated,
channels: state.channels,
weighting: state.meta ? state.meta.weighting : '',
bandCentres: state.meta ? state.meta.bands : [],
bandN0: state.meta ? state.meta.bandN0 : 0,
bandsPerOctave: state.meta ? state.meta.bandsPerOctave : 48,
frame: state.frame,
};
}
function broadcast() {
if (!state) return; // a listener callback landing after teardown
const payload = snapshot();
const line = JSON.stringify(payload);
if (line === state.lastSent) return; // nothing moved since last frame
state.lastSent = line;
for (const res of state.streams) {
try { res.write(`event: state\ndata: ${line}\n\n`); } catch { state.streams.delete(res); }
}
}
function teardown() {
if (!state) return;
if (state.listener) state.listener.stop();
clearInterval(state.pinger);
for (const res of state.streams) { try { res.end(); } catch { /* already gone */ } }
state.streams.clear();
state = null;
}
function listDevices() {
return new Promise((resolve, reject) => {
const { execFile } = require('child_process');
execFile(path.join(__dirname, 'spl-capture'), ['--list'], { timeout: 10000 },
(err, stdout) => {
if (err && !stdout) { reject(err); return; }
try { resolve(JSON.parse(stdout).devices || []); }
catch (e) { reject(e); }
});
});
}
function json(res, code, body) {
const text = JSON.stringify(body);
res.writeHead(code, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(text),
});
res.end(text);
}
+735
View File
@@ -0,0 +1,735 @@
// spl-capture — calibrated sound-level measurement from a CoreAudio input.
//
// Sibling of the Timers module's ltc-capture: same device enumeration, same
// "stdout is data, stderr is talk" contract, same one-file-no-dependencies
// rule. The difference is where the work happens. LTC ships raw samples to
// Node because the decode is cheap and single-channel; sound level is
// filtering and FFTs over every channel at the device's rate, so the
// measurement is done here and only the answers cross the pipe.
//
// Everything below uses Accelerate, which ships with macOS. No third-party
// code, no package manager, ~2 s to build:
//
// swiftc -O -o modules/spl-meter/spl-capture \
// modules/spl-meter/spl-capture.swift
//
// spl-capture --list
// every input-capable device: name, input channels, sample rate
// spl-capture --device "Dante Via 16 Channel" --channels 1,2 [--cal 0,0]
// measures those 1-based channels and writes one JSON line per frame
// to stdout, 20×/s. --cal takes one dB offset per channel, in the same
// order, from the calibration route (94 dB reference minus what we
// measured). With no --cal the numbers are dBFS-relative and the line
// says calibrated:false, so nothing downstream can mistake them for
// real SPL.
//
// Per channel, per frame: the level at EVERY averaging a dashboard might
// ask for — fast (125 ms), slow (1 s), inf (Leq since reset) and none (this
// block alone) — plus rolling 1- and 10-minute Leq, C- and Z-weighted peak,
// raw dBFS and a clip flag. Optionally a 1/48-octave band set for the RTA
// and spectrogram tiles, only when --bands is passed.
//
// Everything is sent every frame on purpose. Two dashboards watching the
// same room may want different averaging and different banding, and neither
// choice may disturb the other or restart capture. So the measurement is
// made once, at the finest resolution anyone asked for, and each tile folds
// it down to the view it wants. Nothing here is per-viewer state.
//
// Weighting filters are IEC 61672 pole/zero prototypes, bilinear-transformed
// with the top section prewarped, then normalised to exactly 0 dB at 1 kHz.
// Verified against the standard's table: within 0.15 dB from 31.5 Hz to
// 4 kHz. The top octave is where the bilinear transform runs out of room —
// at 48 kHz the 16 kHz point sits about 3 dB low. That is a rounding error
// on a broadband programme number (A-weighting has already thrown 6.6 dB
// away up there) but it is a real limit, and the fix if it ever matters is
// to run the weighting at 96 kHz. `--selftest` prints the table so this
// claim can be checked rather than believed.
//
// macOS asks for microphone permission on first use, and the prompt belongs
// to whatever launched this — the ProdDash launcher, or Terminal. A server
// started over SSH gets SILENT ZEROS from every input with no error at all,
// which shows up downstream as a meter pinned at the floor.
import AVFoundation
import Accelerate
import CoreAudio
import Foundation
func fail(_ msg: String) -> Never {
FileHandle.standardError.write(("spl-capture: " + msg + "\n").data(using: .utf8)!)
exit(2)
}
func note(_ msg: String) {
FileHandle.standardError.write(("spl-capture: " + msg + "\n").data(using: .utf8)!)
}
/* ── CoreAudio device enumeration ───────────────────────────────────── */
struct InputDevice {
let id: AudioDeviceID
let name: String
let uid: String
let channels: Int
let sampleRate: Double
}
func stringProperty(_ id: AudioObjectID, _ selector: AudioObjectPropertySelector) -> String {
var addr = AudioObjectPropertyAddress(
mSelector: selector, mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain)
var ref: Unmanaged<CFString>? = nil
var size = UInt32(MemoryLayout<Unmanaged<CFString>?>.size)
let err = withUnsafeMutablePointer(to: &ref) {
AudioObjectGetPropertyData(id, &addr, 0, nil, &size, $0)
}
guard err == noErr, let value = ref?.takeRetainedValue() else { return "" }
return value as String
}
func sampleRateProperty(_ id: AudioObjectID) -> Double {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyNominalSampleRate,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain)
var rate: Float64 = 0
var size = UInt32(MemoryLayout<Float64>.size)
guard AudioObjectGetPropertyData(id, &addr, 0, nil, &size, &rate) == noErr else { return 0 }
return rate
}
func inputChannelCount(_ id: AudioDeviceID) -> Int {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioDevicePropertyStreamConfiguration,
mScope: kAudioDevicePropertyScopeInput,
mElement: kAudioObjectPropertyElementMain)
var size: UInt32 = 0
guard AudioObjectGetPropertyDataSize(id, &addr, 0, nil, &size) == noErr, size > 0 else { return 0 }
let listPtr = UnsafeMutableRawPointer.allocate(
byteCount: Int(size), alignment: MemoryLayout<AudioBufferList>.alignment)
defer { listPtr.deallocate() }
guard AudioObjectGetPropertyData(id, &addr, 0, nil, &size, listPtr) == noErr else { return 0 }
let buffers = UnsafeMutableAudioBufferListPointer(
listPtr.assumingMemoryBound(to: AudioBufferList.self))
return buffers.reduce(0) { $0 + Int($1.mNumberChannels) }
}
func listInputDevices() -> [InputDevice] {
var addr = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain)
var size: UInt32 = 0
guard AudioObjectGetPropertyDataSize(
AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size) == noErr else { return [] }
var ids = [AudioDeviceID](repeating: 0, count: Int(size) / MemoryLayout<AudioDeviceID>.size)
guard AudioObjectGetPropertyData(
AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &ids) == noErr else { return [] }
var out: [InputDevice] = []
for id in ids {
let channels = inputChannelCount(id)
if channels == 0 { continue }
out.append(InputDevice(id: id,
name: stringProperty(id, kAudioObjectPropertyName),
uid: stringProperty(id, kAudioDevicePropertyDeviceUID),
channels: channels,
sampleRate: sampleRateProperty(id)))
}
return out
}
/* ── frequency weighting (IEC 61672) ────────────────────────────────── */
/// Pole frequencies from the standard.
private let wf1 = 2 * Double.pi * 20.598997
private let wf2 = 2 * Double.pi * 107.65265
private let wf3 = 2 * Double.pi * 737.86223
private let wf4 = 2 * Double.pi * 12194.217
/// Bilinear-transform one analogue biquad into [b0, b1, b2, a1, a2].
///
/// `warpAt` prewarps the transform so that section's critical frequency
/// lands where the analogue prototype put it. Without it the plain
/// `c = 2·fs` mapping squeezes the top octave badly — it is worth about
/// 3 dB at 16 kHz for the 12.2 kHz pole pair.
func bilinear(_ b: (Double, Double, Double), _ a: (Double, Double, Double),
fs: Double, warpAt: Double = 0) -> [Double] {
let c = warpAt > 0 ? warpAt / tan(warpAt / (2 * fs)) : 2 * fs
let c2 = c * c
let B0 = b.0 * c2 + b.1 * c + b.2
let B1 = 2 * b.2 - 2 * b.0 * c2
let B2 = b.0 * c2 - b.1 * c + b.2
let A0 = a.0 * c2 + a.1 * c + a.2
let A1 = 2 * a.2 - 2 * a.0 * c2
let A2 = a.0 * c2 - a.1 * c + a.2
return [B0 / A0, B1 / A0, B2 / A0, A1 / A0, A2 / A0]
}
/// |H(f)| of a cascade of biquad sections, used to normalise gain at 1 kHz
/// and to print the verification table.
func cascadeResponse(_ secs: [Double], _ f: Double, fs: Double) -> Double {
let th = 2 * Double.pi * f / fs
var reT = 1.0, imT = 0.0
for s in stride(from: 0, to: secs.count, by: 5) {
let (b0, b1, b2, a1, a2) = (secs[s], secs[s+1], secs[s+2], secs[s+3], secs[s+4])
let nr = b0 + b1 * cos(th) + b2 * cos(2 * th)
let ni = -(b1 * sin(th) + b2 * sin(2 * th))
let dr = 1 + a1 * cos(th) + a2 * cos(2 * th)
let di = -(a1 * sin(th) + a2 * sin(2 * th))
let dd = dr * dr + di * di
guard dd > 0 else { return 0 }
let qr = (nr * dr + ni * di) / dd, qi = (ni * dr - nr * di) / dd
let t = reT * qr - imT * qi
imT = reT * qi + imT * qr
reT = t
}
return (reT * reT + imT * imT).squareRoot()
}
enum Weighting: String {
case a = "A", c = "C", z = "Z"
/// Biquad sections for this weighting at `fs`, normalised to 0 dB at 1 kHz.
func sections(fs: Double) -> [Double] {
var s: [Double]
switch self {
case .a:
s = bilinear((1, 0, 0), (1, 2 * wf1, wf1 * wf1), fs: fs)
+ bilinear((1, 0, 0), (1, wf2 + wf3, wf2 * wf3), fs: fs)
+ bilinear((0, 0, 1), (1, 2 * wf4, wf4 * wf4), fs: fs, warpAt: wf4)
case .c:
s = bilinear((1, 0, 0), (1, 2 * wf1, wf1 * wf1), fs: fs)
+ bilinear((0, 0, 1), (1, 2 * wf4, wf4 * wf4), fs: fs, warpAt: wf4)
case .z:
return [1, 0, 0, 0, 0] // flat, one pass-through section
}
let g = 1.0 / cascadeResponse(s, 1000.0, fs: fs)
s[0] *= g; s[1] *= g; s[2] *= g
return s
}
}
/// A weighting filter bound to one channel. The coefficients could be shared
/// but the delay line cannot, and a setup per channel costs a few hundred
/// bytes — not worth the aliasing risk of sharing one.
final class WeightingFilter {
private let setup: vDSP_biquad_Setup
private var delay: [Float]
private let sections: vDSP_Length
init(_ weighting: Weighting, fs: Double) {
let coeffs = weighting.sections(fs: fs)
sections = vDSP_Length(coeffs.count / 5)
guard let s = vDSP_biquad_CreateSetup(coeffs, sections) else {
fail("cannot build \(weighting.rawValue)-weighting filter")
}
setup = s
delay = [Float](repeating: 0, count: Int(sections) * 2 + 2)
}
deinit { vDSP_biquad_DestroySetup(setup) }
func process(_ input: UnsafePointer<Float>, _ output: inout [Float], _ n: Int) {
vDSP_biquad(setup, &delay, input, 1, &output, 1, vDSP_Length(n))
}
}
/* ── third-octave band plan for the RTA ─────────────────────────────── */
/// The wire always carries 1/48-octave bands, and a tile folds them down to
/// whatever banding it wants to draw.
///
/// That works exactly because every banding the dashboard offers divides 48:
/// 1/3 is sixteen of these summed, 1/6 is eight, 1/12 four, 1/24 two. Powers
/// are additive, so a fold is a sum and nothing is approximated. The
/// alternative — the capture re-banding on request — would mean one dashboard
/// choosing 1/6 changes what every other dashboard sees.
///
/// Band n is centred on 1000 · 2^(n/48); n = 0 is 1 kHz, which is what keeps
/// the folded centres on the standard values.
let bandN0 = -271 // ≈ 20 Hz
let bandN1 = 207 // ≈ 20 kHz
let bandCentres: [Double] = (bandN0...bandN1).map { 1000 * pow(2, Double($0) / 48) }
/// FFT bin ranges per band, clamped to what the transform can actually
/// resolve.
///
/// This is the one caveat a reader of the RTA needs and the gear is not
/// allowed to carry (module rule 5, no explanatory text in a tile's
/// settings): below roughly 200 Hz a 1/48-octave band is narrower than one
/// bin, so neighbouring bands start sharing bins and the low end reads
/// smoother than it really is. That is the window length talking, not the
/// room. Folding to 1/6 or 1/3 puts it right, and a multi-resolution
/// transform is the real fix if the bottom octaves ever have to be read at
/// full resolution.
func bandBins(fs: Double, fftSize: Int) -> [(Int, Int)] {
let binHz = fs / Double(fftSize)
let maxBin = fftSize / 2 - 1
return bandCentres.map { fc in
let lo = Int((fc * pow(2, -1.0 / 96.0) / binHz).rounded())
let hi = Int((fc * pow(2, 1.0 / 96.0) / binHz).rounded())
return (max(1, min(lo, maxBin)), max(1, min(max(hi, lo), maxBin)))
}
}
/* ── per-channel measurement state ──────────────────────────────────── */
/// Everything the standard asks for on one channel.
///
/// SPL is an exponential moving average of weighted mean square — Fast is a
/// 125 ms time constant, Slow 1 s, exactly as IEC 61672 defines them. Leq is
/// a plain energy average with no time constant at all, which is why it is
/// accumulated separately rather than read off the integrator.
final class ChannelMeter {
let index: Int // 1-based, as the operator counts them
private let fs: Double
private let calibration: Double // dB added to turn dBFS into dB SPL
private let weightFilter: WeightingFilter
private let cFilter: WeightingFilter
private var weighted: [Float]
private var cWeighted: [Float]
// One integrator per averaging the dashboard might ask for. They all run
// all the time and all go on the wire: a tile choosing "Slow" must not
// restart capture, because the next tile wants "Fast" off the same
// stream and a third wants Inf. Four extra doubles per channel is a
// rounding error next to the filtering; re-measuring per viewer is not.
private var msFast: Double = 0
private var msSlow: Double = 0
private var msNone: Double = 0 // this block only, no time constant
private var flatMeanSquare: Double = 0 // unweighted, Fast — for dBFS
private let alphaFast: Double
private let alphaSlow: Double
// Leq accumulators: running since reset, plus rolling 1 and 10 minute.
private var leqSum: Double = 0
private var leqCount: Double = 0
private var ring: [Double] = [] // one mean-square per emitted frame
private let ringCapacity: Int
private var peakC: Double = 0 // linear, since reset
private var peakZ: Double = 0
private var clipped = false
init(index: Int, fs: Double, weighting: Weighting, calibration: Double,
framesPerSecond: Double) {
self.index = index
self.fs = fs
self.calibration = calibration
weightFilter = WeightingFilter(weighting, fs: fs)
cFilter = WeightingFilter(.c, fs: fs)
weighted = []
cWeighted = []
// The time constants IEC 61672 names: Fast is 125 ms, Slow is 1 s.
alphaFast = 1.0 - exp(-1.0 / (0.125 * fs))
alphaSlow = 1.0 - exp(-1.0 / (1.0 * fs))
ringCapacity = Int((600.0 * framesPerSecond).rounded()) // 10 minutes
}
/// Feed one tap buffer for this channel.
func push(_ samples: UnsafePointer<Float>, _ n: Int) {
if weighted.count < n {
weighted = [Float](repeating: 0, count: n)
cWeighted = [Float](repeating: 0, count: n)
}
weightFilter.process(samples, &weighted, n)
cFilter.process(samples, &cWeighted, n)
// Exponential integration over the weighted signal, sample by sample
// in the power domain. vDSP has no one-pole on squares, and at 48 kHz
// this is a few hundred thousand multiply-adds a second — noise next
// to the filtering above.
var fast = msFast, slow = msSlow, flat = flatMeanSquare
weighted.withUnsafeBufferPointer { w in
for i in 0..<n {
let v = Double(w[i]) * Double(w[i])
fast += alphaFast * (v - fast)
slow += alphaSlow * (v - slow)
let r = Double(samples[i])
flat += alphaFast * (r * r - flat)
}
}
msFast = fast; msSlow = slow; flatMeanSquare = flat
// Mean square of just this block — "None", the reading with no time
// constant at all. Also what Leq accumulates, since Leq is a plain
// energy average and has no time constant either.
var sumSq: Float = 0
weighted.withUnsafeBufferPointer { w in
vDSP_measqv(w.baseAddress!, 1, &sumSq, vDSP_Length(n))
}
msNone = Double(sumSq)
leqSum += Double(sumSq) * Double(n)
leqCount += Double(n)
var cPeak: Float = 0, zPeak: Float = 0
cWeighted.withUnsafeBufferPointer { c in
vDSP_maxmgv(c.baseAddress!, 1, &cPeak, vDSP_Length(n))
}
vDSP_maxmgv(samples, 1, &zPeak, vDSP_Length(n))
peakC = max(peakC, Double(cPeak))
peakZ = max(peakZ, Double(zPeak))
if zPeak >= 0.999 { clipped = true }
}
/// dB SPL from a linear mean-square, with the calibration offset applied.
private func db(_ power: Double) -> Double {
20 * log10(max(power, 1e-20).squareRoot()) + calibration
}
/// Called once per emitted frame; also advances the rolling Leq window.
///
/// Returns a JSON object built by hand. JSONSerialization renders a
/// rounded Double as `-70.120000000000005`, which is both ugly on the
/// wire and noise in a diff — `%.2f` says what a meter can actually
/// resolve and nothing more.
func snapshot() -> String {
ring.append(msNone)
if ring.count > ringCapacity { ring.removeFirst(ring.count - ringCapacity) }
let fps = Double(ringCapacity) / 600.0
func rollingLeq(seconds: Double) -> Double {
let want = max(1, Int((seconds * fps).rounded()))
let slice = ring.suffix(want)
guard !slice.isEmpty else { return -200 }
return db(slice.reduce(0, +) / Double(slice.count))
}
return "{\"i\":\(index)"
+ f("fast", db(msFast))
+ f("slow", db(msSlow))
+ f("inf", leqCount > 0 ? db(leqSum / leqCount) : -200)
+ f("none", db(msNone))
+ f("leq1m", rollingLeq(seconds: 60))
+ f("leq10m", rollingLeq(seconds: 600))
+ f("peakC", db(peakC * peakC))
+ f("peakZ", db(peakZ * peakZ))
+ f("dbfs", 20 * log10(max(flatMeanSquare, 1e-20).squareRoot()))
+ ",\"clip\":\(clipped)}"
}
/// Clears Leq, peaks and the clip flag. The exponential integrator is
/// deliberately left alone — it is a live reading, not an accumulation,
/// and zeroing it would just make the meter dive for a moment.
func reset() {
leqSum = 0; leqCount = 0; ring.removeAll(keepingCapacity: true)
peakC = 0; peakZ = 0; clipped = false
}
}
/// `,"key":-12.34` — two decimals, and a floor instead of -inf or NaN so a
/// silent input can never put a non-number on the wire.
func f(_ key: String, _ v: Double) -> String {
",\"\(key)\":" + num(v)
}
func num(_ v: Double) -> String {
guard v.isFinite else { return "-200.00" }
return String(format: "%.2f", max(v, -200))
}
/// One decimal, for band arrays. 479 bands per channel per frame is the
/// bulk of the wire; a second decimal on a bar nobody can read that finely
/// is 15% of the bandwidth for nothing.
func num1(_ v: Double) -> String {
guard v.isFinite else { return "-200" }
return String(format: "%.1f", max(v, -200))
}
/* ── spectrum for the RTA / spectrograph tiles ──────────────────────── */
final class Spectrum {
private let fftSize: Int
private let log2n: vDSP_Length
private let setup: FFTSetup
private var window: [Float]
private var accum: [Float] // sliding input buffer
private var filled = 0
private let bins: [(Int, Int)]
private let windowPower: Double
init(fs: Double, fftSize: Int) {
self.fftSize = fftSize
log2n = vDSP_Length(log2(Double(fftSize)).rounded())
guard let s = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else {
fail("cannot create FFT setup")
}
setup = s
window = [Float](repeating: 0, count: fftSize)
vDSP_hann_window(&window, vDSP_Length(fftSize), Int32(vDSP_HANN_DENORM))
accum = [Float](repeating: 0, count: fftSize)
bins = bandBins(fs: fs, fftSize: fftSize)
// Coherent gain of the Hann window, so band levels are not 6 dB low.
windowPower = window.reduce(0.0) { $0 + Double($1) * Double($1) } / Double(fftSize)
}
deinit { vDSP_destroy_fftsetup(setup) }
/// Keep the most recent `fftSize` samples, shifting the window along.
/// Buffers larger than the window just overwrite it outright.
func push(_ samples: UnsafePointer<Float>, _ n: Int) {
if n >= fftSize {
accum.withUnsafeMutableBufferPointer { a in
a.baseAddress!.update(from: samples + (n - fftSize), count: fftSize)
}
filled = fftSize
return
}
accum.withUnsafeMutableBufferPointer { a in
let base = a.baseAddress!
// Slide the old tail down, then append the new block.
base.update(from: base + n, count: fftSize - n)
(base + fftSize - n).update(from: samples, count: n)
}
filled = min(fftSize, filled + n)
}
/// Third-octave band levels in dB relative to full scale, plus the
/// calibration offset applied by the caller.
func bands(calibration: Double) -> [Double] {
guard filled >= fftSize else { return bins.map { _ in -200 } }
var windowed = [Float](repeating: 0, count: fftSize)
vDSP_vmul(accum, 1, window, 1, &windowed, 1, vDSP_Length(fftSize))
let half = fftSize / 2
var re = [Float](repeating: 0, count: half)
var im = [Float](repeating: 0, count: half)
var mag = [Float](repeating: 0, count: half)
re.withUnsafeMutableBufferPointer { rp in
im.withUnsafeMutableBufferPointer { ip in
var split = DSPSplitComplex(realp: rp.baseAddress!, imagp: ip.baseAddress!)
windowed.withUnsafeBytes { raw in
vDSP_ctoz(raw.bindMemory(to: DSPComplex.self).baseAddress!, 2,
&split, 1, vDSP_Length(half))
}
vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(FFT_FORWARD))
vDSP_zvmags(&split, 1, &mag, 1, vDSP_Length(half))
}
}
// vDSP's real FFT carries a factor of 2, and zvmags squares it.
let scale = 1.0 / (4.0 * Double(fftSize) * Double(fftSize) * windowPower)
return bins.map { (lo, hi) in
var power = 0.0
for b in lo...hi { power += Double(mag[b]) }
power *= scale * 2.0 // one-sided spectrum
return 10 * log10(max(power, 1e-20)) + calibration
}
}
}
/* ── args ───────────────────────────────────────────────────────────── */
var wantList = false
var wantSelftest = false
var wantDevice: String? = nil
var wantChannels: [Int] = [1]
var wantCal: [Double] = []
var wantWeighting = Weighting.a
var wantBands = false
var framesPerSecond = 20.0
let argv = CommandLine.arguments
var argIdx = 1
func nextArg(_ flag: String) -> String {
argIdx += 1
guard argIdx < argv.count else { fail("\(flag) needs a value") }
return argv[argIdx]
}
while argIdx < argv.count {
switch argv[argIdx] {
case "--list": wantList = true
case "--selftest": wantSelftest = true
case "--device": wantDevice = nextArg("--device")
case "--channels":
wantChannels = nextArg("--channels").split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
if wantChannels.isEmpty { fail("--channels needs at least one 1-based channel number") }
case "--cal":
wantCal = nextArg("--cal").split(separator: ",").compactMap { Double($0.trimmingCharacters(in: .whitespaces)) }
case "--weighting":
let raw = nextArg("--weighting").uppercased()
guard let w = Weighting(rawValue: raw) else { fail("--weighting must be A, C or Z") }
wantWeighting = w
case "--bands": wantBands = true
case "--rate":
guard let r = Double(nextArg("--rate")), r >= 1, r <= 50 else { fail("--rate must be 1-50 (frames per second)") }
framesPerSecond = r
default: fail("unknown flag \(argv[argIdx]) — try --list")
}
argIdx += 1
}
/* ── selftest: prove the weighting curves before trusting a reading ─── */
if wantSelftest {
// IEC 61672-1 table 3, nominal A- and C-weighting.
let table: [(Double, Double, Double)] = [
(31.5, -39.4, -3.0), (63, -26.2, -0.8), (125, -16.1, -0.2), (250, -8.6, 0.0),
(500, -3.2, 0.0), (1000, 0.0, 0.0), (2000, 1.2, -0.2), (4000, 1.0, -0.8),
(8000, -1.1, -3.0), (16000, -6.6, -8.5),
]
for fs in [48000.0, 96000.0] {
let a = Weighting.a.sections(fs: fs), c = Weighting.c.sections(fs: fs)
print("— \(Int(fs)) Hz —")
print(" Hz A IEC err C IEC err")
var worstA = 0.0, worstC = 0.0
for (f, wantA, wantC) in table where f < fs / 2 {
let gotA = 20 * log10(cascadeResponse(a, f, fs: fs))
let gotC = 20 * log10(cascadeResponse(c, f, fs: fs))
worstA = max(worstA, abs(gotA - wantA)); worstC = max(worstC, abs(gotC - wantC))
print(String(format: "%7.0f %+7.2f %+7.2f %+6.2f %+7.2f %+7.2f %+6.2f",
f, gotA, wantA, gotA - wantA, gotC, wantC, gotC - wantC))
}
print(String(format: " worst: A %.2f dB, C %.2f dB\n", worstA, worstC))
}
exit(0)
}
/* ── device selection ───────────────────────────────────────────────── */
let devices = listInputDevices()
if wantList || wantDevice == nil {
if devices.isEmpty { fail("no input-capable audio devices found") }
// stdout, as JSON: the module's /devices route feeds this straight to
// the admin page's device picker.
let payload = devices.map { ["name": $0.name, "uid": $0.uid,
"channels": $0.channels, "sampleRate": $0.sampleRate] }
let data = try! JSONSerialization.data(withJSONObject: ["devices": payload])
FileHandle.standardOutput.write(data)
FileHandle.standardOutput.write("\n".data(using: .utf8)!)
if wantDevice == nil && !wantList { note("pick one with --device <name substring>") }
exit(wantList ? 0 : 2)
}
let query = wantDevice!.lowercased()
let exact = devices.filter { $0.name.lowercased() == query || $0.uid.lowercased() == query }
let matches = exact.count == 1 ? exact
: devices.filter { $0.name.lowercased().contains(query) || $0.uid.lowercased().contains(query) }
guard matches.count == 1 else {
if matches.isEmpty { fail("no input device matches \"\(wantDevice!)\" — see --list") }
fail("\"\(wantDevice!)\" is ambiguous: " + matches.map { $0.name }.joined(separator: ", "))
}
let device = matches[0]
/* ── capture ────────────────────────────────────────────────────────── */
let engine = AVAudioEngine()
guard let unit = engine.inputNode.audioUnit else { fail("no input audio unit") }
var deviceID = device.id
let setErr = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global, 0, &deviceID,
UInt32(MemoryLayout<AudioDeviceID>.size))
guard setErr == noErr else { fail("cannot select \"\(device.name)\" (error \(setErr))") }
let format = engine.inputNode.inputFormat(forBus: 0)
let channelCount = Int(format.channelCount)
let sampleRate = format.sampleRate
guard channelCount > 0, sampleRate > 0 else {
fail("\"\(device.name)\" reports no usable input format — microphone access may be denied "
+ "(System Settings → Privacy & Security → Microphone)")
}
for ch in wantChannels where ch < 1 || ch > channelCount {
fail("channel \(ch) is out of range — \"\(device.name)\" has \(channelCount)")
}
let calibrated = !wantCal.isEmpty
if calibrated && wantCal.count != wantChannels.count {
fail("--cal needs one offset per channel (\(wantChannels.count) given \(wantCal.count))")
}
let meters = wantChannels.enumerated().map { (i, ch) in
ChannelMeter(index: ch, fs: sampleRate, weighting: wantWeighting,
calibration: calibrated ? wantCal[i] : 0, framesPerSecond: framesPerSecond)
}
let spectra = wantBands ? wantChannels.map { _ in Spectrum(fs: sampleRate, fftSize: 16384) } : []
note("capturing \"\(device.name)\": \(channelCount) channels @ \(Int(sampleRate)) Hz, "
+ "measuring \(wantChannels.map(String.init).joined(separator: ",")) "
+ "\(wantWeighting.rawValue)-weighted"
+ (calibrated ? "" : ", UNCALIBRATED"))
// Announced once so the reader knows the band plan without hardcoding it.
let hello: [String: Any] = [
"hello": 1,
"device": device.name,
"sampleRate": sampleRate,
"deviceChannels": channelCount,
"channels": wantChannels,
"weighting": wantWeighting.rawValue,
"calibrated": calibrated,
// Centres and the index of the 1 kHz band, so a tile can fold to any
// banding without hardcoding the plan.
"bands": wantBands ? bandCentres.map { round($0 * 100) / 100 } : [],
"bandN0": bandN0,
"bandsPerOctave": 48,
]
let stdoutHandle = FileHandle.standardOutput
func emitLine(_ json: String) {
do {
try stdoutHandle.write(contentsOf: Data((json + "\n").utf8))
} catch { exit(0) } // downstream pipe closed — nothing to say
}
if let data = try? JSONSerialization.data(withJSONObject: hello),
let line = String(data: data, encoding: .utf8) {
emitLine(line)
}
// A reset is asked for on stdin (one line, "reset") rather than a signal, so
// the listener can clear Leq and peaks without restarting capture and losing
// the filters' settling.
let resetQueue = DispatchQueue(label: "spl-capture.reset")
var resetRequested = false
DispatchQueue.global().async {
while let line = readLine(strippingNewline: true) {
if line.trimmingCharacters(in: .whitespaces).lowercased() == "reset" {
resetQueue.sync { resetRequested = true }
}
}
}
let tapQueue = DispatchQueue(label: "spl-capture.tap")
engine.inputNode.installTap(onBus: 0, bufferSize: 2048, format: format) { buffer, _ in
let frames = Int(buffer.frameLength)
guard frames > 0, let floats = buffer.floatChannelData else { return }
tapQueue.sync {
for (i, ch) in wantChannels.enumerated() {
let src = floats[ch - 1] // tap data is per-channel, not interleaved
meters[i].push(src, frames)
if wantBands { spectra[i].push(src, frames) }
}
}
}
do { try engine.start() } catch {
fail("engine start failed: \(error.localizedDescription) — if this is a permission problem, "
+ "approve microphone access for the launching app and retry")
}
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer.schedule(deadline: .now() + 1.0 / framesPerSecond,
repeating: 1.0 / framesPerSecond)
timer.setEventHandler {
var wantReset = false
resetQueue.sync { wantReset = resetRequested; resetRequested = false }
var line = "{\"t\":\(Int(Date().timeIntervalSince1970 * 1000))"
tapQueue.sync {
if wantReset { meters.forEach { $0.reset() } }
line += ",\"ch\":[" + meters.map { $0.snapshot() }.joined(separator: ",") + "]"
if wantBands {
let sets = spectra.enumerated().map { (i, s) -> String in
"[" + s.bands(calibration: calibrated ? wantCal[i] : 0)
.map(num1).joined(separator: ",") + "]"
}
line += ",\"bands\":[" + sets.joined(separator: ",") + "]"
}
}
emitLine(line + "}")
}
timer.resume()
signal(SIGINT) { _ in exit(0) }
signal(SIGTERM) { _ in exit(0) }
RunLoop.main.run()
+239
View File
@@ -0,0 +1,239 @@
'use strict';
/**
* Sound level listener — owns the native capture child.
*
* Spawns spl-capture (compiled from spl-capture.swift beside it) for the
* admin-configured device and channels, reads its JSON lines, and hands the
* latest frame upward. All measurement happens in the child; this file is
* plumbing and supervision, nothing more.
*
* Reports via onUpdate:
*
* { frame: {...}, meta: {...} } measuring
* { error: '<what is wrong and how to fix it>' } not measuring
*
* The capture binary is per-machine and gitignored, exactly like the Timers
* module's ltc-capture. It normally arrives already built — compiled beside
* the app, or copied from any Mac of the same architecture. When it is
* missing this will build it, but in the background and never on the event
* loop: see ensureBinary for what that cost the first time it was wrong.
*
* The same macOS gotcha applies as for LTC, and is worth repeating because
* it costs an afternoon every time: a ProdDash launched over SSH or from a
* bare launchd job gets SILENT ZEROS from every input, with no error
* anywhere. Here that shows up as a meter pinned at -200. Launch from a
* logged-in GUI context and approve the microphone prompt once.
*/
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');
const RESTART_MS = 5000;
/** An immediate exit is config-shaped (bad device, channel out of range) —
retrying every 5 s would only fill the log with the same sentence. */
const BAD_CONFIG_RETRY_MS = 30000;
/** No frame for this long means the child is alive but not delivering. */
const STALL_MS = 3000;
/**
* @param {{device:string, channels:number[], weighting:string,
* bands:boolean, calibration:number[], moduleDir:string,
* log:Function, onUpdate:(u:object)=>void}} opts
* @returns {{stop:()=>void, reset:()=>void}}
*/
function createSplListener(opts) {
const { device, channels, weighting, bands, calibration, moduleDir, log, onUpdate } = opts;
const bin = path.join(moduleDir, 'spl-capture');
let child = null;
let stopped = false;
let restartTimer = null;
let stallTimer = null;
let startedAt = 0;
let meta = null;
let building = false;
let buildFailed = false;
let lastFrameWall = 0;
const BUILD_HELP = 'Sound level capture tool missing — build it on any Apple Silicon Mac with '
+ '`swiftc -O -o modules/spl-meter/spl-capture modules/spl-meter/spl-capture.swift` '
+ 'and copy it next to spl-capture.swift';
/**
* Build the capture tool if it is missing, WITHOUT blocking.
*
* This used to be a spawnSync, copied from the LTC listener where the
* source is a third the size and builds in a few seconds. Here it took
* nearly two minutes on the production Mac and froze the entire ProdDash
* server for every second of it — one module's optional helper took the
* whole dashboard down, then did it again on every retry. Nothing that
* runs while a service might be on is allowed to hold the event loop.
*
* The build is a fallback for a module installed from the catalog on a
* machine with a Swift toolchain. The normal path is a binary built
* alongside the app, or copied from any same-architecture Mac.
*
* @returns {string} '' when the binary is ready, otherwise what to say.
*/
function ensureBinary() {
if (fs.existsSync(bin)) return '';
const src = bin + '.swift';
if (!fs.existsSync(src)) return 'spl-capture.swift is missing from the module folder';
if (building) return 'Building the capture tool — this takes a minute or two';
if (buildFailed) return BUILD_HELP;
building = true;
log('spl-capture binary missing — building it in the background');
const build = spawn('swiftc', ['-O', '-o', bin, src], { stdio: ['ignore', 'ignore', 'pipe'] });
let buildErr = '';
build.stderr.setEncoding('utf8');
build.stderr.on('data', (t) => { buildErr = (buildErr + t).slice(-800); });
const giveUp = setTimeout(() => {
try { build.kill('SIGKILL'); } catch { /* already gone */ }
}, 300000);
build.on('error', (err) => {
clearTimeout(giveUp);
building = false; buildFailed = true;
log(`swiftc could not be run: ${err.message}`);
});
build.on('exit', (code) => {
clearTimeout(giveUp);
building = false;
if (code === 0 && fs.existsSync(bin)) {
log('spl-capture built');
buildFailed = false;
if (!stopped) { clearTimeout(restartTimer); restartTimer = null; start(); }
return;
}
buildFailed = true;
log(`spl-capture build failed (exit ${code})` + (buildErr ? `: ${buildErr.trim().split('\n').pop()}` : ''));
});
return 'Building the capture tool — this takes a minute or two';
}
function scheduleRestart(ms) {
if (stopped || restartTimer) return;
restartTimer = setTimeout(() => { restartTimer = null; start(); }, ms);
}
function armStallWatch() {
clearTimeout(stallTimer);
stallTimer = setTimeout(() => {
if (stopped || !child) return;
if (Date.now() - lastFrameWall >= STALL_MS) {
log('no frames for 3 s — restarting capture');
try { child.kill('SIGTERM'); } catch { /* already gone */ }
}
}, STALL_MS);
}
function start() {
if (stopped) return;
const missing = ensureBinary();
if (missing) {
onUpdate({ error: missing });
// A build in flight calls start() itself when it lands; anything else
// is config-shaped and should back off hard rather than spin.
if (!building) scheduleRestart(BAD_CONFIG_RETRY_MS);
return;
}
// No averaging or banding flag: the child computes every averaging and
// the finest banding regardless, so tiles can differ without a restart.
const args = ['--device', device, '--channels', channels.join(','),
'--weighting', weighting, '--rate', '20'];
if (bands) args.push('--bands');
if (calibration.length === channels.length) args.push('--cal', calibration.join(','));
startedAt = Date.now();
meta = null;
let stderrTail = '';
let buf = '';
child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] });
child.stderr.setEncoding('utf8');
child.stderr.on('data', (text) => {
stderrTail = (stderrTail + text).slice(-500);
});
child.stdout.setEncoding('utf8');
child.stdout.on('data', (text) => {
buf += text;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i).trim();
buf = buf.slice(i + 1);
if (!line) continue;
let obj;
try { obj = JSON.parse(line); } catch { continue; }
if (obj.hello) {
meta = obj;
log(`measuring ${obj.device} ch ${obj.channels.join(',')} `
+ `${obj.weighting}-weighted`
+ (obj.calibrated ? '' : ' (uncalibrated)'));
continue;
}
if (!obj.ch) continue;
lastFrameWall = Date.now();
armStallWatch();
onUpdate({ frame: obj, meta });
}
// A run of junk with no newline would grow forever; the child never
// emits a line this long, so anything that does is a bug upstream.
if (buf.length > 65536) buf = '';
});
child.on('error', (err) => {
onUpdate({ error: `cannot run spl-capture: ${err.message}` });
child = null;
scheduleRestart(BAD_CONFIG_RETRY_MS);
});
child.on('exit', (code, signal) => {
child = null;
clearTimeout(stallTimer);
if (stopped) return;
const ranFor = Date.now() - startedAt;
const why = stderrTail.trim().split('\n').pop() || `exit ${code}${signal ? ' ' + signal : ''}`;
// Exiting almost immediately means it never got as far as capturing —
// an unknown device, an out-of-range channel, a denied microphone.
// Those do not fix themselves, so back off hard and say why.
if (ranFor < 2000) {
onUpdate({ error: why });
scheduleRestart(BAD_CONFIG_RETRY_MS);
} else {
log(`capture exited after ${Math.round(ranFor / 1000)}s: ${why}`);
scheduleRestart(RESTART_MS);
}
});
armStallWatch();
}
start();
return {
/** Clear Leq and peak hold without restarting capture — the filters keep
their settling, so the live number never dips. */
reset() {
if (child && child.stdin.writable) {
try { child.stdin.write('reset\n'); } catch { /* child going away */ }
}
},
stop() {
stopped = true;
clearTimeout(restartTimer); restartTimer = null;
clearTimeout(stallTimer); stallTimer = null;
if (child) {
try { child.kill('SIGTERM'); } catch { /* already gone */ }
child = null;
}
},
};
}
module.exports = { createSplListener };
+154
View File
@@ -0,0 +1,154 @@
/* SPL Meter — every colour comes from the shell's variables so themes and
per-tile tints reach in. Nothing here is hardcoded except the canvas
heat ramp, which client.js owns because it has to interpolate. */
[data-module="spl-meter"] .spl {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
/* ── readout ──────────────────────────────────────────────────────── */
[data-module="spl-meter"] .spl-readout {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.25em;
min-height: 0;
padding: 0.25rem;
}
[data-module="spl-meter"] .spl-value {
display: flex;
align-items: baseline;
gap: 0.2em;
line-height: 1;
color: var(--text);
}
/* A first-paint size only. client.js measures the text and sets the real
one inline, because CSS has to assume a digit count and gets it wrong the
moment the reading needs a sixth character: the coefficient that fills a
tile for "-45.9" pushes "-100.5" straight out through the side. */
[data-module="spl-meter"] .spl-num {
font-size: clamp(1.25rem, min(26cqw, 60cqh), 100rem);
font-variant-numeric: tabular-nums;
font-weight: 600;
letter-spacing: -0.02em;
}
[data-module="spl-meter"] .spl-unit {
font-size: clamp(0.65rem, min(7cqw, 15cqh), 26rem);
color: var(--muted);
}
[data-module="spl-meter"] .spl-sub {
font-size: 0.7rem;
color: var(--muted);
text-align: center;
line-height: 1.3;
}
[data-module="spl-meter"] .spl-readout[data-level="warn"] .spl-num { color: var(--warn); }
[data-module="spl-meter"] .spl-readout[data-level="alarm"] .spl-num { color: var(--danger); }
[data-module="spl-meter"] .spl-readout[data-level="idle"] .spl-num { color: var(--muted); }
/* A dead input reads danger, not muted: silence that is a fault should not
look like silence that is a quiet room. */
[data-module="spl-meter"] .spl-readout[data-level="dead"] .spl-num { color: var(--danger); }
[data-module="spl-meter"] .spl-readout[data-level="dead"] .spl-sub { color: var(--danger); }
/* ── level bars ───────────────────────────────────────────────────── */
[data-module="spl-meter"] .spl-bars {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
gap: 0.35rem;
padding: 0.4rem;
min-height: 0;
overflow-y: auto;
}
[data-module="spl-meter"] .spl-bar {
display: grid;
grid-template-columns: 1.4em 1fr 3.4em;
align-items: center;
gap: 0.5rem;
font-size: 0.75rem;
}
[data-module="spl-meter"] .spl-bar-label { color: var(--muted); text-align: right; }
[data-module="spl-meter"] .spl-bar-track {
position: relative;
height: 0.65rem;
border-radius: 0.35rem;
background: color-mix(in srgb, var(--border) 60%, transparent);
overflow: hidden;
}
[data-module="spl-meter"] .spl-bar-fill {
position: absolute;
inset: 0 auto 0 0;
width: 0;
border-radius: inherit;
background: var(--accent);
transition: width 60ms linear;
}
[data-module="spl-meter"] .spl-bar[data-level="warn"] .spl-bar-fill { background: var(--warn); }
[data-module="spl-meter"] .spl-bar[data-level="alarm"] .spl-bar-fill { background: var(--danger); }
[data-module="spl-meter"] .spl-bar[data-level="idle"] .spl-bar-fill { background: var(--muted); }
[data-module="spl-meter"] .spl-bar[data-level="dead"] .spl-bar-value { color: var(--danger); }
/* Peak hold sits on the track rather than inside the fill, so it stays
visible when the bar falls away underneath it. */
[data-module="spl-meter"] .spl-bar-peak {
position: absolute;
top: 0;
bottom: 0;
width: 2px;
background: var(--text);
opacity: 0.75;
}
[data-module="spl-meter"] .spl-bar-value {
font-variant-numeric: tabular-nums;
text-align: right;
color: var(--text);
}
[data-module="spl-meter"] .spl-bar.clip .spl-bar-value { color: var(--danger); }
/* ── canvas tiles ─────────────────────────────────────────────────── */
[data-module="spl-meter"] .spl-canvas {
flex: 1;
display: block;
width: 100%;
min-height: 0;
border-radius: 0.25rem;
}
/* The readout scales off both of the tile's dimensions, so the container
has to be sized on both axes — inline-size alone leaves cqh undefined. */
[data-module="spl-meter"] .spl { container-type: size; }
/* The sub-line is the first thing to go when the tile gets short: the
number is the point, and a clipped caption under it is worse than none. */
[data-module="spl-meter"] .spl-sub {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
@container (max-height: 90px) {
[data-module="spl-meter"] .spl-sub { display: none; }
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "proddash",
"version": "1.5.0",
"version": "1.9.0",
"private": true,
"description": "Modular production dashboard for Waters Church \u2014 zero-dependency Node server + vanilla client",
"license": "UNLICENSED",
+68
View File
@@ -451,6 +451,36 @@ a.btn { text-decoration: none; }
/* one swatch per preset: a miniature dashboard (page, a tile on it, the
accent as a status dot) and the name; the current one wears the accent */
/* ── a collapsible admin section ─────────────────────────────────────
The pattern for any section of this page that folds. The markup is a
<details class="admin-fold"> holding the section's contents, headed by a
<summary class="admin-h1 admin-fold-title">: the title keeps the same
type as every other section heading — a <summary> would otherwise come
out at the normal weight — and the caret follows the words, so a folded
section still reads as a heading first. The whole row is the hit target. */
details.admin-fold > summary.admin-fold-title {
cursor: pointer;
list-style: none;
display: flex;
align-items: center;
gap: 8px;
font-weight: 700; /* matches h1.admin-h1; summary defaults to normal */
user-select: none;
}
details.admin-fold > summary.admin-fold-title::-webkit-details-marker { display: none; }
/* after the title, not before it — the heading reads first, the caret says
there is more behind it */
details.admin-fold > summary.admin-fold-title::after {
content: "";
width: 0; height: 0;
border-left: 6px solid var(--muted);
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
transition: transform 0.15s;
}
details.admin-fold[open] > summary.admin-fold-title::after { transform: rotate(90deg); }
details.admin-fold > summary.admin-fold-title:hover { color: var(--accent); }
.theme-swatches {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(116px, 1fr));
@@ -512,3 +542,41 @@ a.btn { text-decoration: none; }
color: var(--accent);
}
#theme-status { margin-top: 4px; }
/* ── the admin PIN ── */
/* Digits, evenly spaced, so six of them read as a PIN rather than a word. */
.pin-input {
font-variant-numeric: tabular-nums;
letter-spacing: 0.35em;
text-align: center;
max-width: 9em;
}
.pin-form {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
}
.pin-field {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12px;
color: var(--muted);
}
.pin-field[hidden] { display: none; }
.pin-field input {
padding: 8px 10px;
font-size: 14px;
color: var(--text);
background: var(--bg);
border: 1px solid var(--border);
border-radius: 7px;
}
.pin-field input:focus { outline: none; border-color: var(--accent); }
.pin-actions {
display: flex;
gap: 8px;
margin-left: auto;
}
+110 -3
View File
@@ -2,8 +2,10 @@
Everything here is server-wide: module enable/disable and admin config
(written to config/modules.json, module re-inited on save), plus named
layout management. Guarded by the shared passcode when one is set. */
layout management. Behind the admin PIN when one is set — a shell setting of
its own, nothing to do with a module's PIN (Slack's send PIN, say). */
const securitySection = document.getElementById('security-section');
const loginCard = document.getElementById('login-card');
const loginStatus = document.getElementById('login-status');
const passcodeInput = document.getElementById('passcode');
@@ -62,20 +64,30 @@ function showLogin() {
layoutsSection.hidden = true;
updateCard.hidden = true;
themeSection.hidden = true;
securitySection.hidden = true;
passcodeInput.value = '';
passcodeInput.focus();
}
let loggingIn = false;
async function login() {
if (loggingIn) return;
loggingIn = true;
loginStatus.textContent = '';
loginStatus.className = 'admin-status';
try {
await api('/api/admin/login', { method: 'POST', body: JSON.stringify({ passcode: passcodeInput.value }) });
await api('/api/admin/login', { method: 'POST', body: JSON.stringify({ pin: passcodeInput.value }) });
passcodeInput.value = '';
loginCard.hidden = true;
await loadState();
} catch (e) {
passcodeInput.value = '';
loginStatus.textContent = e.message;
loginStatus.className = 'admin-status error';
passcodeInput.focus();
} finally {
loggingIn = false;
}
}
@@ -83,6 +95,82 @@ document.getElementById('login-btn').addEventListener('click', login);
passcodeInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') login();
});
// Six digits is the whole PIN, so there is nothing left to press.
passcodeInput.addEventListener('input', () => {
passcodeInput.value = passcodeInput.value.replace(/\D/g, '').slice(0, 6);
if (passcodeInput.value.length === 6) login();
});
/* ── the admin PIN ───────────────────────────────────────────────────── */
const pinCurrentField = document.getElementById('pin-current-field');
const pinCurrent = document.getElementById('pin-current');
const pinNew = document.getElementById('pin-new');
const pinRepeat = document.getElementById('pin-repeat');
const pinSaveBtn = document.getElementById('pin-save');
const pinClearBtn = document.getElementById('pin-clear');
const pinStatus = document.getElementById('pin-status');
const pinStateEl = document.getElementById('pin-state');
for (const input of [pinCurrent, pinNew, pinRepeat]) {
input.addEventListener('input', () => {
input.value = input.value.replace(/\D/g, '').slice(0, 6);
});
}
/** Paint the section for "no PIN yet" or "one is set". */
function renderPin(state) {
const set = Boolean(state.pinSet);
const fromEnv = Boolean(state.pinFromEnv);
securitySection.hidden = false;
pinCurrentField.hidden = !set;
pinClearBtn.hidden = !set;
document.getElementById('pin-new-label').textContent = set ? 'New PIN' : 'PIN';
pinSaveBtn.textContent = set ? 'Change PIN' : 'Set PIN';
pinStateEl.textContent = fromEnv
? 'A passcode is set in this server’s environment (PRODDASH_PASSCODE) and takes precedence. Anything set here applies once that is removed.'
: set
? 'Admin is locked. This page asks for the PIN, and so does every admin request.'
: 'Admin is open to anyone on the network. Set a 6-digit PIN to lock it.';
}
function pinMessage(text, bad = false) {
pinStatus.textContent = text;
pinStatus.className = 'admin-status' + (bad ? ' error' : ' ok');
}
async function savePin(clearing = false) {
pinStatus.textContent = '';
pinStatus.className = 'admin-status';
const current = pinCurrent.value;
const next = clearing ? '' : pinNew.value;
if (!clearing) {
if (!/^\d{6}$/.test(next)) return pinMessage('The PIN must be exactly 6 digits.', true);
if (next !== pinRepeat.value) return pinMessage('The two PINs are not the same.', true);
}
if (!pinCurrentField.hidden && !/^\d{6}$/.test(current)) {
return pinMessage('Enter the current PIN to change it.', true);
}
pinSaveBtn.disabled = true;
pinClearBtn.disabled = true;
try {
const body = await api('/api/admin/pin', { method: 'POST', body: JSON.stringify({ pin: next, current }) });
for (const i of [pinCurrent, pinNew, pinRepeat]) i.value = '';
pinMessage(body.pinSet ? 'PIN saved. It is asked for from the next visit.' : 'PIN removed — admin is open again.');
await loadState();
} catch (e) {
pinMessage(e.message, true);
} finally {
pinSaveBtn.disabled = false;
pinClearBtn.disabled = false;
}
}
pinSaveBtn.addEventListener('click', () => savePin(false));
pinClearBtn.addEventListener('click', () => {
if (confirm('Turn the admin PIN off? Anyone on the network could then change this server’s settings.')) savePin(true);
});
pinRepeat.addEventListener('keydown', (e) => { if (e.key === 'Enter') savePin(false); });
/* ── module cards ───────────────────────────────────────────────────── */
@@ -821,7 +909,25 @@ async function loadLayouts() {
else toast(e.message, true);
}
});
row.append(name, meta, rename, del);
// The copy the last save replaced, one back. Restoring swaps the two,
// so a restore is itself one restore away from being undone.
const restore = document.createElement('button');
restore.className = 'btn';
restore.textContent = 'Restore previous';
restore.title = 'Put back the copy the last save replaced';
restore.hidden = !layout.hasPrevious;
restore.addEventListener('click', async () => {
if (!confirm(`Go back to the previous version of “${layout.name}”? The current one becomes its previous version, so this can be undone the same way.`)) return;
try {
await api(`/api/layouts/${encodeURIComponent(layout.name)}/restore`, { method: 'POST', body: '{}' });
toast('Previous version restored');
loadLayouts();
} catch (e) {
if (e.authRequired) showLogin();
else toast(e.message, true);
}
});
row.append(name, meta, restore, rename, del);
layoutsList.appendChild(row);
}
}
@@ -856,6 +962,7 @@ async function loadState() {
for (const mod of state.modules || []) {
modulesList.appendChild(buildModuleCard(mod));
}
renderPin(state);
loadTheme();
loadLayouts();
loadCatalog(false);
+37 -5
View File
@@ -18,10 +18,11 @@
<main id="admin-main">
<section class="admin-card" id="login-card" hidden>
<h2>Admin passcode</h2>
<h2>Admin PIN</h2>
<p class="admin-copy">This page changes the server-wide configuration for every dashboard in the building.</p>
<div class="login-row">
<input type="password" id="passcode" placeholder="Passcode" autocomplete="current-password">
<input type="password" id="passcode" class="pin-input" inputmode="numeric" autocomplete="off"
maxlength="6" placeholder="••••••" aria-label="Admin PIN">
<button class="btn primary" id="login-btn">Unlock</button>
</div>
<div class="admin-status" id="login-status"></div>
@@ -40,9 +41,11 @@
</section>
<section id="theme-section" hidden>
<h1 class="admin-h1">Theme</h1>
<div class="theme-swatches" id="theme-swatches" role="radiogroup" aria-label="Theme"></div>
<div class="admin-status" id="theme-status"></div>
<details class="admin-fold">
<summary class="admin-h1 admin-fold-title">Theme</summary>
<div class="theme-swatches" id="theme-swatches" role="radiogroup" aria-label="Theme"></div>
<div class="admin-status" id="theme-status"></div>
</details>
</section>
<section id="modules-section" hidden>
@@ -65,6 +68,35 @@
<h1 class="admin-h1">Saved layouts</h1>
<div id="layouts-list"></div>
</section>
<section id="security-section" hidden>
<h1 class="admin-h1">Admin PIN</h1>
<p class="admin-copy" id="pin-state"></p>
<div class="admin-card">
<div class="pin-form">
<label class="pin-field" id="pin-current-field" hidden>
<span>Current PIN</span>
<input type="password" id="pin-current" class="pin-input" inputmode="numeric"
autocomplete="off" maxlength="6" placeholder="••••••">
</label>
<label class="pin-field">
<span id="pin-new-label">New PIN</span>
<input type="password" id="pin-new" class="pin-input" inputmode="numeric"
autocomplete="off" maxlength="6" placeholder="6 digits">
</label>
<label class="pin-field">
<span>Repeat</span>
<input type="password" id="pin-repeat" class="pin-input" inputmode="numeric"
autocomplete="off" maxlength="6" placeholder="6 digits">
</label>
<div class="pin-actions">
<button class="btn primary" id="pin-save">Set PIN</button>
<button class="btn" id="pin-clear" hidden>Turn off</button>
</div>
</div>
<div class="admin-status" id="pin-status"></div>
</div>
</section>
</main>
<div id="toast" hidden></div>
+8
View File
@@ -19,6 +19,14 @@
<span class="spacer"></span>
<button class="tb-btn icon" id="autohide-btn" title="Auto-hide bars" aria-label="Auto-hide tile title bars" aria-pressed="false">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M9 6l3-3 3 3"/>
<rect x="4" y="10" width="16" height="10" rx="1.5"/>
<path d="M4 14h16"/>
</svg>
</button>
<button class="tb-btn icon" id="fs-btn" title="Fullscreen" aria-label="Fullscreen">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M4 9V5a1 1 0 0 1 1-1h4"/><path d="M20 9V5a1 1 0 0 0-1-1h-4"/>
+519 -105
View File
@@ -5,7 +5,18 @@
settings) autosaves to this browser's localStorage — every browser is fully
independent. Modules render inside tile bodies and never touch the shell. */
const COLS = 12;
/* ── grid density ─────────────────────────────────────────────────────
How many columns the board is cut into. Twelve is the default; a finer
grid lets tiles be smaller and more of them fit across (a 4K wall), a
coarser one suits a small screen read close up. It is this browser's
choice — two displays at one location may want different densities — so
it saves with the layout, local and named, and a named layout comes back
at the density it was arranged on. Row height follows the column width, so
cells keep their shape: a 3×2 tile is still a 3×2 tile, only smaller. */
const GRID_STEPS = [8, 10, 12, 16, 20, 24];
const GRID_DEFAULT = 12;
const CELL_H_DEFAULT = 72; // px per row at the default density
let COLS = GRID_DEFAULT;
const LS_LAYOUT = 'proddash:layout';
const grid = document.getElementById('grid');
@@ -16,14 +27,27 @@ const toastEl = document.getElementById('toast');
/* ── tiny helpers ───────────────────────────────────────────────────── */
let toastTimer = null;
function toast(msg, isError = false) {
function toast(msg, isError = false, { action = null, ms } = {}) {
toastEl.textContent = msg;
if (action) {
// One button, one verb — "Undo" — for a change worth taking back.
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = action.label;
btn.addEventListener('click', () => {
clearTimeout(toastTimer);
toastEl.hidden = true;
action.onClick();
});
toastEl.appendChild(btn);
}
toastEl.classList.toggle('error', isError);
toastEl.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { toastEl.hidden = true; }, 3200);
toastTimer = setTimeout(() => { toastEl.hidden = true; }, ms ?? (action ? 8000 : 3200));
}
const autoHideBtn = document.getElementById('autohide-btn');
const modalBackdrop = document.getElementById('modal-backdrop');
const modalEl = document.getElementById('modal');
@@ -69,6 +93,41 @@ function promptModal({ title, placeholder = '', value = '', okLabel = 'Save' })
});
}
/** A yes-or-no question in the same window: resolves true for the OK button. */
function confirmModal({ title, body = '', okLabel = 'OK' }) {
return new Promise((resolve) => {
modalEl.innerHTML = '';
const h = document.createElement('h2');
h.textContent = title;
const copy = document.createElement('p');
copy.className = 'modal-copy';
copy.textContent = body;
const actions = document.createElement('div');
actions.className = 'actions';
const cancel = document.createElement('button');
cancel.className = 'btn';
cancel.textContent = 'Cancel';
const ok = document.createElement('button');
ok.className = 'btn primary';
ok.textContent = okLabel;
actions.append(cancel, ok);
modalEl.append(h, copy, actions);
modalBackdrop.hidden = false;
ok.focus();
const done = (result) => {
modalBackdrop.hidden = true;
modalEl.innerHTML = '';
resolve(result);
};
cancel.addEventListener('click', () => done(false));
ok.addEventListener('click', () => done(true));
modalEl.addEventListener('keydown', (e) => { if (e.key === 'Escape') done(false); }, { once: true });
modalBackdrop.addEventListener('click', (e) => {
if (e.target === modalBackdrop) done(false);
}, { once: true });
});
}
/* ── dropdown menus ─────────────────────────────────────────────────── */
/* A menu opens the moment its button is clicked, drawn from what the page
@@ -161,18 +220,43 @@ async function loadRegistry() {
let tiles = [];
const tileEls = new Map(); // tile id -> { el, body, dot, titleEl, instance }
/* Whether tile title bars fold away until you point at them. It is part of
how a dashboard is arranged rather than a preference of this browser, so
it saves with the layout — including a named layout on the server — and a
fresh dashboard starts with the bars showing. Fullscreen folds every bar
away regardless; this is the windowed equivalent, asked for by hand. */
let autoHideHeads = false;
/* Beside the layout itself: the copy it replaced (restored if the layout
ever fails to parse) and, after loading a named layout, the arrangement
that was on screen before (what Undo goes back to). */
const LS_LAYOUT_BACKUP = LS_LAYOUT + '.backup';
const LS_LAYOUT_PREVIOUS = LS_LAYOUT + '.previous';
function saveLayout() {
try {
localStorage.setItem(LS_LAYOUT, JSON.stringify({ v: 1, tiles }));
const next = JSON.stringify({ v: 1, autoHideHeads, gridCols: COLS, tiles });
const current = localStorage.getItem(LS_LAYOUT);
if (current && current !== next) localStorage.setItem(LS_LAYOUT_BACKUP, current);
localStorage.setItem(LS_LAYOUT, next);
} catch { /* private mode / full — layout just won't persist */ }
}
function loadLayoutFromStorage() {
try {
const raw = JSON.parse(localStorage.getItem(LS_LAYOUT) || 'null');
if (raw && Array.isArray(raw.tiles)) return raw.tiles;
} catch { /* corrupted — start fresh */ }
return [];
for (const key of [LS_LAYOUT, LS_LAYOUT_BACKUP]) {
try {
const raw = JSON.parse(localStorage.getItem(key) || 'null');
if (raw && Array.isArray(raw.tiles)) {
// A layout that would not parse is not a reason for an empty wall.
if (key === LS_LAYOUT_BACKUP) {
toast('This browser’s layout was unreadable — the last good copy is back', true);
try { localStorage.setItem(LS_LAYOUT, JSON.stringify(raw)); } catch { /* fine */ }
}
return raw;
}
} catch { /* unreadable — try the copy behind it */ }
}
return { tiles: [] };
}
function sanitizeTile(t) {
@@ -185,7 +269,7 @@ function sanitizeTile(t) {
w,
h: Math.max(1, Number(t.h) || 2),
settings: (t.settings && typeof t.settings === 'object') ? t.settings : {},
headHidden: Boolean(t.headHidden),
headPinned: Boolean(t.headPinned),
// set when the tile was added from a module's tile list (multi-tile modules)
variant: t.variant ? String(t.variant) : '',
title: t.title ? String(t.title) : '',
@@ -202,6 +286,87 @@ function newId() {
/* ── grid geometry & collision ──────────────────────────────────────── */
function normalizeGridCols(value) {
const n = Number(value);
return GRID_STEPS.includes(n) ? n : GRID_DEFAULT;
}
function cellHeightFor(cols) {
return Math.round((CELL_H_DEFAULT * GRID_DEFAULT) / cols);
}
/** Cut the board into `cols` columns. Tiles keep their grid units — the
board gets denser or coarser and everything on it changes size with it.
A tile now past the right edge is pulled back in, and one that would then
sit on another moves to the first free spot instead. */
function setGridCols(value, { save = true } = {}) {
const next = normalizeGridCols(value);
const changed = next !== COLS;
COLS = next;
grid.style.gridTemplateColumns = `repeat(${COLS}, minmax(0, 1fr))`;
document.documentElement.style.setProperty('--cell-h', cellHeightFor(COLS) + 'px');
if (changed) {
// A coarser board may not have room for every tile where it was. Settle
// them in reading order: pull a tile past the right edge back in, and
// give one that would then land on a tile already settled the first free
// spot instead — tiles never overlap here, any more than under a drag.
const settled = [];
for (const tile of tiles.slice().sort((a, b) => a.y - b.y || a.x - b.x)) {
tile.w = Math.max(1, Math.min(COLS, tile.w));
tile.x = Math.max(0, Math.min(COLS - tile.w, tile.x));
if (settled.some((s) => overlaps(tile, s))) Object.assign(tile, spotAmong(tile.w, tile.h, settled));
settled.push(tile);
applyRect(tile);
notifyResize(tile);
}
rebuildDividers();
if (document.body.classList.contains('fullscreen')) applyFullscreenFit();
}
if (save) saveLayout();
}
const STEP_MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14"/></svg>';
const STEP_PLUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>';
/** The Layouts menu's density row — Grid Size − 12 + — which steps without
closing the menu, so the board can be watched changing behind it. */
function gridStepper() {
const row = document.createElement('div');
row.className = 'menu-stepper';
const label = document.createElement('span');
label.className = 'menu-stepper-label';
label.textContent = 'Grid Size';
const minus = document.createElement('button');
minus.type = 'button';
minus.className = 'menu-stepper-btn';
minus.setAttribute('data-tip', 'Coarser');
minus.innerHTML = STEP_MINUS_SVG;
const value = document.createElement('span');
value.className = 'menu-stepper-value';
const plus = document.createElement('button');
plus.type = 'button';
plus.className = 'menu-stepper-btn';
plus.setAttribute('data-tip', 'Finer');
plus.innerHTML = STEP_PLUS_SVG;
const paint = () => {
const i = GRID_STEPS.indexOf(COLS);
value.textContent = String(COLS);
minus.disabled = i <= 0;
plus.disabled = i >= GRID_STEPS.length - 1;
};
const step = (dir) => {
const i = GRID_STEPS.indexOf(COLS) + dir;
if (i < 0 || i >= GRID_STEPS.length) return;
setGridCols(GRID_STEPS[i]);
paint();
};
minus.addEventListener('click', () => step(-1));
plus.addEventListener('click', () => step(1));
paint();
row.append(label, minus, value, plus);
return row;
}
function cellMetrics() {
const style = getComputedStyle(grid);
const gapRaw = parseFloat(style.columnGap);
@@ -224,6 +389,17 @@ function isFree(rect, excludeId) {
return isFreeExcept(rect, [excludeId]);
}
/** First spot, scanning top-to-bottom, left-to-right, clear of these tiles. */
function spotAmong(w, h, others) {
for (let y = 0; y < 400; y += 1) {
for (let x = 0; x <= COLS - w; x += 1) {
const rect = { x, y, w, h };
if (!others.some((o) => overlaps(rect, o))) return { x, y };
}
}
return { x: 0, y: 0 };
}
/** First free spot scanning top-to-bottom, left-to-right. */
function findSpot(w, h) {
for (let y = 0; y < 200; y += 1) {
@@ -249,11 +425,116 @@ function minSizeOf(tile) {
};
}
/* ── title bars that fold away ──────────────────────────────────────── */
/* A bar is "off" when it is folded out of sight: the dashboard has auto-hide
on and this tile is not pinned, or the screen is in fullscreen, which folds
every bar for watching whatever the tiles say. Off is never gone — the top
edge of the tile brings it back for as long as the pointer is there. */
/** How close to the tile's top edge the pointer opens a folded-away bar. */
const HEAD_REVEAL_PX = 22;
/** How far down it may wander before that bar folds away again (bar + a little). */
const HEAD_HOLD_PX = 38;
function headIsOff(tile) {
if (document.body.classList.contains('fullscreen')) return true;
return autoHideHeads && !tile.headPinned;
}
function applyHeadState(tile, el = tileEls.get(tile.id)?.el) {
if (!el) return;
const off = headIsOff(tile);
el.classList.toggle('head-off', off);
if (!off) el.classList.remove('head-peek');
}
/** Re-read every tile's bar — after the toggle, or after fullscreen changes. */
function applyAllHeadStates() {
for (const tile of tiles) applyHeadState(tile);
}
function setAutoHideHeads(on, { save = true } = {}) {
autoHideHeads = Boolean(on);
document.body.classList.toggle('autohide-heads', autoHideHeads);
autoHideBtn?.classList.toggle('is-on', autoHideHeads);
autoHideBtn?.setAttribute('aria-pressed', autoHideHeads ? 'true' : 'false');
applyAllHeadStates();
if (save) saveLayout();
}
/* ── tile DOM ───────────────────────────────────────────────────────── */
const CLOSE_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>';
const PIN_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16.5V22"/><path class="pin-head" d="M8.5 3h7l-1.2 7 3.2 3.2H6.5L9.7 10 8.5 3z"/></svg>';
const GEAR_SVG = '<svg viewBox="0 0 90 90" fill="currentColor" aria-hidden="true"><path d="M 82.94 32.538 c -2.685 0 -5.093 -1.545 -6.327 -3.929 c -0.245 -0.476 -0.504 -0.948 -0.774 -1.416 c -0.27 -0.468 -0.55 -0.928 -0.84 -1.378 c -1.448 -2.26 -1.582 -5.117 -0.239 -7.443 c 1.951 -3.378 0.792 -7.696 -2.584 -9.645 l -9.352 -5.4 c -3.378 -1.951 -7.696 -0.792 -9.645 2.584 l -0.002 0.003 c -1.322 2.291 -3.815 3.641 -6.456 3.512 c -1.149 -0.056 -2.301 -0.057 -3.455 0 c -2.638 0.128 -5.124 -1.226 -6.444 -3.513 l -0.002 -0.002 c -1.951 -3.378 -6.269 -4.535 -9.645 -2.584 l -9.352 5.4 c -3.378 1.951 -4.535 6.269 -2.584 9.645 l 0.002 0.002 c 1.321 2.286 1.25 5.117 -0.18 7.336 c -0.625 0.972 -1.201 1.97 -1.726 2.993 c -1.209 2.353 -3.625 3.836 -6.269 3.836 H 7.063 c -3.9 0 -7.061 3.162 -7.061 7.061 v 10.801 c 0 3.9 3.162 7.061 7.061 7.061 l 0 0 c 2.685 0 5.093 1.545 6.327 3.929 c 0.245 0.475 0.504 0.948 0.774 1.416 c 0.27 0.468 0.55 0.928 0.84 1.378 c 1.448 2.26 1.582 5.117 0.239 7.443 c -1.951 3.378 -0.792 7.696 2.584 9.645 l 9.352 5.4 c 3.378 1.951 7.696 0.792 9.645 -2.584 l 0.002 -0.003 c 1.322 -2.291 3.815 -3.641 6.456 -3.512 c 1.149 0.056 2.301 0.057 3.455 0 c 2.638 -0.128 5.124 1.226 6.444 3.513 l 0.002 0.002 c 1.951 3.378 6.268 4.535 9.645 2.584 l 9.352 -5.4 c 3.378 -1.949 4.535 -6.268 2.584 -9.645 l -0.002 -0.002 c -1.321 -2.286 -1.25 -5.117 0.18 -7.336 c 0.625 -0.972 1.201 -1.97 1.726 -2.993 c 1.209 -2.353 3.625 -3.836 6.269 -3.836 h 0.003 c 3.9 0 7.061 -3.162 7.061 -7.061 V 39.599 C 90.001 35.7 86.84 32.538 82.94 32.538 z M 54.998 62.318 c -9.565 5.523 -21.796 2.245 -27.317 -7.32 c -5.523 -9.565 -2.245 -21.796 7.32 -27.317 s 21.796 -2.245 27.317 7.32 C 67.841 44.566 64.563 56.797 54.998 62.318 z"/></svg>';
/* ── what a saved tile can be shown as ─────────────────────────────────
A layout keeps every tile it was given; the board shows the ones whose
module is installed and enabled and — for a tile added from a picker
entry — whose entry (or an alias of it) the module offers right now. The
rest keep their place and draw nothing, and appear the moment the
registry offers them again: a Service timer waits for PCO Plan, a
transcript for its channel. Never the module's default in their place —
a wall of "All timers" where five different timers were is worse than
five gaps that fill themselves in. */
function tileIsOffered(tile) {
const man = registry.get(tile.module);
if (!man) return false;
const variant = String(tile.variant || '');
if (!variant) return true; // the plain module tile — the module says what that means
const entries = Array.isArray(man.tiles) ? man.tiles : [];
// No list at all is a module whose tiles() did not answer in time (the
// server falls back to the classic single entry): mount, and let it sort
// its own variant out rather than blank the board over a slow answer.
if (!entries.length) return true;
return entries.some((e) => String(e.id) === variant || (Array.isArray(e.aliases) && e.aliases.includes(variant)));
}
/** Show tiles that have become offered; fold away tiles that have stopped being. */
function reconcileOfferedTiles() {
let changed = false;
for (const tile of tiles) {
const shown = tileEls.has(tile.id);
const offered = tileIsOffered(tile);
if (offered && !shown) {
buildTile(tile);
changed = true;
} else if (!offered && shown) {
unmountModule(tile);
tileEls.get(tile.id)?.el.remove();
tileEls.delete(tile.id);
changed = true;
}
}
if (changed) rebuildDividers();
scheduleOfferedRecheck();
}
/* A module's entry list can change without anyone saving admin config: PCO
Plan comes back and, a few seconds later, the timers module is offering
its timers again. No event marks that moment, so while any tile is folded
away the registry is re-read every few seconds until nothing is. It costs
one GET while something is hidden and nothing at all otherwise. */
const OFFERED_RECHECK_MS = 6000;
let offeredRecheck = 0;
function scheduleOfferedRecheck() {
clearTimeout(offeredRecheck);
if (!tiles.some((t) => !tileEls.has(t.id))) return;
offeredRecheck = setTimeout(async () => {
offeredRecheck = 0;
if (await loadRegistry()) reconcileOfferedTiles();
else scheduleOfferedRecheck();
}, OFFERED_RECHECK_MS);
}
/** The tiles a layout holds that the board is not showing, by name. */
function unshownTileNames() {
return tiles.filter((t) => !tileEls.has(t.id))
.map((t) => t.title || registry.get(t.module)?.name || t.module);
}
function buildTile(tile) {
const man = registry.get(tile.module);
@@ -278,7 +559,34 @@ function buildTile(tile) {
const controls = document.createElement('span');
controls.className = 'tile-controls';
head.append(dot, title, controls);
/* Pinned tiles keep their bar through auto-hide. The switch sits right
beside the label rather than out with the actions, because it is about
this bar rather than about the tile's contents. */
const pin = document.createElement('button');
pin.className = 'tile-btn pin';
pin.innerHTML = PIN_SVG;
const paintPin = () => {
const on = Boolean(tile.headPinned);
pin.classList.toggle('is-pinned', on);
pin.setAttribute('aria-pressed', on ? 'true' : 'false');
// Instant tooltips read `title` the first time and `data-tip` after.
pin.title = on ? 'Unpin bar' : 'Pin bar';
pin.setAttribute('data-tip', pin.title);
};
paintPin();
pin.addEventListener('click', (e) => {
e.stopPropagation();
tile.headPinned = !tile.headPinned;
paintPin();
applyHeadState(tile, el);
saveLayout();
});
// Keeps the label hugging the pin however wide the tile gets.
const gap = document.createElement('span');
gap.className = 'tile-head-gap';
head.append(dot, title, pin, gap, controls);
// Every tile has something to set: its own settings when the module
// offers any, and the tint either way.
@@ -307,45 +615,47 @@ function buildTile(tile) {
const body = document.createElement('div');
body.className = 'tile-body';
const resize = document.createElement('div');
resize.className = 'tile-resize';
resize.title = 'Drag to resize';
/* The rim: both bottom corners resize in two directions, the bottom edge
moves that edge (trading rows with tiles below), and the other three
move only themselves — the top edge changes where the tile starts, the
sides how wide it is — each stopping where a neighbour or the tile's own
minimum says it must. None of them draw anything: the cursor over an
edge is what says it can be dragged, as on a window. */
const grip = (cls) => {
const gripEl = document.createElement('div');
gripEl.className = cls;
return gripEl;
};
const resize = grip('tile-resize');
const resizeLeft = grip('tile-resize-left');
const resizeBottom = grip('tile-resize-bottom');
const edgeTop = grip('tile-resize-top');
const edgeRight = grip('tile-resize-right');
const edgeLeft = grip('tile-resize-side');
const resizeLeft = document.createElement('div');
resizeLeft.className = 'tile-resize-left';
resizeLeft.title = 'Drag to resize';
// pill on the bottom edge: moves that edge (trading rows with tiles below)
const resizeBottom = document.createElement('div');
resizeBottom.className = 'tile-resize-bottom';
resizeBottom.title = 'Drag to adjust height';
// notch on the title bar's bottom edge: hides/shows the bar
const notch = document.createElement('button');
notch.className = 'tile-notch';
notch.title = 'Hide / show the title bar';
notch.addEventListener('click', (e) => {
e.stopPropagation();
// In fullscreen the bars are all folded away for watching; the notch
// peeks one open for a moment without touching what this tile saved.
if (document.body.classList.contains('fullscreen')) {
peekHead(tile, el, !el.classList.contains('head-peek'));
return;
}
tile.headHidden = !tile.headHidden;
el.classList.toggle('head-hidden', tile.headHidden);
saveLayout();
// A folded-away bar is still reachable: point at the tile's top edge and it
// slides in over the content, where its buttons click and its whole width
// drags the tile exactly as when it is showing.
el.addEventListener('pointermove', (ev) => {
if (!headIsOff(tile)) return;
// Mid-drag the tile moves under the pointer, and mid-resize the edges do
// — neither is a moment to take the bar away.
if (el.classList.contains('dragging') || el.classList.contains('resizing')) return;
const y = ev.clientY - el.getBoundingClientRect().top;
const shown = el.classList.contains('head-peek');
// It takes less to hold the bar open than to open it, so a bar that
// appears under the pointer cannot flicker straight back out.
if (!shown && y <= HEAD_REVEAL_PX) el.classList.add('head-peek');
else if (shown && y > HEAD_HOLD_PX) el.classList.remove('head-peek');
});
// A peeked title bar stays while the pointer is on its tile, and starts
// counting down as soon as it leaves.
el.addEventListener('pointerenter', () => clearPeekTimer(tile.id));
el.addEventListener('pointerleave', () => {
if (el.classList.contains('head-peek')) schedulePeekHide(tile.id, el);
if (el.classList.contains('dragging') || el.classList.contains('resizing')) return;
el.classList.remove('head-peek');
});
el.append(head, body, resize, resizeLeft, resizeBottom, notch);
el.classList.toggle('head-hidden', Boolean(tile.headHidden));
el.append(head, body, resize, resizeLeft, resizeBottom, edgeTop, edgeRight, edgeLeft);
applyHeadState(tile, el);
grid.appendChild(el);
const entry = { el, body, dot, titleEl: title, controls, instance: null };
@@ -356,6 +666,9 @@ function buildTile(tile) {
wireResize(tile, el, resize, false);
wireResize(tile, el, resizeLeft, true);
wireBottomResize(tile, el, resizeBottom);
wireEdgeResize(tile, el, edgeTop, 'n');
wireEdgeResize(tile, el, edgeRight, 'e');
wireEdgeResize(tile, el, edgeLeft, 'w');
mountModule(tile);
return entry;
@@ -369,7 +682,7 @@ function refreshEmptyState() {
function wireDrag(tile, el, handle) {
handle.addEventListener('pointerdown', (ev) => {
if (ev.target.closest('.tile-btn') || ev.target.closest('.tile-menu') || ev.target.closest('.tile-notch')) return;
if (ev.target.closest('.tile-btn') || ev.target.closest('.tile-menu')) return;
if (ev.button !== 0 && ev.pointerType === 'mouse') return;
if (document.body.classList.contains('fullscreen')) return;
ev.preventDefault();
@@ -486,6 +799,80 @@ function wireResize(tile, el, handle, fromLeft) {
});
}
/* ── drag the top, left or right edge ───────────────────────────────── */
/* One edge moves and the opposite one stays where it is, so the tile grows
or shrinks into the space beside it. Unlike the bottom-edge pill these do
not trade rows or columns with a neighbour: the edge simply stops when it
meets one, which is what "resize this tile" should mean. */
function wireEdgeResize(tile, el, handle, edge) {
handle.addEventListener('pointerdown', (ev) => {
if (ev.button !== 0 && ev.pointerType === 'mouse') return;
if (document.body.classList.contains('fullscreen')) return;
ev.preventDefault();
ev.stopPropagation();
closeSettingsPopovers();
handle.setPointerCapture(ev.pointerId);
const m = cellMetrics();
const sx = ev.clientX;
const sy = ev.clientY;
const startX = tile.x;
const startY = tile.y;
const startW = tile.w;
const startH = tile.h;
const min = minSizeOf(tile);
el.classList.add('resizing');
grid.classList.add('no-dividers');
let changed = false;
const onMove = (e) => {
const dCols = Math.round((e.clientX - sx) / (m.cw + m.gap));
const dRows = Math.round((e.clientY - sy) / (m.ch + m.gap));
let cand;
if (edge === 'n') {
// the top edge moves; the bottom edge stays put
const y = Math.max(0, Math.min(startY + startH - min.h, startY + dRows));
cand = { x: tile.x, y, w: tile.w, h: startY + startH - y };
} else if (edge === 'w') {
// the left edge moves; the right edge stays put
const x = Math.max(0, Math.min(startX + startW - min.w, startX + dCols));
cand = { x, y: tile.y, w: startX + startW - x, h: tile.h };
} else {
cand = {
x: tile.x,
y: tile.y,
w: Math.max(min.w, Math.min(COLS - tile.x, startW + dCols)),
h: tile.h,
};
}
if (cand.x === tile.x && cand.y === tile.y && cand.w === tile.w && cand.h === tile.h) return;
if (!isFree(cand, tile.id)) return;
tile.x = cand.x;
tile.y = cand.y;
tile.w = cand.w;
tile.h = cand.h;
applyRect(tile);
changed = true;
notifyResize(tile);
};
const onUp = () => {
handle.removeEventListener('pointermove', onMove);
handle.removeEventListener('pointerup', onUp);
handle.removeEventListener('pointercancel', onUp);
el.classList.remove('resizing');
grid.classList.remove('no-dividers');
if (changed) {
saveLayout();
rebuildDividers();
}
};
handle.addEventListener('pointermove', onMove);
handle.addEventListener('pointerup', onUp);
handle.addEventListener('pointercancel', onUp);
});
}
/* ── drag the bottom edge: height only ──────────────────────────────── */
/* The pill on a tile's bottom edge moves that edge. When other tiles sit
@@ -588,6 +975,7 @@ function rebuildDividers() {
for (const L of tiles) {
for (const R of tiles) {
if (L === R || L.x + L.w !== R.x) continue;
if (!tileEls.has(L.id) || !tileEls.has(R.id)) continue;
const top = Math.max(L.y, R.y);
const bottom = Math.min(L.y + L.h, R.y + R.h);
if (bottom <= top) continue;
@@ -613,7 +1001,6 @@ function seamPairsAt(boundary) {
function buildDivider(L, R, top, bottom) {
const el = document.createElement('div');
el.className = 'tile-divider';
el.title = 'Drag to resize this column';
const place = () => {
const m = cellMetrics();
@@ -626,14 +1013,6 @@ function buildDivider(L, R, top, bottom) {
const boundary = () => L.x + L.w;
const groupEls = () => dividers.filter((d) => d.boundary() === boundary()).map((d) => d.el);
const unlink = () => { for (const d of dividers) d.el.classList.remove('linked'); };
// Before anything is dragged, show which seams travel with this one.
el.addEventListener('pointerenter', () => {
if (document.body.classList.contains('fullscreen')) return;
for (const other of groupEls()) other.classList.add('linked');
});
el.addEventListener('pointerleave', unlink);
el.addEventListener('pointerdown', (ev) => {
if (ev.button !== 0 && ev.pointerType === 'mouse') return;
@@ -689,7 +1068,6 @@ function buildDivider(L, R, top, bottom) {
el.removeEventListener('pointerup', onUp);
el.removeEventListener('pointercancel', onUp);
for (const other of group) other.classList.remove('active');
unlink();
if (changed) saveLayout();
rebuildDividers(); // adjacencies may have changed
};
@@ -715,10 +1093,14 @@ function addTile(moduleId, entry = null) {
toast(`${entry.name} is already on this dashboard`);
return;
}
// Sizes are declared for the default twelve-column grid; scaled so a new
// tile lands at about the size its author meant, whatever the density here.
const scale = COLS / GRID_DEFAULT;
const defaultSize = entry?.defaultSize || man?.defaultSize;
const floor = minSizeOf({ module: moduleId, minSize: entry?.minSize });
const size = {
w: Math.max(1, Math.min(COLS, defaultSize?.w || 4)),
h: Math.max(1, defaultSize?.h || 3),
w: Math.max(floor.w, 1, Math.min(COLS, Math.round((defaultSize?.w || 4) * scale))),
h: Math.max(floor.h, 1, Math.round((defaultSize?.h || 3) * scale)),
};
const spot = findSpot(size.w, size.h);
const settings = {};
@@ -727,7 +1109,7 @@ function addTile(moduleId, entry = null) {
if (spec && 'default' in spec) settings[key] = spec.default;
}
Object.assign(settings, entry?.settings || {});
const tile = { id: newId(), module: moduleId, ...spot, ...size, settings };
const tile = { id: newId(), module: moduleId, ...spot, ...size, settings, headPinned: false };
if (entry) {
tile.variant = String(entry.id);
tile.title = String(entry.name || '');
@@ -743,7 +1125,6 @@ function addTile(moduleId, entry = null) {
function removeTile(id) {
const idx = tiles.findIndex((t) => t.id === id);
if (idx < 0) return;
clearPeekTimer(id);
unmountModule(tiles[idx]);
tiles.splice(idx, 1);
const entry = tileEls.get(id);
@@ -997,7 +1378,7 @@ function buildModuleApi(tile, man, entry) {
/**
* The tile's title bar. Controls added here live next to the gear/close
* buttons and are removed automatically when the instance stops. The
* whole bar can be hidden by the user via the notch, so nothing
* whole bar folds away when the dashboard auto-hides it, so nothing
* essential should exist ONLY as a header control.
*/
header: {
@@ -1712,10 +2093,17 @@ function remountTile(tile) {
/* ── layout apply / reset ───────────────────────────────────────────── */
function renderLayout(list) {
function renderLayout(layout) {
// Callers pass a whole layout; an array on its own is still understood so
// "reset" can simply hand over no tiles.
const list = Array.isArray(layout) ? layout : (layout?.tiles || []);
clearAllTiles();
// Density first: the tiles are clamped and placed against it.
if (!Array.isArray(layout)) setGridCols(layout?.gridCols ?? GRID_DEFAULT, { save: false });
tiles = list.map(sanitizeTile);
for (const tile of tiles) buildTile(tile);
if (!Array.isArray(layout)) setAutoHideHeads(Boolean(layout?.autoHideHeads), { save: false });
for (const tile of tiles) if (tileIsOffered(tile)) buildTile(tile);
scheduleOfferedRecheck();
refreshEmptyState();
rebuildDividers();
if (document.body.classList.contains('fullscreen')) applyFullscreenFit();
@@ -1778,6 +2166,13 @@ function renderAddMenu(menu) {
wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
menu.innerHTML = '';
// Density first: the one thing in here that is not a layout but the board
// the layouts are arranged on.
menu.appendChild(gridStepper());
const stepperDivider = document.createElement('div');
stepperDivider.className = 'menu-divider';
menu.appendChild(stepperDivider);
menu.appendChild(menuItem('Save as named layout…', async () => {
menu.hidden = true;
if (!tiles.length) {
@@ -1791,14 +2186,31 @@ wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
});
if (!name) return;
try {
// Saving over a name is asked about first — and the copy it replaces
// is kept one back on the server, so a yes is not the end of it either.
const existing = await fetch('/api/layouts')
.then((r) => (r.ok ? r.json() : { layouts: [] }))
.then((b) => (b.layouts || []).find((l) => l.name === name))
.catch(() => null);
if (existing) {
const when = existing.updated ? new Date(existing.updated).toLocaleString() : 'earlier';
const go = await confirmModal({
title: `Replace “${name}”?`,
body: `It was saved ${when} with ${existing.tiles} tile${existing.tiles === 1 ? '' : 's'}. The copy it replaces is kept as its previous version.`,
okLabel: 'Replace',
});
if (!go) return;
}
const res = await fetch('/api/layouts/' + encodeURIComponent(name), {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ layout: { tiles } }),
body: JSON.stringify({ layout: { autoHideHeads, gridCols: COLS, tiles } }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body.error || 'Save failed (' + res.status + ')');
toast(`Saved “${name}” — any browser can load it now`);
toast(body.replaced
? `Replaced “${name}” — the earlier copy is kept as its previous version`
: `Saved “${name}” — any browser can load it now`);
} catch (e) {
toast(e.message, true);
}
@@ -1838,9 +2250,33 @@ wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
if (!res.ok) throw new Error(body.error || 'Load failed (' + res.status + ')');
// Loading copies the layout into this browser's own state — it
// does not live-link browsers together.
renderLayout(body.layout.tiles || []);
let outgoing = null;
try { outgoing = localStorage.getItem(LS_LAYOUT); } catch { /* fine */ }
const gridBefore = COLS;
renderLayout(body.layout);
saveLayout();
toast(`Loaded “${l.name}”`);
try { if (outgoing) localStorage.setItem(LS_LAYOUT_PREVIOUS, outgoing); } catch { /* fine */ }
const unshown = unshownTileNames();
const count = `${tiles.length} tile${tiles.length === 1 ? '' : 's'}`;
const gridNote = COLS !== gridBefore ? ` on a ${COLS}-column grid` : '';
const note = unshown.length
? `, ${unshown.length} not shown — ${unshown.join(', ')} ${unshown.length === 1 ? 'isn’t' : 'aren’t'} offered right now`
: '';
toast(`Loaded “${l.name}”: ${count}${gridNote}${note}`, false, {
ms: unshown.length ? 10000 : 7000,
action: outgoing ? {
label: 'Undo',
onClick() {
try {
renderLayout(JSON.parse(outgoing));
saveLayout();
toast('Back to the arrangement you had');
} catch {
toast('Could not go back', true);
}
},
} : null,
});
} catch (e) {
toast(e.message, true);
}
@@ -1850,7 +2286,7 @@ wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
menu.insertBefore(block, reset);
});
/* ── menu bar show/hide (notch, like the tile title bars) ───────────── */
/* ── menu bar show/hide (its own notch, at the top-left) ────────────── */
const topbar = document.getElementById('topbar');
const topbarNotch = document.getElementById('topbar-notch');
@@ -1877,41 +2313,6 @@ try {
if (localStorage.getItem(LS_MENU) === '1') setMenuHidden(true, { persist: false });
} catch { /* fine */ }
/* ── fullscreen: peeking at a tile's title bar ──────────────────────── */
/** How long a peeked title bar stays after the pointer leaves its tile. */
const PEEK_HIDE_MS = 10000;
const peekTimers = new Map(); // tile id → timeout
function clearPeekTimer(id) {
const timer = peekTimers.get(id);
if (timer === undefined) return;
clearTimeout(timer);
peekTimers.delete(id);
}
function schedulePeekHide(id, el) {
clearPeekTimer(id);
peekTimers.set(id, setTimeout(() => {
peekTimers.delete(id);
el.classList.remove('head-peek');
}, PEEK_HIDE_MS));
}
function peekHead(tile, el, on) {
el.classList.toggle('head-peek', on);
clearPeekTimer(tile.id);
// Opened from a click the pointer is on the tile, so the countdown waits
// for it to leave — unless it already has (a keyboard or touch open).
if (on && !el.matches(':hover')) schedulePeekHide(tile.id, el);
}
/** Back to a plain screen: no peeks left open, no timers left running. */
function clearPeeks() {
for (const id of [...peekTimers.keys()]) clearPeekTimer(id);
document.querySelectorAll('.tile.head-peek').forEach((el) => el.classList.remove('head-peek'));
}
/* ── fullscreen: auto-fit the layout to the screen ──────────────────── */
/* Fullscreen is a viewing mode. The occupied columns stretch proportionally
@@ -2017,7 +2418,8 @@ function applyFullscreenFit() {
}
function clearFullscreenFit() {
grid.style.gridTemplateColumns = '';
// Back to this browser's density, not the stylesheet's twelve.
grid.style.gridTemplateColumns = `repeat(${COLS}, minmax(0, 1fr))`;
grid.style.gridAutoRows = '';
gridwrap.classList.remove('no-scroll');
for (const tile of tiles) {
@@ -2026,6 +2428,13 @@ function clearFullscreenFit() {
}
}
autoHideBtn?.addEventListener('click', () => {
setAutoHideHeads(!autoHideHeads);
toast(autoHideHeads
? 'Title bars hide until you point at a tile\u2019s top edge'
: 'Title bars stay put');
});
fsBtn.addEventListener('click', () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen?.().catch(() => {});
@@ -2039,14 +2448,15 @@ document.addEventListener('fullscreenchange', () => {
document.body.classList.toggle('fullscreen', active);
if (active) {
closeSettingsPopovers();
applyAllHeadStates(); // fullscreen has its own rule for the bars
menuHiddenBeforeFs = document.body.classList.contains('menu-hidden');
setMenuHidden(true, { persist: false }); // the menu auto-hides; its notch brings it back
// let the collapsed menubar's space settle before measuring
requestAnimationFrame(() => requestAnimationFrame(applyFullscreenFit));
} else {
setMenuHidden(menuHiddenBeforeFs, { persist: false });
clearPeeks();
clearFullscreenFit();
applyAllHeadStates();
}
});
@@ -2069,7 +2479,7 @@ function subscribeEvents() {
// Rides on the page's one stream connection (see sseSubscribe) as `shell:`.
sseSubscribe('/api/events', {
events: {
'modules-changed': () => handleModulesChanged(),
'modules-changed': () => handleModulesChanged().then(reconcileOfferedTiles),
theme: handleThemeEvent,
},
});
@@ -2151,6 +2561,10 @@ async function boot() {
}
renderLayout(loadLayoutFromStorage());
subscribeEvents();
// Entries a module builds at runtime (a timer per discovered source) can
// land a beat after the first registry read; look once more shortly after
// boot so a tile hidden only by that timing appears without a nudge.
setTimeout(async () => { if (await loadRegistry()) reconcileOfferedTiles(); }, 5000);
}
boot();
+264 -120
View File
@@ -126,6 +126,14 @@ body.menu-hidden #topbar {
line-height: 1;
}
.tb-btn.icon svg { display: block; }
/* A top-bar button that is a switch rather than an action lights up the same
way an open tile button does, so "on" reads the same everywhere. */
.tb-btn.is-on,
.tb-btn.is-on:hover {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-text);
}
/* ── dropdown menus ────────────────────────────────────────────────── */
@@ -179,6 +187,36 @@ body.menu-hidden #topbar {
white-space: normal;
}
.menu-divider { height: 1px; background: var(--border); margin: 5px 4px; }
/* the Layouts menu's grid-density row: Grid Size − 12 + */
.menu-stepper {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 10px 8px;
font-size: 13px;
}
.menu-stepper-label { flex: 1; }
.menu-stepper-btn {
width: 26px;
height: 26px;
display: inline-flex;
align-items: center;
justify-content: center;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
cursor: pointer;
}
.menu-stepper-btn:hover { border-color: var(--muted); }
.menu-stepper-btn[disabled] { opacity: 0.35; cursor: default; }
.menu-stepper-btn svg { width: 12px; height: 12px; display: block; }
.menu-stepper-value {
min-width: 28px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.menu-title {
padding: 6px 10px 3px;
color: var(--muted);
@@ -270,11 +308,33 @@ body.menu-hidden #topbar {
transition: height 0.22s ease, border-bottom-width 0.22s ease;
}
.tile.dragging .tile-head { cursor: grabbing; }
/* hidden = collapsed, not removed, so the notch toggle animates */
.tile.head-hidden .tile-head {
height: 0;
border-bottom-width: 0;
overflow: hidden;
/* Folded away: the bar leaves the flow and parks just above the tile, so the
module keeps the whole body and nothing reflows as the bar comes and goes.
Pointing at the tile's top edge slides it back in over the content
(shell.js adds .head-peek) — and because it is the same element, its
buttons click and its width drags the tile just as they always did. */
.tile.head-off > .tile-head {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 7;
background: color-mix(in srgb, var(--panel) 90%, transparent);
-webkit-backdrop-filter: blur(7px);
backdrop-filter: blur(7px);
transform: translateY(-100%);
opacity: 0;
pointer-events: none;
transition: transform 0.18s ease, opacity 0.18s ease;
}
.tile.head-off.head-peek > .tile-head {
transform: none;
opacity: 1;
pointer-events: auto;
}
.tile.is-tinted.head-off > .tile-head {
background: color-mix(in srgb, var(--tile-tint) 20%, var(--panel));
}
.tile-head .dot {
@@ -290,7 +350,7 @@ body.menu-hidden #topbar {
.tile-head .dot.error { background: var(--danger); }
.tile-title {
flex: 1;
flex: 0 1 auto;
min-width: 0;
font-size: 12px;
font-weight: 700;
@@ -321,6 +381,33 @@ body.menu-hidden #topbar {
.tile-btn.is-open,
.tile-btn.is-open:hover { background: var(--accent); color: var(--accent-text); }
/* The pin: a state, not an action, so it stays quiet until it is on and
sits closer to the label than to the buttons at the other end. It fades
in with the rest of the tile's chrome so a wall of unpinned tiles is not
a wall of pins. */
.tile-btn.pin {
width: 18px;
height: 18px;
margin-left: 2px;
opacity: 0;
transition: opacity 0.15s ease;
}
.tile-btn.pin svg { width: 12px; height: 12px; }
.tile:hover .tile-btn.pin,
.tile-btn.pin:focus-visible { opacity: 0.75; }
.tile-btn.pin:hover { opacity: 1; }
/* Pinned reads at a glance, whether or not anything is being pointed at. */
.tile-btn.pin.is-pinned,
.tile:hover .tile-btn.pin.is-pinned {
opacity: 1;
color: var(--accent);
}
.tile-btn.pin.is-pinned .pin-head { fill: currentColor; }
.tile-btn.pin.is-pinned:hover { background: var(--border); }
/* Keeps the label hugging its pin however wide the tile is. */
.tile-head-gap { flex: 1 1 auto; min-width: 0; }
/* the shell's tooltip: shown at once under the button the pointer is on */
#tip {
position: fixed;
@@ -374,55 +461,6 @@ body.menu-hidden #topbar {
}
.tile-menu[hidden] { display: none; }
/* notch on the title bar's bottom edge: click to hide/show the bar
(same idea as the ProdCom Listener's pull-down menubar handle) */
.tile-notch {
position: absolute;
top: 32px;
left: 50%;
transform: translateX(-50%);
width: 46px;
height: 13px;
padding: 0;
background: var(--panel);
border: 1px solid var(--border);
border-top: none;
border-radius: 0 0 10px 10px;
cursor: pointer;
z-index: 6;
opacity: 0;
transition: opacity 0.15s ease, top 0.22s ease;
}
.tile:hover .tile-notch { opacity: 0.6; }
.tile .tile-notch:hover { opacity: 1; }
.tile.head-hidden .tile-notch { top: 0; }
.tile-notch::after {
content: "";
display: block;
width: 18px;
height: 3px;
margin: 4px auto 0;
border-radius: 999px;
background: var(--muted);
}
.tile-notch:hover::after { background: var(--text); }
/* Fullscreen is for watching, not arranging: every title bar folds away, and
a tile's own hidden/shown preference is left untouched for when the screen
comes back. The notch still peeks one open, and it folds back once the
pointer has been off that tile for a while (PEEK_HIDE_MS in shell.js). */
body.fullscreen .tile:not(.head-peek) .tile-head {
height: 0;
border-bottom-width: 0;
overflow: hidden;
}
body.fullscreen .tile:not(.head-peek) .tile-notch { top: 0; }
body.fullscreen .tile.head-peek .tile-head {
height: 32px;
border-bottom-width: 1px;
}
body.fullscreen .tile.head-peek .tile-notch { top: 32px; }
.tile-body {
flex: 1;
position: relative;
@@ -431,80 +469,67 @@ body.fullscreen .tile.head-peek .tile-notch { top: 32px; }
overflow: hidden;
}
/* ── resizing: the whole rim of a tile, drawn nowhere ────────────────
Every edge and both bottom corners resize, so there is nothing to point
at — the grips are invisible and the cursor says what each one does, the
way a window's own edges do. Together they tile the tile's outer 8px
without a gap: the top strip runs corner to corner, the sides run between
it and the bottom corners, and the bottom strip fills between those. */
.tile-resize,
.tile-resize-left,
.tile-resize-bottom,
.tile-resize-top,
.tile-resize-right,
.tile-resize-side {
position: absolute;
z-index: 5;
touch-action: none;
}
/* the two bottom corners: both directions at once */
.tile-resize,
.tile-resize-left {
position: absolute;
bottom: 0;
width: 20px;
height: 20px;
touch-action: none;
z-index: 5;
color: var(--muted);
opacity: 0; /* corner indicators only show while hovering the tile */
transition: opacity 0.15s ease;
}
.tile-resize { right: 0; cursor: nwse-resize; }
.tile-resize-left { left: 0; cursor: nesw-resize; }
.tile:hover .tile-resize,
.tile:hover .tile-resize-left { opacity: 0.6; }
.tile .tile-resize:hover,
.tile .tile-resize-left:hover { opacity: 1; color: var(--text); }
.tile-resize::after,
.tile-resize-left::after {
content: "";
position: absolute;
bottom: 4px;
width: 9px;
height: 9px;
border-bottom: 2px solid currentColor;
}
.tile-resize::after {
right: 4px;
border-right: 2px solid currentColor;
border-radius: 0 0 3px 0;
}
.tile-resize-left::after {
left: 4px;
border-left: 2px solid currentColor;
border-radius: 0 0 0 3px;
}
/* bottom edge: drag to move the tile's bottom edge (height only). Drawn as
the same 2px line as the corner handles it sits between, on the same
4px inset, so the three read as one set of marks along the bottom. */
/* top and bottom: height only */
.tile-resize-top,
.tile-resize-bottom {
position: absolute;
left: 24px;
right: 24px;
bottom: 0;
height: 10px;
z-index: 5;
display: flex;
align-items: flex-end;
justify-content: center;
height: 8px;
cursor: ns-resize;
touch-action: none;
color: var(--muted);
opacity: 0;
transition: opacity 0.15s ease;
}
.tile-resize-bottom::after {
content: "";
width: 44px;
max-width: 60%;
height: 0;
margin-bottom: 4px;
border-bottom: 2px solid currentColor;
.tile-resize-top {
top: 0;
left: 0;
right: 0;
/* Above a revealed title bar: the bar slides in under the pointer here,
and this strip has to stay the top edge rather than become part of it. */
z-index: 8;
}
.tile:hover .tile-resize-bottom { opacity: 0.6; }
.tile .tile-resize-bottom:hover,
.tile.resizing .tile-resize-bottom { opacity: 1; color: var(--text); }
.tile-resize-bottom { bottom: 0; left: 20px; right: 20px; }
/* left and right: width only, between the top strip and the bottom corners */
.tile-resize-right,
.tile-resize-side {
top: 8px;
bottom: 20px;
width: 8px;
cursor: ew-resize;
}
.tile-resize-right { right: 0; }
.tile-resize-side { left: 0; }
/* ── seam divider between adjacent tiles ───────────────────────────── */
/* When two tiles share a vertical edge, an invisible strip sits on the seam;
hovering reveals a small macOS-split-view-style grab pill. Dragging it
trades width between the two tiles. */
/* When two tiles share a vertical edge, an invisible strip sits on the seam.
Dragging it trades width between the two tiles rather than resizing one,
so it sits above their own edge grips. Like them it draws nothing at rest
— only while it is being dragged, to show which seam is moving. */
.tile-divider {
position: absolute;
width: 14px;
@@ -528,22 +553,24 @@ body.fullscreen .tile.head-peek .tile-notch { top: 32px; }
transition: opacity 0.15s ease, background 0.15s ease;
}
.tile-divider:hover::after,
.tile-divider.linked::after { opacity: 0.7; }
.tile-divider.active::after { opacity: 1; background: var(--text); }
/* Hide the pills while a tile itself is being moved or corner-resized —
they're rebuilt for the new geometry on release. */
/* Drop the seams while a tile itself is being moved or resized — they're
rebuilt for the new geometry on release. */
#grid.no-dividers .tile-divider { display: none; }
/* ── fullscreen mode ───────────────────────────────────────────────── */
/* Fullscreen is a viewing mode: the layout auto-fits the screen, so the
editing affordances (corner handles, seam pills) are parked. */
editing affordances (the rim grips and the seams) are parked. */
body.fullscreen .tile-resize,
body.fullscreen .tile-resize-left,
body.fullscreen .tile-resize-bottom,
body.fullscreen .tile-resize-top,
body.fullscreen .tile-resize-right,
body.fullscreen .tile-resize-side,
body.fullscreen .tile-divider,
body.fullscreen #autohide-btn,
body.fullscreen #admin-link { display: none; }
body.fullscreen #grid { padding-bottom: 0; }
#gridwrap.no-scroll { overflow-y: hidden; }
@@ -909,6 +936,24 @@ body.fullscreen #grid { padding-bottom: 0; }
transition: opacity 0.25s ease;
}
#toast[hidden] { display: none; }
#toast button {
margin-left: 12px;
padding: 3px 10px;
border: 1px solid var(--accent);
border-radius: 5px;
background: none;
color: var(--accent);
font: inherit;
font-weight: 700;
cursor: pointer;
}
#toast button:hover { background: var(--accent); color: var(--accent-text); }
#modal .modal-copy {
color: var(--muted);
font-size: 13px;
line-height: 1.5;
margin: 6px 0 14px;
}
#toast.error { border-color: var(--danger); }
/* ── scrollbars ────────────────────────────────────────────────────── */
@@ -944,8 +989,10 @@ body.fullscreen #grid { padding-bottom: 0; }
every shell element follows, and a colour a tile is configured with (set
on the tile itself) still wins. The :root block at the top of this file is
"booth", the default; the list of ids and names lives in server.js
(GET /api/theme). All four are booth-grade: high contrast, the accent
nowhere near the danger red or the warning amber, muted still readable. */
(GET /api/theme). Every one is booth-grade: high contrast, the accent
nowhere near the danger red or the warning amber, muted still readable.
Each sets --accent-text too when the default (a near-black green, for
booth's mint) would look wrong against its own accent. */
/* Harbor — deep navy, cyan accent */
html[data-theme="harbor"] {
@@ -996,3 +1043,100 @@ html[data-theme="daylight"] {
--danger: #d1242f;
--warn: #b26a00;
}
/* Midnight — indigo night, violet accent */
html[data-theme="midnight"] {
--bg: #0a0b18;
--panel: #14162b;
--border: #272a4a;
--text: #e8e9fb;
--muted: #9a9cc8;
--accent: #9d8cff;
--accent-text: #12103a;
--danger: #ff5a72;
--warn: #f5b93a;
}
/* Moss — forest floor, lime accent (warn pushed orange so the two greens
and the amber never read as one another) */
html[data-theme="moss"] {
--bg: #08120c;
--panel: #101e15;
--border: #1f3728;
--text: #e9f4ea;
--muted: #8fb09a;
--accent: #8fdb3f;
--accent-text: #15250a;
--danger: #ff5a52;
--warn: #ff9f1c;
}
/* Plum — aubergine, purple accent */
html[data-theme="plum"] {
--bg: #110a17;
--panel: #1d1228;
--border: #332042;
--text: #f2e9f8;
--muted: #b195c2;
--accent: #c084fc;
--accent-text: #260a37;
--danger: #ff4d4f;
--warn: #f7b53b;
}
/* Sepia — warm brown room, cool teal accent: the opposite arrangement to
Ember, which is warm throughout */
html[data-theme="sepia"] {
--bg: #12100b;
--panel: #1d1913;
--border: #33291d;
--text: #f4ede0;
--muted: #b3a48b;
--accent: #5eead4;
--accent-text: #06231e;
--danger: #ff5a52;
--warn: #ffc247;
}
/* Blackout — true black for a dark room, where any glow off the screen
carries; everything else is as bright as it can be against it */
html[data-theme="blackout"] {
--bg: #000000;
--panel: #0a0a0a;
--border: #1f1f1f;
--text: #ffffff;
--muted: #9e9e9e;
--accent: #00e5ff;
--accent-text: #00212a;
--danger: #ff3b30;
--warn: #ffcc00;
}
/* Paper — the warm light one, next to Daylight's cool white. Danger and warn
darken, as they must on a light background, and the indigo accent takes
white text. */
html[data-theme="paper"] {
--bg: #f5f1e8;
--panel: #fffdf8;
--border: #ddd5c4;
--text: #1c1a15;
--muted: #6b6455;
--accent: #4f46e5;
--accent-text: #ffffff;
--danger: #c8102e;
--warn: #9a6700;
}
/* Iron — no colour of its own: the accent is near-white, so the only hues on
screen are a module's own and the red/amber that mean something */
html[data-theme="iron"] {
--bg: #0c0c0d;
--panel: #161617;
--border: #2b2b2d;
--text: #f2f2f3;
--muted: #9a9a9d;
--accent: #d8d8dc;
--accent-text: #131314;
--danger: #ff4d4f;
--warn: #ffb224;
}
+347 -29
View File
@@ -12,7 +12,8 @@
* Configure via config/proddash.json (defaults, in the repo), an optional
* proddash.json in the data directory (this machine's overrides), or env vars:
* PORT (default: value in proddash.json, else 24500)
* PRODDASH_PASSCODE (overrides adminPasscode in proddash.json)
* PRODDASH_PASSCODE (a passcode that overrides the stored admin PIN —
* also the way back in if the PIN is ever forgotten)
* PRODDASH_FORGE (overrides `forge`: "github", or a Gitea/Forgejo base
* URL such as http://10.3.8.90:3000)
* PRODDASH_DATA_DIR (where module config + layouts are kept; see below)
@@ -711,6 +712,13 @@ const THEMES = [
{ id: 'graphite', name: 'Graphite', colors: { bg: '#0f1012', panel: '#17191d', accent: '#6cb4ff' } },
{ id: 'ember', name: 'Ember', colors: { bg: '#120c0a', panel: '#1d1411', accent: '#ff8f3a' } },
{ id: 'daylight', name: 'Daylight', colors: { bg: '#eef1f5', panel: '#ffffff', accent: '#0b8a5f' } },
{ id: 'midnight', name: 'Midnight', colors: { bg: '#0a0b18', panel: '#14162b', accent: '#9d8cff' } },
{ id: 'moss', name: 'Moss', colors: { bg: '#08120c', panel: '#101e15', accent: '#8fdb3f' } },
{ id: 'plum', name: 'Plum', colors: { bg: '#110a17', panel: '#1d1228', accent: '#c084fc' } },
{ id: 'sepia', name: 'Sepia', colors: { bg: '#12100b', panel: '#1d1913', accent: '#5eead4' } },
{ id: 'blackout', name: 'Blackout', colors: { bg: '#000000', panel: '#0a0a0a', accent: '#00e5ff' } },
{ id: 'paper', name: 'Paper', colors: { bg: '#f5f1e8', panel: '#fffdf8', accent: '#4f46e5' } },
{ id: 'iron', name: 'Iron', colors: { bg: '#0c0c0d', panel: '#161617', accent: '#d8d8dc' } },
];
const DEFAULT_THEME = THEMES[0].id;
@@ -1096,12 +1104,13 @@ function uninstallModule(id) {
/* — updating the shell itself — */
function copyTree(src, dst) {
function copyTree(src, dst, include = null) {
fs.mkdirSync(dst, { recursive: true });
for (const e of fs.readdirSync(src, { withFileTypes: true })) {
if (include && !include(e.name)) continue;
const s = path.join(src, e.name);
const d = path.join(dst, e.name);
if (e.isDirectory()) copyTree(s, d);
if (e.isDirectory()) copyTree(s, d, include);
else fs.copyFileSync(s, d);
}
}
@@ -1121,25 +1130,83 @@ async function updateShell() {
const out = git(['pull', '--ff-only', 'origin', REPO.branch], 120000);
console.log('[proddash] git pull:', out.split('\n').filter(Boolean).slice(-2).join(' | '));
} else {
const keep = (rel) => rel === 'config/modules.json' || rel.startsWith('config/layouts/') || rel.startsWith('.git/');
const staging = path.join(ROOT, '.proddash-update');
fs.rmSync(staging, { recursive: true, force: true });
for (const [rel, data] of remote.files) {
if (!safeRelPath(rel) || keep(rel)) continue;
if (!safeRelPath(rel) || isKeptOnUpdate(rel)) continue;
const target = path.join(staging, rel);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, data);
}
if (!fs.existsSync(path.join(staging, 'server.js'))) {
const newServer = path.join(staging, 'server.js');
if (!fs.existsSync(newServer)) {
fs.rmSync(staging, { recursive: true, force: true });
throw httpError(502, 'The downloaded archive does not look like ProdDash (no server.js).');
}
// Nothing is swapped in until the new server at least parses. A file that
// arrived truncated or mangled would otherwise be found only by a process
// that cannot start — the one state this app cannot talk its way out of.
try {
execFileSync(process.execPath, ['--check', newServer], { timeout: 30000, stdio: ['ignore', 'ignore', 'pipe'] });
} catch (err) {
fs.rmSync(staging, { recursive: true, force: true });
// node --check leads with the staging path and a caret diagram; the
// line that names the fault is the one worth repeating.
const lines = String(err?.stderr || err?.message || err).split('\n').map((l) => l.trim());
const why = lines.find((l) => /^[A-Za-z]*Error\b/.test(l)) || 'it does not parse';
throw httpError(502, `The downloaded ProdDash will not run — nothing was changed (${why}).`);
}
keepPreviousCopy();
copyTree(staging, ROOT);
fs.rmSync(staging, { recursive: true, force: true });
}
return { from: SHELL_VERSION, to: remote.version || '', method: status.method };
}
/* ── what an update must not touch ───────────────────────────────────
Anything inside the data directory. Normally it sits well outside the app
folder and none of this applies, but when it cannot (an unwritable
Application Support, or PRODDASH_DATA_DIR aimed inside the app) the data
directory IS the app's config/ — and an update would then write the repo's
shipped defaults over this machine's own proddash.json, taking the admin
PIN, the theme and the forge with it. The two legacy names stay listed for
an install whose state never moved out. */
const DATA_DIR_INSIDE_ROOT = (() => {
const rel = path.relative(ROOT, DATA_DIR);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return '';
return rel.split(path.sep).join('/') + '/';
})();
function isKeptOnUpdate(rel) {
if (rel.startsWith('.git/')) return true;
if (rel === 'config/modules.json' || rel.startsWith('config/layouts/')) return true;
return Boolean(DATA_DIR_INSIDE_ROOT) && `${rel}/`.startsWith(DATA_DIR_INSIDE_ROOT);
}
/* ── the way back ────────────────────────────────────────────────────
The copy being replaced is set aside first, so there is always one known
version to return to. The launcher restores it if the new one will not
stay up (see ServerController); by hand it is a rename. It is replaced by
the next update, never accumulated. */
function previousCopyPath() {
return `${ROOT}.previous`;
}
function keepPreviousCopy() {
const previous = previousCopyPath();
try {
fs.rmSync(previous, { recursive: true, force: true });
copyTree(ROOT, previous, (rel) => rel !== '.proddash-update' && rel !== '.git');
fs.writeFileSync(path.join(previous, '.proddash-version'), SHELL_VERSION);
console.log(`[proddash] kept ${SHELL_VERSION} at ${previous} in case the new one will not run`);
} catch (err) {
// Worth saying, not worth refusing the update over.
console.warn('[proddash] could not set the current copy aside:', err?.message || err);
}
}
/**
* Exit so the new code runs. Exit code 75 tells a launcher loop to start us
* again; when nothing is supervising (PRODDASH_LAUNCHER unset) we start our
@@ -1170,12 +1237,109 @@ function restartServer(reason) {
/* ── admin API ──────────────────────────────────────────────────────── */
/* Admin is behind a 6-digit PIN, set in the admin page and kept in this
machine's proddash.json as a scrypt hash — never in the clear, because that
file gets copied between machines. A dashboard needs no PIN; only /admin
and the admin API do. Two ways back in if it is ever forgotten: set
PRODDASH_PASSCODE in the environment, or delete "adminPin" from
proddash.json in the data directory and restart. `adminPasscode` (the older
free-text setting) still works so an existing install keeps running. */
const PIN_RE = /^\d{6}$/;
const PIN_MAX_WRONG = 5;
const PIN_LOCKOUT_MS = 30000;
const ADMIN_PASSCODE = String(process.env.PRODDASH_PASSCODE || shellConfig.adminPasscode || '');
/** Session token: regenerating it every boot is fine — admins just re-enter the passcode. */
/** Session token: regenerating it every boot is fine — admins just re-enter the PIN. */
const adminToken = crypto.randomBytes(24).toString('hex');
/** The stored PIN, as "scrypt$<salt>$<hash>"; '' when admin is open. */
let adminPinHash = String(shellConfig.adminPin || '');
const pinAttempts = new Map(); // ip → { count, lockedUntil }
function hashPin(pin, salt = crypto.randomBytes(16).toString('hex')) {
return `scrypt$${salt}$${crypto.scryptSync(String(pin), salt, 32).toString('hex')}`;
}
/** Constant-time check of a PIN against the stored hash. */
function pinMatches(given, stored) {
const parts = String(stored || '').split('$');
if (parts.length !== 3 || parts[0] !== 'scrypt') return false;
const expected = Buffer.from(parts[2], 'hex');
const actual = crypto.scryptSync(String(given), parts[1], expected.length);
return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
}
/** Is a credential required at all? */
function adminLocked() {
return Boolean(ADMIN_PASSCODE || adminPinHash);
}
/** True when `given` is the credential in force (the env passcode, or the PIN). */
function credentialOk(given) {
const s = String(given ?? '');
if (!s) return false;
if (ADMIN_PASSCODE) {
const a = Buffer.from(s);
const b = Buffer.from(ADMIN_PASSCODE);
if (a.length === b.length && crypto.timingSafeEqual(a, b)) return true;
}
return adminPinHash ? pinMatches(s, adminPinHash) : false;
}
function clientIp(req) {
return String(req.socket?.remoteAddress || 'unknown');
}
/** Seconds of lockout left for this address, or 0. */
function lockoutLeft(ip) {
const a = pinAttempts.get(ip);
if (!a || !a.lockedUntil) return 0;
const left = a.lockedUntil - Date.now();
if (left <= 0) {
pinAttempts.delete(ip);
return 0;
}
return Math.ceil(left / 1000);
}
function noteWrongPin(ip) {
const a = pinAttempts.get(ip) || { count: 0, lockedUntil: 0 };
a.count += 1;
if (a.count >= PIN_MAX_WRONG) {
a.count = 0;
a.lockedUntil = Date.now() + PIN_LOCKOUT_MS;
console.warn(`[proddash] ${PIN_MAX_WRONG} wrong admin PINs from ${ip} — locked out for ${PIN_LOCKOUT_MS / 1000} s`);
}
pinAttempts.set(ip, a);
}
/**
* Store a new PIN (6 digits), or '' to open admin up again. Keeps every other
* key in this machine's proddash.json. Throws an httpError the route reports.
*/
function setAdminPin(pin) {
const next = String(pin ?? '');
if (next && !PIN_RE.test(next)) throw httpError(400, 'The PIN must be exactly 6 digits.');
const file = path.join(DATA_DIR, 'proddash.json');
let existing = {};
if (fs.existsSync(file)) {
existing = readJson(file, null);
if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
throw httpError(500, `${file} is not a JSON object — fix it by hand before changing the PIN.`);
}
}
const hash = next ? hashPin(next) : '';
const out = { ...existing };
if (hash) out.adminPin = hash;
else delete out.adminPin;
writeJson(file, out);
adminPinHash = hash;
shellConfig.adminPin = hash;
pinAttempts.clear();
console.log(`[proddash] admin PIN ${hash ? 'set' : 'removed — admin is open again'}`);
return { pinSet: Boolean(hash) };
}
function isAuthed(req) {
if (!ADMIN_PASSCODE) return true;
if (!adminLocked()) return true;
const cookies = String(req.headers.cookie || '');
return cookies.split(';').some((c) => c.trim() === 'proddash_admin=' + adminToken);
}
@@ -1183,7 +1347,7 @@ function isAuthed(req) {
/** Guard a state-changing admin route. Returns true when the request was refused. */
function refuseAdminWrite(req, res) {
if (!isAuthed(req)) {
sendJson(res, 401, { error: 'Enter the admin passcode first.', authRequired: true });
sendJson(res, 401, { error: 'Enter the admin PIN first.', authRequired: true });
return true;
}
// Requiring application/json forces a CORS preflight that a hostile page
@@ -1268,10 +1432,19 @@ async function handleAdminApi(req, res, urlPath) {
} catch {
return sendJson(res, 400, { error: 'Malformed request.' });
}
if (!ADMIN_PASSCODE) return sendJson(res, 200, { ok: true, authRequired: false });
if (String(body.passcode || '') !== ADMIN_PASSCODE) {
return sendJson(res, 403, { error: 'Wrong passcode.' });
if (!adminLocked()) return sendJson(res, 200, { ok: true, authRequired: false });
const ip = clientIp(req);
const left = lockoutLeft(ip);
if (left) return sendJson(res, 429, { error: `Too many wrong PINs — try again in ${left} s.`, retryAfter: left });
// `passcode` is what the older admin page sent; `pin` is what this one does.
if (!credentialOk(body.pin ?? body.passcode)) {
noteWrongPin(ip);
const now = lockoutLeft(ip);
return sendJson(res, 403, now
? { error: `Too many wrong PINs — try again in ${now} s.`, retryAfter: now }
: { error: 'Wrong PIN.' });
}
pinAttempts.delete(ip);
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Set-Cookie': `proddash_admin=${adminToken}; Path=/; SameSite=Lax; HttpOnly`,
@@ -1280,12 +1453,50 @@ async function handleAdminApi(req, res, urlPath) {
return res.end(JSON.stringify({ ok: true }));
}
if (urlPath === '/api/admin/pin' && req.method === 'POST') {
if (refuseAdminWrite(req, res)) return;
let body = {};
try {
body = JSON.parse((await readBody(req)) || '{}');
} catch {
return sendJson(res, 400, { error: 'Malformed request.' });
}
// Changing a credential re-asserts it, so a browser left open on the
// admin page can't be used to take the machine over.
if (adminPinHash) {
const ip = clientIp(req);
const left = lockoutLeft(ip);
if (left) return sendJson(res, 429, { error: `Too many wrong PINs — try again in ${left} s.`, retryAfter: left });
if (!pinMatches(String(body.current ?? ''), adminPinHash)) {
noteWrongPin(ip);
return sendJson(res, 403, { error: 'That is not the current PIN.' });
}
pinAttempts.delete(ip);
}
try {
const result = setAdminPin(body.pin);
// Whoever just set it has proved they are allowed, so hand them the
// session rather than bouncing them to the unlock card they just built.
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Set-Cookie': `proddash_admin=${adminToken}; Path=/; SameSite=Lax; HttpOnly`,
'Cache-Control': 'no-store',
});
return res.end(JSON.stringify(result));
} catch (err) {
return sendJson(res, err.status || 500, { error: err.message || 'Could not save the PIN.' });
}
}
if (urlPath === '/api/admin/state' && req.method === 'GET') {
if (!isAuthed(req)) {
return sendJson(res, 401, { authRequired: true, authed: false });
}
return sendJson(res, 200, {
authRequired: Boolean(ADMIN_PASSCODE),
authRequired: adminLocked(),
// The env passcode can't be changed from here; the page says so.
pinSet: Boolean(adminPinHash),
pinFromEnv: Boolean(ADMIN_PASSCODE),
authed: true,
version: SHELL_VERSION,
dataDir: DATA_DIR,
@@ -1390,19 +1601,76 @@ function layoutPath(name) {
return path.join(LAYOUTS_DIR, name + '.json');
}
/** Keep only the fields a layout is made of; everything else is dropped. */
/** The copy a save replaced — one back, kept until the next save replaces it.
Names cannot contain a dot (layoutNameOk), so this can never be a real
layout's own file. */
function previousLayoutPath(name) {
return path.join(LAYOUTS_DIR, name + '.previous.json');
}
/* A saved layout is `{ v, autoHideHeads, tiles }`. The fields the shell knows
are checked for shape; anything else a tile carries rides along untouched.
That second part is the lesson of a bug: this function used to rebuild each
tile from the fields it knew and drop the rest, and for seventeen days it
dropped `variant` — every solo timer saved to a server came back as "All
timers". The server is the part of ProdDash that lags (a booth updates
weeks after the dev machine), so it must never be the one deciding which
tile fields exist. Retired fields are the one exception: they are dropped
so an old file does not haunt a new client. */
const LAYOUT_VERSION = 2;
const GRID_STEPS = [8, 10, 12, 16, 20, 24]; // the shell's grid densities
const MAX_LAYOUT_TILES = 100;
const KNOWN_TILE_FIELDS = new Set(['id', 'module', 'x', 'y', 'w', 'h', 'settings', 'variant', 'title', 'headPinned', 'minSize']);
const RETIRED_TILE_FIELDS = new Set(['headHidden']);
/** An unknown tile field is kept when it is a sane key holding small, plain JSON. */
function keepUnknownTileField(key, value) {
if (!/^[A-Za-z][A-Za-z0-9_]{0,39}$/.test(key)) return false;
switch (typeof value) {
case 'string': return value.length <= 2000;
case 'number': return Number.isFinite(value);
case 'boolean': return true;
case 'object':
if (value === null) return false;
try { return JSON.stringify(value).length <= 20000; } catch { return false; }
default: return false;
}
}
function sanitizeLayout(raw) {
const tiles = Array.isArray(raw?.tiles) ? raw.tiles.slice(0, 100) : [];
const tiles = Array.isArray(raw?.tiles) ? raw.tiles : [];
return {
tiles: tiles.map((t) => ({
id: String(t?.id || ''),
module: String(t?.module || ''),
x: Number(t?.x) || 0,
y: Number(t?.y) || 0,
w: Number(t?.w) || 1,
h: Number(t?.h) || 1,
settings: t?.settings && typeof t.settings === 'object' ? t.settings : {},
})),
v: LAYOUT_VERSION,
// Whether tile title bars auto-hide is part of how a dashboard is
// arranged, so it travels with the layout like the tiles themselves.
autoHideHeads: Boolean(raw?.autoHideHeads),
// The grid density the layout was arranged on, when it says and it is one
// the shell knows; a browser loading it cuts its board the same way.
...(GRID_STEPS.includes(Number(raw?.gridCols)) ? { gridCols: Number(raw.gridCols) } : {}),
tiles: tiles.map((t) => {
const tile = {
id: String(t?.id || ''),
module: String(t?.module || ''),
x: Number(t?.x) || 0,
y: Number(t?.y) || 0,
w: Number(t?.w) || 1,
h: Number(t?.h) || 1,
settings: t?.settings && typeof t.settings === 'object' ? t.settings : {},
// Which picker entry the tile came from, and what it was called.
variant: String(t?.variant || ''),
title: String(t?.title || ''),
headPinned: Boolean(t?.headPinned),
};
if (Number(t?.minSize?.w) > 0 && Number(t?.minSize?.h) > 0) {
tile.minSize = { w: Number(t.minSize.w), h: Number(t.minSize.h) };
}
for (const [key, value] of Object.entries(t && typeof t === 'object' ? t : {})) {
if (KNOWN_TILE_FIELDS.has(key) || RETIRED_TILE_FIELDS.has(key)) continue;
if (keepUnknownTileField(key, value)) tile[key] = value;
}
return tile;
}),
};
}
@@ -1414,17 +1682,23 @@ async function handleLayoutsApi(req, res, urlPath) {
} catch { /* no layouts dir yet */ }
const layouts = [];
for (const file of files.sort()) {
if (file.endsWith('.previous.json')) continue; // a save's one-back copy, listed on its layout
const name = file.slice(0, -5);
const data = readJson(path.join(LAYOUTS_DIR, file), null);
if (!data) continue;
let updated = null;
try { updated = fs.statSync(path.join(LAYOUTS_DIR, file)).mtime.toISOString(); } catch { /* fine */ }
layouts.push({ name, tiles: Array.isArray(data.tiles) ? data.tiles.length : 0, updated });
layouts.push({
name,
tiles: Array.isArray(data.tiles) ? data.tiles.length : 0,
updated,
hasPrevious: fs.existsSync(previousLayoutPath(name)),
});
}
return sendJson(res, 200, { layouts });
}
const m = urlPath.match(/^\/api\/layouts\/([^/]+)(\/rename)?$/);
const m = urlPath.match(/^\/api\/layouts\/([^/]+)(\/rename|\/restore)?$/);
if (!m) return sendJson(res, 404, { error: 'Unknown endpoint.' });
let name;
try {
@@ -1457,25 +1731,34 @@ async function handleLayoutsApi(req, res, urlPath) {
}
const layout = sanitizeLayout(body.layout);
if (!layout.tiles.length) return sendJson(res, 400, { error: 'Refusing to save an empty layout.' });
if (layout.tiles.length > MAX_LAYOUT_TILES) {
// Saying no beats quietly saving the first hundred and losing the rest.
return sendJson(res, 400, { error: `A layout can hold ${MAX_LAYOUT_TILES} tiles; this one has ${layout.tiles.length}.` });
}
const replaced = fs.existsSync(layoutPath(name));
try {
// The copy being replaced is kept one back, so a save over the wrong
// name is a restore away rather than gone.
if (replaced) fs.copyFileSync(layoutPath(name), previousLayoutPath(name));
writeJson(layoutPath(name), layout);
} catch (err) {
return sendJson(res, 500, { error: `Could not save ${layoutPath(name)}: ${err?.message || err}` });
}
return sendJson(res, 200, { ok: true, name });
return sendJson(res, 200, { ok: true, name, replaced });
}
if (!m[2] && req.method === 'DELETE') {
if (!isAuthed(req)) return sendJson(res, 401, { error: 'Enter the admin passcode first.', authRequired: true });
if (!isAuthed(req)) return sendJson(res, 401, { error: 'Enter the admin PIN first.', authRequired: true });
try {
fs.unlinkSync(layoutPath(name));
} catch {
return sendJson(res, 404, { error: `No layout named "${name}".` });
}
fs.rmSync(previousLayoutPath(name), { force: true });
return sendJson(res, 200, { ok: true });
}
if (m[2] && req.method === 'POST') {
if (m[2] === '/rename' && req.method === 'POST') {
if (refuseAdminWrite(req, res)) return;
let body = {};
try {
@@ -1499,6 +1782,25 @@ async function handleLayoutsApi(req, res, urlPath) {
return sendJson(res, 200, { ok: true, name: next });
}
// Put back the copy the last save replaced. The two swap, so a restore is
// itself one restore away from being undone.
if (m[2] === '/restore' && req.method === 'POST') {
if (refuseAdminWrite(req, res)) return;
const current = layoutPath(name);
const previous = previousLayoutPath(name);
if (!fs.existsSync(previous)) return sendJson(res, 404, { error: `"${name}" has no previous version to go back to.` });
try {
const swapTmp = current + '.swap';
const hadCurrent = fs.existsSync(current);
if (hadCurrent) fs.renameSync(current, swapTmp);
fs.renameSync(previous, current);
if (hadCurrent) fs.renameSync(swapTmp, previous);
} catch (err) {
return sendJson(res, 500, { error: 'Restore failed: ' + (err?.message || err) });
}
return sendJson(res, 200, { ok: true, name });
}
sendJson(res, 405, { error: 'Method not allowed.' });
}
@@ -1751,6 +2053,22 @@ server.on('error', (err) => {
server.listen(PORT, '0.0.0.0');
/* An update proves itself by staying up. Once this version has, the copy it
replaced is dropped — so `app.previous` existing always means "the last
update has not proven itself yet", which is exactly what the launcher
should roll back to and nothing more. */
const UPDATE_PROVEN_AFTER_MS = 90000;
setTimeout(() => {
const previous = previousCopyPath();
if (!fs.existsSync(previous)) return;
try {
fs.rmSync(previous, { recursive: true, force: true });
console.log(`[proddash] ${SHELL_VERSION} has stayed up — dropped the copy it replaced`);
} catch (err) {
console.warn('[proddash] could not drop the previous copy:', err?.message || err);
}
}, UPDATE_PROVEN_AFTER_MS).unref();
// Update check: shortly after boot, then every few hours (the admin page
// shows the result; nothing is installed without someone clicking).
if (!process.env.PRODDASH_NO_REMOTE_CHECK) {
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env node
'use strict';
/**
* A pretend AbleSet for testing the ableset module without the booth rig.
* Speaks AbleSet's OSC API over UDP: answers /subscribe, /getValues and
* /unsubscribe, sends /heartbeat every 2 s and pushes value changes while a
* setlist plays through — sections, a tempo per song, a section that loops
* twice, a song queued out of order, and the time left in song and set.
*
* node tools/ableset-mock.js [port] (default 39051)
* --stopped start with the transport stopped (press nothing; it stays)
* --no-live report Ableton Live as not connected
* --speed <x> play x times faster than real time (default 1)
*
* Point the AbleSet module at host 127.0.0.1 and this port.
*/
const dgram = require('dgram');
const { encodeMessage, decodePacket } = require('../modules/ableset/osc');
const argv = process.argv.slice(2);
const PORT = Number(argv.find((a) => /^\d+$/.test(a))) || 39051;
const SPEED = Number(argv[argv.indexOf('--speed') + 1]) > 0 && argv.includes('--speed') ? Number(argv[argv.indexOf('--speed') + 1]) : 1;
let playing = !argv.includes('--stopped');
const live = !argv.includes('--no-live');
// name, tempo, [section name, bars] …
const SONGS = [
['1- CALL TO WORSHIP', 72, [['INTRO', 4], ['READING', 12], ['OUTRO', 4]]],
['2 -ALLELUIA - A', 125, [['INTRO', 8], ['CHORUS', 8], ['VERSE 1', 16], ['PRE-CHORUS', 8], ['CHORUS', 16], ['BRIDGE', 16], ['CHORUS', 16], ['ENDING', 8]]],
['3- WHAT A GOD - A', 76.81, [['INTRO', 4], ['VERSE 1', 16], ['CHORUS', 8], ['VERSE 2', 16], ['CHORUS', 8], ['BRIDGE', 8], ['BRIDGE', 8], ['CHORUS', 16], ['TAG', 4], ['ENDING', 8]]],
['4- The Blood - Gb', 68, [['INTRO', 4], ['VERSE 1', 8], ['CHORUS', 8], ['VERSE 2', 8], ['CHORUS', 8], ['OUTRO', 4]]],
['LOOP', 100, [['LOOP', 16]]],
['5- BE PRAISED- Db', 140, [['INTRO', 8], ['VERSE', 16], ['CHORUS', 16], ['INSTRUMENTAL', 8], ['CHORUS', 16], ['ENDING', 4]], '6/8'],
];
const COLORS = ['default', 'blue', 'default', 'red', 'default', 'purple'];
// Lay the songs end to end on one arrangement, as AbleSet does.
let cursor = 8;
const songs = SONGS.map(([name, tempo, parts, sig], i) => {
const [n, d] = (sig || '4/4').split('/').map(Number);
const bpb = (n * 4) / d;
const start = cursor;
const sections = parts.map(([sname, bars]) => {
const s = { name: sname, start: cursor, end: cursor + bars * bpb };
cursor = s.end;
return s;
});
return { name, tempo, sig: [n, d], start, end: cursor, sections, color: COLORS[i] || 'default' };
});
const secs = (song, beats) => (beats * 60) / song.tempo;
const songDuration = (song) => secs(song, song.end - song.start);
let songIdx = 1;
let beats = songs[songIdx].start + 40; // a little way into the second song
let loopsLeft = 0; // section-loop repeats still to play
let queued = null; // index of a song queued out of order
const subscribers = new Map(); // "ip:port" → { ip, port }
const sock = dgram.createSocket('udp4');
const sent = new Map();
function values() {
const song = songs[songIdx];
const sIdx = Math.max(0, song.sections.findIndex((s) => beats >= s.start && beats < s.end));
const sect = song.sections[sIdx];
const nextSect = song.sections[sIdx + 1] || null;
const nextSongIdx = queued != null ? queued : songIdx + 1 < songs.length ? songIdx + 1 : -1;
const nextSong = songs[nextSongIdx] || null;
const leftInSong = secs(song, song.end - beats);
const leftInSet = leftInSong + songs.slice(songIdx + 1).reduce((a, s) => a + songDuration(s), 0);
const col = (name) => [name, name === 'default' ? '#FFFFFF' : { blue: '#3B82F6', red: '#EF4444', purple: '#A855F7' }[name] || '#FFFFFF'];
return {
'/global/isConnected': [live ? 1 : 0],
'/global/isLoadingFile': [0],
'/global/isPlaying': [playing ? 1 : 0],
'/global/isRecording': [0],
'/global/tempo': [song.tempo],
'/global/timeSignature': song.sig,
'/global/beatsPosition': [Math.floor(beats)],
'/global/finePosition': [beats],
'/setlist/name': ['260927 AB (mock)'],
'/setlist/songs': songs.map((s) => s.name),
'/setlist/songDurations': songs.map(songDuration),
'/setlist/songColors': songs.map((s) => s.color),
'/setlist/sections': song.sections.map((s) => s.name),
'/setlist/sectionColors': song.sections.map((s) => (s.name === 'BRIDGE' ? 'purple' : 'default')),
'/setlist/activeSongName': [song.name],
'/setlist/activeSongIndex': [songIdx],
'/setlist/activeSongStart': [song.start],
'/setlist/activeSongEnd': [song.end],
'/setlist/activeSongDuration': [songDuration(song)],
'/setlist/activeSongColor': col(song.color),
'/setlist/activeSectionName': [sect.name],
'/setlist/activeSectionIndex': [sIdx],
'/setlist/activeSectionStart': [sect.start],
'/setlist/activeSectionEnd': [sect.end],
'/setlist/activeSectionDuration': [secs(song, sect.end - sect.start)],
'/setlist/activeSectionColor': col(sect.name === 'BRIDGE' ? 'purple' : 'default'),
'/setlist/activeSectionLoopMode': [loopsLeft > 0 ? 'loop' : null],
'/setlist/activeSectionLoopCount': [loopsLeft],
'/setlist/isInActiveSectionLoop': [loopsLeft > 0 ? 1 : 0],
'/setlist/nextSectionName': [nextSect ? nextSect.name : null],
'/setlist/nextSectionIndex': [nextSect ? sIdx + 1 : -1],
'/setlist/nextSectionStart': [nextSect ? nextSect.start : null],
'/setlist/nextSectionEnd': [nextSect ? nextSect.end : null],
'/setlist/nextSongName': [nextSong ? nextSong.name : null],
'/setlist/nextSongIndex': [nextSongIdx],
'/setlist/nextSongDuration': [nextSong ? songDuration(nextSong) : null],
'/setlist/nextSongColor': col(nextSong ? nextSong.color : 'default'),
'/setlist/queuedName': [queued != null ? songs[queued].name : null, null],
'/setlist/queuedIndex': [queued != null ? queued : -1, -1],
'/setlist/queuedType': [queued != null ? 'song' : null],
'/setlist/loopEnabled': [0],
'/setlist/isCountingIn': [0],
'/setlist/remainingTimeInSong': [Math.round(leftInSong)],
'/setlist/remainingTimeInSet': [Math.round(leftInSet)],
'/audioInterfaces/connected': [1],
'/audioInterfaces/count': [1],
'/audioInterfaces/names': ['PlayAUDIO12'],
'/audioInterfaces/status': ['sceneA'],
'/version/app': ['mock'],
};
}
function sendTo(sub, address, args) {
sock.send(encodeMessage(address, args), sub.port, sub.ip); // null goes out as nil, as AbleSet sends it
}
function push(force = false) {
const now = values();
for (const [address, args] of Object.entries(now)) {
const key = JSON.stringify(args);
if (!force && sent.get(address) === key && address !== '/global/finePosition') continue;
if (address === '/global/finePosition' && !playing && !force) continue;
sent.set(address, key);
for (const sub of subscribers.values()) sendTo(sub, address, args);
}
}
sock.on('message', (buf, rinfo) => {
let msgs;
try { msgs = decodePacket(buf); } catch { return; }
for (const { address, args } of msgs) {
const ip = args[0] === 'auto' || !args[0] ? rinfo.address : String(args[0]);
const port = Number(args[1]) || rinfo.port;
if (address === '/subscribe') {
subscribers.set(`${ip}:${port}`, { ip, port });
sendTo({ ip, port }, '/subscribed', []);
console.log(`subscribed ${ip}:${port} (${args[2] || 'no name'})`);
} else if (address === '/unsubscribe') {
subscribers.delete(`${ip}:${port}`);
console.log(`unsubscribed ${ip}:${port}`);
} else if (address === '/getValues') {
const sub = { ip, port };
for (const [a, v] of Object.entries(values())) sendTo(sub, a, v);
}
}
});
setInterval(() => {
for (const sub of subscribers.values()) sendTo(sub, '/heartbeat', []);
}, 2000);
let last = Date.now();
setInterval(() => {
const now = Date.now();
const dtSec = ((now - last) / 1000) * SPEED;
last = now;
if (playing) {
const song = songs[songIdx];
const before = song.sections.find((s) => beats >= s.start && beats < s.end);
beats += dtSec * (song.tempo / 60);
// The second BRIDGE of song 3 loops twice before it lets go.
if (before && beats >= before.end && loopsLeft > 0) {
loopsLeft -= 1;
beats = before.start + (beats - before.end);
}
const after = song.sections.find((s) => beats >= s.start && beats < s.end);
if (after && after !== before && after.name === 'BRIDGE' && song.sections.indexOf(after) === 6) loopsLeft = 2;
if (beats >= song.end) {
// Stop at the end of each song, as a service does, then carry on.
const nextIdx = queued != null ? queued : songIdx + 1 < songs.length ? songIdx + 1 : 0;
queued = null;
songIdx = nextIdx;
beats = songs[songIdx].start;
playing = false;
push();
setTimeout(() => { playing = true; last = Date.now(); push(); }, 4000 / SPEED);
// Halfway through the set someone queues the last song early.
if (songIdx === 3) setTimeout(() => { queued = 5; push(); }, 8000 / SPEED);
}
}
push();
}, 100);
sock.bind(PORT, () => console.log(`AbleSet mock on udp ${PORT}${playing ? '' : ' (stopped)'}${live ? '' : ' (Live not connected)'}${SPEED !== 1 ? ` at ${SPEED}×` : ''}`));
+159
View File
@@ -0,0 +1,159 @@
'use strict';
/**
* Round-trips a layout through the server's layouts API and checks that
* nothing is lost on the way: a fully-populated tile, a tile field the server
* has never heard of, the one-back copy a save leaves behind, restore, the
* tile cap and delete.
*
* node tools/layout-roundtrip.test.js
*
* Plain Node, no dependencies. Starts server.js on a spare port with a
* temporary data directory, talks to it over HTTP, exits non-zero on the
* first failure and always stops the server it started.
*
* It exists because of one bug: for seventeen days the server rebuilt each
* saved tile from the fields it knew and dropped the rest — including
* `variant`, so every solo timer saved to a booth came back as "All timers".
* A field added on the client must survive a server that has not heard of
* it, and this is where that is checked.
*/
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const net = require('node:net');
const os = require('node:os');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
function freePort() {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, '127.0.0.1', () => {
const { port } = probe.address();
probe.close(() => resolve(port));
});
probe.on('error', reject);
});
}
async function waitFor(url, ms = 15000) {
const deadline = Date.now() + ms;
let last = '';
while (Date.now() < deadline) {
try {
const r = await fetch(url);
if (r.ok) return;
last = 'HTTP ' + r.status;
} catch (err) {
last = err.message;
}
await new Promise((r) => setTimeout(r, 200));
}
throw new Error('server did not come up: ' + last);
}
(async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'proddash-layout-test-'));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: ROOT,
env: { ...process.env, PRODDASH_DATA_DIR: dataDir, PORT: String(port), PRODDASH_NO_REMOTE_CHECK: '1', PRODDASH_LAUNCHER: '1' },
stdio: ['ignore', 'pipe', 'pipe'],
});
let log = '';
child.stdout.on('data', (d) => { log += d; });
child.stderr.on('data', (d) => { log += d; });
const base = `http://127.0.0.1:${port}`;
const api = async (p, init = {}) => {
const r = await fetch(base + p, { headers: { 'Content-Type': 'application/json' }, ...init });
return { status: r.status, body: await r.json().catch(() => ({})) };
};
const layoutsDir = path.join(dataDir, 'layouts');
let failed = false;
try {
await waitFor(base + '/api/theme');
// Every field the shell writes today, one it will write tomorrow, and one
// it has stopped writing.
const tile = {
id: 't1', module: 'propresenter-timers', x: 4, y: 2, w: 3, h: 2,
settings: { showNames: false, __tint: '#112233' },
variant: 'solo:pco-plan:service', title: 'Service', headPinned: true, minSize: { w: 2, h: 1 },
futureField: 'kept', futureFlag: true, futureBox: { a: 1 },
headHidden: true,
};
let r = await api('/api/layouts/Booth%20A', { method: 'PUT', body: JSON.stringify({ layout: { autoHideHeads: true, gridCols: 16, tiles: [tile] } }) });
assert.equal(r.status, 200, 'save: ' + JSON.stringify(r.body));
assert.equal(r.body.replaced, false, 'a first save replaces nothing');
r = await api('/api/layouts/Booth%20A');
assert.equal(r.status, 200);
const got = r.body.layout;
assert.equal(got.v, 2, 'the file carries a schema version');
assert.equal(got.autoHideHeads, true);
assert.equal(got.gridCols, 16, 'grid density travels with the layout');
const t = got.tiles[0];
for (const k of ['id', 'module', 'x', 'y', 'w', 'h', 'variant', 'title', 'headPinned']) assert.deepEqual(t[k], tile[k], k);
assert.deepEqual(t.settings, tile.settings, 'settings');
assert.deepEqual(t.minSize, tile.minSize, 'minSize');
assert.equal(t.futureField, 'kept', 'an unknown string field survives');
assert.equal(t.futureFlag, true, 'an unknown boolean survives');
assert.deepEqual(t.futureBox, { a: 1 }, 'an unknown object survives');
assert.equal('headHidden' in t, false, 'a retired field is dropped');
// Saving over the name keeps the copy it replaced.
r = await api('/api/layouts/Booth%20A', { method: 'PUT', body: JSON.stringify({ layout: { gridCols: 13, tiles: [{ ...tile, title: 'Service v2' }] } }) });
assert.equal(r.status, 200);
assert.equal(r.body.replaced, true, 'the second save reports a replacement');
assert.ok(fs.existsSync(path.join(layoutsDir, 'Booth A.previous.json')), 'the replaced copy is kept');
r = await api('/api/layouts');
assert.deepEqual(r.body.layouts.map((l) => [l.name, l.hasPrevious]), [['Booth A', true]],
'the listing shows one layout with a previous copy — not two layouts');
// Restore swaps them, so a second restore undoes the first. Admin is open
// here (no PIN), which is what a fresh data directory gives.
r = await api('/api/layouts/Booth%20A/restore', { method: 'POST', body: '{}' });
assert.equal(r.status, 200, 'restore: ' + JSON.stringify(r.body));
r = await api('/api/layouts/Booth%20A');
assert.equal(r.body.layout.tiles[0].title, 'Service', 'restore brings the earlier save back');
r = await api('/api/layouts/Booth%20A/restore', { method: 'POST', body: '{}' });
assert.equal(r.status, 200);
r = await api('/api/layouts/Booth%20A');
assert.equal(r.body.layout.tiles[0].title, 'Service v2', 'restoring again goes forward again');
assert.equal('gridCols' in r.body.layout, false, 'a density the shell does not offer is dropped, not stored');
r = await api('/api/layouts/Never%20Saved/restore', { method: 'POST', body: '{}' });
assert.equal(r.status, 404, 'nothing to restore is said, not faked');
// Too many tiles is refused, not trimmed.
const many = Array.from({ length: 101 }, (_, i) => ({ ...tile, id: 't' + i }));
r = await api('/api/layouts/Too%20Big', { method: 'PUT', body: JSON.stringify({ layout: { tiles: many } }) });
assert.equal(r.status, 400);
assert.match(String(r.body.error || ''), /100 tiles/, 'the refusal names the cap');
assert.equal(fs.existsSync(path.join(layoutsDir, 'Too Big.json')), false, 'nothing was written');
// Delete takes the previous copy with it.
r = await api('/api/layouts/Booth%20A', { method: 'DELETE' });
assert.equal(r.status, 200);
assert.equal(fs.existsSync(path.join(layoutsDir, 'Booth A.json')), false);
assert.equal(fs.existsSync(path.join(layoutsDir, 'Booth A.previous.json')), false, 'the previous copy is gone too');
r = await api('/api/layouts');
assert.deepEqual(r.body.layouts, [], 'nothing left listed');
console.log('layout round-trip: every check passed');
} catch (err) {
failed = true;
console.error('FAIL:', err.message);
console.error('--- last of the server log ---\n' + log.slice(-2000));
} finally {
child.kill('SIGTERM');
await new Promise((r) => setTimeout(r, 400));
fs.rmSync(dataDir, { recursive: true, force: true });
}
process.exit(failed ? 1 : 0);
})();
+49
View File
@@ -0,0 +1,49 @@
// Minimal Planning Center mock for the Band Lineup module: service types, one
// plan today, its team_members (with person+team includes), People birthdates,
// and avatar bytes. Enough to exercise the whole board build.
const http = require('http');
const PORT = Number(process.argv[2] || 24710);
const JPEG = Buffer.from('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAEBAREA/8QAFAABAAAAAAAAAAAAAAAAAAAAAP/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AfwD/2Q==', 'base64');
const TODAY = new Date();
const iso = (d) => d.toISOString();
// One person's birthday lands in this Wed–Tue week (today is a Wed in the test).
const inWeek = new Date(TODAY.getFullYear(), TODAY.getMonth(), TODAY.getDate() + 2);
const bdayInWeek = `1994-${String(inWeek.getMonth()+1).padStart(2,'0')}-${String(inWeek.getDate()).padStart(2,'0')}`;
const PEOPLE = {
p1: { name: 'Lemuel Maldonado', pos: 'Vox 1', team: 'Vocals', bd: '1990-03-04' },
p2: { name: 'Wes Carter', pos: 'Vox 2', team: 'Vocals', bd: null },
p3: { name: 'Jessica Proulx', pos: 'Vox 3', team: 'Vocals', bd: '1992-11-01' },
p4: { name: 'Jeremy Cruz', pos: 'Guitar / Lead', team: 'Band', bd: null },
p5: { name: 'Alex Gaitan', pos: 'Drums', team: 'Band', bd: bdayInWeek }, // celebrating
p6: { name: 'Rosaliz Gomez', pos: 'Piano', team: 'Band', bd: null },
p7: { name: 'George Acosta', pos: 'MC', team: 'Production', bd: null },
p8: { name: 'Not Shown', pos: 'Camera 2', team: 'Video', bd: null }, // team not allowed → filtered out
};
const TEAMS = { Vocals: 't1', Band: 't2', Production: 't3', Video: 't4' };
function send(res, obj) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); }
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
if (p.startsWith('/avatar/')) { res.writeHead(200, { 'Content-Type': 'image/jpeg' }); return res.end(JPEG); }
if (p === '/services/v2/folders') return send(res, { data: [] });
if (p === '/services/v2/service_types') return send(res, { data: [{ id: '1', type: 'ServiceType', attributes: { name: 'Sunday Service' }, relationships: { parent: { data: null } } }] });
if (/^\/services\/v2\/service_types\/1\/plans$/.test(p)) {
if (u.searchParams.get('filter') === 'past') return send(res, { data: [] });
return send(res, { data: [{ id: '100', type: 'Plan', attributes: { sort_date: iso(TODAY), title: 'Taking Thoughts Captive - Part 4', dates: 'September 20, 2026' } }] });
}
if (/^\/services\/v2\/service_types\/1\/plans\/100\/team_members$/.test(p)) {
const data = []; const included = [];
for (const [id, v] of Object.entries(PEOPLE)) {
data.push({ id: `tm-${id}`, type: 'PlanPerson', attributes: { status: 'C', team_position_name: v.pos }, relationships: { person: { data: { type: 'Person', id } }, team: { data: { type: 'Team', id: TEAMS[v.team] } } } });
included.push({ id, type: 'Person', attributes: { full_name: v.name, photo_url: `http://127.0.0.1:${PORT}/avatar/${id}` } });
}
for (const [name, id] of Object.entries(TEAMS)) included.push({ id, type: 'Team', attributes: { name } });
return send(res, { data, included, links: {} });
}
const person = p.match(/^\/people\/v2\/people\/([^/]+)$/);
if (person) { const v = PEOPLE[person[1]]; return send(res, { data: { id: person[1], type: 'Person', attributes: { birthdate: v ? v.bd : null } } }); }
res.writeHead(404); res.end('{}');
});
server.listen(PORT, '127.0.0.1', () => console.log(`[pco-band-mock] on http://127.0.0.1:${PORT}`));
+134
View File
@@ -11,6 +11,8 @@
* GET /services/v2/service_types every service type, with its
* parent folder relationship
* GET /services/v2/service_types/{id}
* GET /services/v2/service_types/{id}/teams every team, including one
* nobody is scheduled on
* GET /services/v2/service_types/{id}/item_note_categories
* the note categories the
* items below use, plus one
@@ -25,6 +27,15 @@
* "Starts in" state is visible
* GET …/plans/{id}/items?include=… items + Song / Arrangement /
* ItemNote compound documents
* GET …/plans/{id}/team_members?include=… who is scheduled: PlanPerson
* records + Team / Person, with
* confirmed / unconfirmed /
* declined statuses, a team
* nobody is on, and people with
* and without a photo
* GET /avatars/{personId}.svg those photos (initials on a
* disc) — the module proxies
* them like the real CDN
*
* Item titles deliberately match band-lineup-display/tmp/pp-mock.js's
* playlist, so running both mocks exercises the ProPresenter matching.
@@ -194,6 +205,107 @@ function itemsDocument(planId, include) {
/* ── JSON:API plumbing ──────────────────────────────────────────────── */
/**
* Who is scheduled, as Planning Center returns it from
* /plans/{id}/team_members?include=team,person: teams in their own order,
* people with a position and a scheduling status ("C" confirmed,
* "U" unconfirmed, "D" declined). `photo` false is somebody Planning Center
* has no picture for — the tile draws their initials instead.
*/
const TEAMS = [
{
id: 't1', name: 'Worship', sequence: 1, members: [
{ id: 'tp1', person: 'p1', name: 'Sarah Miles', position: 'Worship Leader', status: 'C', photo: true },
{ id: 'tp2', person: 'p2', name: 'Dan Whitfield', position: 'Acoustic Guitar', status: 'C', photo: true },
{ id: 'tp3', person: 'p3', name: 'Priya Raman', position: 'Keys', status: 'U', photo: true },
{ id: 'tp4', person: 'p4', name: 'Marcus Webb', position: 'Drums', status: 'C', photo: false },
{ id: 'tp5', person: 'p5', name: 'Elena Fischer', position: 'Bass', status: 'D', photo: true, decline: 'Out of town' },
{ id: 'tp6', person: 'p6', name: 'Joy Adeyemi', position: 'Vocals', status: 'C', photo: true },
{ id: 'tp7', person: 'p7', name: 'Tom Brennan', position: 'Vocals', status: 'U', photo: false },
],
},
{
id: 't2', name: 'Production', sequence: 2, members: [
{ id: 'tp8', person: 'p8', name: 'Chris Nolan', position: 'FOH Audio', status: 'C', photo: true, notes: 'Arrives 7:15 for line check' },
{ id: 'tp9', person: 'p9', name: 'Amara Okafor', position: 'ProPresenter', status: 'C', photo: true },
{ id: 'tp10', person: 'p10', name: 'Nate Sørensen', position: 'Lighting', status: 'U', photo: false },
{ id: 'tp11', person: 'p11', name: 'Bethany Cruz', position: 'Camera 1', status: 'C', photo: true },
{ id: 'tp12', person: 'p12', name: 'Owen Hart', position: 'Camera 2', status: 'C', photo: false },
],
},
{
id: 't3', name: 'Hosting', sequence: 3, members: [
{ id: 'tp13', person: 'p13', name: 'Pastor Mike Alvarez', position: 'MC', status: 'C', photo: true },
{ id: 'tp14', person: 'p14', name: 'Grace Lin', position: 'Greeter', status: 'C', photo: true },
{ id: 'tp15', person: 'p15', name: 'Sam Okonkwo', position: 'Greeter', status: 'U', photo: false },
],
},
// A team with nobody on it — a tile hides it unless "Teams with nobody" is on.
{ id: 't4', name: 'Kids', sequence: 4, members: [] },
];
/** A stand-in avatar: initials on a coloured disc, as an SVG the module can proxy. */
function avatarSvg(name) {
const words = String(name).trim().split(/\s+/);
const initials = (words.length > 1 ? words[0][0] + words[words.length - 1][0] : words[0].slice(0, 2)).toUpperCase();
let hash = 0;
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) % 360;
return `<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">`
+ `<circle cx="48" cy="48" r="48" fill="hsl(${hash} 55% 42%)"/>`
+ `<text x="48" y="48" fill="#fff" font-family="system-ui,sans-serif" font-size="38" font-weight="700"`
+ ` text-anchor="middle" dominant-baseline="central">${initials}</text></svg>`;
}
function teamMembersDocument(planId, include, port) {
const wants = new Set(String(include || '').split(',').map((s) => s.trim()).filter(Boolean));
const data = [];
const included = [];
const seenTeams = new Set();
for (const team of TEAMS) {
for (const m of team.members) {
data.push({
type: 'PlanPerson',
id: m.id,
attributes: {
name: m.name,
status: m.status,
team_position_name: m.position,
notes: m.notes || null,
decline_reason: m.decline || null,
photo_thumbnail: m.photo ? `http://127.0.0.1:${port}/avatars/${m.person}.svg` : null,
status_updated_at: iso(bootedAt - 3600000),
},
relationships: {
plan: { data: { type: 'Plan', id: planId } },
team: { data: { type: 'Team', id: team.id } },
person: { data: { type: 'Person', id: m.person } },
},
});
if (wants.has('person')) {
included.push({
type: 'Person',
id: m.person,
attributes: {
name: m.name,
first_name: m.name.split(' ')[0],
last_name: m.name.split(' ').slice(-1)[0],
avatar: m.photo ? `http://127.0.0.1:${port}/avatars/${m.person}.svg` : null,
},
});
}
if (wants.has('team') && !seenTeams.has(team.id)) {
seenTeams.add(team.id);
included.push({
type: 'Team',
id: team.id,
attributes: { name: team.name, sequence: team.sequence, schedule_to: 'plan' },
});
}
}
}
return { data, included };
}
function folderRecord(f) {
return {
type: 'Folder',
@@ -242,6 +354,16 @@ const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
console.log(`[pco-mock] ${req.method} ${url.pathname}${url.search}`);
// Photos are plain images on Planning Center's CDN — no auth there, none here.
const avatar = url.pathname.match(/^\/avatars\/([A-Za-z0-9_-]+)\.svg$/);
if (avatar) {
const person = [].concat(...TEAMS.map((t) => t.members)).find((m) => m.person === avatar[1]);
if (!person) return notFound(res);
const body = avatarSvg(person.name);
res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Content-Length': Buffer.byteLength(body), 'Cache-Control': 'public, max-age=3600' });
return void res.end(body);
}
if (!/^(Basic|Bearer) \S+/.test(String(req.headers.authorization || ''))) {
return send(res, 401, { errors: [{ code: 'unauthorized', title: 'Unauthorized', status: '401', detail: 'This request could not be authenticated.' }] });
}
@@ -266,6 +388,13 @@ const server = http.createServer((req, res) => {
const st = SERVICE_TYPES.find((x) => x.id === parts[1]);
if (!st) return notFound(res);
if (parts.length === 2) return send(res, 200, { data: serviceTypeRecord(st) });
if (parts[2] === 'teams' && parts.length === 3) {
return collection(res, TEAMS.map((t) => ({
type: 'Team', id: t.id,
attributes: { name: t.name, sequence: t.sequence, schedule_to: 'plan' },
relationships: { service_type: { data: { type: 'ServiceType', id: st.id } } },
})), url);
}
if (parts[2] === 'item_note_categories' && parts.length === 3) {
return collection(res, NOTE_CATEGORIES.map((name, i) => noteCategoryRecord(name, i, st.id)), url);
}
@@ -286,6 +415,11 @@ const server = http.createServer((req, res) => {
if (!plan) return notFound(res);
if (parts.length === 4) return send(res, 200, { data: planRecord(plan) });
if (parts[4] === 'plan_times') return collection(res, plan.times.map(planTimeRecord), url);
if (parts[4] === 'team_members') {
const doc = teamMembersDocument(plan.id, url.searchParams.get('include'), PORT);
doc.links = { self: url.pathname + url.search };
return send(res, 200, doc);
}
if (parts[4] === 'items') {
const doc = itemsDocument(plan.id, url.searchParams.get('include'));
doc.links = { self: url.pathname + url.search };