Skip to content

Commit dc0790f

Browse files
committed
Keep the readout across refreshes, roll the history window daily, and add keyboard access
Refreshes that bring the same answer leave the cards alone, and a redraw restores the day being read and the keyboard focus. The 30-day window is worked out at each render in UTC days, so a tab left open moves to the new day's shared read and drops the old watcher. Each sparkline is a focusable slider: arrow keys, Page Up/Down, Home and End read one day, with the same readout as the pointer and an aria-valuetext.
1 parent 6b3b409 commit dc0790f

3 files changed

Lines changed: 123 additions & 29 deletions

File tree

‎live-dashboard/README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ team's connection.
1111
| File | What it does |
1212
| --- | --- |
1313
| `sf.jsonc` | Declares the `rates` role: one `team` connection, two read tools, pinned arguments, and a 15-minute cache |
14-
| `index.html` | Imports `/__spacefast/client.js`, watches both tools every 60 seconds, and renders each state the route answers |
14+
| `index.html` | Imports `/__spacefast/client.js`, watches both tools every 60 seconds, and renders each state the route answers. Each sparkline reads one day by pointer or by keyboard (focus it, then use the arrow keys, Home and End) |
1515
| `styles.css` | Light and dark styles |
1616

1717
The data comes from [Frankfurter](https://frankfurter.dev), a free, open-source
@@ -60,7 +60,9 @@ sf connectors public-serving set rates --enable
6060
connector answers `connector_tool_not_allowed`.
6161
- **One shared read.** Every viewer asking the same question in the same
6262
15 minutes shares one upstream request (`cache: "15m"`). The 60-second
63-
refresh on the page only checks that shared answer. When the answer came
63+
refresh on the page only checks that shared answer. The 30-day window is
64+
worked out at each refresh in UTC days, so a tab left open overnight moves to
65+
the new day's window and keeps sharing it with new visitors. When the answer came
6466
from that shared read, the footer shows when it was fetched upstream
6567
(`cachedAt`); otherwise it shows when the page received it.
6668
- **Real states.** Before anything is connected, the route answers a state

‎live-dashboard/index.html‎

Lines changed: 113 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,6 @@ <h1>Euro, live</h1>
3030
const SYMBOLS = ["USD", "GBP", "JPY", "CHF"];
3131
const DAYS = 30;
3232

33-
// The 30-day window starts on a whole day, so every viewer asks the same
34-
// question that day and shares one cached read.
35-
const since = new Date(Date.now() - DAYS * 86_400_000).toISOString().slice(0, 10);
36-
3733
const escape = (text) =>
3834
String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
3935
const rate = new Intl.NumberFormat(undefined, { maximumSignificantDigits: 5 });
@@ -76,16 +72,19 @@ <h2>${escape(title)}</h2>
7672
return { title: `The ${what} are unavailable right now.`, body: message ?? "", link: { href: location.href, label: "Try again" } };
7773
}
7874

79-
function sparkline(points) {
75+
function sparkline(symbol, points) {
8076
if (points.length < 2) return "";
8177
const values = points.map((p) => p.value);
8278
const min = Math.min(...values);
8379
const max = Math.max(...values);
8480
const x = (i) => (i / (points.length - 1)) * 100;
8581
const y = (v) => 30 - ((v - min) / (max - min || 1)) * 26 - 2;
8682
const d = points.map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(2)},${y(p.value).toFixed(2)}`).join("");
87-
const label = `${DAYS}-day range ${rate.format(min)} to ${rate.format(max)}`;
88-
return `<svg viewBox="0 0 100 32" preserveAspectRatio="none" role="img" aria-label="${label}"
83+
// A slider: focus it, then use the arrow keys, Home and End to read one day.
84+
return `<svg viewBox="0 0 100 32" preserveAspectRatio="none" tabindex="0" role="slider"
85+
aria-label="EUR to ${symbol}, last ${DAYS} days, ${rate.format(min)} to ${rate.format(max)}"
86+
aria-valuemin="0" aria-valuemax="${points.length - 1}" aria-valuenow="${points.length - 1}"
87+
aria-valuetext="${escape(`${points.at(-1).day}: ${rate.format(points.at(-1).value)}`)}"
8988
data-points='${escape(JSON.stringify(points))}'>
9089
<path d="${d}" vector-effect="non-scaling-stroke" />
9190
<line class="cursor" x1="0" x2="0" y1="0" y2="32" vector-effect="non-scaling-stroke" />
@@ -107,13 +106,13 @@ <h2>${escape(title)}</h2>
107106
const first = points[0]?.value;
108107
const change = first ? now / first - 1 : null;
109108
return `
110-
<article class="tile">
109+
<article class="tile" data-symbol="${symbol}">
111110
<h2>EUR → ${symbol}</h2>
112111
<p class="value" data-default="${rate.format(now)}">${rate.format(now)}</p>
113112
<p class="meta" data-default="${change === null ? "" : `${percent.format(change)} in ${DAYS} days`}">
114113
${change === null ? "&nbsp;" : `${percent.format(change)} in ${DAYS} days`}
115114
</p>
116-
${sparkline(points)}
115+
${sparkline(symbol, points)}
117116
</article>`;
118117
}).join("")}</div>${historyNote(past)}`;
119118
}
@@ -125,30 +124,90 @@ <h2>EUR → ${symbol}</h2>
125124
return "";
126125
}
127126

