'use client' import { SizableText, XStack, YStack } from '@hanzo/gui' import { Grid } from '@hanzo/ui/grid' import { useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react' import { Code } from './code' import { paint } from '../material/paint' import { Answer, Nothing } from './table' /** * The drawings a surface makes out of numbers: a series over time, the same * series in the width of a cell, and a whole with its parts. * * No library. A path is an array turned into a string; every charting package * this could import brings a second layout engine, a second colour system and a * second opinion about what a missing reading is. * * Each of the three takes a reading rather than an array, for the reason the * rest of this directory does: a read that failed and a read that came back * with nothing are one value in any client that keeps an array and a flag, and * drawn as a flat line at zero the first of them is a claim that nothing moved. * * And each of them holds its room. A box that collapses to the height of one * sentence carries everything under it up the page, so a screen settles at a * different depth on the read that worked and the read that did not. * * How much room, precisely, because the two are not the same shape. A series * holds ITS WHOLE BOX in all four states — the drawing's height and the row of * figures under it — since the box is a stated height and every state can fill * it. A division holds its TRACK, and no more: the legend under the track is * one row per part written in the caller's own words, so three parts and six * are different heights by construction and a reservation that claimed * otherwise would be a number nothing could keep. */ /** The drawing's own units. A shape rather than a size: the box is stretched to * whatever width the column gives it, and the height is the one number a * caller can change. */ const WIDE = 600 const TALL = 140 /** Half a stroke. Every rule this file draws is one pixel wide and does not * scale with the box, so a rule placed ON an edge has half of itself outside * it and the root element clips that half away. The marks are already inset by * half their own width; this is the same inset for the things that have no * width but the stroke. */ const HALF = 0.5 /** * The row the readings are read in, held whether or not there are readings to * put in it. * * The floor of both rows, not just the empty one. Reserved on one side only it * is a guess at what the other side comes to, and the two settle a couple of * pixels apart — enough that the stats, the address and the card below move * every time the series is re-read. One number decides both. */ const READOUT = 'var(--leading-base)' /** One reading, at the moment it was taken. Seconds, because that is the unit * an indexer dates a day in. */ export interface Point { at: number value: number } /** * A session in the four prices that close it. * * `value` is the close, so a candle IS a point that also knows what happened * between its ends — which is what lets the cursor, the bounds and the readout * treat both alike and only the drawing tell them apart. */ export interface Candle extends Point { open: number high: number low: number } /** * A reading a drawing puts somewhere: a close, or the session that closed at * it. * * Not `Reading`, which this directory already spends on the other meaning — the * `reading | read | failed` a component takes instead of an array. Two senses * of one word inside one family is the ambiguity the family exists to remove, * so the datum is a datum. */ type Datum = Point | Candle /** * What is known about a series. * * The shape rides on the answer rather than on the component, because a caller * does not choose a drawing — it says what it read. Closes are a line, the four * prices are candles, what crossed is bars. A failure carries no shape at all, * which is the point: there is nothing to draw and no way to say there is. * * Each of the four is drawn under its own name, so no two of them are ever the * same element in the same place. The stack primitive asks for one more hook * when it is given an element to render through, which the drawn state is and * the other three are not; reconciled as one element, moving between them * raises `Rendered more hooks than during the previous render` and takes the * screen down. Pressing a period control is exactly that move. */ export type Series = | { at: 'reading' } | { at: 'read'; shape: 'line' | 'bars'; points: readonly Point[] } | { at: 'read'; shape: 'candle'; points: readonly Candle[] } | { at: 'failed'; why: string } /** * What a drawing says in the states it has nothing to draw in. * * Props and not English written into this file, because a surface that reads a * chain in one language and says "Loading" in another has published a sentence * nobody translated — and a component that reaches into a catalog has taken * that dependency on the caller's behalf. */ export interface Blank { /** Said while a read is running. */ reading: ReactNode /** The title over a read that failed. The reason is the reading's own. */ failed: ReactNode /** * Where there is nothing to draw. Required for the reason a table's is: only * the caller knows whether that means the indexer has ingested nothing or * this asset has never traded, and those are different facts about a venue. */ nothing: ReactNode } /** The drawing's own coordinates. */ export interface Box { width: number height: number } /** The lowest and highest value a box has to cover. */ export interface Bounds { low: number high: number } /** Whether a reading can be drawn at all. A single `NaN` reaches the path as * `L NaN NaN`, which renders as nothing — a chart that vanishes rather than * one that reports a gap. */ const sound = (p: Datum): boolean => Number.isFinite(p.at) && Number.isFinite(p.value) && ('low' in p ? Number.isFinite(p.open) && Number.isFinite(p.high) && Number.isFinite(p.low) : true) /** * The readings, oldest first and only the ones that carry numbers. * * In time order here rather than trusted to arrive in it. A line through rows * in the order they happened to be returned is a shape nothing happened in, and * it looks exactly like a chart. */ export const ordered =

(of: readonly P[]): P[] => of.filter(sound).sort((a, b) => a.at - b.at) /** * What the readings span. A candle spans its own high and low, which are * outside its ends — a body scaled to the closes alone has wicks leaving the * box. * * The extremes of the middle ninety-eight per cent, not of everything. An * indexer's high and low are computed from whatever crossed that day, and a * single trade against an empty pool prints a number with no relation to the * asset. Scaled to one of those, a hundred real days occupy less than a pixel * and the drawing is a single vertical line: the outlier is the only thing * visible, and it is the one number that means nothing. * * The domain is trimmed, not the DATA. Every reading is still drawn, and one * outside the box is clamped to its edge rather than dropped, so the day it * happened is still there to reach. What changes is which points the vertical * scale is chosen for. */ export function bounds(of: readonly Datum[]): Bounds { const all: number[] = [] for (const p of of) { all.push('low' in p ? p.low : p.value, 'high' in p ? p.high : p.value) } if (all.length === 0) return { low: Infinity, high: -Infinity } const sorted = [...all].sort((a, b) => a - b) const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))))]! const low = at(0.01) const high = at(0.99) // A series where the trimmed ends meet — every reading identical, or too few // to trim — has no spread to scale to, so it keeps its true extremes and the // flat-line case is handled where the box is drawn. return high > low ? { low, high } : { low: sorted[0]!, high: sorted[sorted.length - 1]! } } /** * Where each reading sits across the box. * * Along the clock, not along the row of rows. An indexer closes a day only * where it saw something, so a series has gaps — spaced evenly, a fortnight of * silence and a busy Tuesday are drawn the same width, which is a different * shape from the one that happened. Where every reading shares one timestamp * there is no time to place them along, and they fall back to even spacing * rather than to a division by zero. */ export function spread(of: readonly Datum[], width: number): number[] { const first = of[0]?.at ?? 0 const span = (of[of.length - 1]?.at ?? 0) - first return of.map((p, i) => span > 0 ? ((p.at - first) / span) * width : of.length > 1 ? (i / (of.length - 1)) * width : width / 2, ) } /** * Where a figure sits down the box. Down the screen is up the axis, since SVG * counts y from the top. * * A series that never moved sits through the middle. The obvious arithmetic * divides by a range of zero there and every coordinate comes out `NaN`, so the * drawing disappears exactly when the price held still. */ export const ordinate = (value: number, within: Bounds, height: number): number => { const rise = within.high - within.low if (rise <= 0) return height / 2 // Held to the box. The domain is the middle ninety-eight per cent, so a // reading outside it is one the scale was deliberately not chosen for — and // placed where the arithmetic puts it, a single bad print lands a million // pixels above a box a hundred and forty deep, where the root element clips // it away. Nothing is drawn at all, on the one day a reader most wants a mark // to ask about; in a cell-width line there is no cursor and no readout to // reach it by either. Pinned to the edge it is a mark at the top of the // range, which is what it is. return Math.min(height, Math.max(0, height - ((value - within.low) / rise) * height)) } /** Two places is finer than any screen resolves and keeps the path short. */ const round = (n: number) => Math.round(n * 100) / 100 /** The line through the readings. */ export function trace(of: readonly Point[], box: Box, within: Bounds): string { const xs = spread(of, box.width) return of .map( (p, i) => `${i === 0 ? 'M' : 'L'}${round(xs[i]!)} ${round(ordinate(p.value, within, box.height))}`, ) .join(' ') } /** * How wide one mark is drawn. * * The closest pair decides it, so marks never overlap however unevenly the * readings fall in time — a share of the average would draw two readings an * hour apart on top of each other and report a session that was never there. */ export function thickness(xs: readonly number[], box: Box): number { let least = box.width for (let i = 1; i < xs.length; i++) least = Math.min(least, xs[i]! - xs[i - 1]!) // Against the room that is left, not the room there was. A mark and the // spacing it stands in decide each other: inserting the mark takes width out // of the box, which draws the readings closer together, which is less room // than the width was taken from. Measured at the full width and then inset, // two readings come out four hundred and twenty wide in a box of six hundred // with three hundred and fifty-three left between them, and the pair overlaps // across two fifths of the drawing. This is the width that is a share of the // spacing it itself produces. const share = least * 0.7 return Math.max(1, (share * box.width) / (box.width + share)) } /** * Which reading a key selects, or nothing for a key that is not ours. * * It stops at both ends rather than wrapping. A series is time, and arriving at * the newest reading to land on the oldest is a jump the reader takes for a * series that loops. */ export function stepped(key: string, at: number, of: number): number | null { switch (key) { case 'ArrowRight': return Math.min(at + 1, of - 1) case 'ArrowLeft': return Math.max(at - 1, 0) case 'Home': return 0 case 'End': return of - 1 default: return null } } /** A moment, as the calendar writes it. UTC, because an indexer closes its days * there and a date shifted into the reader's zone names the day before for * half the world. A caller whose readings are the reader's own days hands in * `figures().day` instead. */ const calendar = (at: number): string => new Date(at * 1000).toISOString().slice(0, 10) /** Stretched across whatever column it lands in, fixed in height. Clipped at * its own edges, so a stroke at the top of the range is half a stroke rather * than a pixel of bleed. */ const canvas = (height: number): CSSProperties => ({ display: 'block', width: '100%', height }) export interface ChartProps { /** What is drawn, as a short noun — "closing price", "volume each day". It * names the image for a screen reader and titles a failure. */ name: string series: Series say: Blank & { /** The two words under the drawing, naming what the box covers. Axes would * be four more figures claiming a precision an indexer has not earned. */ low: ReactNode high: ReactNode } /** Taller where the drawing is what the screen is for. */ height?: number /** * The figure, written. Required rather than defaulted: a number is not a * string until a locale has been applied to it, and a component that picks * one has pinned every reader to it. `figures().precise` is the usual answer. */ format: (value: number) => string /** The moment, written. The indexer's own UTC day unless a caller says * otherwise. */ when?: (at: number) => string } /** * A series over time. * * Three shapes, and each carries its value a different way. A line carries it * in POSITION, a bar in LENGTH, a candle in the two ends of a body. That is why * they are not one drawing with a style prop: a bar measured from anywhere but * zero is a length that means nothing, and a line forced down to zero flattens * a day spent between 0.000109 and 0.000111 into a grey rule. Each shape gets * the axis its own mark needs, and the range it was given is written under the * box, so what the box covers is read rather than inferred. * * Two readings, or none of it is drawn. One is not a series: a lone close is a * dot on an axis whose range it alone decided, a lone session is a body filling * the box top to bottom, and either reads as a chart of an asset that never * moved. */ export function Chart({ name, series, say, height = TALL, format, when = calendar }: ChartProps) { const [cursor, setCursor] = useState(null) const box: Box = { width: WIDE, height } const frame = `0 0 ${WIDE} ${height}` if (series.at === 'reading') { return ( {/* A block exactly as tall as the drawing that replaces it. A placeholder of another height is a promise about layout that the layout then breaks. */} {say.reading} ) } // In the box, not instead of it. A read that failed is the state a surface // spends the most time settling into and out of, and returned as a bare alert // it stood 72 pixels where the drawing stands 173 — so the address, the stats // and every card under a chart jumped a hundred pixels up the page each time // an indexer stopped answering, and back down when it resumed. The alert says // the same thing standing in the room the drawing holds. if (series.at === 'failed') { return ( {series.why} ) } // The four prices, where four prices were read. Everything that does not care // which shape it is — the bounds, the cursor, the readout — works on the // readings, because a candle is one. const sessions = series.shape === 'candle' ? ordered(series.points) : null const points: readonly Point[] = sessions ?? ordered(series.points) // The line, and not a card. A frame around one sentence makes the sentence // the subject of the screen, and the subject is the drawing that is missing // from it; `Nothing` is what every other list on this surface says that with. if (points.length < 2) { return ( {say.nothing} ) } const seen = bounds(points) // Bars are measured from zero because a bar's length is its value; everything // else is measured from what was read, because a line's height is a // comparison with the readings beside it. Either way the box is full, and the // range under it says what the box covers — so the row under the drawing // quotes THIS and not the readings' own extremes. Ten days that each crossed // between a hundred and a hundred and ninety stand on a zero rule and fill // the box from it, and a row reading "low 100" under them prices the shortest // bar at the wrong end of a range the drawing never used. const within = series.shape === 'bars' ? { low: Math.min(0, seen.low), high: Math.max(0, seen.high) } : seen // Where each reading falls, and how wide a mark drawn on it is. // // A mark has width and the box has edges, so a mark centred on x=0 or on the // far edge is drawn half outside the box and clipped to half its width. The // newest session is the one a person came for, and it was arriving as a // half-body. The readings are placed across a box inset by half a mark at // each end and shifted back into it, which draws every mark whole and moves // the rest by less than a mark's width. // // A line is not inset. It carries its value in position and has no width to // clip, and a line that stops short of both edges is a series that appears // to begin after the box does. const across = spread(points, box.width) const thick = thickness(across, box) const xs = series.shape === 'line' ? across : spread(points, box.width - thick).map((x) => x + thick / 2) // Zero, which only a bar is measured against. It is inside the box for that // shape and nowhere near it for the others, which never draw it. // // Held half a stroke inside, for the reason a mark is. A series that never // went below zero puts the rule ON the floor of the box, where half of a // one-pixel stroke is outside it: measured at two device pixels per point, // the rule the bars are read against came to one row where a rule inside the // box comes to two. Half a hairline on a hairline is nothing. const ground = Math.min(height - HALF, Math.max(HALF, ordinate(0, within, height))) const at = Math.min(cursor ?? points.length - 1, points.length - 1) const shown = points[at]! // The cursor stands on the newest reading until a key moves it, and the // newest reading is at the far edge of the box on a line — where the same // half of the same stroke falls outside. It is the mark that says WHICH // reading the figures under the box belong to, and at rest and at either end // of the arrows it was the one drawn at half weight. const hair = Math.min(box.width - HALF, Math.max(HALF, xs[at]!)) return ( { const to = stepped(e.key, at, points.length) if (to === null) return e.preventDefault() setCursor(to) }} /> } // A slider over the readings: one tab stop, arrows along it, and the // date and figure announced on every step. A stop per reading would put // a year of days in the tab order of a page with a button under it. role="slider" aria-label={name} aria-orientation="horizontal" aria-valuemin={0} aria-valuemax={points.length - 1} aria-valuenow={at} aria-valuetext={`${when(shown.at)}, ${format(shown.value)}`} tabIndex={0} focusVisibleStyle={paint.focus} minWidth={0} > {/* Called by its published name and nothing beyond it. A sentence composed here out of the name, the span and the range would be English prose nobody wrote down and nobody approved, spoken to the one reader who cannot see the figures it describes — and the span and the range are on the screen already, in the row under the drawing and in the value the slider announces on every step. */} {name} {sessions ? ( sessions.map((c, i) => { const open = ordinate(c.open, within, height) const close = ordinate(c.value, within, height) const hue = c.value >= c.open ? paint.good : paint.bad return ( ) }) ) : series.shape === 'bars' ? ( <> {points.map((p, i) => { const top = ordinate(p.value, within, height) return ( ) })} {/* Zero, and the only rule drawn on any of these shapes. It is here because the bars are measured from it. */} ) : ( )} {/* Where the readout is reading. It stands on the newest reading until a key moves it, which is the one a person came for. */} {/* The drawing for anybody not looking at it, and the only place the numbers are written out. */} {/* The figure and its date in ONE line box, the way the range beside them already is. A bare `Code` is a flex item and carries the page's own size; baseline-aligned against the date's it made the row taller than the floor under it — the drawn row came to 25 against a floor of 21.6, so the row the floor exists to equalise was the one state that overshot it, and the read that worked settled three pixels below the read that did not. Quoted inside the text it takes its own correction from, the two sides are one size and one line box. */} {format(shown.value)} {when(shown.at)} {say.low} {format(within.low)} {say.high}{' '} {format(within.high)} ) } /** The box a series gets inside a table cell. Fixed, not stretched: a column * whose marks change width row by row is a column nothing can be read down. */ const SPARK: Box = { width: 96, height: 24 } /** * A series in the width of a cell — the line and nothing else. * * No cursor, no readout, no range under it. A movement line is read down a * column against the rows either side of it, and forty of them carrying their * own figures is forty charts on one screen; the figure that matters sits in * the column beside this one. * * Nothing at all where there are fewer than two readings — the same rule the * full drawing keeps, and here it draws nothing rather than a line, because the * cell beside it already says which kind of nothing it is. */ export function Spark({ of, name, colour = paint.plain, }: { of: readonly Point[] /** What the line is of, for a screen reader — "WLUX by day". */ name: string /** The token layer's own name for a colour. A sign is a colour here and a * figure in the column beside it; never a colour alone. */ colour?: Hue }) { const points = ordered(of) if (points.length < 2) return null const within = bounds(points) return ( ) } /** One part of a whole. */ export interface Slice { /** What this part is, in the fewest words that stay unambiguous. */ name: string /** How much of the whole it holds, in the unit the others are in. */ value: number /** * What it is drawn in, as a token name. Unsaid, the parts take the ramp in * the order they were given. * * A part whose meaning is carried by hue — a vote for and a vote against — * says so with `paint.good` and `paint.bad`, which are the only two hues this * brand spends outside the achromatic ladder. * * A token name and not a colour. A literal cannot retune between one ground * and the other, so a bar that reads on black is invisible on white. * * The type asks for the shape of a name; it does not decide what is inside * one. `var(--anything, #ff0000)` satisfies it, and a fallback is exactly * where a literal gets in — it is the shape `tokens-referenced.spec.ts` was * written about. Inside this package the literal gate reads that back out of * the source; a caller's own slice is beyond anything a type can see. */ paint?: Hue } /** * What is known about a division. * * `whole` is what the parts are parts OF, where that is more than they come to: * a quorum of a hundred thousand with forty thousand behind it is a bar that is * two fifths full, and the same forty thousand with no whole stated is a bar * that is entirely one part. Unsaid, the parts are the whole. */ export type Slices = | { at: 'reading' } | { at: 'failed'; why: string } | { at: 'read'; of: readonly Slice[]; whole?: number } /** * A colour, as the token layer names one. * * Every value on `paint` is one of these, which is the point: the drawings take * a name rather than a colour, so what they are painted with moves when the * token set moves and cannot be pinned to one ground. */ export type Hue = `var(--${string})` /** How tall the bar stands, and the room it holds in every state. Deep enough * to read a part that holds a per cent of the whole, and short enough that the * legend under it is what carries the figures. */ const BAR = 10 /** A part that is not a finite number, or is less than none, holds none of the * whole. Its figure is still written under the bar, where the caller's own * formatter says what it was — a length is a claim about a proportion, and * there is no proportion in a number nobody could read. */ const held = (of: number): number => (Number.isFinite(of) && of > 0 ? of : 0) /** * What each part holds of the whole. * * The whole is what was stated, or what the parts come to. A stated whole * SMALLER than its parts is not a whole, so the larger of the two wins: a * quorum already passed draws a full bar rather than one that overflows its * own track. * * Nothing divided is not a division. Every part at zero comes back as a whole * of zero and no shares, which is what the drawing puts its empty words in the * room of — a bar of no length is a picture a reader takes for a reading. */ export function shares( of: readonly Slice[], whole?: number, ): { whole: number; each: readonly number[] } { const held_ = of.map((p) => held(p.value)) const sum = held_.reduce((a, b) => a + b, 0) const all = Math.max(sum, Number.isFinite(whole ?? Number.NaN) ? (whole as number) : 0) return all > 0 ? { whole: all, each: held_.map((n) => n / all) } : { whole: 0, each: [] } } /** * A whole, and how it divides. * * One bar rather than a ring. A reader compares parts of a ring by angle, which * is the one measurement people read worst; along a bar the same parts are * lengths on a shared baseline, and the two largest can be told apart at a * glance. It is also the shape that survives a column three hundred pixels * wide, which is where a vote result and a quorum actually stand. * * The parts are drawn and then written out under the bar, because a length is * only ever an approximation of a figure and half the readers of this drawing * came for the figure. */ export function Split({ name, of, say, format, percent, }: { /** What is divided, as a short noun — "votes cast", "the treasury". It names * the drawing for a screen reader and titles a failure. */ name: string of: Slices say: Blank /** A part's own figure, written. Required for the reason `Chart`'s is. */ format: (value: number) => string /** The share a part holds, as this reader's percentage. `figures().rate` is * one: a share is not a movement and takes no sign. */ percent: (of: number) => string }) { if (of.at === 'reading') { return ( {say.reading} ) } // The track, then the reason. What a division holds in every state is its // TRACK and not its whole height: the legend under it is one row per part // with the caller's own names in it, so a drawing of three parts and a // drawing of six are different heights by construction and no reservation // could make them equal. The track is the drawing, and it was missing from // exactly the two states where a reader most needs to see that a bar is // supposed to be there. if (of.at === 'failed') { return ( {of.why} ) } const parts = of.of const { whole, each } = shares(parts, of.whole) if (whole <= 0) { return ( {say.nothing} ) } const colour = (p: Slice, i: number): Hue => p.paint ?? paint.ramp[i % paint.ramp.length]! return ( {/* One box, clipped, with the parts laid along it. The remainder of a stated whole is what is left of the track, and the track is the ground a figure is quoted on — a step off the page in BOTH grounds, so an unmet quorum reads as a bar with room left in it rather than as a shorter bar. The page's own surface is white on white here, which is the whole of the difference: on black it drew the remainder plainly and on white it drew nothing at all. */} {parts.map((p, i) => ( ))} {/* The figures, which is what the bar is an approximation of. A grid rather than a row of stacks: the names are the reader's and run to different lengths, and a column edge that moves per part is what makes three shares unreadable against each other. */} {parts.map((p, i) => ( {p.name} {format(p.value)} {percent(each[i]!)} ))} ) }