'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{format(shown.value)} {when(shown.at)}
{format(within.low)} {say.high}{' '}
{format(within.high)}