Mão na massa. Tudo ao vivo.
Escolha um exemplo para abrir em tela inteira, com a visualização ao vivo e o código lado a lado.
Escolha um exemplo para abrir em tela inteira, com a visualização ao vivo e o código lado a lado.
Cards que se atualizam em ritmos diferentes, de 20 vezes por segundo até uma por segundo. Cada card é um scope(), e o timer dele chama update() com o id do card, então cada tick avalia só aquele card. Todo valor dinâmico é contado na tela: troque para um update() simples e o relógio será avaliado cerca de cem vezes por segundo para mudar uma só vez.
0dynamic values evaluated per second
Every card is a scope(), and its timer calls update("its id"): a tick evaluates that card and nothing else. Switch to update() everything: the page looks the same, but every tick now evaluates every card. The clock still changes once a second; watch how often it is evaluated.
update("dash-tickers")update("dash-load")update("dash-clock")update("dash-log")// app.ts: the dashboard. Every card is a scope() with its own timer: the timer // moves the card's feed one step, then calls update() with the card's id, so a // tick evaluates that card's dynamic values and nothing else. Every dynamic // value goes through count(), which is how the page shows the cost. In // "update() everything" mode each timer calls update() with no id: the page // looks the same, but every tick of every timer evaluates every card. import "nuclo"; import { HISTORY, SAMPLES, change, clock, load, orders, pushOrder, stepClock, stepLoad, stepTickers, tickers, type Ticker } from "./feeds.ts"; import { s } from "./styles.ts"; type Count = <T>(fn: () => T) => () => T; let scoped = true; // false: every timer calls update() instead of update(id) let paused = false; // Evaluations per scope id: counted as they happen, turned into a rate once a second. const meters = new Map<string, { count: number; rate: number }>(); function counter(id: string) { const meter = { count: 0, rate: 0 }; meters.set(id, meter); // a card built again (the example reopened) starts from zero const count: Count = (fn) => () => { meter.count++; return fn(); }; return { meter, count }; } const refresh = (id: string) => (scoped ? update(id) : update()); // Runs step() after every delay(), then refreshes the card it feeds. function every(delay: () => number, id: string, step: () => void) { let timer = setTimeout(function tick() { if (!paused) { step(); refresh(id); } timer = setTimeout(tick, delay()); }, delay()); return () => clearTimeout(timer); } // "x,y x,y …" for a polyline: x is the index, y puts min at the bottom of an // h-tall box and max at the top. function points(values: number[], h: number, min = Math.min(...values), max = Math.max(...values)) { return values.map((v, i) => `${i},${(h - ((v - min) / (max - min || 1)) * h).toFixed(1)}`).join(" "); } const percent = (values: number[]) => points(values, 100, 0, 100); const latest = (values: number[]) => Math.round(values[SAMPLES - 1]); const signed = (n: number) => `${n < 0 ? "" : "+"}${n.toFixed(2)}%`; const money = (cents: number) => `$${(cents / 100).toFixed(2)}`; // A card is one scope. Its head names the call its timer makes and how many // of its dynamic values ran in the last second. That label also carries the // shared "dash-meter" id: one update("dash-meter") refreshes it in every card. function Card(id: string, title: string, rate: string, body: (count: Count) => NodeModLike<"section">[]) { const { meter, count } = counter(id); return section( s.card, scope(id), header(s.cardHead, h3(title), span(s.rate, rate), span(s.evals, scope("dash-meter"), count(() => `${meter.rate} evals/s`))), code(s.call, count(() => (scoped ? `update("${id}")` : "update()"))), ...body(count), ); } function TickerRow(t: Ticker, count: Count) { return li( s.ticker, { class: count(() => cx(s.ticker, change(t) < 0 ? s.down : s.up).className) }, strong(t.symbol), svgSvg( s.spark, { viewBox: `0 0 ${HISTORY - 1} 20`, preserveAspectRatio: "none", "aria-hidden": "true" }, polylineSvg(s.line, { points: count(() => points(t.history, 20)) }), ), span(s.price, count(() => t.price.toFixed(2))), span(count(() => signed(change(t)))), ); } const Tickers = () => Card("dash-tickers", "Tickers", "20/s", (count) => [s.tall, ul(s.tickers, ...tickers.map((t) => TickerRow(t, count)))]); const Load = () => Card("dash-load", "Server load", "4/s", (count) => [ s.wide, div( s.readings, span(s.cpu, count(() => `CPU ${latest(load.cpu)}%`)), span(s.memory, count(() => `Memory ${latest(load.memory)}%`)), span(count(() => `${load.rps} req/s`)), ), svgSvg( s.chart, { viewBox: `0 0 ${SAMPLES - 1} 100`, preserveAspectRatio: "none", role: "img", "aria-label": "CPU and memory, last 15 seconds" }, ...[25, 50, 75].map((y) => lineSvg(s.rule, { x1: 0, y1: y, x2: SAMPLES - 1, y2: y })), polygonSvg(s.area, { points: count(() => `0,100 ${percent(load.cpu)} ${SAMPLES - 1},100`) }), // the CPU line, closed along the bottom polylineSvg(s.line, s.cpu, { points: count(() => percent(load.cpu)) }), polylineSvg(s.line, s.memory, { points: count(() => percent(load.memory)) }), ), ]); const Clock = () => Card("dash-clock", "Clock", "1/s", (count) => [ div( s.clock, strong(count(() => clock.now?.toLocaleTimeString() ?? "--:--:--")), span(count(() => clock.now?.toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" }) ?? "")), ), ]); // A new order builds one row on top (it flashes) and the oldest row goes: the rest are kept. const Orders = () => Card("dash-log", "Orders", "~1/s", (count) => [ ol( s.log, list(count(() => orders), (o) => li(s.order, span(s.id, `#${o.id}`), span(s.what, `${o.who} · ${o.qty} × ${o.item}`), span(money(o.cents)))), ), ]); function Stats() { const { count } = counter("dash-stats"); const total = () => [...meters.values()].reduce((sum, m) => sum + m.rate, 0); const mode = (value: boolean, text: string) => button( s.mode, { class: count(() => cx(s.mode, scoped === value ? s.on : null).className), "aria-pressed": count(() => String(scoped === value)) }, text, { onClick: () => { scoped = value; update(); } }, // every card's call label changes ); return header( s.stats, scope("dash-stats"), p(s.total, scope("dash-meter"), strong(count(() => String(total()))), "dynamic values evaluated per second"), div( s.controls, div(s.modes, { role: "group", "aria-label": "Update mode" }, mode(true, "Scoped updates"), mode(false, "update() everything")), button(s.btn, count(() => (paused ? "Resume" : "Pause")), { onClick: () => { paused = !paused; update("dash-stats"); } }), ), p( s.hint, "Every card is a ", code("scope()"), ", and its timer calls ", code('update("its id")'), ": a tick evaluates that card and nothing else. Switch to ", code("update()"), " everything: the page looks the same, but every tick now evaluates every card. The clock still changes once a second; watch how often it is evaluated.", ), ); } export function LiveDashboard() { return div( s.app, on("mount", () => { const stops = [ every(() => 50, "dash-tickers", stepTickers), every(() => 250, "dash-load", stepLoad), every(() => 1000 - (Date.now() % 1000), "dash-clock", stepClock), // on the second, like a real clock every(() => 300 + Math.random() * 1700, "dash-log", pushOrder), // whenever an order comes in ]; // The meter ignores Pause: it keeps showing what still runs. const meter = setInterval(() => { for (const m of meters.values()) { m.rate = m.count; m.count = 0; } refresh("dash-meter"); }, 1000); return () => { stops.forEach((stop) => stop()); clearInterval(meter); }; }), Stats(), div(s.grid, Tickers(), Load(), Clock(), Orders()), ); }
// feeds.ts: the data sources. Stock prices, server load, an order log and a // clock, each moved one step forward by its own function. They are plain // numbers and arrays, and none of them knows who shows them or how often. // The first values come from a hash of an index, so the server and the // browser start from the same numbers; Math.random() only runs once they tick. export const HISTORY = 40; // prices kept per ticker export const SAMPLES = 60; // load samples kept: 15 seconds at 4 a second const LOG_SIZE = 8; // orders kept // A small integer hash, as in infinite-scroll/api.ts. unit() maps it to [0, 1). function hash(n: number) { n = Math.imul(n ^ (n >>> 16), 0x45d9f3b); n = Math.imul(n ^ (n >>> 16), 0x45d9f3b); return (n ^ (n >>> 16)) >>> 0; } const unit = (n: number) => hash(n) / 2 ** 32; const pick = <T,>(list: T[], id: number, salt: number) => list[hash(id * 31 + salt) % list.length]; // `length` values, each one next() of the one before it, fed a fixed random number. function series(first: number, length: number, salt: number, next: (prev: number, r: number) => number) { const values = [first]; while (values.length < length) values.push(next(values[values.length - 1], unit(salt + values.length))); return values; } // Drops the oldest value and appends the newest, in place. function roll(values: number[], value: number) { values.shift(); values.push(value); return value; } // ── Tickers: a random walk, one step per tick ──────────────────────────── export interface Ticker { symbol: string; open: number; // the first price: the change is measured from it price: number; history: number[]; // the last HISTORY prices, oldest first } const walk = (price: number, r: number) => price * (1 + (r - 0.5) * 0.004); // ±0.2% at most export const tickers: Ticker[] = ["NUCL", "ACME", "BYTE", "CORE", "HTML", "LIST", "NODE", "WHEN"].map((symbol, i) => { const history = series(20 + unit(i + 1) * 300, HISTORY, i * 100, walk); return { symbol, open: history[0], price: history[HISTORY - 1], history }; }); /** The change since the open, in percent. */ export const change = (t: Ticker) => (t.price / t.open - 1) * 100; export function stepTickers() { for (const t of tickers) t.price = roll(t.history, walk(t.price, Math.random())); } // ── Server load: CPU and memory in percent, and requests per second ────── // Each sample lands up to `step` points away from the last one. const wander = (step: number) => (prev: number, r: number) => Math.min(98, Math.max(2, prev + (r - 0.5) * 2 * step)); const nextCpu = wander(9); const nextMemory = wander(1.5); export const load = { cpu: series(40, SAMPLES, 1000, nextCpu), memory: series(62, SAMPLES, 2000, nextMemory), rps: 1000 }; export function stepLoad() { const cpu = roll(load.cpu, nextCpu(load.cpu[SAMPLES - 1], Math.random())); roll(load.memory, nextMemory(load.memory[SAMPLES - 1], Math.random())); load.rps = Math.round(cpu * 24 + Math.random() * 120); // a busier server is serving more } // ── Orders: newest first, the oldest falls off ─────────────────────────── export interface Order { id: number; who: string; qty: number; item: string; cents: number; } const NAMES = ["Ada", "Grace", "Linus", "Margaret", "Dennis", "Barbara", "Ken", "Radia"]; const ITEMS: [string, number][] = [["keyboard", 8900], ["monitor", 24900], ["mouse", 3900], ["desk lamp", 4500], ["headset", 12900], ["webcam", 7900]]; // An order is a fixed function of its id, like a post in infinite-scroll/api.ts. // Only when the next one arrives is random, and the app's timer decides that. function order(id: number): Order { const [item, price] = pick(ITEMS, id, 1); const qty = pick([1, 1, 1, 2, 3], id, 2); return { id, who: pick(NAMES, id, 3), qty, item, cents: qty * price }; } let nextId = 1000; export const orders: Order[] = Array.from({ length: LOG_SIZE }, () => order(nextId++)).reverse(); export function pushOrder() { orders.unshift(order(nextId++)); if (orders.length > LOG_SIZE) orders.pop(); } // ── Clock ──────────────────────────────────────────────────────────────── // null until the first tick: the server and the browser have no "now" to agree on. export const clock = { now: null as Date | null }; export function stepClock() { clock.now = new Date(); }
// styles.ts: the cards and their grid. One column on phones, two on tablets, // three on desktops, where the tickers run down the left. The queries do not // overlap: media rules are emitted in the order they were first seen, so two // min-width queries that both match would not cascade by size. import "nuclo"; const mono = "ui-monospace, monospace"; const desktop = "@media (min-width: 900px)"; // the tickers span two rows, the load chart two columns const flash = keyframes({ from: { backgroundColor: "var(--c-primary-alpha-19)" }, to: { backgroundColor: "transparent" } }); export const s = { app: css("dash-app", { display: "flex", flexDirection: "column", gap: "12px", width: "100%", height: "100%" }), stats: css("dash-stats", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px 16px" }), total: css("dash-total", { display: "flex", alignItems: "baseline", gap: "8px", flex: "1 1 260px", fontSize: "0.875rem", color: "var(--c-text-dim)", "& strong": { fontFamily: mono, fontSize: "1.625rem", color: "var(--c-primary-ink)", fontVariantNumeric: "tabular-nums" } }), controls: css("dash-controls", { display: "flex", flexWrap: "wrap", gap: "8px" }), modes: css("dash-modes", { display: "flex", padding: "2px", borderRadius: "9px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)" }), mode: css("dash-mode", { height: "28px", padding: "0 10px", borderRadius: "7px", fontSize: "0.8125rem", fontWeight: "600", color: "var(--c-text-dim)", whiteSpace: "nowrap", hover: { color: "var(--c-text)" } }), on: css("dash-on", { backgroundColor: "var(--c-primary-dark)", color: "#fff", hover: { color: "#fff" } }), btn: css("dash-btn", { height: "34px", padding: "0 14px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontSize: "0.8125rem", fontWeight: "600", hover: { backgroundColor: "var(--c-bg-secondary)" } }), hint: css("dash-hint", { flexBasis: "100%", fontSize: "0.8125rem", lineHeight: "1.5", color: "var(--c-text-dim)", "& code": { fontFamily: mono, fontSize: "0.75rem", color: "var(--c-primary-ink)" } }), grid: css("dash-grid", { display: "grid", gridTemplateColumns: "minmax(0, 1fr)", alignContent: "start", gap: "12px", flex: "1", minHeight: "0", overflowY: "auto", "@media (min-width: 600px) and (max-width: 899px)": { gridTemplateColumns: "repeat(2, minmax(0, 1fr))" }, [desktop]: { gridTemplateColumns: "repeat(3, minmax(0, 1fr))" } }), card: css("dash-card", { display: "flex", flexDirection: "column", gap: "8px", minWidth: "0", padding: "12px 14px", borderRadius: "12px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg-card)" }), tall: css("dash-tall", { [desktop]: { gridRow: "span 2" } }), wide: css("dash-wide", { [desktop]: { gridColumn: "span 2" } }), cardHead: css("dash-cardHead", { display: "flex", alignItems: "center", gap: "8px", "& h3": { fontSize: "0.875rem", fontWeight: "600" } }), rate: css("dash-rate", { padding: "1px 7px", borderRadius: "999px", backgroundColor: "var(--c-bg-light)", fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-dim)" }), evals: css("dash-evals", { marginLeft: "auto", fontFamily: mono, fontSize: "0.75rem", color: "var(--c-primary-ink)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }), call: css("dash-call", { marginTop: "-4px", fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-muted)" }), // On the desktop grid the card is two rows tall: the rows share the height. tickers: css("dash-tickers", { display: "flex", flexDirection: "column", justifyContent: "space-around", flex: "1", listStyle: "none" }), ticker: css("dash-ticker", { display: "grid", gridTemplateColumns: "44px minmax(0, 1fr) 60px 60px", alignItems: "center", gap: "8px", height: "30px", fontFamily: mono, fontSize: "0.8125rem", fontVariantNumeric: "tabular-nums", textAlign: "right", "& strong": { textAlign: "left", color: "var(--c-text)" } }), up: css("dash-up", { color: "var(--c-accent-cool)" }), down: css("dash-down", { color: "var(--c-accent-warm)" }), spark: css("dash-spark", { width: "100%", height: "18px", overflow: "visible" }), line: css("dash-line", { raw: { fill: "none", stroke: "currentColor", "stroke-width": "1.5", "stroke-linejoin": "round", "vector-effect": "non-scaling-stroke" } }), price: css("dash-price", { color: "var(--c-text)" }), readings: css("dash-readings", { display: "flex", flexWrap: "wrap", gap: "4px 16px", fontFamily: mono, fontSize: "0.8125rem", fontVariantNumeric: "tabular-nums", color: "var(--c-text-dim)" }), cpu: css("dash-cpu", { color: "var(--c-primary)" }), memory: css("dash-memory", { color: "var(--c-accent-cool)" }), chart: css("dash-chart", { width: "100%", height: "120px", overflow: "visible" }), rule: css("dash-rule", { raw: { stroke: "var(--c-border)", "vector-effect": "non-scaling-stroke" } }), area: css("dash-area", { color: "var(--c-primary)", raw: { fill: "currentColor", "fill-opacity": "0.12" } }), clock: css("dash-clock", { display: "flex", flexDirection: "column", justifyContent: "center", gap: "2px", flex: "1", "& strong": { fontFamily: mono, fontSize: "2rem", fontWeight: "600", fontVariantNumeric: "tabular-nums" }, "& span": { fontSize: "0.8125rem", color: "var(--c-text-dim)" } }), log: css("dash-log", { listStyle: "none", fontSize: "0.8125rem" }), order: css("dash-order", { display: "flex", gap: "8px", padding: "3px 6px", borderRadius: "6px", fontVariantNumeric: "tabular-nums", animation: `${flash} 1s ease-out` }), id: css("dash-id", { fontFamily: mono, fontSize: "0.75rem", color: "var(--c-text-muted)" }), what: css("dash-what", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), };