Compare commits
80
Commits
@@ -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
|
||||
|
||||
@@ -32,18 +32,26 @@ 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`).
|
||||
|
||||
## Reference code (read-only forks — don't develop these here)
|
||||
|
||||
- `prodcom-listener/` — live ProdCom transcript web app. Zero-dependency Node
|
||||
`server.js` that serves `public/` and proxies `/prodcom/*` (including the SSE
|
||||
transcript stream) to the ProdCom API at `config.json → prodcomUrl`
|
||||
(default `http://10.3.11.152:24480`). Good reference for: SSE handling,
|
||||
(set per site; each campus runs its own). Good reference for: SSE handling,
|
||||
reconnect logic, channel colors/filtering, PWA install.
|
||||
- `band-lineup-display/` — backstage Electron app (stage lineup photos with
|
||||
mic/pack labels) plus ProPresenter Now/Next:
|
||||
|
||||
@@ -15,9 +15,10 @@ touching the shell (see [docs/MODULE-GUIDE.md](docs/MODULE-GUIDE.md)).
|
||||
2. Discovers modules in `modules/` and serves each one's client at
|
||||
`/modules/<id>/`.
|
||||
3. Mounts each enabled module's server routes under `/api/modules/<id>/` —
|
||||
that's where module servers proxy ProdCom, poll ProPresenter, and stream
|
||||
live updates over SSE, so browsers never talk to production gear
|
||||
directly (no CORS, and API keys never leave the server).
|
||||
that's where module servers follow ProdCom, poll ProPresenter, and stream
|
||||
live updates over SSE — one upstream connection per module, however many
|
||||
dashboards are open — so browsers never talk to production gear directly
|
||||
(no CORS, and API keys never leave the server).
|
||||
4. Stores server-wide module config and named layouts in a per-machine data
|
||||
directory outside the app folder, so updating ProdDash never loses them.
|
||||
|
||||
@@ -98,11 +99,34 @@ 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. |
|
||||
| `theme` | The dashboard palette: `booth` (default), `harbor`, `graphite`, `ember` or `daylight`. The admin page's **Theme** section writes this one — see [Themes](#themes). |
|
||||
| `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`, `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
|
||||
base URL and `repo` at the owner/repo there:
|
||||
|
||||
```json
|
||||
{ "forge": "http://10.3.8.90:3000", "repo": "michael/ProdDash", "branch": "main" }
|
||||
```
|
||||
|
||||
Gitea spells an archive URL differently from GitHub, which is the only thing
|
||||
that changes; the tarball itself is identical, commit hash included, so update
|
||||
detection and module installs behave exactly as before. Make the repository
|
||||
readable without signing in, or ProdDash cannot fetch it.
|
||||
|
||||
Environment variables override both files: `PORT`, `PRODDASH_PASSCODE`, and
|
||||
`PRODDASH_DATA_DIR` to put the data directory somewhere else (a relative path
|
||||
`PRODDASH_FORGE`, and `PRODDASH_DATA_DIR` to put the data directory somewhere else (a relative path
|
||||
is taken from the app folder; `PRODDASH_DATA_DIR=config` restores the old
|
||||
in-repo location). If the default directory can't be created, the server says
|
||||
so and falls back to the app's `config/` folder.
|
||||
@@ -116,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
|
||||
@@ -130,10 +168,11 @@ set on a tile itself (a PCO Plan header colour, say) is deliberately kept.
|
||||
|
||||
## Installing modules and updating
|
||||
|
||||
Everything below happens in the **admin page**; ProdDash talks to its GitHub
|
||||
repository (`michaelmcgary2008/ProdDash`, branch `main` — change with
|
||||
`repo` / `branch` in `proddash.json` or the `PRODDASH_REPO` variable,
|
||||
`owner/repo#branch`). It downloads one small archive of the branch, at most
|
||||
Everything below happens in the **admin page**; ProdDash talks to its git
|
||||
repository — `michael/ProdDash` on the church's own Gitea at
|
||||
`chronicles-ab.waterschurch.org:3000`, branch `main`. Change it with `forge`,
|
||||
`repo` and `branch` in `proddash.json`, or the `PRODDASH_FORGE` and
|
||||
`PRODDASH_REPO` variables (`owner/repo#branch`). It downloads one small archive of the branch, at most
|
||||
every few minutes, only while the admin page is open or for the update check
|
||||
below. Nothing is installed without someone clicking.
|
||||
|
||||
@@ -161,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
|
||||
@@ -173,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
|
||||
@@ -189,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
|
||||
@@ -200,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.
|
||||
@@ -215,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"
|
||||
@@ -249,6 +335,38 @@ below. Nothing is installed without someone clicking.
|
||||
(gear menu): the top-bar text (placeholders such as
|
||||
`{series} • {part} | {serviceType} • {date}`), colors, text size, and a
|
||||
show/hide checklist for every detail.
|
||||
- **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
|
||||
of each per dashboard): **Send message**, a free-text box with the admin's
|
||||
quick emojis one press away, and **Quick replies**, a grid of preset
|
||||
buttons. Both post to the channel of whichever transcript was clicked last
|
||||
— its bottom edge lights up in the accent color — and to the first
|
||||
configured channel until one is clicked. Messages arrive with avatars,
|
||||
names and times, Slack's inline formatting and the workspace's custom
|
||||
emoji; a right-click on one opens the reaction menu, and text size and
|
||||
jump-to-latest sit in the title bar. Nothing leaves the machine until the
|
||||
PIN is entered: one PIN unlocks every Slack tile on that dashboard page
|
||||
until the auto-lock idles out, a reload asks again, and the lock button on
|
||||
a send tile's title bar ends it early.
|
||||
Admin config is in four groups: **Slack account** (the location account's
|
||||
User OAuth Token — `xoxp-…`, so messages are literally from the campus —
|
||||
or a bot token plus "Send as"), **Channels** (the joined channels to
|
||||
follow, one transcript tile each), **Transcript** (refresh interval,
|
||||
messages kept, thread replies) and **Sending** (the switch on the group's
|
||||
title row, a 4–8 digit PIN, auto-lock minutes, quick replies one per line
|
||||
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.
|
||||
- **Band Lineup** — the backstage stage board: 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. Guests and MCs not on the plan are pinned
|
||||
per slot from the title bar's Edit button. 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 a
|
||||
Google Drive folder for manual photos. Tile settings: names, mic labels,
|
||||
parallax, and the birthday confetti with its intensity.
|
||||
- **Clock** — a big booth clock; also the smallest possible module and the
|
||||
reference for module authors.
|
||||
|
||||
@@ -256,10 +374,15 @@ To develop modules against mocks instead of real gear:
|
||||
`node tools/prodcom-mock.js` (ProdCom on `127.0.0.1:24480`),
|
||||
`node band-lineup-display/tmp/pp-mock.js 1599` (ProPresenter slides on
|
||||
`127.0.0.1:1599`), `node tools/pp-timers-mock.js 1600` (ProPresenter
|
||||
timers + timecode on `127.0.0.1:1600`) and `node tools/pco-mock.js`
|
||||
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`). See the testing section of the
|
||||
[module guide](docs/MODULE-GUIDE.md).
|
||||
`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`) 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
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ modules/<id>/
|
||||
"minSize": { "w": 2, "h": 2 },
|
||||
"defaultSize": { "w": 4, "h": 3 },
|
||||
"configSchema": {
|
||||
"prodcomUrl": { "type": "string", "label": "ProdCom URL", "default": "http://10.3.11.152:24480" },
|
||||
"prodcomUrl": { "type": "string", "label": "ProdCom URL", "default": "" },
|
||||
"apiKey": { "type": "password", "label": "API key (if PSK auth enabled)", "default": "" }
|
||||
},
|
||||
"instanceSchema": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"port": 24500,
|
||||
"adminPasscode": "",
|
||||
"repo": "michaelmcgary2008/ProdDash",
|
||||
"forge": "http://chronicles-ab.waterschurch.org:3000",
|
||||
"repo": "michael/ProdDash",
|
||||
"branch": "main"
|
||||
}
|
||||
|
||||
+144
-30
@@ -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**. |
|
||||
@@ -104,7 +144,7 @@ the app); its settings are kept for a later reinstall.
|
||||
Both schemas map field names to specs:
|
||||
|
||||
```
|
||||
{ "type": "string" | "number" | "boolean" | "switch" | "select" | "color" | "password" | "endpoint",
|
||||
{ "type": "string" | "text" | "number" | "boolean" | "switch" | "select" | "multiselect" | "template" | "color" | "password" | "endpoint",
|
||||
"label": "Shown next to the field",
|
||||
"default": <value>,
|
||||
"group": "Section heading", // optional; see below
|
||||
@@ -125,6 +165,24 @@ shown or enabled, off means hidden or disabled, and the label shouldn't say
|
||||
so twice.
|
||||
`color` renders a swatch picker and stores a `#rrggbb` string (give it a hex
|
||||
default; the tile applies it as a CSS custom property — see `pco-plan`).
|
||||
`multiselect` is several picks from one list — the same `options` /
|
||||
`optionsRoute` as `select`, rendered as one switch per option and stored as
|
||||
an array of values. A saved value the list no longer offers stays checked and
|
||||
marked, so nothing is dropped behind anyone's back. In a tile's gear popover
|
||||
it also takes `columns` (2–4) and `allByDefault: true`: a tile that has never
|
||||
chosen shows every option on and saves nothing until someone flips one, so
|
||||
options that turn up later are on as well (give it no `default` then).
|
||||
`select` and `multiselect` may use `optionsRoute` in `instanceSchema` too —
|
||||
the popover GETs `/api/modules/<id><optionsRoute>` like the admin page does.
|
||||
|
||||
`template` (tile settings) is a text with placeholders, built by dragging or
|
||||
clicking the variables the module offers into it: `"variables": [ { "value":
|
||||
"{series}", "label": "Series" }, … ]`. Keep `help` to the joining rules; the
|
||||
chips carry the names.
|
||||
|
||||
`text` is a multi-line string — a `<textarea>` in the admin page, stored with
|
||||
its newlines; one item per line is the convention (the `slack` module's quick
|
||||
replies). Admin config only.
|
||||
|
||||
`group` gathers consecutive fields under a labeled subsection in the admin
|
||||
page, so a module with several distinct concerns (e.g. a ProPresenter
|
||||
@@ -159,17 +217,35 @@ 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`). 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.
|
||||
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
|
||||
offer, the shell adds **Tile tint** — a colour the operator can wash that
|
||||
tile's chrome in, saved with the layout. It is not yours to declare and it
|
||||
never remounts you; don't offer one of your own.
|
||||
|
||||
A picker entry (see **Presenting multiple tiles**) may carry its own
|
||||
`instanceSchema` and `instanceGroups`: tiles added from that entry get those
|
||||
instead of the module's. A tile that shows one ProPresenter timer has no use
|
||||
for a clock's format switches — give it a schema of what applies.
|
||||
|
||||
`showWhen: "<key>"` hides a field until the boolean/`switch` field named
|
||||
`<key>` is on — e.g. the audio device and channel appear only once the LTC
|
||||
listener switch is enabled. The hidden field still keeps its stored value.
|
||||
It works the same in a tile's gear (`instanceSchema`): "Short day" and
|
||||
"Short month" appear once the clock's "Date" is on.
|
||||
|
||||
A `select` whose choices are only knowable at runtime (audio devices, serial
|
||||
ports, discovered sources) sets `optionsRoute` instead of — or as a fallback
|
||||
@@ -286,7 +362,7 @@ export default function create({ root, moduleApi }) {
|
||||
| `instanceId` | Unique per tile — two tiles of the same module get different ids. Handy for keying anything per-tile. |
|
||||
| `variant` | For multi-tile modules: the id of the tile-list entry this tile was added as, `''` otherwise (see **Presenting multiple tiles**). |
|
||||
| `config` | Admin (server-wide) config, read-only, always current. Password fields are absent — they never reach the client. |
|
||||
| `instanceSettings` | This tile's settings: your `instanceSchema` defaults overlaid with whatever this tile has saved. Read it fresh whenever you render — don't cache it. |
|
||||
| `instanceSettings` | This tile's settings: your `instanceSchema` defaults overlaid with whatever this tile has saved. Read it fresh whenever you render — don't cache it. Keys beginning `__` are the shell's own (`__tint`, the tile's colour) — never use that prefix, and ignore the ones you find. |
|
||||
| `saveInstanceSettings(patch)` | Merge `patch` into this tile's settings and persist them with the layout. No restart happens — you made the change, you already know. Use it for state the user sets *inside* your tile (a toggled filter, a chosen tab). |
|
||||
| `fetch(path, opts)` | `fetch` scoped to your server routes: `fetch('/state')` hits `/api/modules/<id>/state`. |
|
||||
| `sse(path, handlers)` | An `EventSource` scoped the same way, **with auto-reconnect** (see below). Returns a handle with `close()`. |
|
||||
@@ -301,16 +377,17 @@ bar, next to the shell's gear/close buttons:
|
||||
|
||||
```js
|
||||
const btn = moduleApi.header.addButton({
|
||||
icon: '<svg …>…</svg>', // inline SVG string, and/or
|
||||
label: 'A+', // short text
|
||||
title: 'Larger text', // hover tooltip
|
||||
icon: '<svg …>…</svg>', // inline SVG string (13 px), and/or
|
||||
label: 'Timers ▾', // short text
|
||||
title: 'Larger text', // tooltip — one or two words; the shell shows
|
||||
// it the moment the pointer arrives
|
||||
onClick() { … },
|
||||
});
|
||||
btn.classList.add('active'); // toggle styling for on/off buttons
|
||||
|
||||
const menu = moduleApi.header.addMenu({
|
||||
label: 'Channels ▾',
|
||||
title: 'Choose visible channels',
|
||||
title: 'Channels',
|
||||
build(menuEl) {
|
||||
// called on every open with an emptied menu element — fill it with
|
||||
// buttons (give them your scoped classes; the container is styled and
|
||||
@@ -321,12 +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.
|
||||
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 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 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 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:
|
||||
@@ -341,14 +431,20 @@ const stream = moduleApi.sse('/stream', {
|
||||
// later: stream.close()
|
||||
```
|
||||
|
||||
Browsers' `EventSource` retries transient drops itself but gives up for good
|
||||
when a retry gets a completed non-SSE response — which is what a proxy's 502
|
||||
looks like while the upstream is down. The shell's `sse()` recreates closed
|
||||
streams on a 3-second timer until they work again, so **reconnect logic is
|
||||
free**: handle `open` (refresh/backfill your state; you may have missed
|
||||
events) and `error` (report degraded status), and you're resilient. Streams
|
||||
you forget to close are force-closed when the tile unmounts — but close your
|
||||
own in `stop()` anyway.
|
||||
Your route serves a plain SSE stream; how it reaches the page is the
|
||||
shell's business. A dashboard holds **one** connection for every stream on
|
||||
it (`GET /api/stream`, which the server feeds from your route over
|
||||
loopback) — browsers allow about six connections to a host and a tile per
|
||||
stream ran out of them — so `open` also fires whenever that shared
|
||||
connection is remade (a tile was added or removed) and whenever your route
|
||||
comes back after a drop. Browsers' `EventSource` retries transient drops
|
||||
itself but gives up for good when a retry gets a completed non-SSE
|
||||
response — which is what a proxy's 502 looks like while the upstream is
|
||||
down; the shell recreates a closed connection on a 3-second timer until it
|
||||
works again, so **reconnect logic is free**: handle `open` (refresh/backfill
|
||||
your state; you may have missed events) and `error` (report degraded
|
||||
status), and you're resilient. Streams you forget to close are force-closed
|
||||
when the tile unmounts — but close your own in `stop()` anyway.
|
||||
|
||||
### Lifecycle you must expect
|
||||
|
||||
@@ -469,7 +565,7 @@ module.exports = {
|
||||
return config.pages.map((page) => ({
|
||||
id: page.name, // stable id, stored with the tile
|
||||
name: page.name, // picker label AND the tile's title
|
||||
description: page.url, // optional line under the label
|
||||
description: page.url, // optional; the picker's tooltip
|
||||
settings: { page: page.name }, // preset instance settings
|
||||
defaultSize: { w: 4, h: 3 }, // optional per-entry size overrides
|
||||
minSize: { w: 2, h: 2 },
|
||||
@@ -482,13 +578,31 @@ module.exports = {
|
||||
keep it fast (answer from state you already hold; don't fetch upstream on
|
||||
demand). A throw or a hang (>2 s) falls back to the classic single entry,
|
||||
so a dead upstream can't break the picker.
|
||||
- `instanceSchema` / `instanceGroups` on an entry replace the module's for
|
||||
tiles added from it — settings that fit that tile, nothing else.
|
||||
- `aliases: ['old-id', …]` on an entry names earlier variant ids it stands
|
||||
for: a tile added under one of them (a layout saved by an older version of
|
||||
your module) gets this entry's settings too. A tile whose variant matches
|
||||
no entry and no alias falls back to the module's full `instanceSchema`.
|
||||
- Entry `description`s are tooltips in the + picker now, not visible lines —
|
||||
one short sentence.
|
||||
- `single: true` on an entry allows at most one such tile per dashboard: the
|
||||
picker greys the entry out once it is placed. Use it for a control surface
|
||||
that would only confuse in duplicate — a send box, a master switch.
|
||||
- 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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)."
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Band Lineup module
|
||||
|
||||
The backstage stage board as a ProdDash tile: everyone scheduled on the band /
|
||||
vocal / production teams for the upcoming Planning Center plan, placed into their
|
||||
mic slot with photo, name and mic/pack label. People whose birthday falls in the
|
||||
current service week (Wednesday→Tuesday) get raining confetti and a gold glow.
|
||||
|
||||
This is the display half of the standalone **Band Lineup** Electron app, ported
|
||||
to ProdDash. (The ProPresenter Now/Next half of that app is the separate
|
||||
`propresenter-now-next` module.)
|
||||
|
||||
## How it fills the board
|
||||
|
||||
1. **Slots** are the mic/pack labels you write in admin, one per line, in the
|
||||
order they sit on stage — e.g. `[VOX 2] MIX 2`, `[DRUMS]`, `[MC] MC1`. A
|
||||
blank line is an empty spot.
|
||||
2. Each refresh the server reads the upcoming plan's **team members** (any team
|
||||
whose name matches a line in *Teams to include*), and matches each person to
|
||||
a slot by their Planning Center **position** — the same loose matching the
|
||||
Electron app uses (`matching.js`; `[VOX 2] MIX 2` takes whoever is on *Vox
|
||||
2*). A numbered role only matches the same number, and the `MIX n` part is
|
||||
ignored, so Vox 2 and Vox 3 never swap.
|
||||
3. **Photos and birthdays** come from Planning Center (birthdays via the People
|
||||
API; only month + day is kept). Photos are cached on disk and served by the
|
||||
module; birthdays drive the confetti.
|
||||
|
||||
## Manual photos (people not on the plan)
|
||||
|
||||
Guest speakers, MCs, stage managers — anyone not scheduled in Planning Center —
|
||||
are pinned per slot from the tile's **Edit** button (title bar): set a name,
|
||||
optionally upload a photo, optionally a `MM-DD` birthday. A manual pin overrides
|
||||
the PCO match for that slot and is kept until you Clear it. Uploaded photos live
|
||||
in the ProdDash data directory, never in the repo.
|
||||
|
||||
## Settings
|
||||
|
||||
- **Admin** (server-wide): Planning Center credentials, service type, plan, the
|
||||
teams to include, the stage slots, columns, refresh interval.
|
||||
- **Per tile** (gear): birthday confetti on/off + intensity, a force-birthday
|
||||
test picker, parallax, and show/hide for names and mic labels.
|
||||
|
||||
## Testing without Planning Center
|
||||
|
||||
```bash
|
||||
node tools/pco-band-mock.js 24710 # mock PCO
|
||||
BAND_LINEUP_API_BASE=http://127.0.0.1:24710 node server.js # point the module at it
|
||||
node modules/band-lineup/matching.test.js # slot-matching unit tests
|
||||
```
|
||||
|
||||
Then in `/admin` under Band Lineup enter any Client ID + Secret, pick "Sunday
|
||||
Service", and the board fills — one person (on Drums) has a birthday this week,
|
||||
so their tile rains confetti.
|
||||
@@ -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 = '';
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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 ✓');
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) }); }
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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; }
|
||||
@@ -4,10 +4,16 @@
|
||||
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 →
|
||||
moduleApi.instanceSettings: show/hide checklist, top-bar template,
|
||||
colors, text size); /admin only holds the connection settings. */
|
||||
colors, item-note categories); the text size is the title bar's A− / A+
|
||||
(saved with the tile, 14 px until someone presses one); /admin only holds
|
||||
the connection settings. */
|
||||
|
||||
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 */
|
||||
const MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14"/></svg>';
|
||||
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 }) {
|
||||
let state = null;
|
||||
let skew = 0; // server clock − local clock, ms
|
||||
@@ -53,7 +59,7 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
const refreshBtn = moduleApi.header.addButton({
|
||||
icon: REFRESH_SVG,
|
||||
title: 'Re-read the plan from Planning Center now',
|
||||
title: 'Refresh',
|
||||
onClick() {
|
||||
refreshBtn.classList.add('active');
|
||||
moduleApi.fetch('/refresh', { method: 'POST' })
|
||||
@@ -67,8 +73,8 @@ export default function create({ root, moduleApi }) {
|
||||
moduleApi.saveInstanceSettings({ textSize: Math.min(40, Math.max(9, size + delta)) });
|
||||
applyPrefs();
|
||||
}
|
||||
moduleApi.header.addButton({ label: 'A−', title: 'Smaller text', onClick: () => bumpTextSize(-1) });
|
||||
moduleApi.header.addButton({ label: 'A+', title: 'Larger text', onClick: () => bumpTextSize(1) });
|
||||
moduleApi.header.addButton({ icon: MINUS_SVG, title: 'Smaller text', onClick: () => bumpTextSize(-1) });
|
||||
moduleApi.header.addButton({ icon: PLUS_SVG, title: 'Larger text', onClick: () => bumpTextSize(1) });
|
||||
|
||||
/* ── formatting ─────────────────────────────────────────────────── */
|
||||
|
||||
@@ -87,6 +93,16 @@ export default function create({ root, moduleApi }) {
|
||||
return `${sign}${m}:${String(sec).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** "Starts in": under a day like fmtDur; a day or more reads "2 Days, 05:12:44". */
|
||||
function fmtStartsIn(totalSec) {
|
||||
const s = Math.max(0, Math.round(totalSec));
|
||||
const days = Math.floor(s / 86400);
|
||||
if (!days) return fmtDur(s);
|
||||
const rest = s % 86400;
|
||||
const pad = (v) => String(v).padStart(2, '0');
|
||||
return `${days} ${days === 1 ? 'Day' : 'Days'}, ${pad(Math.floor(rest / 3600))}:${pad(Math.floor((rest % 3600) / 60))}:${pad(rest % 60)}`;
|
||||
}
|
||||
|
||||
function fmtMinutes(totalSec) {
|
||||
const m = Math.round(totalSec / 60);
|
||||
if (m < 60) return `${m} min`;
|
||||
@@ -121,10 +137,19 @@ export default function create({ root, moduleApi }) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Which note categories this tile shows. Unset (never chosen in the gear
|
||||
* window) means every category, including ones Planning Center gains
|
||||
* later; an array is exactly those, by name. A layout saved before the
|
||||
* categories were a list holds a comma-separated string — read as that
|
||||
* list, blank as unset.
|
||||
*/
|
||||
function noteFilter() {
|
||||
const raw = String(cfg().noteCategories || '');
|
||||
const wanted = raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
|
||||
return wanted.length ? (note) => wanted.includes(String(note.category || '').toLowerCase()) : () => true;
|
||||
const raw = cfg().noteCategories;
|
||||
const names = Array.isArray(raw) ? raw : String(raw ?? '').split(',');
|
||||
const wanted = new Set(names.map((s) => String(s).trim().toLowerCase()).filter(Boolean));
|
||||
if (!Array.isArray(raw) && !wanted.size) return () => true;
|
||||
return (note) => wanted.has(String(note.category || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/* ── status dot ─────────────────────────────────────────────────── */
|
||||
@@ -250,7 +275,7 @@ export default function create({ root, moduleApi }) {
|
||||
const startsAt = svc.startsAt || plan.serviceStartsAt || 0;
|
||||
if (on('showCountdown') && startsAt > now) {
|
||||
clockLabelEl.textContent = 'Starts in';
|
||||
clockValueEl.textContent = fmtDur((startsAt - now) / 1000);
|
||||
clockValueEl.textContent = fmtStartsIn((startsAt - now) / 1000);
|
||||
return;
|
||||
}
|
||||
if (on('showRunningClock') && startsAt) {
|
||||
|
||||
+259
-48
@@ -1,15 +1,23 @@
|
||||
{
|
||||
"id": "pco-plan",
|
||||
"name": "PCO Plan",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.0",
|
||||
"proddash": ">=1.4.0",
|
||||
"description": "Order of service from Planning Center Services",
|
||||
"provides": ["timers"],
|
||||
"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": {
|
||||
@@ -121,56 +140,248 @@
|
||||
"collapsed": false,
|
||||
"columns": 2
|
||||
},
|
||||
"Show / hide": {
|
||||
"Item notes": {
|
||||
"toggle": "showNotes"
|
||||
},
|
||||
"Show": {
|
||||
"collapsed": true,
|
||||
"columns": 3,
|
||||
"help": "Switch off anything this tile should not show."
|
||||
"columns": 2
|
||||
}
|
||||
},
|
||||
"instanceSchema": {
|
||||
"textSize": { "type": "number", "label": "Text size (px)", "default": 14 },
|
||||
"autoScroll": { "type": "boolean", "label": "Keep the current item in view", "default": true },
|
||||
"noteCategories": {
|
||||
"type": "string",
|
||||
"label": "Item note categories to show (comma-separated, blank = all)",
|
||||
"default": ""
|
||||
"autoScroll": {
|
||||
"type": "boolean",
|
||||
"label": "Auto-scroll",
|
||||
"default": true
|
||||
},
|
||||
"headerTemplate": {
|
||||
"type": "string",
|
||||
"type": "template",
|
||||
"label": "Top bar text",
|
||||
"default": "{series} • {part} | {serviceType} • {date}",
|
||||
"group": "Top bar",
|
||||
"help": "Placeholders: {series} series name · {part} plan title / part number · {serviceType} · {date} · {shortDate} · {time} service start time · {length} planned length · {items} item count. Use • between items (an item whose placeholders are empty or hidden is dropped) and | to start a second line."
|
||||
"variables": [
|
||||
{
|
||||
"value": "{series}",
|
||||
"label": "Series"
|
||||
},
|
||||
"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" },
|
||||
"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" },
|
||||
"showNotes": { "type": "boolean", "label": "Item notes", "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" }
|
||||
{
|
||||
"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": "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",
|
||||
"group": "Item notes",
|
||||
"optionsRoute": "/note-categories",
|
||||
"columns": 3,
|
||||
"allByDefault": true
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
* GET /plans?serviceTypeId=… → { options } for the admin "Plan" select
|
||||
* GET /documents → { options } for the admin start / end document selects
|
||||
* (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 /timers → snapshot for the Timers module (guide: "Offering
|
||||
* GET /timers/stream → SSE, `timers` events timers to the Timers module")
|
||||
*
|
||||
@@ -26,6 +28,7 @@
|
||||
* GET /service_types/{st}/plans/{id} (title, dates…)
|
||||
* 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)
|
||||
*
|
||||
* Following ProPresenter: instead of talking to ProPresenter a second time,
|
||||
* this module reads the propresenter-now-next module's own SSE feed over
|
||||
@@ -78,6 +81,8 @@ const NOW_NEXT_RETRY_MS = 3000;
|
||||
const NOW_NEXT_MISSING_RETRY_MS = 15000;
|
||||
/** How many distinct documents seen live are remembered for the admin selects. */
|
||||
const SEEN_DOCUMENTS_MAX = 200;
|
||||
/** How long a service type's item note categories are believed before Planning Center is asked again. */
|
||||
const NOTE_CATEGORIES_TTL_MS = 10 * MINUTE;
|
||||
/**
|
||||
* Service timer tone (the Timers module colours by it): running behind the
|
||||
* plan — completed items over their planned length, plus the current item's
|
||||
@@ -591,6 +596,44 @@ module.exports = {
|
||||
syncServiceSafe(Date.now(), null);
|
||||
}
|
||||
|
||||
/* — item note categories (a tile's "Item notes" → Categories switches) — */
|
||||
|
||||
let noteCategories = { at: 0, options: [] }; // the last good answer from Planning Center
|
||||
let noteCategoriesInFlight = null;
|
||||
|
||||
/**
|
||||
* The service type's item note categories, by name — notes are matched
|
||||
* to categories by name, so the names are the values. Believed for
|
||||
* NOTE_CATEGORIES_TTL_MS, read once however many tiles ask at the same
|
||||
* moment; a failed re-read keeps serving the last good list. A module
|
||||
* that cannot ask (no credentials, no service type) answers an empty
|
||||
* list — the gear window then says there is nothing to choose from yet.
|
||||
*/
|
||||
async function noteCategoryOptions() {
|
||||
if (!pco.configured || !serviceTypeId) return [];
|
||||
if (Date.now() - noteCategories.at < NOTE_CATEGORIES_TTL_MS) return noteCategories.options;
|
||||
if (!noteCategoriesInFlight) {
|
||||
noteCategoriesInFlight = (async () => {
|
||||
const body = await pco.getAll(`${SERVICES}/service_types/${encodeURIComponent(serviceTypeId)}/item_note_categories`);
|
||||
const seen = new Set();
|
||||
const options = (body.data || [])
|
||||
.filter((c) => !c?.attributes?.deleted_at)
|
||||
.map((c) => ({ name: String(c.attributes?.name || '').trim(), sequence: Number(c.attributes?.sequence) || 0 }))
|
||||
.sort((a, b) => a.sequence - b.sequence)
|
||||
.filter((c) => c.name && !seen.has(c.name.toLowerCase()) && seen.add(c.name.toLowerCase()))
|
||||
.map((c) => ({ value: c.name, label: c.name }));
|
||||
noteCategories = { at: Date.now(), options };
|
||||
return options;
|
||||
})().finally(() => { noteCategoriesInFlight = null; });
|
||||
}
|
||||
try {
|
||||
return await noteCategoriesInFlight;
|
||||
} catch (err) {
|
||||
log(`item note categories read failed: ${err?.message || err}`);
|
||||
return noteCategories.options;
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePoll(ms) {
|
||||
if (stopped) return;
|
||||
clearTimeout(pollTimer);
|
||||
@@ -1214,6 +1257,7 @@ module.exports = {
|
||||
pickPlan,
|
||||
timersSnapshot,
|
||||
documentOptions,
|
||||
noteCategoryOptions,
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -1312,6 +1356,23 @@ module.exports = {
|
||||
json(res, 200, current.documentOptions());
|
||||
},
|
||||
|
||||
/**
|
||||
* Options for a tile's "Item notes" → Categories switches: the
|
||||
* configured service type's item note categories, by name. Always a
|
||||
* 200 with a list — empty while the module is unconfigured, not
|
||||
* running or cannot reach Planning Center — because the gear window
|
||||
* has nothing better to do with an error than show an empty list.
|
||||
*/
|
||||
'GET /note-categories': async (req, res) => {
|
||||
let options = [];
|
||||
try {
|
||||
if (current) options = await current.noteCategoryOptions();
|
||||
} catch (err) {
|
||||
log(`note categories: ${err?.message || err}`);
|
||||
}
|
||||
json(res, 200, { options });
|
||||
},
|
||||
|
||||
/**
|
||||
* Options for the admin page's "Service type" select: every service
|
||||
* type, grouped by its Planning Center folder path — so the folders
|
||||
|
||||
@@ -3,8 +3,13 @@
|
||||
Ported from prodcom-listener/public/app.js into the ProdDash module
|
||||
contract: everything lives inside the tile's root, per-tile state
|
||||
(hidden channels, channel icons, timestamps, text size, flow direction)
|
||||
persists in instance settings, and all network traffic goes through
|
||||
moduleApi (the module's server proxy at /prodcom/*). */
|
||||
persists in instance settings, and the data comes from the module's own
|
||||
server, which keeps one connection to ProdCom for every dashboard: a
|
||||
snapshot on connect (`state`), then each changed entry (`entry`). */
|
||||
|
||||
/* the text-size buttons: a drawn − and + at the icon size, like every other header icon */
|
||||
const MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14"/></svg>';
|
||||
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 }) {
|
||||
/* ── per-instance state ─────────────────────────────────────────── */
|
||||
@@ -15,7 +20,6 @@ export default function create({ root, moduleApi }) {
|
||||
let pinnedToLatest = true;
|
||||
let hiddenChannels = new Set(moduleApi.instanceSettings.hiddenChannels || []);
|
||||
let stream = null; // moduleApi.sse handle
|
||||
let bootTimer = null;
|
||||
let stopped = false;
|
||||
|
||||
/* ── DOM skeleton ───────────────────────────────────────────────── */
|
||||
@@ -48,7 +52,7 @@ export default function create({ root, moduleApi }) {
|
||||
let channelMenuEl = null; // the open menu's element (filled on each open)
|
||||
const channelsMenu = moduleApi.header.addMenu({
|
||||
icon: CHANNELS_SVG,
|
||||
title: 'Choose visible channels',
|
||||
title: 'Channels',
|
||||
build(menu) {
|
||||
menu.classList.add('pt-menu');
|
||||
channelMenuEl = menu;
|
||||
@@ -65,7 +69,7 @@ export default function create({ root, moduleApi }) {
|
||||
let timeBtn = null;
|
||||
timeBtn = moduleApi.header.addButton({
|
||||
icon: CLOCK_SVG,
|
||||
title: 'Show / hide timestamps',
|
||||
title: 'Timestamps',
|
||||
onClick() {
|
||||
moduleApi.saveInstanceSettings({ showTimes: !moduleApi.instanceSettings.showTimes });
|
||||
applyInstanceSettings();
|
||||
@@ -77,8 +81,8 @@ export default function create({ root, moduleApi }) {
|
||||
moduleApi.saveInstanceSettings({ textSize: Math.min(48, Math.max(10, current + delta)) });
|
||||
applyInstanceSettings();
|
||||
}
|
||||
moduleApi.header.addButton({ label: 'A−', title: 'Smaller text', onClick: () => bumpTextSize(-2) });
|
||||
moduleApi.header.addButton({ label: 'A+', title: 'Larger text', onClick: () => bumpTextSize(2) });
|
||||
moduleApi.header.addButton({ icon: MINUS_SVG, title: 'Smaller text', onClick: () => bumpTextSize(-2) });
|
||||
moduleApi.header.addButton({ icon: PLUS_SVG, title: 'Larger text', onClick: () => bumpTextSize(2) });
|
||||
|
||||
// icon and tooltip track the current direction — applyInstanceSettings sets both
|
||||
const flowBtn = moduleApi.header.addButton({
|
||||
@@ -93,7 +97,7 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
moduleApi.header.addButton({
|
||||
icon: JUMP_SVG,
|
||||
title: 'Jump to latest',
|
||||
title: 'Latest',
|
||||
onClick() {
|
||||
pinnedToLatest = true;
|
||||
jumpBtn.hidden = true;
|
||||
@@ -103,7 +107,7 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
const clearBtn = moduleApi.header.addButton({
|
||||
icon: CLEAR_SVG,
|
||||
title: 'Clear this tile (does not affect ProdCom)',
|
||||
title: 'Clear',
|
||||
onClick: clearView,
|
||||
});
|
||||
clearBtn.classList.add('pt-clear');
|
||||
@@ -120,9 +124,7 @@ export default function create({ root, moduleApi }) {
|
||||
wrap.classList.toggle('newest-first', up);
|
||||
flowBtn.innerHTML = up ? FLOW_UP_SVG : FLOW_DOWN_SVG;
|
||||
flowBtn.classList.toggle('active', up);
|
||||
flowBtn.title = up
|
||||
? 'Newest at top — click for newest at bottom'
|
||||
: 'Newest at bottom — click for newest at top';
|
||||
flowBtn.title = up ? 'Newest first' : 'Oldest first';
|
||||
jumpBtn.textContent = (up ? '↑' : '↓') + ' New messages';
|
||||
}
|
||||
applyInstanceSettings();
|
||||
@@ -174,9 +176,7 @@ export default function create({ root, moduleApi }) {
|
||||
channelCountEl.textContent = filtering ? `${visibleCount}/${channels.size}` : '';
|
||||
channelCountEl.hidden = !filtering;
|
||||
channelsMenu.button.classList.toggle('active', filtering);
|
||||
channelsMenu.button.title = filtering
|
||||
? `Channels — showing ${visibleCount} of ${channels.size}`
|
||||
: 'Choose visible channels';
|
||||
channelsMenu.button.title = filtering ? `Channels ${visibleCount}/${channels.size}` : 'Channels';
|
||||
}
|
||||
|
||||
function rebuildChannelMenu() {
|
||||
@@ -353,120 +353,68 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
/* The stream sends JSON objects for new/updated/completed transcript
|
||||
entries. Be liberal about the envelope shape. */
|
||||
function extractEntries(obj) {
|
||||
if (!obj || typeof obj !== 'object') return [];
|
||||
if (Array.isArray(obj)) return obj.flatMap(extractEntries);
|
||||
if (typeof obj.text === 'string' && (obj.id || obj.channelId)) return [obj];
|
||||
for (const key of ['data', 'payload', 'entry', 'entries', 'transcript']) {
|
||||
if (obj[key] && typeof obj[key] === 'object') {
|
||||
const found = extractEntries(obj[key]);
|
||||
if (found.length) return found;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
/* ── the module's feed: one snapshot, then each change ─────────── */
|
||||
|
||||
function applyStatus(st) {
|
||||
if (!st || typeof st !== 'object') return;
|
||||
if (st.state === 'ok') moduleApi.setStatus('ok', st.message || 'Live');
|
||||
else moduleApi.setStatus(st.state === 'error' ? 'error' : 'connecting', st.message || 'Connecting to ProdCom…');
|
||||
}
|
||||
|
||||
function handleEventData(raw) {
|
||||
let obj;
|
||||
try { obj = JSON.parse(raw); } catch { return; }
|
||||
const kind = String(obj.type || obj.event || '').toLowerCase();
|
||||
if (kind.includes('clear')) {
|
||||
entryEls.forEach((el) => el.remove());
|
||||
entryEls.clear();
|
||||
emptyEl.hidden = false;
|
||||
return;
|
||||
}
|
||||
extractEntries(obj).forEach(upsertEntry);
|
||||
}
|
||||
|
||||
/* ── data loading (all via the module's proxy) ──────────────────── */
|
||||
|
||||
async function loadChannels() {
|
||||
const res = await moduleApi.fetch('/prodcom/api/v1/channels');
|
||||
if (!res.ok) throw new Error('channels ' + res.status);
|
||||
const body = await res.json();
|
||||
function applySnapshot(snap) {
|
||||
if (!snap || typeof snap !== 'object') return;
|
||||
channels.clear();
|
||||
for (const ch of body.data || []) {
|
||||
channels.set(ch.id, { name: ch.name, color: ch.color || '#8b98a5' });
|
||||
}
|
||||
rebuildChannelMenu();
|
||||
}
|
||||
|
||||
async function loadGroups() {
|
||||
const res = await moduleApi.fetch('/prodcom/api/v1/groups');
|
||||
if (!res.ok) throw new Error('groups ' + res.status);
|
||||
const body = await res.json();
|
||||
for (const ch of snap.channels || []) channels.set(String(ch.id), { name: ch.name, color: ch.color || '#8b98a5' });
|
||||
groups.clear();
|
||||
for (const g of body.data || []) {
|
||||
groups.set(g.id, { name: g.name, channelIds: g.channelIds || [] });
|
||||
}
|
||||
for (const g of snap.groups || []) groups.set(String(g.id), { name: g.name, channelIds: g.channelIds || [] });
|
||||
rebuildChannelMenu();
|
||||
const list = (snap.entries || []).slice().sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||
list.forEach(upsertEntry); // dedupes by id, so a snapshot after a reconnect is harmless
|
||||
applyStatus(snap.status);
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
const res = await moduleApi.fetch('/prodcom/api/v1/transcript?limit=100');
|
||||
if (!res.ok) throw new Error('transcript ' + res.status);
|
||||
const body = await res.json();
|
||||
const entries = (body.data || []).slice();
|
||||
entries.sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||
entries.forEach(upsertEntry);
|
||||
async function loadState() {
|
||||
try {
|
||||
const res = await moduleApi.fetch('/state');
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
applySnapshot(await res.json());
|
||||
} catch { /* the stream's own snapshot covers it */ }
|
||||
}
|
||||
|
||||
/* ── live stream ────────────────────────────────────────────────── */
|
||||
|
||||
const SSE_EVENT_NAMES = [
|
||||
'transcript', 'transcript.new', 'transcript.updated', 'transcript.update',
|
||||
'transcript.completed', 'transcript.complete', 'entry', 'new', 'update',
|
||||
'updated', 'complete', 'completed',
|
||||
];
|
||||
|
||||
function connect() {
|
||||
const onEvent = (ev) => handleEventData(ev.data);
|
||||
const events = {};
|
||||
for (const name of SSE_EVENT_NAMES) events[name] = onEvent;
|
||||
|
||||
stream = moduleApi.sse('/prodcom/api/v1/transcript/stream', {
|
||||
stream = moduleApi.sse('/stream', {
|
||||
open() {
|
||||
moduleApi.setStatus('ok', 'Live');
|
||||
// refresh channels/groups and backfill entries missed while
|
||||
// disconnected (upsertEntry dedupes by id, so this is harmless)
|
||||
loadChannels().catch(() => {});
|
||||
loadGroups().catch(() => {});
|
||||
loadHistory().catch(() => {});
|
||||
loadState(); // a late joiner, or a reconnect: catch up on what was missed
|
||||
},
|
||||
error() {
|
||||
moduleApi.setStatus('error', 'ProdCom unreachable — reconnecting…');
|
||||
moduleApi.setStatus('error', 'ProdDash ProdCom module unreachable — reconnecting…');
|
||||
},
|
||||
events: {
|
||||
state(ev) {
|
||||
try { applySnapshot(JSON.parse(ev.data)); } catch { /* a bad frame is skipped */ }
|
||||
},
|
||||
entry(ev) {
|
||||
try { upsertEntry(JSON.parse(ev.data)); } catch { /* skipped */ }
|
||||
},
|
||||
clear() {
|
||||
clearView();
|
||||
},
|
||||
status(ev) {
|
||||
try { applyStatus(JSON.parse(ev.data)); } catch { /* skipped */ }
|
||||
},
|
||||
},
|
||||
message: onEvent,
|
||||
events,
|
||||
});
|
||||
}
|
||||
|
||||
/* ── lifecycle ──────────────────────────────────────────────────── */
|
||||
|
||||
async function boot() {
|
||||
if (stopped) return;
|
||||
moduleApi.setStatus('connecting', 'Connecting to ProdCom…');
|
||||
try {
|
||||
await loadChannels();
|
||||
await loadGroups().catch(() => {}); // groups are optional
|
||||
await loadHistory();
|
||||
} catch {
|
||||
moduleApi.setStatus('error', 'ProdCom unreachable — retrying…');
|
||||
bootTimer = setTimeout(boot, 5000);
|
||||
return;
|
||||
}
|
||||
scrollToLatest();
|
||||
connect();
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
boot();
|
||||
moduleApi.setStatus('connecting', 'Connecting to ProdCom…');
|
||||
connect();
|
||||
},
|
||||
stop() {
|
||||
stopped = true;
|
||||
clearTimeout(bootTimer);
|
||||
stream?.close();
|
||||
root.innerHTML = ''; // header controls are removed by the shell
|
||||
},
|
||||
|
||||
@@ -1,22 +1,35 @@
|
||||
{
|
||||
"id": "prodcom-transcript",
|
||||
"name": "ProdCom",
|
||||
"version": "1.2.1",
|
||||
"version": "1.3.2",
|
||||
"proddash": ">=1.1.0",
|
||||
"description": "Live ProdCom transcript stream",
|
||||
"description": "Live ProdCom transcript",
|
||||
"permissions": [
|
||||
{ "kind": "local-network", "reason": "Reaching the ProdCom API on this network" }
|
||||
{
|
||||
"kind": "local-network",
|
||||
"reason": "Reaching the ProdCom API on this network"
|
||||
}
|
||||
],
|
||||
"client": "client.js",
|
||||
"server": "server.js",
|
||||
"style": "style.css",
|
||||
"minSize": { "w": 3, "h": 2 },
|
||||
"defaultSize": { "w": 4, "h": 4 },
|
||||
"minSize": {
|
||||
"w": 3,
|
||||
"h": 2
|
||||
},
|
||||
"defaultSize": {
|
||||
"w": 4,
|
||||
"h": 4
|
||||
},
|
||||
"configSchema": {
|
||||
"prodcom": {
|
||||
"type": "endpoint",
|
||||
"label": "ProdCom server",
|
||||
"default": { "host": "10.3.11.152", "port": 24480 }
|
||||
"default": {
|
||||
"host": "",
|
||||
"port": 24480
|
||||
},
|
||||
"help": "The ProdCom server at THIS location — every campus has its own. Blank until you set it, so a new install never reads another campus's comms."
|
||||
},
|
||||
"apiKey": {
|
||||
"type": "password",
|
||||
@@ -27,18 +40,8 @@
|
||||
"instanceSchema": {
|
||||
"showAvatars": {
|
||||
"type": "boolean",
|
||||
"label": "Show channel icons",
|
||||
"label": "Channel icons",
|
||||
"default": true
|
||||
},
|
||||
"newestFirst": {
|
||||
"type": "boolean",
|
||||
"label": "Newest first (transcript reads bottom-up)",
|
||||
"default": false
|
||||
},
|
||||
"showTimes": {
|
||||
"type": "boolean",
|
||||
"label": "Show timestamps",
|
||||
"default": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,73 +3,34 @@
|
||||
/**
|
||||
* ProdCom Transcript — server part.
|
||||
*
|
||||
* One wildcard route that proxies /prodcom/* (including the SSE transcript
|
||||
* stream) to the ProdCom API configured in the admin page, so browsers never
|
||||
* talk to ProdCom directly (no CORS, and the API key never reaches clients).
|
||||
* Ported from prodcom-listener/server.js.
|
||||
* One connection to ProdCom for the whole server, however many dashboards
|
||||
* show the transcript. The module holds the channel list, the groups and
|
||||
* the last entries, follows ProdCom's SSE stream, and hands every browser a
|
||||
* snapshot on connect plus each change as it happens. (It used to proxy each
|
||||
* browser's stream to ProdCom one to one — N screens meant N upstream
|
||||
* connections; ProdCom now sees one.)
|
||||
*
|
||||
* Routes (under /api/modules/prodcom-transcript):
|
||||
* GET /state → { status, channels, groups, entries } (entries by date)
|
||||
* GET /stream → SSE: `state` (the snapshot, first), then `entry` for each
|
||||
* changed entry, `clear`, and `status` when the link changes
|
||||
*
|
||||
* ProdCom's API, as the reference listener speaks it:
|
||||
* GET /api/v1/channels, /api/v1/groups, /api/v1/transcript?limit=N and the
|
||||
* SSE /api/v1/transcript/stream, whose frames carry an entry, or a
|
||||
* { type, entry | data } wrapper, in a few historical shapes (see
|
||||
* extractEntries). A bearer API key is sent when one is configured.
|
||||
*/
|
||||
|
||||
const http = require('http');
|
||||
|
||||
// Hop-by-hop headers that must not be forwarded
|
||||
const HOP_HEADERS = new Set([
|
||||
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
||||
'te', 'trailer', 'transfer-encoding', 'upgrade',
|
||||
]);
|
||||
|
||||
/** Health shown in the admin page: outcome of the most recent proxied request. */
|
||||
let health = { status: 'connecting', message: 'No traffic yet' };
|
||||
|
||||
function proxy(req, res, target, apiKey) {
|
||||
const upstreamPath = (req.wildcard || '/') + (req.search || '');
|
||||
const headers = {};
|
||||
for (const [k, v] of Object.entries(req.headers)) {
|
||||
if (!HOP_HEADERS.has(k.toLowerCase())) headers[k] = v;
|
||||
}
|
||||
headers.host = target.host;
|
||||
delete headers['accept-encoding']; // keep SSE unbuffered and simple
|
||||
if (apiKey) headers.authorization = 'Bearer ' + apiKey;
|
||||
|
||||
const preq = http.request(
|
||||
{
|
||||
hostname: target.hostname,
|
||||
port: target.port || 80,
|
||||
path: upstreamPath,
|
||||
method: req.method,
|
||||
headers,
|
||||
},
|
||||
(pres) => {
|
||||
health = { status: 'ok', message: `ProdCom reachable (last: HTTP ${pres.statusCode})` };
|
||||
const outHeaders = {};
|
||||
for (const [k, v] of Object.entries(pres.headers)) {
|
||||
if (!HOP_HEADERS.has(k.toLowerCase())) outHeaders[k] = v;
|
||||
}
|
||||
res.writeHead(pres.statusCode, outHeaders);
|
||||
// Flush immediately — SSE streams may send no bytes for a while, and
|
||||
// the browser needs the headers to consider the stream open.
|
||||
res.flushHeaders();
|
||||
pres.pipe(res);
|
||||
// If ProdCom dies mid-stream, pipe() unpipes on error without ending
|
||||
// the browser's response, leaving SSE clients hanging on a dead
|
||||
// stream. Destroy it so they notice immediately and reconnect.
|
||||
pres.on('close', () => {
|
||||
if (!res.writableEnded) res.destroy();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
preq.on('error', (e) => {
|
||||
health = { status: 'error', message: 'ProdCom unreachable: ' + (e.code || String(e)) };
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(502, { 'Content-Type': 'application/json' });
|
||||
}
|
||||
res.end(JSON.stringify({ error: 'ProdCom unreachable', detail: e.code || String(e) }));
|
||||
});
|
||||
|
||||
// Tear down the upstream connection when the browser disconnects
|
||||
res.on('close', () => preq.destroy());
|
||||
req.pipe(preq);
|
||||
}
|
||||
const HISTORY_LIMIT = 100; // entries asked for on (re)connect
|
||||
const ENTRIES_MAX = 300; // entries kept in memory
|
||||
const RETRY_MIN_MS = 2000;
|
||||
const RETRY_MAX_MS = 15000;
|
||||
const REQUEST_TIMEOUT_MS = 8000;
|
||||
const REFRESH_LISTS_MS = 5 * 60 * 1000; // channels and groups re-read
|
||||
const HEARTBEAT_MS = 15000;
|
||||
|
||||
/** The ProdCom base URL from the endpoint config. A legacy prodcomUrl (saved
|
||||
before the endpoint field existed) can only still be present until the
|
||||
@@ -82,23 +43,284 @@ function resolveTarget(config) {
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init({ config }) {
|
||||
health = resolveTarget(config)
|
||||
? { status: 'connecting', message: 'No traffic yet' }
|
||||
: { status: 'error', message: 'No ProdCom server configured' };
|
||||
/** Entries inside whatever ProdCom sent: a bare entry, or one wrapped in data / payload / entry / entries / transcript. */
|
||||
function extractEntries(obj) {
|
||||
if (!obj || typeof obj !== 'object') return [];
|
||||
if (Array.isArray(obj)) return obj.flatMap(extractEntries);
|
||||
if (typeof obj.text === 'string' && (obj.id || obj.channelId)) return [obj];
|
||||
for (const key of ['data', 'payload', 'entry', 'entries', 'transcript']) {
|
||||
if (obj[key] && typeof obj[key] === 'object') {
|
||||
const found = extractEntries(obj[key]);
|
||||
if (found.length) return found;
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** One entry as the tiles read it; an entry without an id is keyed by channel and time. */
|
||||
function normalizeEntry(e) {
|
||||
const id = e.id !== undefined && e.id !== null && e.id !== '' ? String(e.id) : `${e.channelId || ''}|${e.date || ''}`;
|
||||
return {
|
||||
stop() { /* nothing persistent to tear down — streams die with their sockets */ },
|
||||
health: () => health,
|
||||
id,
|
||||
channelId: e.channelId === undefined || e.channelId === null ? '' : String(e.channelId),
|
||||
channelName: e.channelName ? String(e.channelName) : '',
|
||||
text: String(e.text ?? ''),
|
||||
date: e.date ? String(e.date) : new Date().toISOString(),
|
||||
inProgress: Boolean(e.inProgress),
|
||||
};
|
||||
}
|
||||
|
||||
let current = null; // the running instance, for routes()
|
||||
|
||||
module.exports = {
|
||||
init({ config, log }) {
|
||||
const target = resolveTarget(config);
|
||||
const apiKey = String(config.apiKey || '');
|
||||
const channels = [];
|
||||
const groups = [];
|
||||
const entries = new Map(); // id → entry, in arrival order
|
||||
const streams = new Set(); // browsers' SSE responses
|
||||
let status = { state: 'connecting', message: target ? 'Connecting to ProdCom…' : 'No ProdCom server configured' };
|
||||
let stopped = false;
|
||||
let upstream = null;
|
||||
let generation = 0; // callbacks from a superseded connection are ignored
|
||||
let retryTimer = null;
|
||||
let retryMs = RETRY_MIN_MS;
|
||||
|
||||
const authHeaders = () => (apiKey ? { authorization: `Bearer ${apiKey}` } : {});
|
||||
|
||||
async function getJson(pathname) {
|
||||
const res = await fetch(new URL(pathname, target), {
|
||||
headers: { accept: 'application/json', ...authHeaders() },
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status} for ${pathname}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function sortedEntries() {
|
||||
return [...entries.values()].sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||
}
|
||||
|
||||
function snapshot() {
|
||||
return { status, channels, groups, entries: sortedEntries() };
|
||||
}
|
||||
|
||||
function broadcast(event, data) {
|
||||
if (!streams.size) return;
|
||||
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
||||
for (const res of streams) {
|
||||
try {
|
||||
res.write(frame);
|
||||
} catch {
|
||||
streams.delete(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(state, message) {
|
||||
if (status.state === state && status.message === message) return;
|
||||
status = { state, message };
|
||||
broadcast('status', status);
|
||||
}
|
||||
|
||||
function trim() {
|
||||
while (entries.size > ENTRIES_MAX) entries.delete(entries.keys().next().value);
|
||||
}
|
||||
|
||||
/** A changed entry: kept, and told to every browser. */
|
||||
function upsert(raw) {
|
||||
const e = normalizeEntry(raw);
|
||||
const prev = entries.get(e.id);
|
||||
if (prev && prev.text === e.text && prev.inProgress === e.inProgress && prev.channelId === e.channelId) return;
|
||||
entries.set(e.id, e);
|
||||
trim();
|
||||
broadcast('entry', e);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
entries.clear();
|
||||
broadcast('clear', {});
|
||||
}
|
||||
|
||||
async function loadLists() {
|
||||
const [ch, gr] = await Promise.all([
|
||||
getJson('/api/v1/channels'),
|
||||
getJson('/api/v1/groups').catch(() => ({ data: [] })), // groups are optional in ProdCom
|
||||
]);
|
||||
channels.splice(0, channels.length, ...(ch.data || []).map((c) => ({ id: String(c.id), name: String(c.name || c.id), color: c.color || '#8b98a5' })));
|
||||
groups.splice(0, groups.length, ...(gr.data || []).map((g) => ({ id: String(g.id), name: String(g.name || g.id), channelIds: Array.isArray(g.channelIds) ? g.channelIds.map(String) : [] })));
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
const body = await getJson(`/api/v1/transcript?limit=${HISTORY_LIMIT}`);
|
||||
for (const e of extractEntries(body).map(normalizeEntry)) entries.set(e.id, e);
|
||||
trim();
|
||||
}
|
||||
|
||||
function handleFrame(block) {
|
||||
const data = [];
|
||||
for (const line of block.split('\n')) {
|
||||
if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
||||
}
|
||||
if (!data.length) return;
|
||||
let obj;
|
||||
try {
|
||||
obj = JSON.parse(data.join('\n'));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const kind = String(obj?.type || obj?.event || '').toLowerCase();
|
||||
if (kind.includes('clear')) return clearAll();
|
||||
extractEntries(obj).forEach(upsert);
|
||||
}
|
||||
|
||||
function scheduleRetry() {
|
||||
if (stopped) return;
|
||||
clearTimeout(retryTimer);
|
||||
retryTimer = setTimeout(connect, retryMs);
|
||||
retryMs = Math.min(RETRY_MAX_MS, retryMs * 2);
|
||||
}
|
||||
|
||||
function fail(gen, why) {
|
||||
if (stopped || gen !== generation) return;
|
||||
generation += 1; // whatever else this connection reports is stale now
|
||||
try { upstream?.destroy(); } catch { /* already gone */ }
|
||||
upstream = null;
|
||||
setStatus('error', `ProdCom unreachable (${why}) — retrying`);
|
||||
log(`ProdCom ${target.origin}: ${why} — retrying in ${retryMs / 1000} s`);
|
||||
scheduleRetry();
|
||||
}
|
||||
|
||||
/** Lists and history first (a fresh snapshot for the tiles), then the live stream. */
|
||||
async function connect() {
|
||||
if (stopped || !target) return;
|
||||
const gen = ++generation;
|
||||
try {
|
||||
await loadLists();
|
||||
await loadHistory();
|
||||
} catch (err) {
|
||||
if (gen !== generation || stopped) return;
|
||||
return fail(gen, err.cause?.code || err.code || err.message);
|
||||
}
|
||||
if (gen !== generation || stopped) return;
|
||||
broadcast('state', snapshot());
|
||||
const url = new URL('/api/v1/transcript/stream', target);
|
||||
const req = http.request({
|
||||
hostname: url.hostname,
|
||||
port: url.port || 80,
|
||||
path: url.pathname,
|
||||
method: 'GET',
|
||||
headers: { accept: 'text/event-stream', ...authHeaders() },
|
||||
}, (res) => {
|
||||
if (gen !== generation) return void res.destroy();
|
||||
if (res.statusCode !== 200) {
|
||||
res.resume();
|
||||
return fail(gen, `HTTP ${res.statusCode} from the transcript stream`);
|
||||
}
|
||||
retryMs = RETRY_MIN_MS;
|
||||
setStatus('ok', 'Live');
|
||||
log(`following ${target.origin} — ${channels.length} channels, ${entries.size} entries`);
|
||||
let buf = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (chunk) => {
|
||||
if (gen !== generation) return;
|
||||
buf += chunk;
|
||||
let i;
|
||||
while ((i = buf.indexOf('\n\n')) >= 0) {
|
||||
handleFrame(buf.slice(0, i));
|
||||
buf = buf.slice(i + 2);
|
||||
}
|
||||
if (buf.length > 1e6) buf = ''; // a frame that never ends is dropped
|
||||
});
|
||||
res.on('end', () => fail(gen, 'stream ended'));
|
||||
res.on('error', (err) => fail(gen, err.code || err.message));
|
||||
});
|
||||
req.on('error', (err) => fail(gen, err.code || err.message));
|
||||
req.end();
|
||||
upstream = req;
|
||||
}
|
||||
|
||||
const listsTimer = setInterval(() => {
|
||||
if (stopped || status.state !== 'ok') return;
|
||||
loadLists().then(() => broadcast('state', snapshot())).catch(() => { /* the next reconnect re-reads them */ });
|
||||
}, REFRESH_LISTS_MS);
|
||||
listsTimer.unref?.();
|
||||
const heartbeat = setInterval(() => {
|
||||
for (const res of streams) {
|
||||
try {
|
||||
res.write(': ping\n\n');
|
||||
} catch {
|
||||
streams.delete(res);
|
||||
}
|
||||
}
|
||||
}, HEARTBEAT_MS);
|
||||
heartbeat.unref?.();
|
||||
|
||||
if (target) {
|
||||
log(`one connection to ProdCom at ${target.origin}, shared by every dashboard`);
|
||||
connect();
|
||||
} else {
|
||||
log('no ProdCom server configured — set the endpoint in /admin');
|
||||
}
|
||||
|
||||
current = {
|
||||
snapshot,
|
||||
streams,
|
||||
health() {
|
||||
if (status.state === 'ok') return { status: 'ok', message: `Live — ${channels.length} channel${channels.length === 1 ? '' : 's'}, ${entries.size} entries` };
|
||||
// Nothing to connect to is a setting that is missing, not a link that
|
||||
// is coming up — it reads red, like the other modules say it.
|
||||
if (!target) return { status: 'error', message: status.message };
|
||||
return { status: status.state === 'error' ? 'error' : 'connecting', message: status.message };
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
stop() {
|
||||
stopped = true;
|
||||
generation += 1;
|
||||
clearTimeout(retryTimer);
|
||||
clearInterval(listsTimer);
|
||||
clearInterval(heartbeat);
|
||||
try { upstream?.destroy(); } catch { /* already gone */ }
|
||||
for (const res of streams) {
|
||||
try { res.end(); } catch { /* gone */ }
|
||||
}
|
||||
streams.clear();
|
||||
if (current?.streams === streams) current = null;
|
||||
},
|
||||
health: () => (current ? current.health() : { status: 'connecting', message: 'Restarting…' }),
|
||||
};
|
||||
},
|
||||
|
||||
routes({ config, log }) {
|
||||
// An invalid host/URL throws here, which surfaces as a mount error in /admin.
|
||||
const target = resolveTarget(config) || new URL('http://10.3.11.152:24480');
|
||||
log(`proxying /prodcom/* → ${target.origin}`);
|
||||
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));
|
||||
};
|
||||
return {
|
||||
'* /prodcom/*': (req, res) => proxy(req, res, target, config.apiKey || ''),
|
||||
'GET /state': (req, res) => {
|
||||
if (!current) return sendJson(res, 503, { error: 'ProdCom module is restarting — try again' });
|
||||
sendJson(res, 200, current.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',
|
||||
'X-Accel-Buffering': 'no',
|
||||
});
|
||||
res.write('retry: 3000\n\n');
|
||||
if (!current) {
|
||||
res.write(`event: state\ndata: ${JSON.stringify({ status: { state: 'connecting', message: 'ProdCom module is restarting…' }, channels: [], groups: [], entries: [] })}\n\n`);
|
||||
return void res.end();
|
||||
}
|
||||
res.write(`event: state\ndata: ${JSON.stringify(current.snapshot())}\n\n`);
|
||||
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
|
||||
current.streams.add(res);
|
||||
req.on('close', () => current && current.streams.delete(res));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -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 ──────────────────────────────────────────────────── */
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -15,9 +15,13 @@
|
||||
|
||||
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
|
||||
picker entry's own schema — see tiles() in server.js), so a setting may
|
||||
simply be absent here: every read goes through pref(), which falls back
|
||||
to DEFAULTS rather than to whatever schema the tile happens to have.
|
||||
|
||||
Feedback — the state colours, and the thresholds behind them:
|
||||
running elapsed, no planned length running
|
||||
@@ -37,8 +41,6 @@
|
||||
theme; left at their defaults they follow the theme's variables. */
|
||||
|
||||
/** Which instance switch governs a source kind. */
|
||||
const SOURCE_SWITCH = { propresenter: 'showProPresenter', ltc: 'showLtc', clock: 'showClock', module: 'showModules' };
|
||||
|
||||
/** Colour settings → custom property, and the schema default (module.json) that means "follow the theme". */
|
||||
const COLOR_SETTINGS = [
|
||||
['runningColor', '--tm-ok', '#2ee59a'],
|
||||
@@ -56,6 +58,25 @@ const PAINT_MS = 200;
|
||||
|
||||
const LTC_KEY = 'ltc:ltc';
|
||||
|
||||
/** What the tile assumes for a setting its schema doesn't carry (a solo
|
||||
tile offers only what applies to its card) or that was never saved. The
|
||||
switches default to on, the clock to 24-hour with seconds and no date —
|
||||
the same values module.json gives the full "All timers" schema. */
|
||||
const DEFAULTS = {
|
||||
showNames: true,
|
||||
groupBySource: false,
|
||||
showHeadings: true,
|
||||
showStatus: true,
|
||||
showDetail: true,
|
||||
showSeconds: true,
|
||||
leadingZeros: false,
|
||||
clock24h: true,
|
||||
clockSeconds: true,
|
||||
clockDate: false,
|
||||
dateShortDay: false,
|
||||
dateShortMonth: false,
|
||||
};
|
||||
|
||||
/* ── SMPTE timecode math (module-scope, exported for tests) ─────────
|
||||
The server anchors us ~4×/s with { time, fps, df, ageMs }; the card
|
||||
counts every frame in between locally. That needs exact frame↔timecode
|
||||
@@ -120,14 +141,26 @@ export function valueAt(timer, sourceUpdatedAt, now) {
|
||||
}
|
||||
|
||||
/** Signed ms → "M:SS" / "H:MM:SS" (whole seconds, floor of the magnitude). */
|
||||
export function fmtDuration(ms) {
|
||||
/**
|
||||
* A duration as digits. `seconds: false` shows minutes only — a countdown
|
||||
* rounds up (3:59 left reads "4", 0:30 over reads "-1"), an elapsed timer
|
||||
* rounds down; `zeros` pads the leading field to two digits ("05:07").
|
||||
*/
|
||||
export function fmtDuration(ms, { seconds = true, zeros = false, up = false } = {}) {
|
||||
const sign = ms < 0 ? '-' : '';
|
||||
const s = Math.floor(Math.abs(ms) / 1000);
|
||||
const total = Math.abs(ms) / 1000;
|
||||
const pad = (v) => String(v).padStart(2, '0');
|
||||
if (!seconds) {
|
||||
const mins = up ? Math.ceil(total / 60) : Math.floor(total / 60);
|
||||
const h = Math.floor(mins / 60);
|
||||
const m = mins % 60;
|
||||
return h ? `${sign}${zeros ? pad(h) : h}:${pad(m)}` : `${sign}${zeros ? pad(m) : m}`;
|
||||
}
|
||||
const s = Math.floor(total);
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const sec = s % 60;
|
||||
const pad = (v) => String(v).padStart(2, '0');
|
||||
return h ? `${sign}${h}:${pad(m)}:${pad(sec)}` : `${sign}${m}:${pad(sec)}`;
|
||||
return h ? `${sign}${zeros ? pad(h) : h}:${pad(m)}:${pad(sec)}` : `${sign}${zeros ? pad(m) : m}:${pad(sec)}`;
|
||||
}
|
||||
|
||||
function warnWindow(targetMs) {
|
||||
@@ -163,6 +196,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;
|
||||
@@ -174,6 +211,15 @@ export default function create({ root, moduleApi }) {
|
||||
let needFit = true;
|
||||
|
||||
const settings = () => moduleApi.instanceSettings;
|
||||
/** One setting, resolved here: what this tile saved, else DEFAULTS — never
|
||||
whatever its (possibly slimmer) schema would or wouldn't default. */
|
||||
const pref = (key) => {
|
||||
const v = settings()[key];
|
||||
if (v !== undefined && v !== null) return v;
|
||||
// A layout from before the 24-hour switch chose a "clockFormat".
|
||||
if (key === 'clock24h' && settings().clockFormat === '12h') return false;
|
||||
return DEFAULTS[key];
|
||||
};
|
||||
const keyOf = (source, timer) => `${source.id}:${timer.id}`;
|
||||
|
||||
/* Per-tile hidden timers, keyed source:id. Layouts saved by the earlier
|
||||
@@ -185,7 +231,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 || '');
|
||||
@@ -193,8 +239,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 ───────────────────────────────────────────────── */
|
||||
|
||||
@@ -241,8 +285,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 which timers this tile shows',
|
||||
icon: TIMERS_SVG,
|
||||
title: 'Timers',
|
||||
build(menu) {
|
||||
// the shell hands over an emptied element on every open
|
||||
menu.classList.add('tm-menu');
|
||||
@@ -250,6 +294,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 = [];
|
||||
@@ -277,7 +327,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 = '';
|
||||
@@ -322,31 +374,24 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
/* ── state → what this tile shows ───────────────────────────────── */
|
||||
|
||||
function sourceShown(source) {
|
||||
const key = SOURCE_SWITCH[source.kind] || 'showModules';
|
||||
return settings()[key] !== false;
|
||||
}
|
||||
|
||||
/** [{ 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) {
|
||||
if (!sourceShown(source)) continue;
|
||||
const items = [];
|
||||
for (const timer of source.timers) {
|
||||
const key = keyOf(source, timer);
|
||||
@@ -356,7 +401,18 @@ export default function create({ root, moduleApi }) {
|
||||
if (!items.length && source.timers.length) continue;
|
||||
groups.push({ id: source.id, source, items });
|
||||
}
|
||||
return groups;
|
||||
if (pref('groupBySource') === true) return groups;
|
||||
// Grouping off: every timer in one grid, filled row by row. A source in
|
||||
// trouble is still named, in one line above the cards.
|
||||
const trouble = groups.filter((g) => g.source && g.source.status !== 'ok');
|
||||
return [{
|
||||
id: 'all',
|
||||
source: null,
|
||||
flat: true,
|
||||
items: groups.flatMap((g) => g.items),
|
||||
status: trouble.length ? 'error' : 'ok',
|
||||
message: trouble.map((g) => `${g.source.label}: ${g.source.message || 'unavailable'}`).join(' · '),
|
||||
}];
|
||||
}
|
||||
|
||||
/* ── cards ──────────────────────────────────────────────────────── */
|
||||
@@ -392,6 +448,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.source?.kind === 'clock';
|
||||
const isLtc = item.source?.kind === 'ltc';
|
||||
const badge = card.nameEl.querySelector('.tm-ltc-badge');
|
||||
if (isLtc && !badge) {
|
||||
@@ -402,35 +459,22 @@ export default function create({ root, moduleApi }) {
|
||||
} else if (!isLtc && badge) {
|
||||
badge.remove();
|
||||
}
|
||||
setText(card.labelEl, item.missing ? (lastSoloLabel || 'Timer') : 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() {
|
||||
const s = settings();
|
||||
const h12 = s.clockFormat === '12h';
|
||||
const h12 = pref('clock24h') === false;
|
||||
return {
|
||||
hour12: h12,
|
||||
hour: h12 ? 'numeric' : '2-digit',
|
||||
minute: '2-digit',
|
||||
...(s.clockSeconds !== false ? { second: '2-digit' } : {}),
|
||||
...(pref('clockSeconds') !== false ? { second: '2-digit' } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -438,8 +482,43 @@ export default function create({ root, moduleApi }) {
|
||||
return new Date().toLocaleTimeString([], clockOptions());
|
||||
}
|
||||
|
||||
function dateText() {
|
||||
return new Date().toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' });
|
||||
/** The date as the day and the rest — the break, when one is needed, falls between them. */
|
||||
function dateParts() {
|
||||
const d = new Date();
|
||||
return {
|
||||
day: d.toLocaleDateString([], { weekday: pref('dateShortDay') ? 'short' : 'long' }),
|
||||
rest: d.toLocaleDateString([], { month: pref('dateShortMonth') ? 'short' : 'long', day: 'numeric' }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The clock's date under its digits: one line when it fits the card,
|
||||
* otherwise a line break after the day and a size that fits the longer
|
||||
* half. Re-done only when the text or the card width changes.
|
||||
*/
|
||||
function renderDate(card, d) {
|
||||
const cw = lastFit.cw;
|
||||
const lineSize = lastFit.meta * LINE_SCALE;
|
||||
const whole = `${d.day}, ${d.rest}`;
|
||||
const key = `${whole}|${Math.round(cw)}|${lineSize}`;
|
||||
if (card.dateKey === key) return;
|
||||
card.dateKey = key;
|
||||
let px = lineSize;
|
||||
let wrapIt = false;
|
||||
if (textWidth(whole, lineSize, 0.1) > cw) {
|
||||
wrapIt = true;
|
||||
const widest = Math.max(textWidth(`${d.day},`, lineSize, 0.1), textWidth(d.rest, lineSize, 0.1));
|
||||
px = Math.max(8, Math.floor(lineSize * Math.min(1, cw / widest)));
|
||||
}
|
||||
const el = card.statusEl;
|
||||
el.textContent = '';
|
||||
const a = document.createElement('span');
|
||||
a.textContent = `${d.day},`;
|
||||
const b = document.createElement('span');
|
||||
b.textContent = d.rest;
|
||||
el.append(a, document.createTextNode(' '), b);
|
||||
el.style.fontSize = px === lineSize ? '' : `${px}px`;
|
||||
card.dateCls = wrapIt ? ' is-date is-wrap' : ' is-date';
|
||||
}
|
||||
|
||||
/** A provider's kind:"clock" timer carries an ISO time in status.text as of its snapshot. */
|
||||
@@ -529,14 +608,12 @@ export default function create({ root, moduleApi }) {
|
||||
function paint() {
|
||||
if (!state) return;
|
||||
const now = serverNow();
|
||||
const showStatus = settings().showStatus !== false;
|
||||
const showStatus = pref('showStatus') !== false;
|
||||
const showDetail = pref('showDetail') !== false;
|
||||
const digits = { seconds: pref('showSeconds') !== false, zeros: pref('leadingZeros') === true };
|
||||
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;
|
||||
@@ -544,6 +621,7 @@ export default function create({ root, moduleApi }) {
|
||||
let statusTone = '';
|
||||
let detailText = '';
|
||||
let extra = '';
|
||||
let date = null;
|
||||
if (timer.kind === 'clock') {
|
||||
if (source.kind === 'ltc') {
|
||||
const l = timer.ltc || {};
|
||||
@@ -559,7 +637,8 @@ export default function create({ root, moduleApi }) {
|
||||
} else if (source.kind === 'clock') {
|
||||
text = wallClockText();
|
||||
tone = 'plain';
|
||||
statusText = settings().clockDate ? dateText() : '';
|
||||
date = pref('clockDate') ? dateParts() : null;
|
||||
statusText = date ? `${date.day}, ${date.rest}` : '';
|
||||
statusTone = 'muted';
|
||||
} else {
|
||||
text = providerClockText(timer, source, now);
|
||||
@@ -569,7 +648,7 @@ export default function create({ root, moduleApi }) {
|
||||
}
|
||||
} else {
|
||||
const value = valueAt(timer, source.updatedAt, now);
|
||||
text = value === null ? '—' : fmtDuration(value);
|
||||
text = value === null ? '—' : fmtDuration(value, { ...digits, up: timer.kind === 'countdown' });
|
||||
tone = toneFor(timer, value);
|
||||
statusText = timer.status?.text || defaultStatus(timer, value, tone);
|
||||
statusTone = timer.status?.tone || tone;
|
||||
@@ -586,14 +665,21 @@ export default function create({ root, moduleApi }) {
|
||||
}
|
||||
// Notes that must survive the compact look: an unavailable LTC input.
|
||||
const isNote = extra === ' is-unavailable';
|
||||
setText(card.statusEl, statusText);
|
||||
setText(card.statusEl, statusText); // a no-op over the date's two spans: same text
|
||||
card.statusEl.hidden = !statusText || (!showStatus && !isNote);
|
||||
card.statusEl.className = 'tm-status' + (isNote ? ' is-note' : '');
|
||||
if (date && !card.statusEl.hidden) renderDate(card, date);
|
||||
else if (card.dateCls) {
|
||||
card.dateCls = '';
|
||||
card.dateKey = '';
|
||||
card.statusEl.style.fontSize = '';
|
||||
}
|
||||
card.statusEl.className = 'tm-status' + (isNote ? ' is-note' : '') + (card.dateCls || '');
|
||||
card.statusEl.dataset.tone = statusTone;
|
||||
setText(card.detailEl, detailText);
|
||||
card.detailEl.hidden = !detailText || !showStatus;
|
||||
card.detailEl.hidden = !detailText || !showDetail;
|
||||
const kindCls = source.kind === 'ltc' ? ' tm-card-ltc' : source.kind === 'clock' ? ' tm-card-clock' : '';
|
||||
setCardClass(card, `tm-card is-${tone}${extra}${kindCls}`);
|
||||
const stale = source.status === 'error' ? ' is-stale' : '';
|
||||
setCardClass(card, `tm-card is-${tone}${extra}${kindCls}${stale}`);
|
||||
}
|
||||
if (charsChanged) fit();
|
||||
}
|
||||
@@ -626,8 +712,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 ────────── */
|
||||
@@ -664,16 +751,25 @@ export default function create({ root, moduleApi }) {
|
||||
wrap.classList.toggle('tm-mono', mono);
|
||||
needFit = true;
|
||||
}
|
||||
const s = settings();
|
||||
const showHeadings = !solo && s.showHeadings !== false;
|
||||
const showStatus = s.showStatus !== false;
|
||||
// Headings belong to sections; without grouping there is one grid and no heading.
|
||||
const showHeadings = !solo && pref('groupBySource') === true && pref('showHeadings') !== false;
|
||||
wrap.classList.toggle('tm-headings', showHeadings);
|
||||
wrap.classList.toggle('tm-nostatus', !showStatus);
|
||||
for (const [cls, on] of [
|
||||
['tm-grouped', !solo && pref('groupBySource') === true],
|
||||
['tm-nostatus', pref('showStatus') === false],
|
||||
['tm-nodetail', pref('showDetail') === false],
|
||||
['tm-nonames', pref('showNames') === false],
|
||||
]) {
|
||||
if (wrap.classList.contains(cls) !== on) {
|
||||
wrap.classList.toggle(cls, on);
|
||||
needFit = true;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -690,18 +786,24 @@ export default function create({ root, moduleApi }) {
|
||||
structureChanged = true;
|
||||
}
|
||||
const source = g.source;
|
||||
const status = source ? source.status : 'ok';
|
||||
const message = source ? source.message : '';
|
||||
const status = g.status ?? (source ? source.status : 'ok');
|
||||
const message = g.message ?? (source ? source.message : '');
|
||||
ge.headEl.hidden = !showHeadings;
|
||||
setText(ge.titleEl, source ? source.label : 'Timer');
|
||||
setText(ge.titleEl, source ? source.label : 'Timers');
|
||||
setText(ge.noteEl, status !== 'ok' ? message : g.items.length ? '' : 'no timers');
|
||||
// Without headings the source's trouble still has to be said somewhere.
|
||||
const emptyText = status !== 'ok' ? message : 'No timers';
|
||||
const showEmpty = !showHeadings && (status !== 'ok' || !g.items.length);
|
||||
ge.emptyEl.hidden = !showEmpty;
|
||||
setText(ge.emptyEl, showEmpty ? emptyText : '');
|
||||
ge.el.classList.toggle('is-down', status !== 'ok');
|
||||
ge.el.classList.toggle('is-stale', status === 'error' && g.items.length > 0);
|
||||
ge.emptyEl.dataset.tone = showEmpty && status !== 'ok' ? 'warn' : '';
|
||||
// In the flat grid a card dims for its own source (paint), not the whole grid.
|
||||
ge.el.classList.toggle('is-down', !g.flat && status !== 'ok');
|
||||
ge.el.classList.toggle('is-stale', !g.flat && status === 'error' && g.items.length > 0);
|
||||
if (ge.gridEl.classList.contains('is-flow') !== Boolean(g.flat)) {
|
||||
ge.gridEl.classList.toggle('is-flow', Boolean(g.flat));
|
||||
structureChanged = true;
|
||||
}
|
||||
|
||||
const els = [];
|
||||
for (const item of g.items) {
|
||||
@@ -748,6 +850,30 @@ export default function create({ root, moduleApi }) {
|
||||
|
||||
/* ── sizing: the column count that gives the biggest digits ─────── */
|
||||
|
||||
/** Status and detail lines are drawn at this share of the label's size (style.css agrees). */
|
||||
const LINE_SCALE = 0.8;
|
||||
|
||||
/* Text measured off-screen the way the CSS draws it (bold, uppercase,
|
||||
letter-spaced), so a title or the date can shrink before the card
|
||||
would cut it off. */
|
||||
const measurer = document.createElement('canvas').getContext('2d');
|
||||
let textFamily = '';
|
||||
function textWidth(text, px, spacingEm) {
|
||||
if (!textFamily) textFamily = getComputedStyle(root).fontFamily || 'sans-serif';
|
||||
measurer.font = `700 ${px}px ${textFamily}`;
|
||||
const t = String(text || '').toUpperCase();
|
||||
return measurer.measureText(t).width + spacingEm * px * Math.max(0, t.length - 1);
|
||||
}
|
||||
/** The last fit's card width and label size — what the date is fitted against. */
|
||||
let lastFit = { cw: 200, meta: 12 };
|
||||
function fitLabel(card, meta, avail) {
|
||||
if (card.isClock) return; // the clock has no label line
|
||||
const room = Math.max(24, avail - (card.nameEl.querySelector('.tm-ltc-badge') ? 34 : 0));
|
||||
const natural = textWidth(card.labelEl.textContent, meta, 0.08);
|
||||
const px = natural > room ? Math.max(8, Math.floor((meta * room) / natural)) : meta;
|
||||
card.labelEl.style.fontSize = px === meta ? '' : `${px}px`;
|
||||
}
|
||||
|
||||
function fit() {
|
||||
const list = [...cards.values()];
|
||||
const n = list.length;
|
||||
@@ -759,54 +885,90 @@ export default function create({ root, moduleApi }) {
|
||||
const CARD_PAD = 12; // a card's own vertical padding + borders
|
||||
const HEAD_H = 20; // a source heading line, margin included
|
||||
const groups = [...groupEls.values()].filter((g) => g.el.isConnected);
|
||||
// Grouped: each source's grid wraps on its own, so its rows add up; flat:
|
||||
// one grid. Headings only add a line each — they never decide the rows.
|
||||
const grouped = wrap.classList.contains('tm-grouped') && groups.length > 1;
|
||||
const headings = wrap.classList.contains('tm-headings') ? groups.length : 0;
|
||||
const showStatus = !wrap.classList.contains('tm-nostatus');
|
||||
// Lines under the digits besides the label: status, and detail if any card has one.
|
||||
const metaLines = showStatus ? 1 + (list.some((c) => !c.detailEl.hidden) ? 1 : 0) : 0;
|
||||
const showDetail = !wrap.classList.contains('tm-nodetail');
|
||||
const namesOn = !wrap.classList.contains('tm-nonames');
|
||||
// Lines under the digits: status, and detail if any card has one.
|
||||
const metaLines = (showStatus ? 1 : 0) + (showDetail && list.some((c) => !c.detailEl.hidden) ? 1 : 0);
|
||||
const date = showStatus && pref('clockDate') && list.some((c) => c.isClock) ? dateParts() : null;
|
||||
const dateWhole = date ? `${date.day}, ${date.rest}` : '';
|
||||
|
||||
// For each column count, budget a card's full stack (label, digits,
|
||||
// lines) and score by the digit size it affords — the SMALLEST card's,
|
||||
// so no timer ends up unreadable. Cards too short for the full stack
|
||||
// drop to a compact look (label + digits, the colour carries the
|
||||
// state), but any layout with a readable full stack beats every
|
||||
// compact one.
|
||||
// compact one. The clock has no label line, and its date may take two.
|
||||
const budgetFor = (c, ch, meta, mode, dateWrap) => {
|
||||
const nameLine = namesOn && !c.isClock ? 1.3 * meta : 0;
|
||||
if (mode === 'compact') return ch - nameLine;
|
||||
const lines = metaLines + (c.isClock && dateWrap ? 1 : 0);
|
||||
return ch - nameLine - lines * 1.3 * meta * LINE_SCALE;
|
||||
};
|
||||
const rowsFor = (cols) => (grouped
|
||||
? groups.reduce((a, g) => a + Math.max(1, Math.ceil(g.count / cols)), 0)
|
||||
: Math.ceil(n / cols));
|
||||
let best = null;
|
||||
for (let cols = 1; cols <= n; cols += 1) {
|
||||
const rows = headings
|
||||
? groups.reduce((a, g) => a + Math.max(1, Math.ceil(g.count / cols)), 0)
|
||||
: Math.ceil(n / cols);
|
||||
const rows = rowsFor(cols);
|
||||
const cw = (W - PAD * 2 - GAP * (cols - 1)) / cols - 18;
|
||||
const ch = (H - PAD * 2 - headings * HEAD_H - GAP * (rows - 1) - (headings ? (headings - 1) * GAP : 0)) / rows - CARD_PAD;
|
||||
// Every row the same height: padding, one heading line per group, and
|
||||
// a gap between any two rows (between groups too) come off the top.
|
||||
const rowH = (H - PAD * 2 - headings * HEAD_H - GAP * (rows - 1)) / rows;
|
||||
const ch = rowH - CARD_PAD;
|
||||
if (cw <= 0 || ch <= 0) continue;
|
||||
const meta = Math.max(9, Math.min(22, Math.floor(ch * 0.16)));
|
||||
const fullBudget = ch - (1 + metaLines) * 1.3 * meta;
|
||||
const compactBudget = ch - 1.3 * meta;
|
||||
const dateWrap = Boolean(dateWhole) && textWidth(dateWhole, meta * LINE_SCALE, 0.1) > cw;
|
||||
let full = Infinity;
|
||||
let compact = Infinity;
|
||||
for (const c of list) {
|
||||
const byWidth = (cw * 1.55) / c.chars;
|
||||
full = Math.min(full, byWidth, fullBudget);
|
||||
compact = Math.min(compact, byWidth, compactBudget);
|
||||
full = Math.min(full, byWidth, budgetFor(c, ch, meta, 'full', dateWrap));
|
||||
compact = Math.min(compact, byWidth, budgetFor(c, ch, meta, 'compact', dateWrap));
|
||||
}
|
||||
const mode = full >= 14 ? 'full' : 'compact';
|
||||
const size = mode === 'full' ? full : compact;
|
||||
const score = (mode === 'full' ? 1000 : 0) + size;
|
||||
if (!best || score > best.score) best = { cols, meta, mode, cw, budget: mode === 'full' ? fullBudget : compactBudget, score };
|
||||
if (!best || score > best.score) best = { cols, meta, mode, cw, ch, rowH, dateWrap, score };
|
||||
}
|
||||
if (!best) return;
|
||||
for (const g of groups) {
|
||||
g.gridEl.style.gridTemplateColumns = `repeat(${best.cols}, 1fr)`;
|
||||
// Space is shared in proportion to each group's rows, so a card is
|
||||
// the same height under every heading.
|
||||
g.el.style.flexGrow = String(Math.max(1, Math.ceil(g.count / best.cols)));
|
||||
g.gridEl.style.setProperty('--tm-cols', String(best.cols));
|
||||
// Each group takes exactly the height its rows, gaps and heading need,
|
||||
// so a card is the same height under every heading.
|
||||
const rows = Math.max(1, Math.ceil(g.count / best.cols));
|
||||
const head = headings ? HEAD_H : 0;
|
||||
g.el.style.flexGrow = String(Math.max(1, Math.round(head + rows * best.rowH + (rows - 1) * GAP)));
|
||||
}
|
||||
wrap.style.setProperty('--tm-pad', PAD + 'px');
|
||||
wrap.style.setProperty('--tm-gap', GAP + 'px');
|
||||
wrap.style.setProperty('--tm-meta-size', best.meta + 'px');
|
||||
wrap.classList.toggle('tm-compact', best.mode === 'compact');
|
||||
lastFit = { cw: best.cw, meta: best.meta };
|
||||
for (const c of list) {
|
||||
const px = Math.max(11, Math.floor(Math.min((best.cw * 1.55) / c.chars, best.budget)));
|
||||
const budget = budgetFor(c, best.ch, best.meta, best.mode, best.dateWrap);
|
||||
const px = Math.max(11, Math.floor(Math.min((best.cw * 1.55) / c.chars, budget)));
|
||||
c.timeEl.style.fontSize = px + 'px';
|
||||
fitLabel(c, best.meta, best.cw);
|
||||
c.dateKey = ''; // the date re-fits to the new card width on the next paint
|
||||
}
|
||||
// Then a look at the real thing: the layout is applied, so each card's
|
||||
// height is known. Digits that would still spill past it — an estimate
|
||||
// off by a line, a heading taller than budgeted — shrink to what is
|
||||
// there. Only ever smaller; the estimate above sets the ceiling.
|
||||
for (const c of list) {
|
||||
const box = c.el.clientHeight;
|
||||
if (!box) continue;
|
||||
const parts = [c.nameEl, c.timeEl, c.statusEl, c.detailEl].filter((el) => !el.hidden && getComputedStyle(el).display !== 'none');
|
||||
const others = parts.filter((el) => el !== c.timeEl).reduce((a, el) => a + el.getBoundingClientRect().height, 0);
|
||||
const room = box - CARD_PAD - others - 0.02 * box * Math.max(0, parts.length - 1); // .tm-card's 2% gaps
|
||||
const px = parseFloat(c.timeEl.style.fontSize) || 0;
|
||||
if (room > 0 && px * 1.05 > room) c.timeEl.style.fontSize = `${Math.max(11, Math.floor(room / 1.05))}px`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,33 @@
|
||||
{
|
||||
"id": "propresenter-timers",
|
||||
"name": "Timers",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.1",
|
||||
"proddash": ">=1.4.0",
|
||||
"description": "Timers, Clocks, and LTC From configured Modules",
|
||||
"provides": ["timers"],
|
||||
"provides": [
|
||||
"timers"
|
||||
],
|
||||
"permissions": [
|
||||
{ "kind": "microphone", "reason": "Decoding SMPTE LTC timecode from an audio input on this machine" },
|
||||
{ "kind": "local-network", "reason": "Reaching ProPresenter on this network" }
|
||||
{
|
||||
"kind": "microphone",
|
||||
"reason": "Decoding SMPTE LTC timecode from an audio input on this machine"
|
||||
},
|
||||
{
|
||||
"kind": "local-network",
|
||||
"reason": "Reaching ProPresenter on this network"
|
||||
}
|
||||
],
|
||||
"client": "client.js",
|
||||
"server": "server.js",
|
||||
"style": "style.css",
|
||||
"minSize": { "w": 2, "h": 1 },
|
||||
"defaultSize": { "w": 4, "h": 3 },
|
||||
"minSize": {
|
||||
"w": 2,
|
||||
"h": 1
|
||||
},
|
||||
"defaultSize": {
|
||||
"w": 4,
|
||||
"h": 3
|
||||
},
|
||||
"configGroups": {
|
||||
"ProPresenter": {
|
||||
"toggle": "ppEnabled",
|
||||
@@ -39,7 +53,10 @@
|
||||
"type": "endpoint",
|
||||
"label": "ProPresenter",
|
||||
"group": "ProPresenter",
|
||||
"default": { "host": "", "port": 1025 }
|
||||
"default": {
|
||||
"host": "",
|
||||
"port": 1025
|
||||
}
|
||||
},
|
||||
"password": {
|
||||
"type": "password",
|
||||
@@ -82,42 +99,130 @@
|
||||
"group": "Display",
|
||||
"default": "default",
|
||||
"options": [
|
||||
{ "value": "default", "label": "Default (system)" },
|
||||
{ "value": "monospace", "label": "Monospace — steadier changing digits" }
|
||||
{
|
||||
"value": "default",
|
||||
"label": "Default (system)"
|
||||
},
|
||||
{
|
||||
"value": "monospace",
|
||||
"label": "Monospace — steadier changing digits"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"instanceGroups": {
|
||||
"Show": { "collapsed": false, "columns": 2 },
|
||||
"Clock": { "collapsed": false },
|
||||
"Show": {
|
||||
"collapsed": true,
|
||||
"columns": 2
|
||||
},
|
||||
"Clock": {
|
||||
"collapsed": false,
|
||||
"columns": 2
|
||||
},
|
||||
"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": {
|
||||
"showClock": { "type": "boolean", "label": "Clock", "default": true, "group": "Show" },
|
||||
"showProPresenter": { "type": "boolean", "label": "ProPresenter timers", "default": true, "group": "Show" },
|
||||
"showLtc": { "type": "boolean", "label": "LTC timecode", "default": true, "group": "Show" },
|
||||
"showModules": { "type": "boolean", "label": "Module timers", "default": true, "group": "Show" },
|
||||
"showHeadings": { "type": "boolean", "label": "Source headings", "default": true, "group": "Show" },
|
||||
"showStatus": { "type": "boolean", "label": "Status lines", "default": true, "group": "Show" },
|
||||
"clockFormat": {
|
||||
"type": "select",
|
||||
"label": "Clock format",
|
||||
"default": "24h",
|
||||
"group": "Clock",
|
||||
"options": [
|
||||
{ "value": "24h", "label": "24-hour" },
|
||||
{ "value": "12h", "label": "12-hour" }
|
||||
]
|
||||
"showNames": {
|
||||
"type": "switch",
|
||||
"label": "Names",
|
||||
"default": true,
|
||||
"group": "Show"
|
||||
},
|
||||
"clockSeconds": { "type": "boolean", "label": "Seconds", "default": true, "group": "Clock" },
|
||||
"clockDate": { "type": "boolean", "label": "Date", "default": false, "group": "Clock" },
|
||||
"runningColor": { "type": "color", "label": "Running", "default": "#2ee59a", "group": "Colours" },
|
||||
"warningColor": { "type": "color", "label": "Warning", "default": "#f0b429", "group": "Colours" },
|
||||
"overrunColor": { "type": "color", "label": "Overrun", "default": "#f4433c", "group": "Colours" },
|
||||
"idleColor": { "type": "color", "label": "Idle", "default": "#8b98a5", "group": "Colours" }
|
||||
"showStatus": {
|
||||
"type": "switch",
|
||||
"label": "Status lines",
|
||||
"default": true,
|
||||
"group": "Show"
|
||||
},
|
||||
"showDetail": {
|
||||
"type": "switch",
|
||||
"label": "Detail lines",
|
||||
"default": true,
|
||||
"group": "Show"
|
||||
},
|
||||
"showSeconds": {
|
||||
"type": "switch",
|
||||
"label": "Seconds",
|
||||
"default": true,
|
||||
"group": "Show"
|
||||
},
|
||||
"leadingZeros": {
|
||||
"type": "switch",
|
||||
"label": "Leading zeros",
|
||||
"default": false,
|
||||
"group": "Show"
|
||||
},
|
||||
"groupBySource": {
|
||||
"type": "switch",
|
||||
"label": "Group by source",
|
||||
"default": false,
|
||||
"group": "Show"
|
||||
},
|
||||
"showHeadings": {
|
||||
"type": "switch",
|
||||
"label": "Source headings",
|
||||
"default": true,
|
||||
"group": "Show",
|
||||
"showWhen": "groupBySource"
|
||||
},
|
||||
"clock24h": {
|
||||
"type": "switch",
|
||||
"label": "24-hour",
|
||||
"default": true,
|
||||
"group": "Clock"
|
||||
},
|
||||
"clockSeconds": {
|
||||
"type": "switch",
|
||||
"label": "Seconds",
|
||||
"default": true,
|
||||
"group": "Clock"
|
||||
},
|
||||
"clockDate": {
|
||||
"type": "switch",
|
||||
"label": "Date",
|
||||
"default": false,
|
||||
"group": "Clock"
|
||||
},
|
||||
"dateShortDay": {
|
||||
"type": "switch",
|
||||
"label": "Short day",
|
||||
"default": false,
|
||||
"group": "Clock",
|
||||
"showWhen": "clockDate"
|
||||
},
|
||||
"dateShortMonth": {
|
||||
"type": "switch",
|
||||
"label": "Short month",
|
||||
"default": false,
|
||||
"group": "Clock",
|
||||
"showWhen": "clockDate"
|
||||
},
|
||||
"runningColor": {
|
||||
"type": "color",
|
||||
"label": "Running",
|
||||
"default": "#2ee59a",
|
||||
"group": "Colours"
|
||||
},
|
||||
"warningColor": {
|
||||
"type": "color",
|
||||
"label": "Warning",
|
||||
"default": "#f0b429",
|
||||
"group": "Colours"
|
||||
},
|
||||
"overrunColor": {
|
||||
"type": "color",
|
||||
"label": "Overrun",
|
||||
"default": "#f4433c",
|
||||
"group": "Colours"
|
||||
},
|
||||
"idleColor": {
|
||||
"type": "color",
|
||||
"label": "Idle",
|
||||
"default": "#8b98a5",
|
||||
"group": "Colours"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ const http = require('http');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
const { createLtcListener } = require('./ltc-listener');
|
||||
const manifest = require('./module.json');
|
||||
|
||||
/** This module's id — left out of provider discovery (we don't consume ourselves). */
|
||||
const SELF_ID = 'propresenter-timers';
|
||||
@@ -170,14 +171,14 @@ function fmtMs(ms) {
|
||||
return h ? `${h}:${pad(m)}:${pad(sec)}` : `${m}:${pad(sec)}`;
|
||||
}
|
||||
|
||||
/** ProPresenter's count_down_to_time target: seconds since midnight + am/pm/24h. */
|
||||
/** ProPresenter's count_down_to_time target, short: "9:30a", "12:05p", or "21:30" for a 24-hour clock. */
|
||||
function timeOfDayText(seconds, period) {
|
||||
const s = Number(seconds);
|
||||
if (!Number.isFinite(s)) return '';
|
||||
const h = Math.floor(s / 3600) % 24;
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const p = String(period || '').toLowerCase();
|
||||
if (p === 'am' || p === 'pm') return `${h % 12 || 12}:${String(m).padStart(2, '0')} ${p}`;
|
||||
if (p === 'am' || p === 'pm') return `${h % 12 || 12}:${String(m).padStart(2, '0')}${p[0]}`;
|
||||
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
@@ -277,7 +278,7 @@ function createProPresenterSource({ config, log }) {
|
||||
}
|
||||
if (entry.count_down_to_time) {
|
||||
const at = timeOfDayText(entry.count_down_to_time.time_of_day, entry.count_down_to_time.period);
|
||||
return { type: 'countdown_to_time', targetMs: null, detail: at ? `Counts down to ${at}` : 'Counts down to a time of day' };
|
||||
return { type: 'countdown_to_time', targetMs: null, detail: at ? `to ${at}` : 'to a time of day' };
|
||||
}
|
||||
if (entry.elapsed) {
|
||||
const end = Number(entry.elapsed.end_time);
|
||||
@@ -873,6 +874,70 @@ function createModuleDiscovery({ shellPort, log, flags, onAdd, onRemove }) {
|
||||
};
|
||||
}
|
||||
|
||||
/* ── what each tile's gear offers ─────────────────────────────────────
|
||||
module.json's instanceSchema is the full set — what an "All timers" tile
|
||||
offers, and what the shell falls back to for a tile with no picker entry
|
||||
(one added before the picker listed timers). A solo tile shows one card,
|
||||
so its picker entry carries a schema of just what that card can use, and
|
||||
the shell renders that instead (module guide, "Presenting multiple
|
||||
tiles"): a Message Timer has no use for the clock's format switches.
|
||||
Every field is drawn from the manifest so it is defined once; the client
|
||||
falls back to its own defaults for keys a slimmer schema leaves out. */
|
||||
|
||||
const FULL_SCHEMA = manifest.instanceSchema || {};
|
||||
const FULL_GROUPS = manifest.instanceGroups || {};
|
||||
|
||||
/**
|
||||
* A gear schema of just `keys` (manifest order kept) with the groups they
|
||||
* use. `loose` names keys shown outside their group; `groups` overrides a
|
||||
* group's meta. A group toggle whose switch isn't among the keys is dropped.
|
||||
*/
|
||||
function gearOf(keys, { loose = [], groups = {} } = {}) {
|
||||
const instanceSchema = {};
|
||||
for (const key of Object.keys(FULL_SCHEMA)) {
|
||||
if (!keys.includes(key)) continue;
|
||||
const spec = { ...FULL_SCHEMA[key] };
|
||||
if (loose.includes(key)) delete spec.group;
|
||||
instanceSchema[key] = spec;
|
||||
}
|
||||
const instanceGroups = {};
|
||||
for (const spec of Object.values(instanceSchema)) {
|
||||
if (!spec.group || instanceGroups[spec.group]) continue;
|
||||
const meta = { ...(FULL_GROUPS[spec.group] || {}), ...(groups[spec.group] || {}) };
|
||||
if (meta.toggle && !(meta.toggle in instanceSchema)) delete meta.toggle;
|
||||
instanceGroups[spec.group] = meta;
|
||||
}
|
||||
return { instanceSchema, instanceGroups };
|
||||
}
|
||||
|
||||
const COLOURS = ['runningColor', 'warningColor', 'overrunColor', 'idleColor'];
|
||||
/** What a timer card can show or hide of itself (which timers appear is the header menu's job). */
|
||||
const TIMER_ELEMENTS = ['showNames', 'showStatus', 'showDetail', 'showSeconds', 'leadingZeros'];
|
||||
const CLOCK_ELEMENTS = ['clock24h', 'clockSeconds', 'clockDate', 'dateShortDay', 'dateShortMonth'];
|
||||
/** With one card there is little else to see: the colours start unfolded. */
|
||||
const OPEN_COLOURS = { groups: { Colours: { collapsed: false } } };
|
||||
|
||||
const GEAR = {
|
||||
/** Every card's elements, the headings, how the clock reads, the tones. */
|
||||
all: { instanceSchema: FULL_SCHEMA, instanceGroups: FULL_GROUPS },
|
||||
/** One ProPresenter or module timer: its elements, and the tone its digits take per state. */
|
||||
timer: gearOf([...TIMER_ELEMENTS, ...COLOURS], OPEN_COLOURS),
|
||||
/** The timecode: running, no signal (warning) and stopped (idle) — it never overruns, and frames are frames. */
|
||||
ltc: gearOf(['showNames', 'showStatus', 'runningColor', 'warningColor', 'idleColor'], OPEN_COLOURS),
|
||||
/** The time of day: plain digits, so only how they read. */
|
||||
clock: gearOf(CLOCK_ELEMENTS),
|
||||
/** A clock another module offers: read like the clock, muted while it isn't running. */
|
||||
providerClock: gearOf(['showNames', 'showStatus', 'clock24h', 'clockSeconds', 'idleColor'], OPEN_COLOURS),
|
||||
};
|
||||
|
||||
/** The gear a solo card of this timer gets — by what the card can show. */
|
||||
function gearFor(source, timer) {
|
||||
if (source.kind === 'ltc') return GEAR.ltc;
|
||||
if (source.kind === 'clock') return GEAR.clock;
|
||||
if (timer.kind === 'clock') return GEAR.providerClock;
|
||||
return GEAR.timer;
|
||||
}
|
||||
|
||||
/* ── the module ───────────────────────────────────────────────────────── */
|
||||
|
||||
/** Sort order of the sources in the tile: fixed ones first, then PCO Plan, then other modules by name. */
|
||||
@@ -1058,19 +1123,25 @@ module.exports = {
|
||||
* The Add-tile picker's entries: "All timers" plus one solo card per known
|
||||
* timer from any source (moduleApi.variant carries the entry id — 'all',
|
||||
* or 'solo:<source>:<timer id>'; the older 'timer:<uuid>' / 'ltc' ids keep
|
||||
* working). Answered from the merged state, never from upstream — the
|
||||
* picker must stay instant and a dead upstream must not stall it.
|
||||
* working). Each entry carries the gear settings that fit its tile (see
|
||||
* GEAR above); descriptions are the picker's tooltips, one sentence each.
|
||||
* Answered from the merged state, never from upstream — the picker must
|
||||
* stay instant and a dead upstream must not stall it.
|
||||
*/
|
||||
tiles() {
|
||||
const state = current ? current.getState() : null;
|
||||
if (!state) return [];
|
||||
const KIND_LABEL = { countdown: 'Countdown', elapsed: 'Elapsed timer', clock: 'Clock' };
|
||||
const KIND_WORD = { countdown: 'countdown', elapsed: 'elapsed timer', clock: 'clock' };
|
||||
const oneCard = { defaultSize: { w: 3, h: 2 }, minSize: { w: 2, h: 1 } };
|
||||
const out = [{ id: 'all', name: 'All timers', description: 'Every timer, clock and timecode — choose which per tile' }];
|
||||
const out = [{ id: 'all', name: 'All timers', description: 'Every timer and clock, grouped by source', ...GEAR.all }];
|
||||
for (const src of state.sources) {
|
||||
for (const t of src.timers) {
|
||||
const what = src.id === 'ltc' ? 'Incoming timecode (HH:MM:SS:FF)' : src.id === 'clock' ? 'Time of day' : KIND_LABEL[t.kind] || 'Timer';
|
||||
out.push({ id: `solo:${src.id}:${t.id}`, name: t.label, description: `${src.label} · ${what}`, ...oneCard });
|
||||
const description = src.kind === 'ltc' ? 'The incoming LTC timecode on its own'
|
||||
: src.kind === 'clock' ? 'The time of day on its own'
|
||||
: `This ${src.label} ${KIND_WORD[t.kind] || 'timer'} on its own`;
|
||||
// Layouts from before 1.3.0 hold 'timer:<uuid>' / 'ltc' — the same tiles.
|
||||
const aliases = src.id === 'propresenter' ? [`timer:${t.id}`] : src.kind === 'ltc' ? ['ltc'] : [];
|
||||
out.push({ id: `solo:${src.id}:${t.id}`, name: t.label, description, ...oneCard, ...gearFor(src, t), ...(aliases.length ? { aliases } : {}) });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
visually, per group: the LTC card keeps ticking when only ProPresenter
|
||||
is unreachable. When the ProdDash feed is down everything is old. */
|
||||
[data-module="propresenter-timers"] .tm-group.is-stale .tm-card,
|
||||
[data-module="propresenter-timers"] .tm-card.is-stale,
|
||||
[data-module="propresenter-timers"] .tm-wrap.is-feed-down .tm-card { opacity: 0.45; }
|
||||
|
||||
[data-module="propresenter-timers"] .tm-hint {
|
||||
@@ -126,13 +127,31 @@
|
||||
}
|
||||
[data-module="propresenter-timers"] .tm-grid:empty { display: none; }
|
||||
|
||||
/* Grouping off: one grid for every timer, filled row by row. A wrapping
|
||||
flex row instead of a CSS grid, so the last row's cards widen to use the
|
||||
whole width — nothing is left empty. Rows share the height equally. */
|
||||
[data-module="propresenter-timers"] .tm-grid.is-flow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-content: stretch;
|
||||
align-items: stretch;
|
||||
}
|
||||
[data-module="propresenter-timers"] .tm-grid.is-flow .tm-card {
|
||||
flex: 1 1 calc((100% - var(--tm-gap, 8px) * (var(--tm-cols, 1) - 1)) / var(--tm-cols, 1));
|
||||
min-width: 0;
|
||||
}
|
||||
[data-module="propresenter-timers"] .tm-empty[data-tone="warn"] { color: var(--tm-warn); }
|
||||
|
||||
/* Compact cards (short tiles) and "Status lines" off: the lines under the
|
||||
digits go, the colour stays. A note that explains a missing value (no
|
||||
LTC input, a solo timer no longer offered) must never be hidden. */
|
||||
[data-module="propresenter-timers"] .tm-compact .tm-status:not(.is-note),
|
||||
[data-module="propresenter-timers"] .tm-compact .tm-detail,
|
||||
[data-module="propresenter-timers"] .tm-nostatus .tm-status:not(.is-note),
|
||||
[data-module="propresenter-timers"] .tm-nostatus .tm-detail { display: none; }
|
||||
[data-module="propresenter-timers"] .tm-nodetail .tm-detail { display: none; }
|
||||
/* "Names" off hides every title; the clock never carries one — its digits say what it is */
|
||||
[data-module="propresenter-timers"] .tm-nonames .tm-name,
|
||||
[data-module="propresenter-timers"] .tm-card-clock .tm-name { display: none; }
|
||||
|
||||
/* ── one timer card ── */
|
||||
|
||||
@@ -196,7 +215,7 @@
|
||||
[data-module="propresenter-timers"] .tm-detail {
|
||||
flex: none;
|
||||
max-width: 100%;
|
||||
font-size: var(--tm-meta-size);
|
||||
font-size: calc(var(--tm-meta-size) * 0.8); /* smaller than the title; fit() budgets the same share */
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
@@ -221,6 +240,18 @@
|
||||
[data-module="propresenter-timers"] .tm-status[data-tone="danger"] { color: var(--tm-danger); }
|
||||
[data-module="propresenter-timers"] .tm-status[data-tone="muted"] { color: var(--tm-muted); }
|
||||
|
||||
/* The clock's date: one line when it fits, else the day on its own line
|
||||
(renderDate() sizes it to the longer half). */
|
||||
[data-module="propresenter-timers"] .tm-status.is-date {
|
||||
white-space: normal;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
text-align: center;
|
||||
line-height: 1.15;
|
||||
}
|
||||
[data-module="propresenter-timers"] .tm-status.is-date span { white-space: nowrap; }
|
||||
[data-module="propresenter-timers"] .tm-status.is-date.is-wrap span { display: block; }
|
||||
|
||||
/* Explanatory notes read as sentences, not badges. */
|
||||
[data-module="propresenter-timers"] .tm-status.is-note {
|
||||
text-transform: none;
|
||||
@@ -264,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 ── */
|
||||
|
||||
@@ -290,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;
|
||||
@@ -352,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; }
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Cal Henderson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,129 @@
|
||||
{
|
||||
"id": "slack",
|
||||
"name": "Slack",
|
||||
"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",
|
||||
"server": "server.js",
|
||||
"style": "style.css",
|
||||
"minSize": {
|
||||
"w": 2,
|
||||
"h": 2
|
||||
},
|
||||
"defaultSize": {
|
||||
"w": 4,
|
||||
"h": 4
|
||||
},
|
||||
"configGroups": {
|
||||
"Slack account": {
|
||||
"collapsed": "whenSet",
|
||||
"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 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",
|
||||
"help": "Messages and emoji reactions leave this machine only after the PIN is entered — on a Send or Quick replies tile, or in the reaction menu a right-click on a transcript message opens. One PIN unlocks every Slack tile on that dashboard page until Auto-lock minutes pass without a send; a reload asks again. Sending stays refused until a 4–8 digit PIN is set here. A message goes to the channel of the transcript clicked last. Quick emojis are sent with one press from the Send message tile and offered first when reacting. Quick replies are one per line, Label | Message, with an optional | #channel-name to bind that one to a channel: a bound reply always goes there, whichever transcript is selected."
|
||||
}
|
||||
},
|
||||
"configSchema": {
|
||||
"token": {
|
||||
"type": "password",
|
||||
"label": "Token",
|
||||
"default": "",
|
||||
"group": "Slack account",
|
||||
"help": "The location account's User OAuth Token (xoxp-…, recommended) or a Bot User OAuth Token (xoxb-…)."
|
||||
},
|
||||
"sendAs": {
|
||||
"type": "string",
|
||||
"label": "Send as",
|
||||
"default": "",
|
||||
"group": "Slack account",
|
||||
"help": "Only used with a bot token — a user token always sends as its own account; needs the chat:write.customize scope."
|
||||
},
|
||||
"channels": {
|
||||
"type": "multiselect",
|
||||
"label": "Channels",
|
||||
"default": [],
|
||||
"group": "Channels",
|
||||
"optionsRoute": "/channels",
|
||||
"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",
|
||||
"label": "Refresh interval (s)",
|
||||
"default": 2,
|
||||
"group": "Transcript",
|
||||
"help": "How often each channel is re-read (1 s at the fastest). With several channels the interval stretches so the module stays inside Slack's rate limit — at least 1.5 s × the number of channels; the health line shows the interval in use."
|
||||
},
|
||||
"historyCount": {
|
||||
"type": "number",
|
||||
"label": "Messages kept",
|
||||
"default": 40,
|
||||
"group": "Transcript"
|
||||
},
|
||||
"includeReplies": {
|
||||
"type": "switch",
|
||||
"label": "Thread replies",
|
||||
"default": false,
|
||||
"group": "Transcript"
|
||||
},
|
||||
"sendEnabled": {
|
||||
"type": "switch",
|
||||
"label": "Sending",
|
||||
"default": false,
|
||||
"group": "Sending"
|
||||
},
|
||||
"pin": {
|
||||
"type": "password",
|
||||
"label": "PIN",
|
||||
"default": "",
|
||||
"group": "Sending",
|
||||
"help": "4–8 digits; the pad unlocks by itself once they are all in."
|
||||
},
|
||||
"pinIdleMinutes": {
|
||||
"type": "number",
|
||||
"label": "Auto-lock (min)",
|
||||
"default": 10,
|
||||
"group": "Sending"
|
||||
},
|
||||
"quickReplies": {
|
||||
"type": "text",
|
||||
"label": "Quick replies",
|
||||
"default": "",
|
||||
"group": "Sending",
|
||||
"help": "One per line: Label | Message. Add | #channel-name to bind one to a channel — it then ignores which transcript is selected."
|
||||
},
|
||||
"quickEmojis": {
|
||||
"type": "string",
|
||||
"label": "Quick emojis",
|
||||
"default": "👍 🙏 ✅ 👀 🎉",
|
||||
"group": "Sending",
|
||||
"help": "Emoji or :codes: separated by spaces, eight at most. One press sends one from the Send message tile; they also head the reaction menu."
|
||||
}
|
||||
},
|
||||
"instanceSchema": {
|
||||
"showAvatars": {
|
||||
"type": "switch",
|
||||
"label": "Avatars",
|
||||
"default": true
|
||||
},
|
||||
"showTimes": {
|
||||
"type": "switch",
|
||||
"label": "Timestamps",
|
||||
"default": true
|
||||
},
|
||||
"showNames": {
|
||||
"type": "switch",
|
||||
"label": "Names",
|
||||
"default": true
|
||||
},
|
||||
"showSystem": {
|
||||
"type": "switch",
|
||||
"label": "Channel notices",
|
||||
"default": true
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,677 @@
|
||||
/* Slack module — scoped to its tiles, shell variables only.
|
||||
--sl-size (per tile, from the header's A− / A+) drives every font size.
|
||||
Transcript rows follow the ProdCom transcript's layout: a square picture,
|
||||
then a name line with the time, the text, the reactions. */
|
||||
|
||||
[data-module="slack"] .sl-wrap {
|
||||
--sl-size: 14px;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
container-type: size;
|
||||
font-size: var(--sl-size);
|
||||
color: var(--text);
|
||||
}
|
||||
[data-module="slack"] .sl-wrap:focus { outline: none; }
|
||||
[data-module="slack"] [hidden] { display: none !important; }
|
||||
|
||||
/* ── degraded banner (transcript) ── */
|
||||
|
||||
[data-module="slack"] .sl-banner {
|
||||
flex: none;
|
||||
padding: 4px 10px;
|
||||
font-size: 0.8em;
|
||||
color: var(--warn);
|
||||
background: color-mix(in srgb, var(--warn) 12%, transparent);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--warn) 35%, var(--border));
|
||||
}
|
||||
[data-module="slack"] .sl-banner.is-error {
|
||||
color: var(--danger);
|
||||
background: color-mix(in srgb, var(--danger) 12%, transparent);
|
||||
border-bottom-color: color-mix(in srgb, var(--danger) 35%, var(--border));
|
||||
}
|
||||
|
||||
/* ── the send target ── */
|
||||
|
||||
/* A click anywhere in a transcript's body makes its channel the one Send
|
||||
message and Quick replies post to. The chosen one carries a 3px accent
|
||||
stripe along the bottom edge of the tile body — drawn just inside our
|
||||
root, since the tile chrome around it belongs to the shell. The others
|
||||
hint at it faintly on hover. */
|
||||
[data-module="slack"] .sl-transcript::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background: var(--accent);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
z-index: 3;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
[data-module="slack"] .sl-transcript:hover::after { opacity: 0.3; }
|
||||
[data-module="slack"] .sl-transcript.is-target::after { opacity: 1; }
|
||||
|
||||
/* ── transcript stream ── */
|
||||
|
||||
[data-module="slack"] .sl-stream {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 6px 10px 10px;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
[data-module="slack"] .sl-empty {
|
||||
color: var(--muted);
|
||||
font-size: 0.9em;
|
||||
text-align: center;
|
||||
padding: 14% 10px 0;
|
||||
line-height: 1.45;
|
||||
}
|
||||
[data-module="slack"] .sl-empty.is-error { color: var(--danger); }
|
||||
|
||||
[data-module="slack"] .sl-entry {
|
||||
padding: 5px 6px;
|
||||
border-radius: 8px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
[data-module="slack"] .sl-entry:hover { background: var(--bg); }
|
||||
[data-module="slack"] .sl-entry.sl-new { animation: sl-fade-in 0.25s ease-out; }
|
||||
@keyframes sl-fade-in {
|
||||
from { opacity: 0; transform: translateY(4px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* one row: the picture, then everything else (.sl-row — .sl-msg is the
|
||||
send tile's status line, a different thing) */
|
||||
[data-module="slack"] .sl-row,
|
||||
[data-module="slack"] .sl-reply {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
[data-module="slack"] .sl-body { flex: 1; min-width: 0; }
|
||||
|
||||
/* the square: a profile image, a bot's icon or emoji, or initials on a tint
|
||||
of a hue the name hashes to — the same size and corner as ProdCom's */
|
||||
[data-module="slack"] .sl-avatar {
|
||||
flex: none;
|
||||
width: calc(var(--sl-size) * 1.9);
|
||||
height: calc(var(--sl-size) * 1.9);
|
||||
border-radius: 26%;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: hsl(var(--sl-hue, 150) 45% 50% / 0.2);
|
||||
color: hsl(var(--sl-hue, 150) 55% 60%);
|
||||
font-size: 0.72em;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
/* "Avatars" off: the square goes and the row starts at the left edge, as in ProdCom */
|
||||
[data-module="slack"] .sl-wrap.hide-avatars .sl-avatar { display: none; }
|
||||
[data-module="slack"] .sl-avatar-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
[data-module="slack"] .sl-avatar-emoji { font-size: 1.25em; line-height: 1; }
|
||||
[data-module="slack"] .sl-reply .sl-avatar {
|
||||
width: calc(var(--sl-size) * 1.5);
|
||||
height: calc(var(--sl-size) * 1.5);
|
||||
font-size: 0.6em;
|
||||
}
|
||||
|
||||
[data-module="slack"] .sl-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
[data-module="slack"] .sl-name {
|
||||
font-weight: 700;
|
||||
font-size: 0.82em;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--accent);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
[data-module="slack"] .sl-bot .sl-name { color: var(--muted); }
|
||||
[data-module="slack"] .sl-time {
|
||||
flex: none;
|
||||
font-size: 0.72em;
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
[data-module="slack"] .sl-wrap:not(.show-times) .sl-time { display: none; }
|
||||
[data-module="slack"] .sl-wrap:not(.show-names) .sl-body > .sl-meta { display: none; }
|
||||
[data-module="slack"] .sl-wrap.show-times:not(.show-names) .sl-body > .sl-meta { display: flex; }
|
||||
[data-module="slack"] .sl-wrap.show-times:not(.show-names) .sl-name { display: none; }
|
||||
[data-module="slack"] .sl-wrap:not(.show-system) .sl-entry.sl-system { display: none; }
|
||||
|
||||
[data-module="slack"] .sl-text {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--text);
|
||||
}
|
||||
[data-module="slack"] .sl-text b { font-weight: 700; }
|
||||
[data-module="slack"] .sl-text i { font-style: italic; }
|
||||
[data-module="slack"] .sl-text s { color: var(--muted); }
|
||||
[data-module="slack"] .sl-code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
padding: 0 4px;
|
||||
border-radius: 4px;
|
||||
background: color-mix(in srgb, var(--text) 8%, transparent);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
[data-module="slack"] .sl-code.sl-block {
|
||||
display: block;
|
||||
padding: 4px 8px;
|
||||
margin: 3px 0;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
[data-module="slack"] .sl-edited {
|
||||
font-size: 0.75em;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* a custom emoji is an image the size of a character */
|
||||
[data-module="slack"] .sl-emoji {
|
||||
display: inline-block;
|
||||
width: 1.25em;
|
||||
height: 1.25em;
|
||||
object-fit: contain;
|
||||
vertical-align: -0.28em;
|
||||
}
|
||||
|
||||
/* reactions under a message: pills with the emoji and its count; the
|
||||
location's own carry the accent — a click adds yours or takes it back */
|
||||
[data-module="slack"] .sl-reactions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
[data-module="slack"] .sl-reaction {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 1px 7px 1px 5px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--text) 5%, transparent);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.78em;
|
||||
line-height: 1.4;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
[data-module="slack"] .sl-reaction:hover { border-color: var(--accent); }
|
||||
[data-module="slack"] .sl-reaction.is-me {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 16%, transparent);
|
||||
}
|
||||
[data-module="slack"] .sl-reaction .sl-emoji,
|
||||
[data-module="slack"] .sl-reaction .sl-emoji-char { font-size: 1.15em; line-height: 1; vertical-align: middle; }
|
||||
[data-module="slack"] .sl-reaction-count {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
}
|
||||
[data-module="slack"] .sl-reaction.is-me .sl-reaction-count { color: var(--text); }
|
||||
|
||||
/* thread replies nest under their parent; without them, a muted count */
|
||||
[data-module="slack"] .sl-replies {
|
||||
margin: 4px 0 0 10px;
|
||||
padding-left: 10px;
|
||||
border-left: 2px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
[data-module="slack"] .sl-reply { font-size: 0.92em; }
|
||||
[data-module="slack"] .sl-replycount {
|
||||
margin-top: 2px;
|
||||
font-size: 0.75em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* system lines: joins, leaves, topic changes */
|
||||
[data-module="slack"] .sl-sysline {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
font-size: 0.82em;
|
||||
color: var(--muted);
|
||||
font-style: italic;
|
||||
}
|
||||
[data-module="slack"] .sl-sysline .sl-time { font-style: normal; }
|
||||
|
||||
[data-module="slack"] .sl-jump {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 10px;
|
||||
transform: translateX(-50%);
|
||||
padding: 5px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
font: inherit;
|
||||
font-size: 0.8em;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
/* ── send / quick replies: the gate ── */
|
||||
|
||||
[data-module="slack"] .sl-gate,
|
||||
[data-module="slack"] .sl-compose {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 6px 10px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
[data-module="slack"] .sl-note {
|
||||
margin: auto;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
font-size: 0.9em;
|
||||
line-height: 1.45;
|
||||
}
|
||||
[data-module="slack"] .sl-note.is-error { color: var(--danger); }
|
||||
|
||||
/* The pad never shrinks below its content (min-height stays `auto` on it
|
||||
and on the key grid) — a shrunken grid would spill its rows under the
|
||||
message line, which then swallows the taps. A tile too short for it
|
||||
scrolls instead (.sl-gate has overflow: auto). */
|
||||
[data-module="slack"] .sl-pad {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
max-width: 340px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
[data-module="slack"] .sl-pad.sl-shake { animation: sl-shake 0.4s ease; }
|
||||
@keyframes sl-shake {
|
||||
10%, 90% { transform: translateX(-2px); }
|
||||
20%, 80% { transform: translateX(3px); }
|
||||
30%, 50%, 70% { transform: translateX(-5px); }
|
||||
40%, 60% { transform: translateX(5px); }
|
||||
}
|
||||
|
||||
/* one line: "Enter PIN · sending as Apollo Beach → #production" */
|
||||
[data-module="slack"] .sl-pad-head {
|
||||
flex: none;
|
||||
text-align: center;
|
||||
font-size: 0.8em;
|
||||
color: var(--muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
[data-module="slack"] .sl-pad-head b { font-weight: 700; color: var(--text); }
|
||||
|
||||
[data-module="slack"] .sl-dots {
|
||||
flex: none;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
height: 14px;
|
||||
}
|
||||
[data-module="slack"] .sl-dot {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--muted);
|
||||
transition: background 0.12s, border-color 0.12s;
|
||||
}
|
||||
[data-module="slack"] .sl-dot.on { background: var(--accent); border-color: var(--accent); }
|
||||
|
||||
[data-module="slack"] .sl-keys {
|
||||
flex: 1 1 auto;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-rows: repeat(4, minmax(24px, 1fr));
|
||||
gap: 4px;
|
||||
}
|
||||
[data-module="slack"] .sl-key {
|
||||
min-width: 0;
|
||||
min-height: 24px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: color-mix(in srgb, var(--text) 5%, var(--panel));
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: clamp(13px, 9cqh, 26px);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
touch-action: manipulation;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
[data-module="slack"] .sl-key:hover { background: var(--border); }
|
||||
[data-module="slack"] .sl-key:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
|
||||
[data-module="slack"] .sl-key svg { width: 1.1em; height: 1.1em; }
|
||||
[data-module="slack"] .sl-key-back { color: var(--muted); }
|
||||
[data-module="slack"] .sl-key-blank { visibility: hidden; }
|
||||
[data-module="slack"] .sl-pad.is-busy .sl-keys { opacity: 0.6; pointer-events: none; }
|
||||
|
||||
[data-module="slack"] .sl-pad-msg {
|
||||
flex: none;
|
||||
min-height: 1.1em;
|
||||
text-align: center;
|
||||
font-size: 0.78em;
|
||||
line-height: 1.1;
|
||||
color: var(--muted);
|
||||
}
|
||||
[data-module="slack"] .sl-pad-msg.is-error { color: var(--danger); font-weight: 600; }
|
||||
|
||||
/* A tile too short for the keypad (the smallest Send message / Quick replies
|
||||
tiles) shows the dots and a hint instead — digits typed on the keyboard
|
||||
still land, and a taller tile brings the keys back. .sl-wrap is the size
|
||||
container the height is measured against. */
|
||||
[data-module="slack"] .sl-pad-hint {
|
||||
display: none;
|
||||
flex: none;
|
||||
text-align: center;
|
||||
font-size: 0.78em;
|
||||
line-height: 1.3;
|
||||
color: var(--muted);
|
||||
}
|
||||
@container (max-height: 176px) {
|
||||
[data-module="slack"] .sl-pad .sl-keys { display: none; }
|
||||
[data-module="slack"] .sl-pad .sl-pad-hint { display: block; }
|
||||
[data-module="slack"] .sl-pad { justify-content: center; }
|
||||
}
|
||||
|
||||
/* ── send / quick replies: unlocked ── */
|
||||
|
||||
[data-module="slack"] .sl-compose { gap: 6px; }
|
||||
|
||||
[data-module="slack"] .sl-compose-head {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: 0.8em;
|
||||
color: var(--muted);
|
||||
}
|
||||
[data-module="slack"] .sl-sending {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
[data-module="slack"] .sl-lock-link {
|
||||
flex: none;
|
||||
padding: 1px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font: inherit;
|
||||
font-size: 0.9em;
|
||||
cursor: pointer;
|
||||
}
|
||||
[data-module="slack"] .sl-lock-link:hover { color: var(--text); background: var(--border); }
|
||||
|
||||
[data-module="slack"] .sl-input {
|
||||
flex: 1;
|
||||
min-height: 2.6em;
|
||||
width: 100%;
|
||||
resize: none;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
line-height: 1.4;
|
||||
}
|
||||
[data-module="slack"] .sl-input:focus { outline: none; border-color: var(--accent); }
|
||||
|
||||
[data-module="slack"] .sl-compose-foot {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 1.6em;
|
||||
}
|
||||
[data-module="slack"] .sl-msg {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 0.8em;
|
||||
color: var(--muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
[data-module="slack"] .sl-msg.is-flash { color: var(--accent); font-weight: 700; }
|
||||
[data-module="slack"] .sl-msg.is-error { color: var(--danger); white-space: normal; font-weight: 600; }
|
||||
[data-module="slack"] .sl-countdown {
|
||||
flex: none;
|
||||
font-size: 0.75em;
|
||||
color: var(--warn);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
[data-module="slack"] .sl-sendbtn {
|
||||
flex: none;
|
||||
padding: 6px 16px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
color: var(--accent-text);
|
||||
font: inherit;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
[data-module="slack"] .sl-sendbtn:hover { background: color-mix(in srgb, var(--accent) 85%, var(--text)); }
|
||||
[data-module="slack"] .sl-sendbtn:disabled { opacity: 0.6; cursor: default; }
|
||||
|
||||
/* quick emojis: one press each sends it as a message of its own */
|
||||
[data-module="slack"] .sl-emoji-sendrow {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-send {
|
||||
flex: none;
|
||||
width: 2.1em;
|
||||
height: 2.1em;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--text) 5%, var(--panel));
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 1.1em;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
touch-action: manipulation;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-send:hover { border-color: var(--accent); background: var(--border); }
|
||||
[data-module="slack"] .sl-emoji-send:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
|
||||
[data-module="slack"] .sl-emoji-send.is-busy { opacity: 0.6; }
|
||||
[data-module="slack"] .sl-emoji-send.is-sent { background: var(--accent); border-color: transparent; }
|
||||
[data-module="slack"] .sl-emoji-send .sl-emoji { width: 1.2em; height: 1.2em; vertical-align: middle; }
|
||||
|
||||
/* the preset grid: big targets, labels wrap */
|
||||
[data-module="slack"] .sl-grid {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(150px, 100%), 1fr));
|
||||
grid-auto-rows: minmax(44px, auto);
|
||||
gap: 6px;
|
||||
align-content: start;
|
||||
overflow-y: auto;
|
||||
}
|
||||
[data-module="slack"] .sl-grid .sl-note { grid-column: 1 / -1; }
|
||||
[data-module="slack"] .sl-quick {
|
||||
min-width: 0;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: color-mix(in srgb, var(--accent) 12%, var(--panel));
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
touch-action: manipulation;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
[data-module="slack"] .sl-quick:hover { background: color-mix(in srgb, var(--accent) 22%, var(--panel)); }
|
||||
[data-module="slack"] .sl-quick:active { background: color-mix(in srgb, var(--accent) 40%, var(--panel)); }
|
||||
[data-module="slack"] .sl-quick.is-busy { opacity: 0.7; }
|
||||
[data-module="slack"] .sl-quick.is-sent {
|
||||
background: var(--accent);
|
||||
border-color: transparent;
|
||||
color: var(--accent-text);
|
||||
}
|
||||
[data-module="slack"] .sl-quick-label { overflow-wrap: anywhere; }
|
||||
[data-module="slack"] .sl-quick-chan {
|
||||
font-size: 0.72em;
|
||||
font-weight: 500;
|
||||
color: var(--muted);
|
||||
}
|
||||
[data-module="slack"] .sl-quick.is-sent .sl-quick-chan { color: inherit; }
|
||||
|
||||
/* ── the reaction menu (on document.body, so nothing clips it) ── */
|
||||
|
||||
[data-module="slack"].sl-emoji-menu {
|
||||
--sl-size: 14px;
|
||||
position: fixed;
|
||||
z-index: 90;
|
||||
width: 292px;
|
||||
max-width: calc(100vw - 16px);
|
||||
max-height: calc(100vh - 16px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
font-size: var(--sl-size);
|
||||
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55);
|
||||
overflow: hidden;
|
||||
}
|
||||
[data-module="slack"].sl-emoji-menu:focus { outline: none; }
|
||||
[data-module="slack"].sl-emoji-menu.is-busy { opacity: 0.7; pointer-events: none; }
|
||||
[data-module="slack"] .sl-emoji-head {
|
||||
font-size: 0.8em;
|
||||
color: var(--muted);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-quickrow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-quickrow:empty { display: none; }
|
||||
[data-module="slack"] .sl-emoji-btn {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-quickrow .sl-emoji-btn { font-size: 22px; width: 38px; height: 38px; background: color-mix(in srgb, var(--text) 5%, var(--panel)); border-color: var(--border); }
|
||||
[data-module="slack"] .sl-emoji-btn:hover { background: var(--border); border-color: var(--accent); }
|
||||
[data-module="slack"] .sl-emoji-btn .sl-emoji { width: 1.1em; height: 1.1em; vertical-align: middle; }
|
||||
[data-module="slack"] .sl-emoji-search {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 6px 9px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-search:focus { outline: none; border-color: var(--accent); }
|
||||
[data-module="slack"] .sl-emoji-results {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px;
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
min-height: 34px;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-none {
|
||||
width: 100%;
|
||||
padding: 8px 4px;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
font-size: 0.8em;
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-msg {
|
||||
min-height: 1em;
|
||||
font-size: 0.78em;
|
||||
color: var(--muted);
|
||||
}
|
||||
[data-module="slack"] .sl-emoji-msg:empty { display: none; }
|
||||
[data-module="slack"] .sl-emoji-msg.is-error { color: var(--danger); font-weight: 600; }
|
||||
|
||||
/* the PIN pad inside the menu: fixed sizes, no tile to scale with */
|
||||
[data-module="slack"] .sl-emoji-menu .sl-pad { max-width: 100%; gap: 6px; }
|
||||
[data-module="slack"] .sl-emoji-menu .sl-keys { grid-template-rows: repeat(4, 40px); }
|
||||
[data-module="slack"] .sl-emoji-menu .sl-key { font-size: 17px; }
|
||||
@@ -0,0 +1,531 @@
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/** 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 (!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);
|
||||
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 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 = `${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 = fmt(value);
|
||||
el.dataset.level = !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 });
|
||||
let painted = false; // spectrogram: has the background been laid down
|
||||
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');
|
||||
|
||||
if (!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(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;
|
||||
const gutter = showLabels ? axisPad : 0;
|
||||
// Frequency occupies whichever axis time does not.
|
||||
const freqExtent = timeX ? h - gutter : w - gutter;
|
||||
const timeExtent = timeX ? w : h;
|
||||
|
||||
if (!painted) { ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h); painted = true; }
|
||||
|
||||
// Source rect in device pixels, destination in CSS pixels: the context
|
||||
// carries a devicePixelRatio transform but the canvas as an image
|
||||
// source does not, and letting drawImage infer them scales the picture
|
||||
// up and pushes every column off the canvas.
|
||||
if (timeX) {
|
||||
ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, -colW, 0, w, h);
|
||||
} else {
|
||||
ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, -colW, w, h);
|
||||
}
|
||||
|
||||
const bandExtent = freqExtent / values.length;
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
ctx.fillStyle = heat(norm(values[i], payload.calibrated));
|
||||
if (timeX) {
|
||||
// Low frequencies at the bottom, as every spectrogram has them.
|
||||
ctx.fillRect(timeExtent - colW, freqExtent - (i + 1) * bandExtent,
|
||||
colW, Math.ceil(bandExtent) + 1);
|
||||
} else {
|
||||
// Low frequencies at the left.
|
||||
ctx.fillRect(gutter + i * bandExtent, timeExtent - colW,
|
||||
Math.ceil(bandExtent) + 1, colW);
|
||||
}
|
||||
}
|
||||
|
||||
if (grid || showLabels) {
|
||||
const posOf = (f) => {
|
||||
const t = Math.log2(f / freqs[0]) / Math.log2(freqs[freqs.length - 1] / freqs[0]);
|
||||
return timeX ? freqExtent - t * freqExtent : gutter + t * freqExtent;
|
||||
};
|
||||
const labels = chooseLabels(freqs, posOf, timeX ? freqExtent : w, timeX ? 16 : 34);
|
||||
ctx.fillStyle = bg;
|
||||
if (timeX) ctx.fillRect(0, h - gutter, w, gutter);
|
||||
else ctx.fillRect(0, 0, gutter, h);
|
||||
ctx.fillStyle = muted; ctx.font = '9px system-ui';
|
||||
ctx.strokeStyle = border; ctx.globalAlpha = grid ? 0.35 : 0; ctx.beginPath();
|
||||
for (const l of labels) {
|
||||
if (timeX) {
|
||||
const y = Math.round(l.pos) + 0.5;
|
||||
ctx.moveTo(0, y); ctx.lineTo(w, y);
|
||||
} else {
|
||||
const x = Math.round(l.pos) + 0.5;
|
||||
ctx.moveTo(x, 0); ctx.lineTo(x, h);
|
||||
}
|
||||
}
|
||||
ctx.stroke(); ctx.globalAlpha = 1;
|
||||
ctx.textAlign = timeX ? 'left' : 'center';
|
||||
for (const l of showLabels ? labels : []) {
|
||||
if (timeX) ctx.fillText(hzLabel(l.f), 2, Math.min(h - gutter - 2, l.pos + 3));
|
||||
else ctx.fillText(hzLabel(l.f), l.pos, h - 3);
|
||||
}
|
||||
}
|
||||
},
|
||||
resize() { sizeCanvas(); },
|
||||
destroy() { root.innerHTML = ''; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"id": "spl-meter",
|
||||
"name": "SPL Meter",
|
||||
"version": "0.3.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."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
'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;
|
||||
|
||||
/** 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(),
|
||||
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;
|
||||
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 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 ────────────────────────────────────────────────────────── */
|
||||
|
||||
function snapshot() {
|
||||
if (!state) return { error: 'not measuring', calibrated: false, channels: [], frame: null };
|
||||
return {
|
||||
error: state.error,
|
||||
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);
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,148 @@
|
||||
/* 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); }
|
||||
|
||||
/* ── 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); }
|
||||
|
||||
/* 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; }
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "proddash",
|
||||
"version": "1.4.0",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"description": "Modular production dashboard for Waters Church — zero-dependency Node server + vanilla client",
|
||||
"description": "Modular production dashboard for Waters Church \u2014 zero-dependency Node server + vanilla client",
|
||||
"license": "UNLICENSED",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
|
||||
@@ -38,7 +38,7 @@ Edit [config.json](config.json):
|
||||
|
||||
| Key | Meaning |
|
||||
| --- | --- |
|
||||
| `prodcomUrl` | Where the ProdCom API lives (default `http://10.3.11.152:24480`) |
|
||||
| `prodcomUrl` | Where the ProdCom API lives — set it per site, e.g. `http://<prodcom-host>:24480` |
|
||||
| `port` | Port this listener serves on (default `24481`) |
|
||||
| `apiKey` | Only needed if PSK auth is enabled in ProdCom settings |
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"prodcomUrl": "http://10.3.11.152:24480",
|
||||
"prodcomUrl": "",
|
||||
"port": 24481,
|
||||
"apiKey": ""
|
||||
}
|
||||
|
||||
@@ -23,10 +23,15 @@ try {
|
||||
console.warn('config.json not found or invalid, using defaults/env vars');
|
||||
}
|
||||
|
||||
const PRODCOM_URL = process.env.PRODCOM_URL || cfg.prodcomUrl || 'http://10.3.11.152:24480';
|
||||
const PRODCOM_URL = process.env.PRODCOM_URL || cfg.prodcomUrl || '';
|
||||
const PORT = Number(process.env.PORT || cfg.port || 24481);
|
||||
const API_KEY = process.env.PRODCOM_API_KEY || cfg.apiKey || '';
|
||||
|
||||
if (!PRODCOM_URL) {
|
||||
console.error('No ProdCom API configured. Set prodcomUrl in config.json (or the PRODCOM_URL');
|
||||
console.error('environment variable) to this site\'s ProdCom, e.g. http://<prodcom-host>:24480');
|
||||
process.exit(1);
|
||||
}
|
||||
const target = new URL(PRODCOM_URL);
|
||||
const PUBLIC_DIR = path.join(__dirname, 'public');
|
||||
|
||||
|
||||
@@ -135,11 +135,33 @@ body { overflow: auto; }
|
||||
.module-form { margin-top: 12px; border-top: 1px solid var(--border); padding-top: 12px; }
|
||||
.module-form .field { max-width: 420px; }
|
||||
|
||||
/* a multi-line string (manifest type `text`): the same box as the other
|
||||
inputs (those rules live in the shell's style.css), a few lines tall */
|
||||
.field textarea {
|
||||
padding: 7px 9px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
line-height: 1.4;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 7px;
|
||||
resize: vertical;
|
||||
min-height: 72px;
|
||||
}
|
||||
.field textarea:focus { outline: none; border-color: var(--accent); }
|
||||
|
||||
/* endpoint fields: every module's upstream is entered the same way */
|
||||
.field .endpoint-row { display: flex; align-items: center; gap: 7px; }
|
||||
.endpoint-row .ep-host { flex: 1; min-width: 0; }
|
||||
.endpoint-row .ep-port { width: 92px; flex: none; }
|
||||
.endpoint-row .ep-sep { color: var(--muted); font-weight: 600; }
|
||||
/* several picks from a list (manifest type `multiselect`) */
|
||||
.field.multiselect-field { cursor: default; }
|
||||
.field.multiselect-field .multiselect { display: flex; flex-direction: column; gap: 6px; }
|
||||
.multiselect-row { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||
.multiselect-empty { color: var(--muted); font-size: 12px; }
|
||||
|
||||
.module-form-empty { color: var(--muted); font-size: 12px; margin-top: 10px; }
|
||||
|
||||
/* labeled config subsections (manifest field `group`) */
|
||||
@@ -429,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));
|
||||
@@ -490,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;
|
||||
}
|
||||
|
||||
+188
-3
@@ -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 ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -228,6 +316,73 @@ function fieldFor(key, spec, value, passwordSet, moduleId) {
|
||||
field.append(span, select);
|
||||
read = () => select.value;
|
||||
selectEl = select;
|
||||
} else if (type === 'multiselect' && (Array.isArray(spec.options) || spec.optionsRoute)) {
|
||||
// Several picks from one list — a switch per option, stored as an array
|
||||
// of values. A saved value the list no longer offers stays checked and
|
||||
// marked, so a channel the account has left isn't dropped in silence.
|
||||
field.classList.add('multiselect-field');
|
||||
// The wrapper is a <label>; with several controls inside, a click on the
|
||||
// wrapper would activate the FIRST one. `for=""` makes it label nothing.
|
||||
field.htmlFor = '';
|
||||
const span = document.createElement('span');
|
||||
span.textContent = label;
|
||||
const list = document.createElement('div');
|
||||
list.className = 'multiselect';
|
||||
const chosen = new Set((Array.isArray(value) ? value : []).map(String).filter(Boolean));
|
||||
const optValue = (opt) => String(typeof opt === 'object' ? opt.value : opt);
|
||||
const fill = (options) => {
|
||||
for (const input of list.querySelectorAll('input')) {
|
||||
if (input.checked) chosen.add(input.value);
|
||||
else chosen.delete(input.value);
|
||||
}
|
||||
list.innerHTML = '';
|
||||
const missing = [...chosen].filter((v) => !options.some((opt) => optValue(opt) === v));
|
||||
const all = [...options, ...missing.map((v) => ({ value: v, label: `${v} (saved — not listed now)` }))];
|
||||
for (const opt of all) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'multiselect-row';
|
||||
const toggle = document.createElement('span');
|
||||
toggle.className = 'switch';
|
||||
const input = document.createElement('input');
|
||||
input.type = 'checkbox';
|
||||
input.value = optValue(opt);
|
||||
input.checked = chosen.has(input.value);
|
||||
const track = document.createElement('span');
|
||||
track.className = 'track';
|
||||
toggle.append(input, track);
|
||||
const text = document.createElement('span');
|
||||
text.className = 'switch-label';
|
||||
text.textContent = String(typeof opt === 'object' ? (opt.label ?? opt.value) : opt);
|
||||
row.append(toggle, text);
|
||||
row.addEventListener('click', (e) => {
|
||||
if (e.target === input) return; // the box toggles itself
|
||||
input.checked = !input.checked;
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
list.appendChild(row);
|
||||
}
|
||||
if (!all.length) {
|
||||
const none = document.createElement('div');
|
||||
none.className = 'multiselect-empty';
|
||||
none.textContent = 'Nothing to choose from yet.';
|
||||
list.appendChild(none);
|
||||
}
|
||||
};
|
||||
fill(Array.isArray(spec.options) ? spec.options : []);
|
||||
if (spec.optionsRoute && moduleId) {
|
||||
refetch = (query) => {
|
||||
const qs = query && Object.keys(query).length ? `?${new URLSearchParams(query)}` : '';
|
||||
return fetch(`/api/modules/${encodeURIComponent(moduleId)}${spec.optionsRoute}${qs}`)
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((body) => {
|
||||
if (Array.isArray(body?.options)) fill(body.options);
|
||||
})
|
||||
.catch(() => { /* keep the static/saved options */ });
|
||||
};
|
||||
if (!spec.optionsDependsOn) refetch();
|
||||
}
|
||||
field.append(span, list);
|
||||
read = () => [...list.querySelectorAll('input:checked')].map((input) => input.value);
|
||||
} else if (type === 'color') {
|
||||
// A swatch picker; the value is always a #rrggbb string.
|
||||
field.classList.add('color-field');
|
||||
@@ -239,6 +394,17 @@ function fieldFor(key, spec, value, passwordSet, moduleId) {
|
||||
input.value = hex(value, hex(spec?.default, '#2ee59a'));
|
||||
field.append(span, input);
|
||||
read = () => input.value;
|
||||
} else if (type === 'text') {
|
||||
// A multi-line string — one item per line by convention (a list of
|
||||
// presets, say). Stored as-is, newlines included.
|
||||
const span = document.createElement('span');
|
||||
span.textContent = label;
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.rows = 5;
|
||||
textarea.spellcheck = false;
|
||||
textarea.value = value === undefined || value === null ? '' : String(value);
|
||||
field.append(span, textarea);
|
||||
read = () => textarea.value;
|
||||
} else {
|
||||
const span = document.createElement('span');
|
||||
span.textContent = label;
|
||||
@@ -743,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);
|
||||
}
|
||||
}
|
||||
@@ -778,6 +962,7 @@ async function loadState() {
|
||||
for (const mod of state.modules || []) {
|
||||
modulesList.appendChild(buildModuleCard(mod));
|
||||
}
|
||||
renderPin(state);
|
||||
loadTheme();
|
||||
loadLayouts();
|
||||
loadCatalog(false);
|
||||
|
||||
+35
-3
@@ -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>
|
||||
<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>
|
||||
|
||||
+15
-8
@@ -19,7 +19,15 @@
|
||||
|
||||
<span class="spacer"></span>
|
||||
|
||||
<button class="tb-btn icon" id="fs-btn" title="Fullscreen — auto-fits the layout to the screen" aria-label="Fullscreen">
|
||||
<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"/>
|
||||
<path d="M4 15v4a1 1 0 0 0 1 1h4"/><path d="M20 15v4a1 1 0 0 1-1 1h-4"/>
|
||||
@@ -27,12 +35,14 @@
|
||||
</button>
|
||||
|
||||
<div class="dropdown" id="add-dd">
|
||||
<button class="tb-btn icon" id="add-btn" title="Add a module tile" aria-label="Add tile">+</button>
|
||||
<button class="tb-btn icon" id="add-btn" title="Add tile" aria-label="Add tile">
|
||||
<svg width="14" height="14" 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>
|
||||
</button>
|
||||
<div class="menu" id="add-menu" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="dropdown" id="layout-dd">
|
||||
<button class="tb-btn icon" id="layout-btn" title="Save, load or reset layouts" aria-label="Layouts">
|
||||
<button class="tb-btn icon" id="layout-btn" title="Layouts" aria-label="Layouts">
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<rect x="3" y="3" width="8" height="8" rx="1.5"/>
|
||||
<rect x="3" y="13" width="8" height="8" rx="1.5"/>
|
||||
@@ -42,11 +52,8 @@
|
||||
<div class="menu" id="layout-menu" hidden></div>
|
||||
</div>
|
||||
|
||||
<a class="tb-btn" id="admin-link" href="/admin/" title="Configure modules (server-wide)">
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
||||
<path d="M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Zm8.4-2.1.1-1.4-.1-1.4 1.7-1.3-1.6-2.8-2 .7a7.9 7.9 0 0 0-2.4-1.4l-.3-2.1H11l-.3 2.1a7.9 7.9 0 0 0-2.4 1.4l-2-.7L4.7 9.3 6.4 10.6l-.1 1.4.1 1.4-1.7 1.3 1.6 2.8 2-.7a7.9 7.9 0 0 0 2.4 1.4l.3 2.1h2.8l.3-2.1a7.9 7.9 0 0 0 2.4-1.4l2 .7 1.6-2.8-1.7-1.3Z"/>
|
||||
</svg>
|
||||
Admin
|
||||
<a class="tb-btn icon" id="admin-link" href="/admin/" title="Admin" aria-label="Admin">
|
||||
<svg width="14" height="14" 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>
|
||||
</a>
|
||||
</header>
|
||||
|
||||
|
||||
+1078
-225
File diff suppressed because it is too large
Load Diff
+411
-142
@@ -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 ────────────────────────────────────────────────── */
|
||||
|
||||
@@ -170,6 +178,7 @@ body.menu-hidden #topbar {
|
||||
margin-top: 2px;
|
||||
white-space: normal;
|
||||
}
|
||||
.menu-item[disabled] { opacity: 0.45; cursor: default; }
|
||||
.menu-item.danger { color: var(--danger); }
|
||||
.menu-note {
|
||||
padding: 8px 10px;
|
||||
@@ -178,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);
|
||||
@@ -233,6 +272,18 @@ body.menu-hidden #topbar {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* A tile the user gave a colour: a wash over the panel, a stronger edge and
|
||||
a tinted title bar. Module content keeps its own colours — this is the
|
||||
tile's chrome, so a tinted tile still reads like every other one. */
|
||||
.tile.is-tinted {
|
||||
background: color-mix(in srgb, var(--tile-tint) 14%, var(--panel));
|
||||
border-color: color-mix(in srgb, var(--tile-tint) 45%, var(--border));
|
||||
}
|
||||
.tile.is-tinted > .tile-head {
|
||||
background: color-mix(in srgb, var(--tile-tint) 20%, transparent);
|
||||
border-bottom-color: color-mix(in srgb, var(--tile-tint) 35%, var(--border));
|
||||
}
|
||||
|
||||
.tile.dragging,
|
||||
.tile.resizing {
|
||||
z-index: 40;
|
||||
@@ -257,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 {
|
||||
@@ -277,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;
|
||||
@@ -305,6 +378,53 @@ body.menu-hidden #topbar {
|
||||
.tile-btn:hover { background: var(--border); color: var(--text); }
|
||||
.tile-btn.close:hover { color: var(--danger); }
|
||||
.tile-btn.active { color: var(--accent); }
|
||||
.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;
|
||||
z-index: 200;
|
||||
pointer-events: none;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 5px;
|
||||
background: var(--panel);
|
||||
color: var(--text);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
#tip[hidden] { display: none; }
|
||||
.tile-btn svg { width: 13px; height: 13px; display: block; }
|
||||
|
||||
/* controls a module adds to its own title bar (moduleApi.header) */
|
||||
@@ -341,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;
|
||||
@@ -398,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;
|
||||
@@ -495,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; }
|
||||
@@ -533,28 +593,122 @@ body.fullscreen #grid { padding-bottom: 0; }
|
||||
|
||||
/* ── per-tile settings popover ─────────────────────────────────────── */
|
||||
|
||||
/* A small window beside its tile (shell.js places and clamps it), not a
|
||||
box inside the tile: a tile can be smaller than its own settings, and the
|
||||
whole point of live settings is watching the tile change. */
|
||||
.tile-settings {
|
||||
position: absolute;
|
||||
top: 36px;
|
||||
right: 6px;
|
||||
z-index: 45;
|
||||
min-width: 220px;
|
||||
max-width: calc(100% - 12px);
|
||||
max-height: calc(100% - 40px);
|
||||
overflow-y: auto;
|
||||
position: fixed;
|
||||
z-index: 80;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
/* as wide as its content wants and no wider: a couple of switches make a
|
||||
small window, a three-column checklist a wide one */
|
||||
width: max-content;
|
||||
min-width: 150px;
|
||||
max-width: min(560px, calc(100vw - 16px));
|
||||
max-height: calc(100vh - 16px);
|
||||
overflow: hidden;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
/* the grab bar: a slim accent strip with a grip mark, nothing to read or
|
||||
press — the gear that opened the window wears the same colour meanwhile */
|
||||
.tile-settings-bar {
|
||||
flex: none;
|
||||
height: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--accent);
|
||||
cursor: grab;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
touch-action: none;
|
||||
}
|
||||
.tile-settings-bar::before {
|
||||
content: "";
|
||||
width: 34px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--accent-text);
|
||||
opacity: 0.7;
|
||||
transition: opacity 0.12s;
|
||||
}
|
||||
.tile-settings-bar:hover::before { opacity: 1; }
|
||||
.tile-settings .field[hidden] { display: none; }
|
||||
/* the tint, the shell's own setting, under a hairline at the foot */
|
||||
.tile-settings .tint-field {
|
||||
margin: 8px 0 0;
|
||||
padding-top: 9px;
|
||||
border-top: 1px solid var(--border);
|
||||
gap: 8px;
|
||||
}
|
||||
.tile-settings .tint-clear {
|
||||
flex: none;
|
||||
padding: 1px 7px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.tile-settings .tint-clear:hover { color: var(--text); background: var(--border); }
|
||||
.tile-settings .tint-clear[hidden] { display: none; }
|
||||
.tile-settings-bar:active { cursor: grabbing; }
|
||||
.tile-settings-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 10px;
|
||||
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
/* Help lines never widen the window: they take no room of their own when the
|
||||
content is measured, then wrap to whatever width the fields settled on. */
|
||||
.tile-settings .field-help,
|
||||
.tile-settings .field-group-help,
|
||||
.tile-settings .multiselect-empty { width: 0; min-width: 100%; }
|
||||
/* a group's on/off sits in its title row; the body dims while it is off */
|
||||
.tile-settings .field-group-title { display: flex; align-items: center; gap: 8px; }
|
||||
.tile-settings .field-group-name { flex: 1; min-width: 0; }
|
||||
.tile-settings .group-toggle { margin: 0 0 0 auto; }
|
||||
.tile-settings .group-toggle .check-label { display: none; }
|
||||
.tile-settings .field-group.is-off .field-group-body { opacity: 0.45; }
|
||||
/* several picks from a list (type `multiselect`) */
|
||||
.tile-settings .multiselect-field { display: flex; flex-direction: column; gap: 4px; }
|
||||
.tile-settings .multiselect { display: flex; flex-direction: column; gap: 3px; }
|
||||
.tile-settings .multiselect.is-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--cols, 2), minmax(0, 1fr));
|
||||
gap: 3px 14px;
|
||||
}
|
||||
.tile-settings .multiselect-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
.tile-settings .multiselect-row .check-label { flex: 1 1 0; min-width: 0; }
|
||||
.tile-settings .multiselect-empty { color: var(--muted); font-size: 12px; }
|
||||
/* a text built from offered variables (type `template`) */
|
||||
.tile-settings .template-vars { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 2px; }
|
||||
.tile-settings .template-var {
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
cursor: grab;
|
||||
}
|
||||
.tile-settings .template-var:hover { border-color: var(--accent); }
|
||||
.tile-settings .template-var:active { cursor: grabbing; }
|
||||
|
||||
/* A popover with grouped settings needs room for its columns; it still
|
||||
never grows past the tile (max-width above). */
|
||||
.tile-settings.has-groups {
|
||||
min-width: min(540px, calc(100% - 12px));
|
||||
container-type: inline-size;
|
||||
}
|
||||
.tile-settings .field-group {
|
||||
margin: 0 0 10px;
|
||||
padding: 8px 10px;
|
||||
@@ -592,7 +746,7 @@ body.fullscreen #grid { padding-bottom: 0; }
|
||||
.tile-settings .field-group .field:last-child { margin-bottom: 0; }
|
||||
/* Settings apply as they change, so nothing sits under the last field — its
|
||||
bottom margin would only pad the popover's own padding a second time. */
|
||||
.tile-settings > :last-child { margin-bottom: 0; }
|
||||
.tile-settings-body > :last-child { margin-bottom: 0; }
|
||||
.tile-settings .field-group-body.is-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--cols, 2), minmax(0, 1fr));
|
||||
@@ -600,12 +754,10 @@ body.fullscreen #grid { padding-bottom: 0; }
|
||||
}
|
||||
.tile-settings .field-group-body.is-columns .field { margin-bottom: 0; }
|
||||
.tile-settings .field-group-body.is-columns .field-group-help { grid-column: 1 / -1; }
|
||||
@container (max-width: 420px) {
|
||||
.tile-settings .field-group-body.is-columns { grid-template-columns: 1fr 1fr; }
|
||||
}
|
||||
@container (max-width: 260px) {
|
||||
.tile-settings .field-group-body.is-columns { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* a list of switches or a template with its chips is a row of its own, however
|
||||
many columns the group lays its other fields out in */
|
||||
.tile-settings .field-group-body.is-columns .multiselect-field,
|
||||
.tile-settings .field-group-body.is-columns .template-field { grid-column: 1 / -1; }
|
||||
.tile-settings .field-group-help,
|
||||
.tile-settings .field-help {
|
||||
display: block;
|
||||
@@ -784,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 ────────────────────────────────────────────────────── */
|
||||
@@ -819,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"] {
|
||||
@@ -871,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;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
* 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)
|
||||
*/
|
||||
'use strict';
|
||||
@@ -463,7 +466,20 @@ function sanitizeTileEntry(raw) {
|
||||
name: String(raw.name),
|
||||
description: raw.description ? String(raw.description) : '',
|
||||
settings: raw.settings && typeof raw.settings === 'object' ? raw.settings : {},
|
||||
// at most one tile of this entry per dashboard (the picker greys it out)
|
||||
single: raw.single === true,
|
||||
};
|
||||
// An entry may offer its own gear settings — a solo timer wants none of a
|
||||
// full tile's switches. Same shape as the manifest's instanceSchema/Groups.
|
||||
for (const key of ['instanceSchema', 'instanceGroups']) {
|
||||
if (raw[key] && typeof raw[key] === 'object') out[key] = raw[key];
|
||||
}
|
||||
// Earlier variant ids this entry stands for, so a tile added under one of
|
||||
// them (a layout from an older module version) gets this entry's settings.
|
||||
if (Array.isArray(raw.aliases)) {
|
||||
const aliases = raw.aliases.map((a) => String(a)).filter(Boolean);
|
||||
if (aliases.length) out.aliases = aliases;
|
||||
}
|
||||
for (const key of ['minSize', 'defaultSize']) {
|
||||
const size = raw[key];
|
||||
if (size && Number(size.w) > 0 && Number(size.h) > 0) {
|
||||
@@ -546,6 +562,142 @@ setInterval(() => {
|
||||
}
|
||||
}, 25000).unref();
|
||||
|
||||
/* ── one stream per page ─────────────────────────────────────────────
|
||||
Browsers allow about six HTTP/1.1 connections to a host and an open
|
||||
EventSource holds one for as long as it lives. A dashboard with six
|
||||
modules ran out — Safari first — and from then on every further request
|
||||
(a remounted tile's /state, an avatar) waited in the browser's queue for
|
||||
ever. So a page opens ONE EventSource, GET /api/stream?s=<keys>, naming
|
||||
the streams it wants: `slack:/stream`, `pco-plan:/timers/stream`, `shell:`
|
||||
for the shell's own events. The server opens each module stream for it
|
||||
over loopback (the module's route is untouched and still serves curl and
|
||||
other tools), and forwards every frame with the event name prefixed by
|
||||
its key — `event: slack:/stream|state`. Two frames of its own bracket a
|
||||
stream's life: `<key>|__open` when the upstream answers, `<key>|__down`
|
||||
when it ends (it is re-opened after a pause while the page stays). */
|
||||
|
||||
const MUX_MAX_STREAMS = 32;
|
||||
const MUX_RETRY_MS = 3000;
|
||||
const MUX_RETRY_REFUSED_MS = 10000;
|
||||
const MUX_PING_MS = 15000;
|
||||
const MUX_KEY_RE = /^([A-Za-z0-9_-]+):(\/[A-Za-z0-9_\-./]*)?$/;
|
||||
|
||||
function parseMuxKeys(search) {
|
||||
const params = new URLSearchParams(search || '');
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const raw of String(params.get('s') || '').split(',')) {
|
||||
const key = raw.trim();
|
||||
const m = MUX_KEY_RE.exec(key);
|
||||
if (!m || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({ key, id: m[1], subPath: m[2] || '' });
|
||||
if (out.length >= MUX_MAX_STREAMS) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function handleMuxStream(req, res, search) {
|
||||
const wanted = parseMuxKeys(search);
|
||||
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');
|
||||
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
|
||||
let closed = false;
|
||||
const send = (frame) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
res.write(frame);
|
||||
} catch {
|
||||
/* the client is gone; 'close' follows */
|
||||
}
|
||||
};
|
||||
|
||||
// The shell's own events ride along under `shell:` — a stand-in sits in
|
||||
// shellStreams and rewrites the event line of every frame it is handed.
|
||||
let shellProxy = null;
|
||||
const upstreams = [];
|
||||
for (const entry of wanted) {
|
||||
if (entry.id === 'shell') {
|
||||
if (shellProxy) continue;
|
||||
shellProxy = { write(frame) { send(String(frame).replace(/^event: /m, `event: ${entry.key}|`)); } };
|
||||
shellStreams.add(shellProxy);
|
||||
send(`event: ${entry.key}|__open\ndata: {}\n\n`);
|
||||
continue;
|
||||
}
|
||||
upstreams.push({ ...entry, req: null, timer: null, gone: false });
|
||||
}
|
||||
|
||||
function forwardBlock(entry, block) {
|
||||
let name = 'message';
|
||||
const data = [];
|
||||
for (const line of block.split('\n')) {
|
||||
if (line.startsWith(':')) continue; // the upstream's keepalive; this connection pings on its own
|
||||
if (line.startsWith('event:')) name = line.slice(6).trim() || 'message';
|
||||
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
||||
// id: and retry: belong to the upstream connection, not to the page's
|
||||
}
|
||||
if (!data.length) return;
|
||||
send(`event: ${entry.key}|${name}\n${data.map((d) => `data: ${d}`).join('\n')}\n\n`);
|
||||
}
|
||||
|
||||
function down(entry, why, delay) {
|
||||
if (closed || entry.gone) return;
|
||||
entry.gone = true;
|
||||
send(`event: ${entry.key}|__down\ndata: ${JSON.stringify({ why })}\n\n`);
|
||||
try { entry.req?.destroy(); } catch { /* already gone */ }
|
||||
entry.req = null;
|
||||
entry.timer = setTimeout(() => {
|
||||
entry.gone = false;
|
||||
open(entry);
|
||||
}, delay);
|
||||
}
|
||||
|
||||
function open(entry) {
|
||||
if (closed) return;
|
||||
const path = `/api/modules/${encodeURIComponent(entry.id)}${entry.subPath || '/'}`;
|
||||
const up = http.request({ host: '127.0.0.1', port: PORT, path, method: 'GET', headers: { accept: 'text/event-stream' } }, (upRes) => {
|
||||
if (upRes.statusCode !== 200 || !/text\/event-stream/.test(String(upRes.headers['content-type'] || ''))) {
|
||||
upRes.resume();
|
||||
return down(entry, `HTTP ${upRes.statusCode}`, MUX_RETRY_REFUSED_MS);
|
||||
}
|
||||
send(`event: ${entry.key}|__open\ndata: {}\n\n`);
|
||||
let buf = '';
|
||||
upRes.setEncoding('utf8');
|
||||
upRes.on('data', (chunk) => {
|
||||
buf += chunk;
|
||||
let i;
|
||||
while ((i = buf.indexOf('\n\n')) >= 0) {
|
||||
forwardBlock(entry, buf.slice(0, i));
|
||||
buf = buf.slice(i + 2);
|
||||
}
|
||||
if (buf.length > 1e6) buf = ''; // a frame that never ends is dropped, not kept
|
||||
});
|
||||
upRes.on('end', () => down(entry, 'ended', MUX_RETRY_MS));
|
||||
upRes.on('error', (err) => down(entry, err.message, MUX_RETRY_MS));
|
||||
});
|
||||
up.on('error', (err) => down(entry, err.message, MUX_RETRY_MS));
|
||||
up.end();
|
||||
entry.req = up;
|
||||
}
|
||||
|
||||
for (const entry of upstreams) open(entry);
|
||||
const ping = setInterval(() => send(': ping\n\n'), MUX_PING_MS);
|
||||
req.on('close', () => {
|
||||
closed = true;
|
||||
clearInterval(ping);
|
||||
if (shellProxy) shellStreams.delete(shellProxy);
|
||||
for (const entry of upstreams) {
|
||||
clearTimeout(entry.timer);
|
||||
try { entry.req?.destroy(); } catch { /* already gone */ }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ── themes ─────────────────────────────────────────────────────────── */
|
||||
|
||||
/* Preset palettes for the whole dashboard, chosen in Admin → Theme. The
|
||||
@@ -560,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;
|
||||
|
||||
@@ -615,15 +774,53 @@ function parseRepoSetting(value, fallbackBranch) {
|
||||
}
|
||||
|
||||
const REPO = parseRepoSetting(process.env.PRODDASH_REPO || shellConfig.repo, shellConfig.branch)
|
||||
|| parseRepoSetting('michaelmcgary2008/ProdDash', 'main');
|
||||
|| parseRepoSetting('michael/ProdDash', 'main');
|
||||
|
||||
/**
|
||||
* Which server the code comes from. GitHub unless `forge` names another —
|
||||
* give it a Gitea (or Forgejo) base URL, "http://10.3.8.90:3000", and updates
|
||||
* and module installs come from there instead. The two hosts differ only in
|
||||
* how an archive URL is spelled: the tarball itself is the same, pax header
|
||||
* and commit sha included, so everything downstream is untouched.
|
||||
*/
|
||||
function parseForge(value) {
|
||||
const s = String(value || '').trim().replace(/\/+$/, '');
|
||||
if (!s || s.toLowerCase() === 'github') {
|
||||
return { kind: 'github', base: 'https://github.com', archiveBase: 'https://codeload.github.com' };
|
||||
}
|
||||
if (!/^https?:\/\//i.test(s)) return null;
|
||||
// A GitHub URL still means codeload for archives.
|
||||
if (/^https?:\/\/(www\.)?github\.com$/i.test(s)) {
|
||||
return { kind: 'github', base: s, archiveBase: 'https://codeload.github.com' };
|
||||
}
|
||||
return { kind: 'gitea', base: s, archiveBase: s };
|
||||
}
|
||||
|
||||
const FORGE = parseForge(process.env.PRODDASH_FORGE || shellConfig.forge) || parseForge('github');
|
||||
/** Where branch archives come from; tests point this at a local mock. */
|
||||
const ARCHIVE_BASE = String(process.env.PRODDASH_ARCHIVE_BASE || 'https://codeload.github.com').replace(/\/+$/, '');
|
||||
const ARCHIVE_BASE = String(process.env.PRODDASH_ARCHIVE_BASE || FORGE.archiveBase).replace(/\/+$/, '');
|
||||
const REMOTE_TTL_MS = 10 * 60 * 1000;
|
||||
const REMOTE_CHECK_MS = 6 * 60 * 60 * 1000;
|
||||
const MAX_ARCHIVE_BYTES = 80 * 1024 * 1024;
|
||||
|
||||
function tarballUrl() {
|
||||
return `${ARCHIVE_BASE}/${REPO.owner}/${REPO.repo}/tar.gz/${encodeURIComponent(REPO.branch)}`;
|
||||
const branch = encodeURIComponent(REPO.branch);
|
||||
return FORGE.kind === 'gitea'
|
||||
? `${ARCHIVE_BASE}/${REPO.owner}/${REPO.repo}/archive/${branch}.tar.gz`
|
||||
: `${ARCHIVE_BASE}/${REPO.owner}/${REPO.repo}/tar.gz/${branch}`;
|
||||
}
|
||||
|
||||
/** The page a human should read to see what changed between two commits. */
|
||||
function forgeCompareUrl(from, to) {
|
||||
return `${FORGE.base}/${REPO.owner}/${REPO.repo}/compare/${from}...${to}`;
|
||||
}
|
||||
|
||||
/** The commit list for the branch we follow. */
|
||||
function forgeCommitsUrl() {
|
||||
const branch = encodeURIComponent(REPO.branch);
|
||||
return FORGE.kind === 'gitea'
|
||||
? `${FORGE.base}/${REPO.owner}/${REPO.repo}/commits/branch/${branch}`
|
||||
: `${FORGE.base}/${REPO.owner}/${REPO.repo}/commits/${branch}`;
|
||||
}
|
||||
|
||||
function httpError(status, message) {
|
||||
@@ -780,11 +977,11 @@ function shellStatus() {
|
||||
else if (local.branch !== REPO.branch) blocker = `this checkout is on branch "${local.branch}", not "${REPO.branch}"`;
|
||||
else if (local.dirty) blocker = 'this checkout has local changes — commit or discard them first';
|
||||
}
|
||||
const gh = `https://github.com/${REPO.owner}/${REPO.repo}`;
|
||||
return {
|
||||
version: SHELL_VERSION,
|
||||
repo: `${REPO.owner}/${REPO.repo}`,
|
||||
branch: REPO.branch,
|
||||
forge: FORGE.base,
|
||||
local: { isGit: local.isGit, sha: local.sha, branch: local.branch, dirty: local.dirty },
|
||||
remote: { version: remote.version, sha: remote.sha, checkedAt: remote.checkedAt, error: remote.error },
|
||||
updateAvailable: versionBehind || commitsBehind,
|
||||
@@ -792,8 +989,8 @@ function shellStatus() {
|
||||
method: local.isGit ? 'git' : 'archive',
|
||||
updateBlocker: blocker,
|
||||
changesUrl: local.sha && remote.sha
|
||||
? `${gh}/compare/${local.sha.slice(0, 12)}...${remote.sha.slice(0, 12)}`
|
||||
: `${gh}/commits/${REPO.branch}`,
|
||||
? forgeCompareUrl(local.sha.slice(0, 12), remote.sha.slice(0, 12))
|
||||
: forgeCommitsUrl(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -907,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);
|
||||
}
|
||||
}
|
||||
@@ -932,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
|
||||
@@ -981,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);
|
||||
}
|
||||
@@ -994,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
|
||||
@@ -1055,6 +1408,9 @@ function applyConfigPatch(id, patch) {
|
||||
}
|
||||
if (type === 'number') value = Number(value) || 0;
|
||||
else if (type === 'boolean' || type === 'switch') value = Boolean(value);
|
||||
else if (type === 'multiselect') {
|
||||
value = (Array.isArray(value) ? value : []).map((v) => String(v)).filter(Boolean);
|
||||
}
|
||||
else if (type === 'endpoint') {
|
||||
const src = value && typeof value === 'object' ? value : {};
|
||||
value = {
|
||||
@@ -1076,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`,
|
||||
@@ -1088,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,
|
||||
@@ -1198,11 +1601,55 @@ 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) => ({
|
||||
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,
|
||||
@@ -1210,7 +1657,20 @@ function sanitizeLayout(raw) {
|
||||
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;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1222,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 {
|
||||
@@ -1265,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 {
|
||||
@@ -1307,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.' });
|
||||
}
|
||||
|
||||
@@ -1432,6 +1926,11 @@ function handleRequest(req, res) {
|
||||
return sendJson(res, 200, themeView());
|
||||
}
|
||||
|
||||
/* — every stream a page wants, over one connection — */
|
||||
if (urlPath === '/api/stream' && req.method === 'GET') {
|
||||
return handleMuxStream(req, res, search);
|
||||
}
|
||||
|
||||
/* — shell events: open dashboards learn about admin changes live — */
|
||||
if (urlPath === '/api/events' && req.method === 'GET') {
|
||||
res.writeHead(200, {
|
||||
@@ -1536,7 +2035,7 @@ server.on('listening', () => {
|
||||
? ' Modules : ' + ids.map((id) => id + (isEnabled(id) ? '' : ' (disabled)') + (manifests.get(id).incompatible ? ' (needs newer ProdDash)' : '')).join(', ')
|
||||
: ' Modules : none installed');
|
||||
console.log(' Settings : ' + DATA_DIR + (DATA_DIR === REPO_CONFIG_DIR ? ' (inside the app folder)' : ''));
|
||||
console.log(' Repo : ' + REPO.owner + '/' + REPO.repo + '@' + REPO.branch);
|
||||
console.log(' Repo : ' + REPO.owner + '/' + REPO.repo + '@' + REPO.branch + ' (' + FORGE.base + ')');
|
||||
});
|
||||
|
||||
// A restart hands the port over from the exiting ProdDash: wait for it.
|
||||
@@ -1554,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) {
|
||||
|
||||
@@ -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);
|
||||
})();
|
||||
@@ -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}`));
|
||||
@@ -11,6 +11,10 @@
|
||||
* 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}/item_note_categories
|
||||
* the note categories the
|
||||
* items below use, plus one
|
||||
* ("Stage") no note uses yet
|
||||
* GET /services/v2/service_types/{id}/plans ?filter=future|past, order,
|
||||
* per_page — today's plan,
|
||||
* next week's and last week's
|
||||
@@ -129,6 +133,22 @@ const ITEMS = [
|
||||
{ id: 'i13', type: 'media', title: 'Walk-out Loop', pos: 'post', length: 600, notes: [['Video', 'Announcements loop until the room clears']] },
|
||||
];
|
||||
|
||||
/**
|
||||
* Item note categories, per service type in Planning Center: every category
|
||||
* the items above use, in the order the mock account lists them, plus one no
|
||||
* note uses yet — a tile that has never chosen shows it on as well.
|
||||
*/
|
||||
const NOTE_CATEGORIES = ['Audio', 'Video', 'Lighting', 'ProPresenter', 'Stage'];
|
||||
|
||||
function noteCategoryRecord(name, index, stId) {
|
||||
return {
|
||||
type: 'ItemNoteCategory',
|
||||
id: `${stId}-nc${index + 1}`,
|
||||
attributes: { name, sequence: index + 1, frequently_used: index < 2, deleted_at: null },
|
||||
relationships: { service_type: { data: { type: 'ServiceType', id: stId } } },
|
||||
};
|
||||
}
|
||||
|
||||
function itemsDocument(planId, include) {
|
||||
const wants = new Set(String(include || '').split(',').map((s) => s.trim()).filter(Boolean));
|
||||
const data = [];
|
||||
@@ -246,6 +266,9 @@ 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] === 'item_note_categories' && parts.length === 3) {
|
||||
return collection(res, NOTE_CATEGORIES.map((name, i) => noteCategoryRecord(name, i, st.id)), url);
|
||||
}
|
||||
if (parts[2] !== 'plans') return notFound(res);
|
||||
const plans = plansFor(st.id);
|
||||
if (parts.length === 3) {
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* Mock Slack Web API for developing the slack module without a workspace.
|
||||
*
|
||||
* node tools/slack-mock.js [port] (default 24716)
|
||||
* SLACK_API_BASE=http://127.0.0.1:24716/api node server.js
|
||||
*
|
||||
* Then, in /admin → Slack, paste any token that starts with xoxp- (a user
|
||||
* token: auth.test answers as the location account "Apollo Beach") or xoxb-
|
||||
* (a bot token: bot_id set, user "proddash"); anything else is invalid_auth.
|
||||
* Two more tokens exercise the error paths: xoxp-revoked → token_revoked,
|
||||
* xoxp-noscope → missing_scope (needed channels:history) on history reads.
|
||||
*
|
||||
* Methods, all under /api/<method>, POST form or JSON (GET works too):
|
||||
* auth.test identity for the token (see above)
|
||||
* conversations.list #production, #ops, #campus-leads (private) as
|
||||
* member; #announcements not a member; paginated
|
||||
* conversations.info one channel, with is_member
|
||||
* conversations.history newest-first window (limit); not_in_channel for
|
||||
* #announcements
|
||||
* conversations.replies a thread's parent + replies
|
||||
* users.info display names and profile images (SVG squares
|
||||
* served by this mock under /img/u/<id>.svg)
|
||||
* chat.postMessage appends to the channel (echoes `username` for
|
||||
* bots as a bot_message); text containing "!429"
|
||||
* answers HTTP 429 with Retry-After: 3
|
||||
* emoji.list four custom emoji: two images (/img/e/<name>.svg),
|
||||
* an alias of a standard emoji, an alias of a custom
|
||||
* reactions.add/.remove on a message (or reply) by channel + timestamp;
|
||||
* already_reacted / no_reaction / message_not_found
|
||||
* as Slack answers them; name "nope" → invalid_name
|
||||
*
|
||||
* #production is seeded with mrkdwn, mentions, a link, a thread, a bot
|
||||
* attachment and a file; it gains a new fake message every ~8 s, edits one
|
||||
* every ~25 s, deletes one every ~40 s and adds a thread reply every ~30 s.
|
||||
* #ops gets a quieter trickle (every ~20 s), so a dashboard with both
|
||||
* transcripts shows two channels moving at their own pace — and a
|
||||
* chat.postMessage to either lands in that channel's history, which is how
|
||||
* a send to the *selected* transcript can be watched arriving in the right
|
||||
* tile. Every request is logged.
|
||||
*
|
||||
* Multi-channel dev flow: run this, then ProdDash with SLACK_API_BASE set,
|
||||
* paste xoxp-anything in /admin → Slack, tick #production and #ops under
|
||||
* Channels, Apply, and add both transcripts plus Send message from +.
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const http = require('http');
|
||||
|
||||
const PORT = Number.parseInt(process.argv[2] || '24716', 10);
|
||||
|
||||
/* ── data ───────────────────────────────────────────────────────────── */
|
||||
|
||||
const USERS = {
|
||||
U001: { name: 'apollo.beach', real_name: 'Apollo Beach', display_name: 'Apollo Beach' },
|
||||
U002: { name: 'michael', real_name: 'Michael McGary', display_name: 'Michael' },
|
||||
U003: { name: 'sarah.lee', real_name: 'Sarah Lee', display_name: 'Sarah' },
|
||||
U004: { name: 'north.attleboro', real_name: 'North Attleboro', display_name: 'North Attleboro' },
|
||||
U005: { name: 'dan.k', real_name: 'Dan Kowalski', display_name: 'Dan K' },
|
||||
UBOT: { name: 'proddash', real_name: 'ProdDash', display_name: '', is_bot: true },
|
||||
};
|
||||
|
||||
const CHANNELS = [
|
||||
{ id: 'C001', name: 'production', is_private: false, is_member: true },
|
||||
{ id: 'C002', name: 'ops', is_private: false, is_member: true },
|
||||
{ id: 'G001', name: 'campus-leads', is_private: true, is_member: true },
|
||||
{ id: 'C003', name: 'announcements', is_private: false, is_member: false },
|
||||
];
|
||||
|
||||
let tsCounter = 0;
|
||||
function ts(offsetMs = 0) {
|
||||
tsCounter += 1;
|
||||
return `${Math.floor((Date.now() + offsetMs) / 1000)}.${String(tsCounter).padStart(6, '0')}`;
|
||||
}
|
||||
|
||||
/** channel id -> messages (ascending); replies live inside their parent. */
|
||||
const history = new Map();
|
||||
for (const c of CHANNELS) history.set(c.id, []);
|
||||
|
||||
function push(channelId, msg) {
|
||||
const list = history.get(channelId);
|
||||
const m = { type: 'message', ts: msg.ts || ts(), ...msg };
|
||||
list.push(m);
|
||||
if (list.length > 400) list.splice(0, list.length - 400);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** A message or a reply by timestamp, anywhere in a channel. */
|
||||
function findMessage(channelId, stamp) {
|
||||
for (const m of history.get(channelId) || []) {
|
||||
if (m.ts === stamp) return m;
|
||||
for (const r of m.replies || []) if (r.ts === stamp) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Slack's reactions array: [{ name, users, count }], edited in place. */
|
||||
function addReaction(m, name, userId) {
|
||||
m.reactions = m.reactions || [];
|
||||
let r = m.reactions.find((x) => x.name === name);
|
||||
if (r && r.users.includes(userId)) return 'already_reacted';
|
||||
if (!r) {
|
||||
r = { name, users: [], count: 0 };
|
||||
m.reactions.push(r);
|
||||
}
|
||||
r.users.push(userId);
|
||||
r.count = r.users.length;
|
||||
return '';
|
||||
}
|
||||
|
||||
function removeReaction(m, name, userId) {
|
||||
const r = (m.reactions || []).find((x) => x.name === name);
|
||||
if (!r || !r.users.includes(userId)) return 'no_reaction';
|
||||
r.users = r.users.filter((u) => u !== userId);
|
||||
r.count = r.users.length;
|
||||
if (!r.count) m.reactions = m.reactions.filter((x) => x !== r);
|
||||
if (!m.reactions.length) delete m.reactions;
|
||||
return '';
|
||||
}
|
||||
|
||||
/* A square SVG with an initial, one hue per id — the mock's stand-in for a
|
||||
profile image or a custom emoji picture. */
|
||||
const IMAGE_HUES = { U001: 150, U002: 210, U003: 330, U004: 30, U005: 270, UBOT: 0, party_parrot: 120, waters: 200 };
|
||||
function squareSvg(id, letter) {
|
||||
const hue = IMAGE_HUES[id] ?? 180;
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72"><rect width="72" height="72" rx="18" fill="hsl(${hue} 50% 45%)"/><text x="36" y="47" text-anchor="middle" font-family="system-ui, sans-serif" font-size="34" font-weight="700" fill="#fff">${letter}</text></svg>`;
|
||||
}
|
||||
const CUSTOM_EMOJI = {
|
||||
party_parrot: (port) => `http://127.0.0.1:${port}/img/e/party_parrot.svg`,
|
||||
waters: (port) => `http://127.0.0.1:${port}/img/e/waters.svg`,
|
||||
thumbsup_all: () => 'alias:+1',
|
||||
parrot: () => 'alias:party_parrot',
|
||||
};
|
||||
|
||||
function seed() {
|
||||
const min = 60000;
|
||||
const at = (minsAgo) => ts(-minsAgo * min);
|
||||
push('C001', { ts: at(58), user: 'U003', subtype: 'channel_join', text: '<@U003> has joined the channel' });
|
||||
push('C001', { ts: at(55), user: 'U002', text: 'Morning all — doors at 9:15, first service 10:00. Run of show is in <#C002|ops>.' });
|
||||
push('C001', { ts: at(50), user: 'U001', text: 'Apollo Beach is up. Stream key checked, ProPresenter online :white_check_mark:' });
|
||||
push('C001', { ts: at(47), user: 'U004', text: 'North Attleboro here — we have *no audio* on the sermon feed yet, working on it' });
|
||||
push('C001', { ts: at(44), user: 'U002', text: '<@U004> try the Dante patch — `Sermon Feed L/R` should be on 31/32. _Ping me if not._' });
|
||||
const parent = push('C001', { ts: at(40), user: 'U003', text: 'Countdown video is the new one this week, right? ~old one~ <-- not this', reply_count: 2, latest_reply: '' });
|
||||
parent.replies = [
|
||||
{ type: 'message', ts: at(39), user: 'U002', text: 'Yes — "Countdown 5 min (Sept)" in the media bin', thread_ts: parent.ts },
|
||||
{ type: 'message', ts: at(38), user: 'U003', text: 'Got it :+1:', thread_ts: parent.ts },
|
||||
];
|
||||
parent.latest_reply = parent.replies[1].ts;
|
||||
push('C001', {
|
||||
ts: at(35), subtype: 'bot_message', bot_id: 'B002', username: 'Planning Center', text: '',
|
||||
attachments: [{ fallback: 'Plan updated: Sunday Service — Sept 14 (2 items changed)', title: 'Plan updated', text: 'Sunday Service — Sept 14 (2 items changed)' }],
|
||||
});
|
||||
push('C001', { ts: at(30), user: 'U005', text: 'Lower thirds for the announcements: <https://waterschurch.org/plan|this week’s plan>', files: [{ id: 'F001', name: 'lower-thirds-0914.png', title: 'lower-thirds-0914.png' }] });
|
||||
const fixed = push('C001', { ts: at(25), user: 'U004', text: 'Audio fixed — Dante patch was it. Thanks <@U002> :pray:', edited: { user: 'U004', ts: at(24) } });
|
||||
fixed.reactions = [{ name: '+1', users: ['U002', 'U003', 'U001'], count: 3 }, { name: 'party_parrot', users: ['U005'], count: 1 }, { name: 'pray::skin-tone-3', users: ['U002'], count: 1 }];
|
||||
push('C001', { ts: at(23), user: 'U002', text: 'Custom emoji check :party_parrot: :waters: and an unknown :not_an_emoji: stay put' });
|
||||
push('C001', { ts: at(20), user: 'U002', text: '<!here> 10 minutes to doors. Campuses, post "ready" when your pre-service loop is running.' });
|
||||
push('C001', { ts: at(15), user: 'U001', text: 'Apollo Beach ready' });
|
||||
push('C001', { ts: at(14), user: 'U004', text: 'North Attleboro ready' });
|
||||
|
||||
push('C002', { ts: at(120), user: 'U002', text: 'Run of show for Sept 14 is pinned. Changes go here, not in DMs.' });
|
||||
push('C002', { ts: at(90), user: 'U005', text: 'Bumper video is 0:42 this week, not 0:30 — adjust your timers.' });
|
||||
push('G001', { ts: at(200), user: 'U002', text: 'Leads: budget call moved to Tuesday 2pm.' });
|
||||
push('C003', { ts: at(300), user: 'U002', text: 'Staff meeting notes are in the drive.' });
|
||||
}
|
||||
seed();
|
||||
|
||||
const CHATTER = [
|
||||
{ user: 'U003', text: 'Walk-in music is a touch loud at the back, can we come down 2 dB?' },
|
||||
{ user: 'U002', text: 'Cue 4 is the *baptism video* — heads up, it has its own audio' },
|
||||
{ user: 'U005', text: 'Livestream is live, 38 viewers already :tada:' },
|
||||
{ user: 'U004', text: 'North Attleboro: pastor is running about 3 min long today' },
|
||||
{ user: 'U002', text: 'Copy. Apollo Beach, hold your bumper until you hear from us' },
|
||||
{ user: 'U003', text: 'Lyrics slide 3 of "Living Hope" has a typo — fixing for second service' },
|
||||
{ user: 'U005', text: 'Stream bitrate dipped for a sec, back to normal now' },
|
||||
{ user: 'U002', text: 'Offering moment is *after* the sermon this week, not before' },
|
||||
{ user: 'U004', text: 'Anyone else seeing the ProPresenter stage display lag?' },
|
||||
{ user: 'U003', text: 'Kids check-in is slammed, could use one more volunteer at the desk' },
|
||||
{ user: 'U002', text: 'Great first service everyone :clap: reset in 15' },
|
||||
];
|
||||
let chatterIx = 0;
|
||||
|
||||
const OPS_CHATTER = [
|
||||
{ user: 'U005', text: 'Ops: parking team is short two people, sending greeters over' },
|
||||
{ user: 'U002', text: 'Cafe is out of oat milk again :sweat_smile:' },
|
||||
{ user: 'U005', text: 'Second-service headcount: 412 in the room, 38 online' },
|
||||
{ user: 'U002', text: 'Facilities: the lobby HVAC is back, thanks Dan' },
|
||||
];
|
||||
let opsIx = 0;
|
||||
|
||||
function tickNew() {
|
||||
const line = CHATTER[chatterIx % CHATTER.length];
|
||||
chatterIx += 1;
|
||||
const m = push('C001', { user: line.user, text: line.text });
|
||||
console.log(`[slack-mock] + new message ${m.ts} from ${line.user}`);
|
||||
}
|
||||
|
||||
function tickOps() {
|
||||
const line = OPS_CHATTER[opsIx % OPS_CHATTER.length];
|
||||
opsIx += 1;
|
||||
const m = push('C002', { user: line.user, text: line.text });
|
||||
console.log(`[slack-mock] + new message ${m.ts} in #ops from ${line.user}`);
|
||||
}
|
||||
|
||||
function tickEdit() {
|
||||
const list = history.get('C001');
|
||||
const recent = list.slice(-8).filter((m) => m.user && !m.subtype && !m.edited);
|
||||
if (!recent.length) return;
|
||||
const m = recent[Math.floor(Math.random() * recent.length)];
|
||||
m.text += ' — fixed';
|
||||
m.edited = { user: m.user, ts: ts() };
|
||||
console.log(`[slack-mock] ~ edited ${m.ts}`);
|
||||
}
|
||||
|
||||
function tickDelete() {
|
||||
const list = history.get('C001');
|
||||
const candidates = list.slice(-10, -2).filter((m) => m.user && !m.subtype && !m.reply_count);
|
||||
if (!candidates.length) return;
|
||||
const victim = candidates[Math.floor(Math.random() * candidates.length)];
|
||||
list.splice(list.indexOf(victim), 1);
|
||||
console.log(`[slack-mock] - deleted ${victim.ts}`);
|
||||
}
|
||||
|
||||
function tickReply() {
|
||||
const list = history.get('C001');
|
||||
const parent = list.find((m) => m.reply_count);
|
||||
if (!parent) return;
|
||||
const reply = { type: 'message', ts: ts(), user: ['U002', 'U003', 'U005'][parent.replies.length % 3], text: `Thread reply ${parent.replies.length + 1} :eyes:`, thread_ts: parent.ts };
|
||||
parent.replies.push(reply);
|
||||
parent.reply_count = parent.replies.length;
|
||||
parent.latest_reply = reply.ts;
|
||||
console.log(`[slack-mock] ↳ reply on ${parent.ts} (${parent.reply_count} total)`);
|
||||
}
|
||||
|
||||
setInterval(tickNew, 8000).unref();
|
||||
setInterval(tickOps, 20000).unref();
|
||||
setInterval(tickEdit, 25000).unref();
|
||||
setInterval(tickDelete, 40000).unref();
|
||||
setInterval(tickReply, 30000).unref();
|
||||
|
||||
/* ── plumbing ───────────────────────────────────────────────────────── */
|
||||
|
||||
function send(res, status, body, headers = {}) {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
function readBody(req) {
|
||||
return new Promise((resolve) => {
|
||||
let data = '';
|
||||
req.on('data', (c) => { data += c; });
|
||||
req.on('end', () => resolve(data));
|
||||
req.on('error', () => resolve(''));
|
||||
});
|
||||
}
|
||||
|
||||
function parseParams(req, url, raw) {
|
||||
const params = Object.fromEntries(url.searchParams.entries());
|
||||
const ctype = String(req.headers['content-type'] || '');
|
||||
if (raw) {
|
||||
if (ctype.includes('application/json')) {
|
||||
try { Object.assign(params, JSON.parse(raw)); } catch { /* ignore */ }
|
||||
} else {
|
||||
for (const [k, v] of new URLSearchParams(raw)) params[k] = v;
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
function tokenOf(req, params) {
|
||||
const m = /^Bearer\s+(\S+)/.exec(String(req.headers.authorization || ''));
|
||||
return m ? m[1] : String(params.token || '');
|
||||
}
|
||||
|
||||
function identity(token) {
|
||||
if (token === 'xoxp-revoked') return { error: 'token_revoked' };
|
||||
if (/^xoxp-/.test(token)) return { ok: true, url: 'https://waters.slack.com/', team: 'Waters Church', user: 'apollo.beach', team_id: 'T001', user_id: 'U001', noscope: token === 'xoxp-noscope' };
|
||||
if (/^xoxb-/.test(token)) return { ok: true, url: 'https://waters.slack.com/', team: 'Waters Church', user: 'proddash', team_id: 'T001', user_id: 'UBOT', bot_id: 'B001' };
|
||||
return { error: 'invalid_auth' };
|
||||
}
|
||||
|
||||
function channelRecord(c) {
|
||||
return { id: c.id, name: c.name, name_normalized: c.name, is_channel: !c.is_private, is_group: c.is_private, is_private: c.is_private, is_member: c.is_member, is_archived: false, num_members: 12 };
|
||||
}
|
||||
|
||||
function publicMessage(m) {
|
||||
const { replies, ...rest } = m;
|
||||
return rest;
|
||||
}
|
||||
|
||||
function findChannel(ref) {
|
||||
const s = String(ref || '');
|
||||
return CHANNELS.find((c) => c.id === s || c.name === s.replace(/^#/, ''));
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
|
||||
const raw = req.method === 'POST' ? await readBody(req) : '';
|
||||
const params = parseParams(req, url, raw);
|
||||
const method = url.pathname.replace(/^\/api\//, '');
|
||||
const summary = Object.entries(params).filter(([k]) => k !== 'token').map(([k, v]) => `${k}=${String(v).slice(0, 40)}`).join(' ');
|
||||
console.log(`[slack-mock] ${req.method} ${url.pathname} ${summary}`);
|
||||
|
||||
const img = url.pathname.match(/^\/img\/(u|e)\/([A-Za-z0-9_+-]+)\.svg$/);
|
||||
if (img) {
|
||||
const id = img[2];
|
||||
const letter = img[1] === 'u' ? (USERS[id]?.display_name || USERS[id]?.real_name || id)[0].toUpperCase() : id[0].toUpperCase();
|
||||
res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-store' });
|
||||
return res.end(squareSvg(id, letter));
|
||||
}
|
||||
if (!url.pathname.startsWith('/api/')) return send(res, 404, { ok: false, error: 'unknown_method' });
|
||||
|
||||
const token = tokenOf(req, params);
|
||||
const who = identity(token);
|
||||
if (!who.ok) return send(res, 200, { ok: false, error: who.error });
|
||||
|
||||
switch (method) {
|
||||
case 'auth.test': {
|
||||
const { noscope, ...rest } = who;
|
||||
return send(res, 200, rest);
|
||||
}
|
||||
|
||||
case 'users.info': {
|
||||
const u = USERS[String(params.user)];
|
||||
if (!u) return send(res, 200, { ok: false, error: 'user_not_found' });
|
||||
const img = `http://127.0.0.1:${PORT}/img/u/${params.user}.svg`;
|
||||
return send(res, 200, { ok: true, user: { id: params.user, name: u.name, real_name: u.real_name, is_bot: Boolean(u.is_bot), profile: { display_name: u.display_name, real_name: u.real_name, image_48: img, image_72: img } } });
|
||||
}
|
||||
|
||||
case 'conversations.list': {
|
||||
const types = String(params.types || 'public_channel').split(',');
|
||||
let list = CHANNELS.filter((c) => (c.is_private ? types.includes('private_channel') : types.includes('public_channel')));
|
||||
if (who.bot_id) list = list.filter((c) => c.is_member); // a bot sees only what it's in
|
||||
const limit = Math.max(1, Math.min(1000, Number(params.limit) || 100));
|
||||
const start = params.cursor ? Number(Buffer.from(String(params.cursor), 'base64').toString()) || 0 : 0;
|
||||
const page = list.slice(start, start + limit);
|
||||
const next = start + limit < list.length ? Buffer.from(String(start + limit)).toString('base64') : '';
|
||||
return send(res, 200, { ok: true, channels: page.map(channelRecord), response_metadata: { next_cursor: next } });
|
||||
}
|
||||
|
||||
case 'conversations.info': {
|
||||
const c = findChannel(params.channel);
|
||||
if (!c) return send(res, 200, { ok: false, error: 'channel_not_found' });
|
||||
return send(res, 200, { ok: true, channel: channelRecord(c) });
|
||||
}
|
||||
|
||||
case 'conversations.history': {
|
||||
const c = findChannel(params.channel);
|
||||
if (!c) return send(res, 200, { ok: false, error: 'channel_not_found' });
|
||||
if (who.noscope) return send(res, 200, { ok: false, error: 'missing_scope', needed: 'channels:history', provided: 'channels:read,chat:write' });
|
||||
if (!c.is_member) return send(res, 200, { ok: false, error: 'not_in_channel' });
|
||||
const limit = Math.max(1, Math.min(1000, Number(params.limit) || 100));
|
||||
const list = history.get(c.id);
|
||||
const window = list.slice(-limit).reverse().map(publicMessage);
|
||||
return send(res, 200, { ok: true, messages: window, has_more: list.length > limit, pin_count: 0 });
|
||||
}
|
||||
|
||||
case 'conversations.replies': {
|
||||
const c = findChannel(params.channel);
|
||||
if (!c) return send(res, 200, { ok: false, error: 'channel_not_found' });
|
||||
if (!c.is_member) return send(res, 200, { ok: false, error: 'not_in_channel' });
|
||||
const parent = history.get(c.id).find((m) => m.ts === String(params.ts));
|
||||
if (!parent) return send(res, 200, { ok: false, error: 'thread_not_found' });
|
||||
const limit = Math.max(1, Math.min(1000, Number(params.limit) || 100));
|
||||
return send(res, 200, { ok: true, messages: [publicMessage(parent), ...(parent.replies || []).slice(0, limit - 1)], has_more: false });
|
||||
}
|
||||
|
||||
case 'emoji.list': {
|
||||
const emoji = {};
|
||||
for (const [name, v] of Object.entries(CUSTOM_EMOJI)) emoji[name] = v(PORT);
|
||||
return send(res, 200, { ok: true, emoji, cache_ts: '1700000000.000000' });
|
||||
}
|
||||
|
||||
case 'reactions.add':
|
||||
case 'reactions.remove': {
|
||||
const c = findChannel(params.channel);
|
||||
if (!c) return send(res, 200, { ok: false, error: 'channel_not_found' });
|
||||
if (!c.is_member) return send(res, 200, { ok: false, error: 'not_in_channel' });
|
||||
const name = String(params.name || '');
|
||||
if (!name || name === 'nope') return send(res, 200, { ok: false, error: 'invalid_name' });
|
||||
const m = findMessage(c.id, String(params.timestamp || ''));
|
||||
if (!m) return send(res, 200, { ok: false, error: 'message_not_found' });
|
||||
const err = method === 'reactions.add' ? addReaction(m, name, who.user_id) : removeReaction(m, name, who.user_id);
|
||||
if (err) return send(res, 200, { ok: false, error: err });
|
||||
console.log(`[slack-mock] ${method === 'reactions.add' ? '➕' : '➖'} :${name}: on ${m.ts} in #${c.name} by ${who.user}`);
|
||||
return send(res, 200, { ok: true });
|
||||
}
|
||||
|
||||
case 'chat.postMessage': {
|
||||
const c = findChannel(params.channel);
|
||||
if (!c) return send(res, 200, { ok: false, error: 'channel_not_found' });
|
||||
if (!c.is_member) return send(res, 200, { ok: false, error: 'not_in_channel' });
|
||||
const text = String(params.text || '');
|
||||
if (!text.trim()) return send(res, 200, { ok: false, error: 'no_text' });
|
||||
if (text.includes('!429')) return send(res, 429, { ok: false, error: 'ratelimited' }, { 'Retry-After': '3' });
|
||||
let m;
|
||||
if (who.bot_id && params.username) {
|
||||
m = push(c.id, { subtype: 'bot_message', bot_id: who.bot_id, username: String(params.username), icons: params.icon_emoji ? { emoji: String(params.icon_emoji) } : undefined, text });
|
||||
} else if (who.bot_id) {
|
||||
m = push(c.id, { user: who.user_id, bot_id: who.bot_id, bot_profile: { id: who.bot_id, name: 'ProdDash' }, text });
|
||||
} else {
|
||||
m = push(c.id, { user: who.user_id, text });
|
||||
}
|
||||
if (params.thread_ts) m.thread_ts = String(params.thread_ts);
|
||||
console.log(`[slack-mock] ✉ posted to #${c.name} as ${params.username || who.user}: ${text.slice(0, 60)}`);
|
||||
return send(res, 200, { ok: true, channel: c.id, ts: m.ts, message: publicMessage(m) });
|
||||
}
|
||||
|
||||
default:
|
||||
return send(res, 200, { ok: false, error: 'unknown_method' });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(PORT, '127.0.0.1', () => {
|
||||
console.log(`[slack-mock] Slack Web API mock on http://127.0.0.1:${PORT}/api`);
|
||||
console.log('[slack-mock] tokens: xoxp-anything (user "Apollo Beach"), xoxb-anything (bot), xoxp-revoked, xoxp-noscope');
|
||||
console.log('[slack-mock] run ProdDash with: SLACK_API_BASE=http://127.0.0.1:%d/api node server.js', PORT);
|
||||
});
|
||||
Reference in New Issue
Block a user