128-
// Hover a sparkline to read one day.
129-
section.addEventListener("pointermove", (event) => {
130-
const svg = event.target.closest?.("svg[data-points]");
131-
if (!svg) return;
132-
const points = JSON.parse(svg.dataset.points);
133-
const box = svg.getBoundingClientRect();
134-
const i = Math.round(((event.clientX - box.left) / box.width) * (points.length - 1));
135-
const point = points[Math.max(0, Math.min(points.length - 1, i))];
127+
// The day a viewer is reading, by pointer or keyboard. It outlives a
128+
// redraw, so a refresh does not snap the readout back to today.
129+
let selection = null; // { symbol, day }
130+
// True while the cards are replaced, so losing focus to a redraw is not leaving.
131+
let redrawing = false;
132+
133+
const pointsOf = (svg) => JSON.parse(svg.dataset.points);
134+
135+
function showDay(svg, index) {
136+
const points = pointsOf(svg);
137+
const i = Math.max(0, Math.min(points.length - 1, index));
138+
const point = points[i];
136139
const tile = svg.closest(".tile");
137140
tile.querySelector(".value").textContent = rate.format(point.value);
138141
tile.querySelector(".meta").textContent = point.day;
139-
const x = ((points.indexOf(point) / (points.length - 1)) * 100).toFixed(2);
142+
const x = ((i / (points.length - 1)) * 100).toFixed(2);
140143
const cursor = svg.querySelector(".cursor");
141144
cursor.setAttribute("x1", x);
142145
cursor.setAttribute("x2", x);
143146
cursor.classList.add("on");
147+
svg.setAttribute("aria-valuenow", String(i));
148+
svg.setAttribute("aria-valuetext", `${point.day}: ${rate.format(point.value)}`);
149+
selection = { symbol: tile.dataset.symbol, day: point.day };
150+
}
151+
152+
function clearDay(tile) {
153+
for (const el of tile.querySelectorAll("[data-default]")) el.textContent = el.dataset.default || "\u00a0";
154+
tile.querySelector(".cursor")?.classList.remove("on");
155+
if (selection?.symbol === tile.dataset.symbol) selection = null;
156+
}
157+
158+
const selectedIndex = (svg) => {
159+
const symbol = svg.closest(".tile").dataset.symbol;
160+
const points = pointsOf(svg);
161+
const i = selection?.symbol === symbol ? points.findIndex((p) => p.day === selection.day) : -1;
162+
return i === -1 ? points.length - 1 : i;
163+
};
164+
165+
section.addEventListener("pointermove", (event) => {
166+
const svg = event.target.closest?.("svg[data-points]");
167+
if (!svg) return;
168+
const box = svg.getBoundingClientRect();
169+
showDay(svg, Math.round(((event.clientX - box.left) / box.width) * (pointsOf(svg).length - 1)));
144170
});
145171
section.addEventListener("pointerout", (event) => {
146172
const tile = event.target.closest?.(".tile");
147173
if (!tile || tile.contains(event.relatedTarget)) return;
148-
for (const el of tile.querySelectorAll("[data-default]")) el.textContent = el.dataset.default || "\u00a0";
149-
tile.querySelector(".cursor")?.classList.remove("on");
174+
if (document.activeElement !== tile.querySelector("svg")) clearDay(tile);
175+
});
176+
section.addEventListener("focusin", (event) => {
177+
const svg = event.target.closest?.("svg[data-points]");
178+
if (svg) showDay(svg, selectedIndex(svg));
179+
});
180+
section.addEventListener("focusout", (event) => {
181+
const tile = event.target.closest?.(".tile");
182+
if (tile && !redrawing) clearDay(tile);
183+
});
184+
section.addEventListener("keydown", (event) => {
185+
const svg = event.target.closest?.("svg[data-points]");
186+
if (!svg) return;
187+
const last = pointsOf(svg).length - 1;
188+
const now = selectedIndex(svg);
189+
const next = { ArrowLeft: now - 1, ArrowDown: now - 1, ArrowRight: now + 1, ArrowUp: now + 1,
190+
PageDown: now - 5, PageUp: now + 5, Home: 0, End: last }[event.key];
191+
if (next === undefined) return;
192+
event.preventDefault();
193+
showDay(svg, next);
150194
});
151195

196+
// Redraw the cards, keeping the day being read and the keyboard focus.
197+
function redraw(latest, past) {
198+
const kept = selection;
199+
const focused = document.activeElement?.closest?.(".tile")?.dataset.symbol;
200+
redrawing = true;
201+
renderRates(latest, past);
202+
redrawing = false;
203+
selection = null;
204+
const svgFor = (symbol) => section.querySelector(`.tile[data-symbol="${symbol}"] svg`);
205+
if (focused) svgFor(focused)?.focus();
206+
const svg = kept && svgFor(kept.symbol);
207+
const i = svg ? pointsOf(svg).findIndex((p) => p.day === kept.day) : -1;
208+
if (i !== -1) showDay(svg, i);
209+
}
210+
152211
let space = null;
153212
try {
154213
// Served by Spacefast on every Space; there is nothing to install.
@@ -164,19 +223,44 @@ <h2>EUR → ${symbol}</h2>
164223
const rates = space.connectors.rates;
165224
// `base` and `symbols` are pinned in sf.jsonc; the page sends only what is left.
166225
const latest = rates["currentRates.getLatest"].watch({}, { every: "60s" });
167-
const history = rates["historicalRates.getStartDate"].watch({ start_date: since }, { every: "60s" });
226+
227+
// The 30-day window starts on a whole UTC day, so every viewer asks the
228+
// same question that day and shares one cached read. It is worked out on
229+
// every render, which the 60-second refresh drives; when the day turns,
230+
// the page watches the new window, drops the old one, and keeps showing
231+
// the old answer until the new window has its own.
232+
const windowStart = () => new Date(Date.now() - DAYS * 86_400_000).toISOString().slice(0, 10);
233+
let history = null;
234+
function watchHistory() {
235+
const since = windowStart();
236+
if (history?.since === since) return;
237+
const previous = history?.watch.getSnapshot() ?? null;
238+
history?.unsubscribe();
239+
const watch = rates["historicalRates.getStartDate"].watch({ start_date: since }, { every: "60s" });
240+
history = { since, watch, previous, unsubscribe: null };
241+
history.unsubscribe = watch.subscribe(() => render());
242+
}
168243

169244
// When this page received the data on screen. A failed refresh keeps
170245
// the old data, and so keeps this time too.
171246
let shown = null;
172247
let receivedAt = null;
248+
// What the cards show. A refresh that brings the same rates and states
249+
// (each refresh parses a new object, so compare the content) leaves them alone.
250+
let drawn = "";
173251

174-
const render = () => {
252+
function render() {
253+
watchHistory();
175254
const now = latest.getSnapshot();
176-
const past = history.getSnapshot();
255+
let past = history.watch.getSnapshot();
256+
if (past.state === "loading" && history.previous?.data) past = history.previous;
177257
if (now.data) {
178258
if (now.data !== shown) [shown, receivedAt] = [now.data, new Date()];
179-
renderRates(now.data, past);
259+
const inputs = JSON.stringify([now.data, past.data, past.state, past.message, past.connectUrl, past.approvalUrl]);
260+
if (inputs !== drawn) {
261+
drawn = inputs;
262+
redraw(now.data, past);
263+
}
180264
// `cachedAt` is the upstream fetch time of a shared read. A read
181265
// fetched for this request has none, so the page says only when it arrived.
182266
const when = now.cachedAt
@@ -187,12 +271,14 @@ <h2>EUR → ${symbol}</h2>
187271
${now.state === "error" ? `<strong>Showing the last good answer: ${escape(now.message)}</strong>` : ""}
188272
${now.refreshing ? "Checking…" : ""}`;
189273
} else if (now.state !== "loading") {
274+
drawn = "";
190275
notice(stateNotice(now, "rates"));
191276
footer.textContent = "";
192277
}
193-
};
194-
latest.subscribe(render);
195-
history.subscribe(render);
278+
}
279+
// Subscribing starts the first read and calls render; it comes last so
280+
// everything render uses is in place.
281+
latest.subscribe(() => render());
196282
}
197283
</script>
198284
</body>

‎live-dashboard/styles.css‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,3 +186,9 @@ footer strong {
186186
color: var(--text-2);
187187
font-size: 0.8125rem;
188188
}
189+
190+
.tile svg:focus-visible {
191+
outline: 2px solid var(--accent);
192+
outline-offset: 4px;
193+
border-radius: 4px;
194+
}

0 commit comments

Comments
 (0)