Add native dashboard charts
This commit is contained in:
1 parent
6c6a48bd42
commit
f8acb45850
13 files changed
+1330
-69
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- Add native dashboard charts for shared-scale comparisons, signed grouped bars,
|
||||
heatmaps, step and scatter marks, waterfalls, and linked time panes.
|
||||
- Add a runnable dashboard cookbook for Kryon desktop and ZX.
|
||||
@@ -4,7 +4,7 @@ ZIRAN ?= ziran
|
||||
CC ?= cc
|
||||
ZIRAN_INCLUDE := $(shell $(ZIRAN) pkg path ziran)/include
|
||||
|
||||
.PHONY: run build check check-animated-line
|
||||
.PHONY: run build check check-animated-line check-dashboard dashboard-zx check-dashboard-ui
|
||||
|
||||
run build:
|
||||
$(ZIRAN) tool kryon $@
|
||||
@@ -48,7 +48,7 @@ check-animated-line:
|
||||
build/animated-line-chart-c/*.c -lm -o build/animated-line-chart-test
|
||||
build/animated-line-chart-test
|
||||
|
||||
check: check-animated-line
|
||||
check: check-animated-line check-dashboard
|
||||
$(ZIRAN) tool kryon check
|
||||
$(ZIRAN) bundle --project $(BINDS) --entry plot_widget_behavior:main \
|
||||
-o build/plot-widget.zx tests/plot_widget_behavior.zi
|
||||
@@ -82,3 +82,21 @@ check: check-animated-line
|
||||
-Ibuild/indicator-test-c build/indicator-test-c/*.c -lm \
|
||||
-o build/indicator-test
|
||||
build/indicator-test
|
||||
|
||||
check-dashboard:
|
||||
mkdir -p build/dashboard-test-c
|
||||
$(ZIRAN) build --project --target=c --entry dashboard_chart_test:main \
|
||||
-o build/dashboard-test-c tests/dashboard_chart_test.zi
|
||||
$(CC) -std=c99 -pedantic-errors -I$(ZIRAN_INCLUDE) -Ibuild/dashboard-test-c \
|
||||
build/dashboard-test-c/*.c -lm -o build/dashboard-test
|
||||
build/dashboard-test
|
||||
$(ZIRAN) bundle --project --entry dashboard_chart_test:main \
|
||||
-o build/dashboard-test.zx tests/dashboard_chart_test.zi
|
||||
test "$$($(ZIRAN) run --project build/dashboard-test.zx)" = 0
|
||||
|
||||
dashboard-zx:
|
||||
$(ZIRAN) tool kryon build --profile portable
|
||||
|
||||
check-dashboard-ui: dashboard-zx
|
||||
$(ZIRAN) tool kryon build --profile cairo
|
||||
python3 tests/dashboard_render_test.py $(ZIRAN)
|
||||
@@ -4,10 +4,10 @@
|
||||
owns `PlotWidget`, a retained Kryon widget that draws lines, bars, markers,
|
||||
and axes over caller-owned values, and its candle chart draws OHLC bodies and
|
||||
wicks, volume, SMA 20, SMA 50, and EMA 20 over that surface. `ChartMarker` and `CandleMarkers` add dated,
|
||||
clickable markers while leaving each marker's meaning to the caller. It also
|
||||
has a simple line chart. Both accept
|
||||
caller-owned values and colors; market data, networking, price formatting,
|
||||
and time labels stay in the application.
|
||||
clickable markers while leaving each marker's meaning to the caller. The simple
|
||||
line and candle charts accept caller-owned values and colors. The dashboard
|
||||
charts below add shared axes, date labels, legends and value formatting to
|
||||
caller-supplied datasets.
|
||||
|
||||
The shared plot surface, text, border and marks use Kryon's active palette
|
||||
on each draw. The `surface`, `text`, `border` and `accent` style tokens can
|
||||
@@ -16,8 +16,8 @@ style rules can also override the defaults. Existing charts pick up theme
|
||||
changes on their next draw, and callers retain control of their series colors.
|
||||
|
||||
Install the Ziran launcher once with `make install-user` in Ziran, then run
|
||||
`ziran fetch` and `make build` here. `make run` opens a small demo on the Cairo
|
||||
backend. `make check` checks the source and runs the chart and indicator tests.
|
||||
`ziran fetch` and `make build` here. `make run` opens the chart cookbook on
|
||||
the native Cairo backend. `make check` checks the source and runs the chart and indicator tests.
|
||||
The checked-in `ziran.lock` pins both Ziran and Kryon to exact commits. Plot
|
||||
exports `src/Plot/module.zi` for other packages, so `plot/Plot` resolves by
|
||||
its file both in projects and in builds that name `--module-path plot=DIR`.
|
||||
@@ -161,3 +161,60 @@ Invalid/nonpositive prices are not painted on a logarithmic chart.
|
||||
`CandleWindowEnd(bars, timestamp)` resolves a stable retained right edge (zero
|
||||
follows latest); `CandlePanStepsFor` and `CandlePanEnd` support caller-owned drag
|
||||
windows. Chart libraries do not fetch markets or change application selection.
|
||||
|
||||
## Native dashboard charts
|
||||
|
||||
Import `plot/Plot` and call any chart from a Kryon frame with the widget's
|
||||
layout rectangle and a stable key. Chart data is borrowed for that call.
|
||||
`ChartProps.label` names the card in the UI and the retained tree. The palette
|
||||
supplies surface, text, grid and sign colors. A series can use a packed
|
||||
`0xRRGGBBAA` color or leave `color` at zero to use the chart palette.
|
||||
|
||||
[The dashboard cookbook](examples/dashboard_charts.zi) implements these calls
|
||||
with illustrative data in a runnable Kryon frame. `make run` runs it natively.
|
||||
`make dashboard-zx` compiles it to `build/plot-portable.zx`. `ziran tool kryon run --profile portable`
|
||||
opens the bundle in the native Kryon player.
|
||||
|
||||
| Dashboard chart | Plot API and data |
|
||||
| --- | --- |
|
||||
| Strategy and buy-and-hold equity, drawdown, rolling metrics | `XYChart` with named `XYSeries` sharing one x and y scale. Each `XYPointValue` holds full-precision `float64` x and y. Dates use Unix seconds in UTC with `date_x = true`. |
|
||||
| Focused strategy equity | `XYChart` with the strategy slice alone, its original values and unit, a new key, and a descriptive label. It uses its own observed y scale. |
|
||||
| Bad-year returns and sensitivity | `BarChart` with `[]string` labels and one `BarSeries` per comparison. Each group's bars share zero as a baseline. Set `horizontal = true` for long labels or sensitivity rankings. |
|
||||
| Outperformance in bad years | Filter the years using the application's benchmark criteria. Compute strategy return minus buy-and-hold return from their original values and label the result `pp` (percentage points). |
|
||||
| Trait or calendar return matrix | `HeatmapChart` takes column labels, row labels, and a row-major `[]ChartValue`. It colors both signs symmetrically around zero and hatches unavailable cells. |
|
||||
| Trade marks and allocation history | Set `XYSeries.mark` to `.XYPoint` for scatter and `.XYStep` for previous-value hold until the next timestamp. The default `.XYLine` connects consecutive valid points in input order. |
|
||||
| Contribution bridge | `WaterfallChart` draws each delta from its running value. A `total = true` bar starts at zero and sets the new running value. A missing step leaves that value available and breaks the connector. |
|
||||
| Linked OHLC, equity, Sharpe and volatility | `TimeCandleChart64` consumes timestamped `PriceBar64` data. `TimeCandleChart` accepts existing `PriceBar` slices. Pair it with `XYChart` panes using equal widths and x origins, and the same finite `x_min` and `x_max`. All panes use the active date via `link_hover` and `hover_x`. |
|
||||
|
||||
A line or step gap is a sample with `missing = true` or a nonfinite coordinate.
|
||||
Put a gap sample between adjacent observations when they must remain visually
|
||||
separate. Unequal sample dates always use actual coordinate spacing. A
|
||||
nonfinite or missing bar leaves its group slot empty, as does a series shorter
|
||||
than the category slice. Missing or omitted heatmap cells stay distinct from
|
||||
zero. Explicit finite ascending ranges crop the visible geometry. An
|
||||
all-identical numeric domain expands around its sole value. `ChartHit` carries
|
||||
source indices and raw values. An inactive hit has `index = -1` and `series = -1`.
|
||||
For heatmaps, `index` is the column, `series` is the row, and `missing` distinguishes
|
||||
a cell without a value. For linked panes, `hide_x_axis` keeps the plot aligned
|
||||
while suppressing duplicate axis labels. `hide_tooltip` lets the application
|
||||
lay out its own shared hover text from the selected date and each pane's inputs.
|
||||
|
||||
`ChartFormat(value, unit) -> Text` uses Ziran's decimal formatter, trims trailing
|
||||
zeros, and displays at most two decimal places. It compacts large amounts and
|
||||
appends the caller's unit. For example, `ChartFormat(10.37, "%")` displays
|
||||
`10.37%`, and `ChartFormat(74.57, "pp")` displays `74.57 pp`. Pass already-scaled
|
||||
percentage values. Store calculations and chart inputs at their original
|
||||
precision.
|
||||
|
||||
When porting an HTML dashboard, place its cards with Kryon layout and pass
|
||||
those rectangles to Plot. Map SVG paths, circles, and rectangles to Plot
|
||||
marks fed by your dataset. Kryon style tokens and per-series colors cover
|
||||
native palette choices. Rebuild tooltip behavior from `ChartHit` where the
|
||||
default tooltip is insufficient. HTML, JavaScript chart options, SVG markup,
|
||||
and browser CSS layout are inputs to the porting process. The cookbook's
|
||||
`.zi` sources compile into a native host program or a `.zx` bundle.
|
||||
|
||||
Run `make check-dashboard` for the native C and ZX data tests.
|
||||
`make check-dashboard-ui` runs the Cairo and ZX rendering and input fixture
|
||||
at 550 and 1200 pixels. It uses `xvfb-run`, xdotool, ImageMagick, and Python
|
||||
with Pillow.
|
||||
@@ -0,0 +1,103 @@
|
||||
using Plot :: #import "Plot";
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/session"
|
||||
|
||||
// One card uses the shared scale. The second call uses the original strategy
|
||||
// values and unit with its own observed range.
|
||||
Equity :: (session: Session, bounds: Rectangle) {
|
||||
selected: [4]Plot.XYPointValue = .{
|
||||
.{1640995200.0, 100.0, false}, .{1648771200.0, 102.9, false},
|
||||
.{1664582400.0, 0.0, true}, .{1672444800.0, 110.37, false}}
|
||||
benchmark: [3]Plot.XYPointValue = .{
|
||||
.{1640995200.0, 100.0, false}, .{1648771200.0, 163.7, false},
|
||||
.{1672444800.0, 293.58, false}}
|
||||
series: [2]Plot.XYSeries = .{
|
||||
.{.name = "Selected", .points = selected[:]},
|
||||
.{.name = "Buy and hold", .points = benchmark[:]}}
|
||||
props := Plot.ChartProps.{.key = 11, .bounds = bounds,
|
||||
.label = "Equity comparison", .date_x = true, .y_unit = "index",
|
||||
.x_min = 1640995200.0, .x_max = 1672444800.0}
|
||||
unused Plot.XYChart(session, props, series[:])
|
||||
props.key = 12
|
||||
props.label = "Selected under stress"
|
||||
props.bounds.x += bounds.width + 12.0
|
||||
unused Plot.XYChart(session, props, series[0:1])
|
||||
}
|
||||
|
||||
Returns :: (session: Session, bounds: Rectangle) {
|
||||
years: [3]string = .{"2020", "2022", "2025"}
|
||||
strategy: [3]Plot.ChartValue = .{.{4.0, false}, .{10.37, false}, .{-6.43, false}}
|
||||
hold: [3]Plot.ChartValue = .{.{-14.8, false}, .{-64.2, false}, .{-18.5, false}}
|
||||
returns: [2]Plot.BarSeries = .{
|
||||
.{.name = "Selected", .values = strategy[:]}, .{.name = "Buy and hold", .values = hold[:]}}
|
||||
unused Plot.BarChart(session, .{.key = 13, .bounds = bounds,
|
||||
.label = "Returns in down years", .y_unit = "%"}, years[:], returns[:])
|
||||
|
||||
differences: [3]Plot.ChartValue
|
||||
for i: 0..2 { differences[i].value = strategy[i].value - hold[i].value }
|
||||
delta: [1]Plot.BarSeries = .{.{.name = "Return difference", .values = differences[:]}}
|
||||
beside := bounds
|
||||
beside.x += bounds.width + 12.0
|
||||
unused Plot.BarChart(session, .{.key = 14, .bounds = beside,
|
||||
.label = "Outperformance", .y_unit = "pp", .horizontal = true,
|
||||
.hide_legend = true}, years[:], delta[:])
|
||||
}
|
||||
|
||||
Contributions :: (session: Session, bounds: Rectangle) {
|
||||
cols: [3]string = .{"2020", "2022", "2025"}
|
||||
rows: [2]string = .{"Momentum", "Carry"}
|
||||
cells: [6]Plot.ChartValue = .{.{6.0, false}, .{-12.0, false}, .{0.0, true},
|
||||
.{0.0, false}, .{5.0, false}, .{-4.2, false}}
|
||||
unused Plot.HeatmapChart(session, .{.key = 15, .bounds = bounds,
|
||||
.label = "Trait returns", .y_unit = "%"}, cols[:], rows[:], cells[:])
|
||||
|
||||
steps: [4]Plot.WaterfallStep = .{.{"Start", 18.5, true, false},
|
||||
.{"Signals", 7.25, false, false}, .{"Costs", -4.38, false, false},
|
||||
.{"End", 21.37, true, false}}
|
||||
beside := bounds
|
||||
beside.x += bounds.width + 12.0
|
||||
unused Plot.WaterfallChart(session, .{.key = 16, .bounds = beside,
|
||||
.label = "Return contributions", .y_unit = "pp"}, steps[:])
|
||||
}
|
||||
|
||||
Diagnostics :: (session: Session, bounds: Rectangle) {
|
||||
bars: [3]Plot.PriceBar64 = .{
|
||||
.{.timestamp = 1640995200, .open = 100, .high = 118, .low = 98, .close = 111},
|
||||
.{.timestamp = 1641081600, .open = 110, .high = 115, .low = 104, .close = 106},
|
||||
.{.timestamp = 1641340800, .open = 106, .high = 125, .low = 105, .close = 121}}
|
||||
allocation: [4]Plot.XYPointValue = .{.{1640995200.0, 25.0, false},
|
||||
.{1641081600.0, 60.0, false}, .{1641254400.0, 15.0, false},
|
||||
.{1641340800.0, 15.0, false}}
|
||||
trades: [2]Plot.XYPointValue = .{.{1641081600.0, 60.0, false}, .{1641254400.0, 15.0, false}}
|
||||
marks: [2]Plot.XYSeries = .{
|
||||
.{.name = "Allocation", .mark = .XYStep, .points = allocation[:]},
|
||||
.{.name = "Trade", .mark = .XYPoint, .points = trades[:]}}
|
||||
price := Plot.ChartProps.{.key = 17, .label = "Price", .bounds = bounds,
|
||||
.x_min = 1640995200.0, .x_max = 1641340800.0, .y_unit = "USD"}
|
||||
allocations := price
|
||||
allocations.key = 18
|
||||
allocations.label = "Allocation and trades"
|
||||
allocations.y_unit = "%"
|
||||
allocations.date_x = true
|
||||
allocations.bounds.x += bounds.width + 12.0
|
||||
// Resolve the local hit first, then use it for the second pane. A linked
|
||||
// crosshair can also be fed to every pane from an app-owned selected x.
|
||||
hit := Plot.TimeCandleChart64(session, price, bars[:])
|
||||
allocations.link_hover = hit.active
|
||||
allocations.hover_x = hit.x
|
||||
unused Plot.XYChart(session, allocations, marks[:])
|
||||
}
|
||||
|
||||
#program_export
|
||||
Draw :: (session: Session, viewport: Rectangle) {
|
||||
width := (viewport.width - 36.0) / 2.0
|
||||
height := (viewport.height - 54.0) / 4.0
|
||||
bounds := Rectangle.{12.0, 9.0, width, height}
|
||||
Equity(session, bounds)
|
||||
bounds.y += height + 12.0
|
||||
Returns(session, bounds)
|
||||
bounds.y += height + 12.0
|
||||
Contributions(session, bounds)
|
||||
bounds.y += height + 12.0
|
||||
Diagnostics(session, bounds)
|
||||
}
|
||||
@@ -8,3 +8,4 @@ using Candle :: #import "candle_chart";
|
||||
using Line :: #import "line_chart";
|
||||
using Band :: #import "band_chart";
|
||||
using BandProps :: #import "band_chart_props";
|
||||
using Dashboard :: #import "dashboard_chart";
|
||||
@@ -2,3 +2,5 @@
|
||||
using PlotPropsModule :: #import "plot_props";
|
||||
using PlotModule :: #import "plot";
|
||||
using PlotWidgetModule :: #import "plot_widget";
|
||||
// Typed dashboard charts also compose over the retained Plot surface.
|
||||
using Dashboard :: #import "dashboard_chart";
|
||||
+2
-47
@@ -1,54 +1,9 @@
|
||||
using Charts :: #import "Plot";
|
||||
TextWidget :: #import "kryon/text";
|
||||
Theme :: #import "kryon/theme";
|
||||
#import "kryon/drawing_props"
|
||||
DashboardExample :: #import "dashboard_charts";
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/session"
|
||||
|
||||
#program_export
|
||||
Frame :: (session: Session, viewport: Rectangle) -> s32 {
|
||||
closes: [32]float32 = .{
|
||||
42.0, 44.0, 43.0, 47.0, 45.0, 49.0, 48.0, 51.0,
|
||||
46.0, 48.0, 53.0, 52.0, 55.0, 54.0, 58.0, 57.0,
|
||||
56.0, 59.0, 61.0, 58.0, 60.0, 63.0, 62.0, 66.0,
|
||||
64.0, 67.0, 65.0, 68.0, 71.0, 69.0, 73.0, 72.0
|
||||
}
|
||||
bars: [32]PriceBar
|
||||
index: s32 = 0
|
||||
while index < 32 {
|
||||
previous: float32 = closes[0]
|
||||
if index > 0 { previous = closes[index - 1] }
|
||||
bars[index].open = previous
|
||||
bars[index].close = closes[index]
|
||||
bars[index].high = previous
|
||||
bars[index].low = previous
|
||||
if closes[index] > previous { bars[index].high = closes[index] }
|
||||
if closes[index] < previous { bars[index].low = closes[index] }
|
||||
bars[index].high += 1.0
|
||||
bars[index].low -= 1.0
|
||||
bars[index].volume = cast(float32)(80 + index * 7)
|
||||
index += 1
|
||||
}
|
||||
title: TextWidget.Props
|
||||
title.key = cast(u64)1
|
||||
title.text = "Plot"
|
||||
title.size = 28
|
||||
title.bounds = Rectangle.{32.0, 24.0, viewport.width - 64.0, 48.0}
|
||||
unused TextWidget.Draw(session, title)
|
||||
|
||||
chart: CandleChartProps
|
||||
chart.key = cast(u64)2
|
||||
chart.bounds = Rectangle.{48.0, 104.0,
|
||||
viewport.width - 96.0, viewport.height - 168.0}
|
||||
chart.visible_count = 32
|
||||
chart.semantic_label = "Example candlestick chart with volume and SMA 20"
|
||||
chart.up_color = ColorFromPacked(cast(u32)0x168265ff)
|
||||
chart.down_color = ColorFromPacked(cast(u32)0xb34d53ff)
|
||||
chart.grid_color = StyleTokenColorOr("grid",
|
||||
ColorFromPacked(Theme.CurrentPalette().subtle_border))
|
||||
chart.sma20_color = ColorFromPacked(cast(u32)0xd18a1bff)
|
||||
chart.show_sma20 = true
|
||||
values: []PriceBar = bars[:]
|
||||
CandleChart(session, chart, values, CandleRangeFor(values, 32))
|
||||
DashboardExample.Draw(session, viewport)
|
||||
return 0
|
||||
}
|
||||
+2
-1
@@ -3,7 +3,8 @@ ButtonWidget :: #import "kryon/button";
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/paint_queue"
|
||||
#import "kryon/session"
|
||||
using PlotWidget :: #import "PlotWidget";
|
||||
#import "plot_widget"
|
||||
#import "plot_props"
|
||||
ChartMath :: #import "std/math";
|
||||
|
||||
PriceBar :: struct {
|
||||
|
||||
@@ -0,0 +1,941 @@
|
||||
#import "kryon/drawing_props"
|
||||
#import "kryon/font_metrics"
|
||||
#import "kryon/tree_input"
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/paint_queue"
|
||||
#import "kryon/session"
|
||||
#import "kryon/style_sheet"
|
||||
#import "kryon/tree"
|
||||
#import "plot_props"
|
||||
Candle :: #import "candle_chart";
|
||||
using Surface :: #import "plot_widget";
|
||||
using Theme :: #import "kryon/theme";
|
||||
using Number :: #import "std/number_text";
|
||||
using Dates :: #import "std/date_parse";
|
||||
using Finite :: #import "std/finite";
|
||||
|
||||
ChartProps :: struct {
|
||||
bounds: Rectangle
|
||||
key: u64
|
||||
label: string
|
||||
x_unit: string
|
||||
y_unit: string
|
||||
date_x: bool
|
||||
x_min: float64
|
||||
x_max: float64
|
||||
y_min: float64
|
||||
y_max: float64
|
||||
hide_legend: bool
|
||||
hide_x_axis: bool
|
||||
hide_tooltip: bool
|
||||
horizontal: bool
|
||||
link_hover: bool
|
||||
hover_x: float64
|
||||
}
|
||||
|
||||
XYMark :: enum { XYLine :: 0; XYStep :: 1; XYPoint :: 2 }
|
||||
using XYMark;
|
||||
|
||||
XYPointValue :: struct { x: float64; y: float64; missing: bool }
|
||||
XYSeries :: struct { name: string; color: u32; mark: XYMark; points: []XYPointValue }
|
||||
ChartValue :: struct { value: float64; missing: bool }
|
||||
BarSeries :: struct { name: string; color: u32; values: []ChartValue }
|
||||
WaterfallStep :: struct { label: string; value: float64; total: bool; missing: bool }
|
||||
|
||||
ChartHit :: struct {
|
||||
active: bool
|
||||
missing: bool
|
||||
index: s64
|
||||
series: s64
|
||||
x: float64
|
||||
y: float64
|
||||
}
|
||||
|
||||
ChartDomain :: struct { low: float64; high: float64; valid: bool }
|
||||
XYDomains :: struct { x: ChartDomain; y: ChartDomain }
|
||||
|
||||
#program_export
|
||||
ChartFormat :: (value: float64, unit: string = "") -> Text {
|
||||
if !Finite.Finite64(value) { return TextCopy("No data") }
|
||||
amount := value
|
||||
magnitude := ifx value < 0.0 then -value else value
|
||||
suffix := ""
|
||||
exponent: s64 = 0
|
||||
if magnitude >= 1.0e15 {
|
||||
while magnitude >= 9.995 {
|
||||
magnitude /= 10.0
|
||||
amount /= 10.0
|
||||
exponent += 1
|
||||
}
|
||||
} else if magnitude >= 999995000000.0 { amount /= 1.0e12; suffix = "T" }
|
||||
else if magnitude >= 999995000.0 { amount /= 1.0e9; suffix = "B" }
|
||||
else if magnitude >= 999995.0 { amount /= 1.0e6; suffix = "M" }
|
||||
else if magnitude >= 1000.0 { amount /= 1.0e3; suffix = "k" }
|
||||
digits: [32]u8
|
||||
out := Vec(u8).{}
|
||||
BuilderAppend(out, Number.FormatDecimal(amount, 2, digits[:]))
|
||||
BuilderAppend(out, suffix)
|
||||
if exponent > 0 { BuilderPrint(*out, "e%", exponent) }
|
||||
if unit != "" && unit != "%" { BuilderAppend(out, " ") }
|
||||
BuilderAppend(out, unit)
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
#program_export
|
||||
ChartDomainInclude :: (domain: *ChartDomain, value: float64) {
|
||||
if !Finite.Finite64(value) { return }
|
||||
if !domain.valid {
|
||||
domain.* = ChartDomain.{value, value, true}
|
||||
return
|
||||
}
|
||||
if value < domain.low { domain.low = value }
|
||||
if value > domain.high { domain.high = value }
|
||||
}
|
||||
|
||||
#program_export
|
||||
ChartDomainResolve :: (observed: ChartDomain, low: float64 = 0.0,
|
||||
high: float64 = 0.0) -> ChartDomain {
|
||||
if Finite.Finite64(low) && Finite.Finite64(high) && low < high {
|
||||
return ChartDomain.{low, high, true}
|
||||
}
|
||||
if !observed.valid || observed.low < observed.high { return observed }
|
||||
center := observed.low
|
||||
padding := ifx center < 0.0 then -center * 0.02 else center * 0.02
|
||||
if padding < 0.5 { padding = 0.5 }
|
||||
first := center - padding
|
||||
last := center + padding
|
||||
if !Finite.Finite64(first) { first = center }
|
||||
if !Finite.Finite64(last) { last = center }
|
||||
return ChartDomain.{first, last, true}
|
||||
}
|
||||
|
||||
XYValid :: (point: XYPointValue) -> bool {
|
||||
return !point.missing && Finite.Finite64(point.x) && Finite.Finite64(point.y)
|
||||
}
|
||||
|
||||
#program_export
|
||||
XYChartDomains :: (props: ChartProps, series: []XYSeries) -> XYDomains {
|
||||
result: XYDomains
|
||||
for item: series {
|
||||
for point: item.points {
|
||||
ChartDomainInclude(*result.x, point.x)
|
||||
if XYValid(point) { ChartDomainInclude(*result.y, point.y) }
|
||||
}
|
||||
}
|
||||
result.x = ChartResolveX(result.x, props)
|
||||
result.y = ChartDomainResolve(result.y, props.y_min, props.y_max)
|
||||
return result
|
||||
}
|
||||
|
||||
ChartFraction :: (value: float64, domain: ChartDomain) -> float64 {
|
||||
span := domain.high - domain.low
|
||||
if Finite.Finite64(span) { return (value - domain.low) / span }
|
||||
return (value * 0.5 - domain.low * 0.5) / (domain.high * 0.5 - domain.low * 0.5)
|
||||
}
|
||||
|
||||
ChartCoordinate :: (domain: ChartDomain, fraction: float64) -> float64 {
|
||||
return domain.low * (1.0 - fraction) + domain.high * fraction
|
||||
}
|
||||
|
||||
#program_export
|
||||
ChartXPosition :: (bounds: Rectangle, domain: ChartDomain, value: float64) -> float32 {
|
||||
return bounds.x + bounds.width * cast(float32)ChartFraction(value, domain)
|
||||
}
|
||||
|
||||
ChartYPosition :: (bounds: Rectangle, domain: ChartDomain, value: float64) -> float32 {
|
||||
return bounds.y + bounds.height * cast(float32)(1.0 - ChartFraction(value, domain))
|
||||
}
|
||||
|
||||
ChartInDomain :: (value: float64, domain: ChartDomain) -> bool {
|
||||
return domain.valid && value >= domain.low && value <= domain.high
|
||||
}
|
||||
|
||||
ChartInside :: (bounds: Rectangle, x: float32, y: float32) -> bool {
|
||||
return bounds.width > 0.0 && bounds.height > 0.0 && x >= bounds.x && y >= bounds.y &&
|
||||
x <= bounds.x + bounds.width && y <= bounds.y + bounds.height
|
||||
}
|
||||
|
||||
ChartNoHit :: () -> ChartHit { return ChartHit.{.index = -1, .series = -1} }
|
||||
|
||||
#program_export
|
||||
XYChartHit :: (bounds: Rectangle, domains: XYDomains, series: []XYSeries,
|
||||
x: float32, y: float32, linked: bool = false) -> ChartHit {
|
||||
hit := ChartNoHit()
|
||||
if !ChartInside(bounds, x, y) || !domains.x.valid || !domains.y.valid { return hit }
|
||||
best_x: float32 = bounds.width + 1.0
|
||||
best_y: float32 = bounds.height + 1.0
|
||||
for i: 0..series.count-1 {
|
||||
item := series[i]
|
||||
for j: 0..item.points.count-1 {
|
||||
point := item.points[j]
|
||||
if !XYValid(point) || !ChartInDomain(point.x, domains.x) ||
|
||||
!ChartInDomain(point.y, domains.y) { continue }
|
||||
dx := ChartXPosition(bounds, domains.x, point.x) - x
|
||||
if dx < 0.0 { dx = -dx }
|
||||
dy := ChartYPosition(bounds, domains.y, point.y) - y
|
||||
if dy < 0.0 { dy = -dy }
|
||||
if linked && dx > 0.001 { continue }
|
||||
if !linked && item.mark == cast(XYMark)XYPoint && (dx * dx + dy * dy > 100.0) { continue }
|
||||
if dx < best_x || (dx == best_x && dy < best_y) {
|
||||
hit = .{.active = true, .index = j, .series = i, .x = point.x, .y = point.y}
|
||||
best_x = dx
|
||||
best_y = dy
|
||||
}
|
||||
}
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
ChartFrame :: struct {
|
||||
props: ChartProps
|
||||
bounds: Rectangle
|
||||
plot: Rectangle
|
||||
clip: Rectangle
|
||||
node: s32
|
||||
text: Color
|
||||
grid: Color
|
||||
surface: Color
|
||||
accent: Color
|
||||
positive: Color
|
||||
negative: Color
|
||||
mouse: Vector2
|
||||
pointed: bool
|
||||
}
|
||||
|
||||
ChartColor :: (view: ChartFrame, packed: u32, index: s64) -> Color {
|
||||
if packed != 0 { return ColorFromPacked(packed) }
|
||||
if index % 6 == 0 { return view.accent }
|
||||
choices: [5]u32 = .{0xe39a43ff, 0x40a787ff, 0xb381dcff, 0x55adc4ff, 0xd47191ff}
|
||||
return ColorFromPacked(choices[index % 6 - 1])
|
||||
}
|
||||
|
||||
ChartStart :: (session: Session, props: ChartProps, left: float32) -> ChartFrame {
|
||||
view: ChartFrame
|
||||
view.props = props
|
||||
view.bounds = props.bounds
|
||||
view.node = -1
|
||||
if props.bounds.width <= 0.0 || props.bounds.height <= 0.0 { return view }
|
||||
empty: []float32
|
||||
background := PlotProps.{.key = props.key, .bounds = props.bounds,
|
||||
.semantic_label = props.label}
|
||||
view.node = Surface.Plot(session, background, empty)
|
||||
if view.node >= 0 { view.bounds = TreeSubmittedNodeAt(session, view.node).bounds }
|
||||
view.clip = view.bounds
|
||||
geometry := TreeCurrentPaintGeometry(session)
|
||||
if geometry.clipped { view.clip = RectangleIntersection(view.clip, geometry.clip) }
|
||||
face := Surface.PlotFacesFor(background, Surface.DefaultPlotFaces())
|
||||
palette := Theme.CurrentPalette()
|
||||
view.text = ColorFromPacked(face.plot.value.foreground)
|
||||
view.surface = ColorFromPacked(face.plot.value.background)
|
||||
view.grid = StyleTokenColorOr("grid", ColorFromPacked(palette.subtle_border))
|
||||
view.accent = ColorFromPacked(face.mark.value.background)
|
||||
view.positive = StyleTokenColorOr("success", ColorFromPacked(0x269b78ff))
|
||||
view.negative = StyleTokenColorOr("danger", ColorFromPacked(0xcc5a60ff))
|
||||
top: float32 = 12.0
|
||||
if props.label != "" { top = 33.0 }
|
||||
view.plot = .{view.bounds.x + left, view.bounds.y + top,
|
||||
view.bounds.width - left - 17.0, view.bounds.height - top - 27.0}
|
||||
input := PointerSample(session)
|
||||
view.mouse = .{input.x, input.y}
|
||||
view.pointed = ChartInside(view.clip, view.mouse.x, view.mouse.y)
|
||||
ChartText(session, view, props.label, view.bounds.x + 10.0, view.bounds.y + 7.0, 14, view.bounds)
|
||||
return view
|
||||
}
|
||||
|
||||
ChartText :: (session: Session, view: ChartFrame, label: string, x: float32,
|
||||
y: float32, font: s32, clip: Rectangle) {
|
||||
if label == "" || clip.width <= 0.0 || clip.height <= 0.0 { return }
|
||||
PaintClippedLabel(session, view.node, label, cast(s32)x, cast(s32)y, font, view.text, clip)
|
||||
}
|
||||
|
||||
ChartTextWidth :: (text: string, font: s32) -> float32 {
|
||||
return cast(float32)GlyphWidth(text, font, "")
|
||||
}
|
||||
|
||||
ChartLegendItem :: (session: Session, view: *ChartFrame, cursor: *Vector2,
|
||||
label: string, color: Color) {
|
||||
if label == "" || view.props.hide_legend { return }
|
||||
available := view.bounds.width - 20.0
|
||||
if available < 20.0 { return }
|
||||
width := ChartTextWidth(label, 12) + 24.0
|
||||
if width > available { width = available }
|
||||
if cursor.x + width > view.bounds.x + view.bounds.width - 10.0 {
|
||||
cursor.x = view.bounds.x + 10.0
|
||||
cursor.y += 18.0
|
||||
}
|
||||
if cursor.y + 22.0 > view.bounds.y + view.bounds.height - 48.0 { return }
|
||||
PaintRoundedFill(session, view.node, Rectangle.{cursor.x, cursor.y + 4.0, 9.0, 9.0}, 2.0, 8, color)
|
||||
ChartText(session, view.*, label, cursor.x + 14.0, cursor.y, 12,
|
||||
Rectangle.{cursor.x + 14.0, cursor.y, width - 14.0, 17.0})
|
||||
bottom := view.plot.y + view.plot.height
|
||||
view.plot.y = cursor.y + 22.0
|
||||
view.plot.height = bottom - view.plot.y
|
||||
cursor.x += width
|
||||
}
|
||||
|
||||
ChartDate :: (seconds: float64, span: float64, full: bool = false) -> Text {
|
||||
if seconds < -62135596800.0 || seconds >= 253402300800.0 || !Finite.Finite64(seconds) {
|
||||
return TextCopy("Out of range")
|
||||
}
|
||||
second := cast(s64)seconds
|
||||
if cast(float64)second > seconds { second -= 1 }
|
||||
day: [10]u8
|
||||
if Dates.WriteIsoDay(second, day[:]) != 10 { return TextCopy("Out of range") }
|
||||
out := Vec(u8).{}
|
||||
BuilderAppend(out, TextView(day[:]))
|
||||
if span <= 172800.0 || (full && second % 86400 != 0) {
|
||||
clock: [14]u8
|
||||
unused Dates.WriteCompactUtc(second, clock[:])
|
||||
BuilderAppend(out, " ")
|
||||
BuilderAppend(out, TextView(clock[8:10]))
|
||||
BuilderAppend(out, ":")
|
||||
BuilderAppend(out, TextView(clock[10:12]))
|
||||
if full || span < 240.0 {
|
||||
BuilderAppend(out, ":")
|
||||
BuilderAppend(out, TextView(clock[12:14]))
|
||||
}
|
||||
}
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
ChartXText :: (view: ChartFrame, domain: ChartDomain, value: float64, full: bool = false) -> Text {
|
||||
if view.props.date_x { return ChartDate(value, domain.high - domain.low, full) }
|
||||
return ChartFormat(value, view.props.x_unit)
|
||||
}
|
||||
|
||||
ChartCenteredText :: (session: Session, view: ChartFrame, text: string, x: float32,
|
||||
y: float32, width: float32) {
|
||||
clip := RectangleIntersection(view.bounds, Rectangle.{x - width * 0.5, y, width, 16.0})
|
||||
offset := ChartTextWidth(text, 11) * 0.5
|
||||
if offset > width * 0.5 { offset = width * 0.5 }
|
||||
ChartText(session, view, text, x - offset, y, 11, clip)
|
||||
}
|
||||
|
||||
ChartAxes :: (session: Session, view: ChartFrame, domain: ChartDomain, horizontal: bool = false) {
|
||||
if !domain.valid { return }
|
||||
for i: 0..4 {
|
||||
fraction := cast(float64)i / 4.0
|
||||
value := ChartCoordinate(domain, fraction)
|
||||
label: Text = ChartFormat(value, view.props.y_unit)
|
||||
if horizontal {
|
||||
x := ChartXPosition(view.plot, domain, value)
|
||||
PaintLine(session, view.node, Rectangle.{x, view.plot.y, 0.0, view.plot.height}, view.grid)
|
||||
ChartCenteredText(session, view, label, x, view.plot.y + view.plot.height + 5.0,
|
||||
view.plot.width / 4.0 - 2.0)
|
||||
} else {
|
||||
y := ChartYPosition(view.plot, domain, value)
|
||||
PaintLine(session, view.node, Rectangle.{view.plot.x, y, view.plot.width, 0.0}, view.grid)
|
||||
x := view.plot.x - 7.0 - ChartTextWidth(label, 11)
|
||||
if x < view.bounds.x + 2.0 { x = view.bounds.x + 2.0 }
|
||||
ChartText(session, view, label, x, y - 7.0, 11,
|
||||
Rectangle.{view.bounds.x, view.plot.y - 8.0, view.plot.x - view.bounds.x - 4.0, view.plot.height + 16.0})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ChartTimeAxis :: (session: Session, view: ChartFrame, domain: ChartDomain) {
|
||||
if view.props.hide_x_axis || !domain.valid { return }
|
||||
spacing: float32 = ifx view.props.date_x then 142.0 else 92.0
|
||||
ticks := cast(s32)(view.plot.width / spacing) + 1
|
||||
if ticks < 2 { ticks = 2 }
|
||||
if ticks > 7 { ticks = 7 }
|
||||
slot := view.plot.width / cast(float32)(ticks - 1)
|
||||
for i: 0..ticks-1 {
|
||||
value := ChartCoordinate(domain, cast(float64)i / cast(float64)(ticks - 1))
|
||||
label: Text = ChartXText(view, domain, value)
|
||||
x := ChartXPosition(view.plot, domain, value)
|
||||
half := ChartTextWidth(label, 11) * 0.5 + 1.0
|
||||
if x + half > view.bounds.x + view.bounds.width { x = view.bounds.x + view.bounds.width - half }
|
||||
ChartCenteredText(session, view, label, x, view.plot.y + view.plot.height + 5.0, slot - 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
ChartEmpty :: (session: Session, view: ChartFrame) {
|
||||
ChartCenteredText(session, view, "No data", view.plot.x + view.plot.width * 0.5,
|
||||
view.plot.y + view.plot.height * 0.5 - 7.0, view.plot.width)
|
||||
}
|
||||
|
||||
ChartTooltip :: (session: Session, view: ChartFrame, x: float32, y: float32, text: string) {
|
||||
if view.props.hide_tooltip || text == "" { return }
|
||||
width := ChartTextWidth(text, 12) + 16.0
|
||||
if width > view.clip.width { width = view.clip.width }
|
||||
if width < 16.0 || view.clip.height < 23.0 { return }
|
||||
if x + width > view.clip.x + view.clip.width { x = view.clip.x + view.clip.width - width }
|
||||
if x < view.clip.x { x = view.clip.x }
|
||||
if y + 23.0 > view.clip.y + view.clip.height { y = view.clip.y + view.clip.height - 23.0 }
|
||||
if y < view.clip.y { y = view.clip.y }
|
||||
box := Rectangle.{x, y, width, 23.0}
|
||||
PaintRoundedFill(session, view.node, box, 4.0, 10, view.surface)
|
||||
PaintRoundedOutline(session, view.node, box, 4.0, 10, 1.0, view.grid)
|
||||
ChartText(session, view, text, x + 8.0, y + 4.0, 12, box)
|
||||
}
|
||||
|
||||
ChartTipValue :: (session: Session, view: ChartFrame, category: string,
|
||||
name: string, value: float64, missing: bool) {
|
||||
if view.props.hide_tooltip { return }
|
||||
formatted: Text = ChartFormat(value, view.props.y_unit)
|
||||
out := Vec(u8).{}
|
||||
BuilderAppend(out, category)
|
||||
if name != "" { BuilderPrint(*out, " · %", name) }
|
||||
BuilderAppend(out, " · ")
|
||||
if missing { BuilderAppend(out, "No data") } else { BuilderAppend(out, TextView(formatted)) }
|
||||
tip: Text = BuilderFinish(out)
|
||||
ChartTooltip(session, view, view.mouse.x + 10.0, view.mouse.y + 12.0, tip)
|
||||
}
|
||||
|
||||
// Clip each data axis before converting to pixels. Explicit ranges can cut
|
||||
// through a segment while still showing its visible portion.
|
||||
ChartClipAxis :: (a: *XYPointValue, b: *XYPointValue, domain: ChartDomain, x_axis: bool) -> bool {
|
||||
first := ifx x_axis then a.x else a.y
|
||||
last := ifx x_axis then b.x else b.y
|
||||
if (first < domain.low && last < domain.low) ||
|
||||
(first > domain.high && last > domain.high) { return false }
|
||||
old_a := a.*
|
||||
old_b := b.*
|
||||
ordered := first <= last
|
||||
sample := ifx ordered then ChartDomain.{first, last, true} else ChartDomain.{last, first, true}
|
||||
for end: 0..1 {
|
||||
value := ifx end == 0 then first else last
|
||||
if value >= domain.low && value <= domain.high { continue }
|
||||
limit := ifx value < domain.low then domain.low else domain.high
|
||||
fraction := ChartFraction(limit, sample)
|
||||
if !ordered { fraction = 1.0 - fraction }
|
||||
point := ifx end == 0 then a else b
|
||||
if x_axis {
|
||||
point.x = limit
|
||||
point.y = old_a.y * (1.0 - fraction) + old_b.y * fraction
|
||||
} else {
|
||||
point.x = old_a.x * (1.0 - fraction) + old_b.x * fraction
|
||||
point.y = limit
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
ChartSegment :: (session: Session, view: ChartFrame, domains: XYDomains,
|
||||
from: XYPointValue, to: XYPointValue, color: Color) {
|
||||
a := from
|
||||
b := to
|
||||
if !ChartClipAxis(*a, *b, domains.x, true) || !ChartClipAxis(*a, *b, domains.y, false) { return }
|
||||
x := ChartXPosition(view.plot, domains.x, a.x)
|
||||
y := ChartYPosition(view.plot, domains.y, a.y)
|
||||
PaintLine(session, view.node, Rectangle.{x, y,
|
||||
ChartXPosition(view.plot, domains.x, b.x) - x, ChartYPosition(view.plot, domains.y, b.y) - y}, color)
|
||||
}
|
||||
|
||||
ChartPoint :: (session: Session, view: ChartFrame, domains: XYDomains,
|
||||
point: XYPointValue, color: Color) {
|
||||
if !ChartInDomain(point.x, domains.x) || !ChartInDomain(point.y, domains.y) { return }
|
||||
x := ChartXPosition(view.plot, domains.x, point.x)
|
||||
y := ChartYPosition(view.plot, domains.y, point.y)
|
||||
PaintRoundedFill(session, view.node, Rectangle.{x - 3.0, y - 3.0, 6.0, 6.0}, 3.0, 10, color)
|
||||
}
|
||||
|
||||
ChartCrosshair :: (session: Session, view: ChartFrame, domain: ChartDomain, date: float64) {
|
||||
if !ChartInDomain(date, domain) { return }
|
||||
x := ChartXPosition(view.plot, domain, date)
|
||||
PaintLine(session, view.node, Rectangle.{x, view.plot.y, 0.0, view.plot.height}, view.text)
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
#program_export
|
||||
XYChart :: (session: Session, props: ChartProps, series: []XYSeries) -> ChartHit {
|
||||
view := ChartStart(session, props, 78.0)
|
||||
cursor := Vector2.{view.bounds.x + 10.0, view.plot.y - 2.0}
|
||||
for i: 0..series.count-1 {
|
||||
ChartLegendItem(session, *view, *cursor, series[i].name, ChartColor(view, series[i].color, i))
|
||||
}
|
||||
hit := ChartNoHit()
|
||||
if view.plot.width <= 0.0 || view.plot.height <= 0.0 { return hit }
|
||||
domains := XYChartDomains(props, series)
|
||||
ChartAxes(session, view, domains.y)
|
||||
ChartTimeAxis(session, view, domains.x)
|
||||
has_data := false
|
||||
for i: 0..series.count-1 {
|
||||
item := series[i]
|
||||
color := ChartColor(view, item.color, i)
|
||||
for j: 0..item.points.count-1 {
|
||||
point := item.points[j]
|
||||
if !XYValid(point) { continue }
|
||||
has_data = true
|
||||
previous := j > 0 && XYValid(item.points[j - 1])
|
||||
next := j + 1 < item.points.count && XYValid(item.points[j + 1])
|
||||
if item.mark == cast(XYMark)XYPoint || (!previous && !next) { ChartPoint(session, view, domains, point, color) }
|
||||
if !previous || item.mark == cast(XYMark)XYPoint { continue }
|
||||
before := item.points[j - 1]
|
||||
if item.mark == cast(XYMark)XYStep {
|
||||
corner := XYPointValue.{point.x, before.y, false}
|
||||
ChartSegment(session, view, domains, before, corner, color)
|
||||
before = corner
|
||||
}
|
||||
ChartSegment(session, view, domains, before, point, color)
|
||||
}
|
||||
}
|
||||
if !has_data { ChartEmpty(session, view) }
|
||||
if view.pointed { hit = XYChartHit(view.plot, domains, series, view.mouse.x, view.mouse.y) }
|
||||
linked := props.link_hover && ChartInDomain(props.hover_x, domains.x)
|
||||
if !hit.active && !linked { return hit }
|
||||
selected_x := ifx linked then props.hover_x else hit.x
|
||||
ChartCrosshair(session, view, domains.x, selected_x)
|
||||
if props.hide_tooltip { return hit }
|
||||
label: Text = ChartXText(view, domains.x, selected_x, true)
|
||||
x := ChartXPosition(view.plot, domains.x, selected_x)
|
||||
y := view.plot.y + 5.0
|
||||
ChartTooltip(session, view, x + 8.0, y, label)
|
||||
for i: 0..series.count-1 {
|
||||
item := series[i]
|
||||
for point: item.points {
|
||||
if !XYValid(point) || point.x != selected_x { continue }
|
||||
rendered: Text = ChartFormat(point.y, props.y_unit)
|
||||
row := Vec(u8).{}
|
||||
if item.name != "" { BuilderPrint(*row, "% · ", item.name) }
|
||||
BuilderAppend(row, TextView(rendered))
|
||||
tip: Text = BuilderFinish(row)
|
||||
y += 23.0
|
||||
if y + 23.0 <= view.clip.y + view.clip.height {
|
||||
ChartTooltip(session, view, x + 8.0, y, tip)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
CategoricalSlot :: (area: Rectangle, index: s64, count: s64, horizontal: bool) -> Rectangle {
|
||||
if count <= 0 || index < 0 || index >= count { return Rectangle.{} }
|
||||
if horizontal {
|
||||
height := area.height / cast(float32)count
|
||||
return Rectangle.{area.x, area.y + cast(float32)index * height, area.width, height}
|
||||
}
|
||||
width := area.width / cast(float32)count
|
||||
return Rectangle.{area.x + cast(float32)index * width, area.y, width, area.height}
|
||||
}
|
||||
|
||||
ChartClamp :: (value: float64, domain: ChartDomain) -> float64 {
|
||||
if value < domain.low { return domain.low }
|
||||
if value > domain.high { return domain.high }
|
||||
return value
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
#program_export
|
||||
BarChartDomain :: (props: ChartProps, count: s64, series: []BarSeries) -> ChartDomain {
|
||||
domain := ChartDomain.{0.0, 0.0, true}
|
||||
for item: series {
|
||||
limit := ifx item.values.count < count then item.values.count else count
|
||||
for i: 0..limit-1 {
|
||||
value := item.values[i]
|
||||
if !value.missing { ChartDomainInclude(*domain, value.value) }
|
||||
}
|
||||
}
|
||||
return ChartDomainResolve(domain, props.y_min, props.y_max)
|
||||
}
|
||||
|
||||
// The very same rectangle is used for painting and picking each group member.
|
||||
#program_export
|
||||
ChartBarBounds :: (area: Rectangle, domain: ChartDomain, category: s64, categories: s64,
|
||||
series: s64, series_count: s64, start: float64, finish: float64, horizontal: bool = false) -> Rectangle {
|
||||
if !domain.valid || series_count <= 0 || series < 0 || series >= series_count ||
|
||||
!Finite.Finite64(start) || !Finite.Finite64(finish) { return Rectangle.{} }
|
||||
slot := CategoricalSlot(area, category, categories, horizontal)
|
||||
if slot.width <= 0.0 || slot.height <= 0.0 { return Rectangle.{} }
|
||||
a := ChartClamp(start, domain)
|
||||
b := ChartClamp(finish, domain)
|
||||
low := ifx a < b then a else b
|
||||
high := ifx a > b then a else b
|
||||
cross := ifx horizontal then slot.height else slot.width
|
||||
step := 0.8 * cross / cast(float32)series_count
|
||||
offset := cross * 0.1 + step * (cast(float32)series + 0.08)
|
||||
width := step * 0.84
|
||||
if horizontal {
|
||||
x := ChartXPosition(area, domain, low)
|
||||
return Rectangle.{x, slot.y + offset, ChartXPosition(area, domain, high) - x, width}
|
||||
}
|
||||
y := ChartYPosition(area, domain, high)
|
||||
return Rectangle.{slot.x + offset, y, width, ChartYPosition(area, domain, low) - y}
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
ChartPickBar :: (view: ChartFrame, mark: Rectangle, zero: bool, horizontal: bool) -> bool {
|
||||
if !view.pointed || !ChartInside(view.plot, view.mouse.x, view.mouse.y) { return false }
|
||||
if zero {
|
||||
if horizontal { mark.x -= 3.0; mark.width = 6.0 }
|
||||
else { mark.y -= 3.0; mark.height = 6.0 }
|
||||
}
|
||||
return ChartInside(mark, view.mouse.x, view.mouse.y)
|
||||
}
|
||||
|
||||
ChartPaintBar :: (session: Session, view: ChartFrame, mark: Rectangle, zero: bool,
|
||||
horizontal: bool, color: Color) {
|
||||
if zero {
|
||||
if horizontal { mark.x -= 0.5; mark.width = 1.0 }
|
||||
else { mark.y -= 0.5; mark.height = 1.0 }
|
||||
}
|
||||
mark = RectangleIntersection(view.plot, mark)
|
||||
if mark.width > 0.0 && mark.height > 0.0 {
|
||||
PaintRoundedFill(session, view.node, mark, 0.0, 0, color)
|
||||
}
|
||||
}
|
||||
|
||||
ChartZeroLine :: (session: Session, view: ChartFrame, domain: ChartDomain, horizontal: bool) {
|
||||
if !ChartInDomain(0.0, domain) { return }
|
||||
if horizontal {
|
||||
x := ChartXPosition(view.plot, domain, 0.0)
|
||||
PaintLine(session, view.node, Rectangle.{x, view.plot.y, 0.0, view.plot.height}, view.text)
|
||||
} else {
|
||||
y := ChartYPosition(view.plot, domain, 0.0)
|
||||
PaintLine(session, view.node, Rectangle.{view.plot.x, y, view.plot.width, 0.0}, view.text)
|
||||
}
|
||||
}
|
||||
|
||||
ChartCategory :: (session: Session, view: ChartFrame, label: string, index: s64, count: s64,
|
||||
horizontal: bool) {
|
||||
if !horizontal && view.props.hide_x_axis { return }
|
||||
slot := CategoricalSlot(view.plot, index, count, horizontal)
|
||||
if horizontal {
|
||||
y := slot.y + (slot.height - 13.0) * 0.5
|
||||
clip := Rectangle.{view.bounds.x, slot.y, view.plot.x - view.bounds.x - 4.0, slot.height}
|
||||
ChartText(session, view, label, view.bounds.x + 8.0, y, 11, clip)
|
||||
} else {
|
||||
ChartCenteredText(session, view, label, slot.x + slot.width * 0.5,
|
||||
view.plot.y + view.plot.height + 5.0, slot.width - 3.0)
|
||||
}
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
#program_export
|
||||
BarChart :: (session: Session, props: ChartProps, categories: []string, series: []BarSeries) -> ChartHit {
|
||||
left: float32 = 78.0
|
||||
if props.horizontal {
|
||||
left = props.bounds.width * 0.31
|
||||
if left > 190.0 { left = 190.0 }
|
||||
}
|
||||
view := ChartStart(session, props, left)
|
||||
cursor := Vector2.{view.bounds.x + 10.0, view.plot.y - 2.0}
|
||||
for i: 0..series.count-1 {
|
||||
ChartLegendItem(session, *view, *cursor, series[i].name, ChartColor(view, series[i].color, i))
|
||||
}
|
||||
hit := ChartNoHit()
|
||||
if view.plot.width <= 0.0 || view.plot.height <= 0.0 { return hit }
|
||||
domain := BarChartDomain(props, categories.count, series)
|
||||
ChartAxes(session, view, domain, props.horizontal)
|
||||
ChartZeroLine(session, view, domain, props.horizontal)
|
||||
has_data := false
|
||||
for category: 0..categories.count-1 {
|
||||
ChartCategory(session, view, categories[category], category, categories.count, props.horizontal)
|
||||
for i: 0..series.count-1 {
|
||||
item := series[i]
|
||||
if category >= item.values.count { continue }
|
||||
value := item.values[category]
|
||||
if value.missing || !Finite.Finite64(value.value) { continue }
|
||||
has_data = true
|
||||
mark := ChartBarBounds(view.plot, domain, category, categories.count, i, series.count,
|
||||
0.0, value.value, props.horizontal)
|
||||
zero := value.value == 0.0 && ChartInDomain(0.0, domain)
|
||||
ChartPaintBar(session, view, mark, zero, props.horizontal, ChartColor(view, item.color, i))
|
||||
if ChartPickBar(view, mark, zero, props.horizontal) {
|
||||
hit = .{.active = true, .index = category, .series = i,
|
||||
.x = cast(float64)category, .y = value.value}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !has_data { ChartEmpty(session, view) }
|
||||
if hit.active { ChartTipValue(session, view, categories[hit.index], series[hit.series].name, hit.y, false) }
|
||||
return hit
|
||||
}
|
||||
|
||||
#program_export
|
||||
HeatmapHit :: (area: Rectangle, cols: s64, rows: s64, cells: []ChartValue,
|
||||
x: float32, y: float32) -> ChartHit {
|
||||
if cols <= 0 || rows <= 0 || !ChartInside(area, x, y) { return ChartNoHit() }
|
||||
col := cast(s64)((x - area.x) / area.width * cast(float32)cols)
|
||||
row := cast(s64)((y - area.y) / area.height * cast(float32)rows)
|
||||
if col >= cols { col = cols - 1 }
|
||||
if row >= rows { row = rows - 1 }
|
||||
at := row * cols + col
|
||||
hit := ChartHit.{.active = true, .missing = true, .index = col, .series = row, .x = cast(float64)col}
|
||||
if at < cells.count && !cells[at].missing && Finite.Finite64(cells[at].value) {
|
||||
hit.missing = false
|
||||
hit.y = cells[at].value
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
ChartBlend :: (first: Color, last: Color, fraction: float64) -> Color {
|
||||
a := 1.0 - fraction
|
||||
return Color.{.r = cast(u8)(cast(float64)first.r * a + cast(float64)last.r * fraction),
|
||||
.g = cast(u8)(cast(float64)first.g * a + cast(float64)last.g * fraction),
|
||||
.b = cast(u8)(cast(float64)first.b * a + cast(float64)last.b * fraction),
|
||||
.a = cast(u8)(cast(float64)first.a * a + cast(float64)last.a * fraction)}
|
||||
}
|
||||
|
||||
HeatColor :: (view: ChartFrame, value: float64, span: float64) -> Color {
|
||||
if span <= 0.0 { return view.surface }
|
||||
if value < 0.0 { return ChartBlend(view.surface, view.negative, -value / span) }
|
||||
return ChartBlend(view.surface, view.positive, value / span)
|
||||
}
|
||||
|
||||
HeatLegend :: (session: Session, view: *ChartFrame, span: float64) {
|
||||
if view.props.hide_legend || view.plot.width < 100.0 || view.plot.height < 64.0 { return }
|
||||
w := view.plot.width / 2.0
|
||||
if w > 200.0 { w = 200.0 }
|
||||
x := view.plot.x + (view.plot.width - w) * 0.5
|
||||
y := view.plot.y
|
||||
for i: 0..20 {
|
||||
value := (cast(float64)i / 10.0 - 1.0) * span
|
||||
PaintRoundedFill(session, view.node, Rectangle.{x + cast(float32)i * w / 21.0,
|
||||
y, w / 21.0, 6.0}, 0.0, 0, HeatColor(view.*, value, span))
|
||||
}
|
||||
zero: Text = ChartFormat(0.0, view.props.y_unit)
|
||||
ChartCenteredText(session, view.*, zero, x + w / 2.0, y + 9.0, w / 2.0)
|
||||
if span > 0.0 {
|
||||
low: Text = ChartFormat(-span, view.props.y_unit)
|
||||
high: Text = ChartFormat(span, view.props.y_unit)
|
||||
ChartCenteredText(session, view.*, low, x, y + 9.0, w / 2.0)
|
||||
ChartCenteredText(session, view.*, high, x + w, y + 9.0, w / 2.0)
|
||||
}
|
||||
view.plot.y += 30.0
|
||||
view.plot.height -= 30.0
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
#program_export
|
||||
HeatmapChart :: (session: Session, props: ChartProps, columns: []string,
|
||||
rows: []string, cells: []ChartValue) -> ChartHit {
|
||||
view := ChartStart(session, props, 88.0)
|
||||
hit := ChartNoHit()
|
||||
if view.plot.width <= 0.0 || view.plot.height <= 0.0 { return hit }
|
||||
if columns.count == 0 || rows.count == 0 { ChartEmpty(session, view); return hit }
|
||||
span: float64 = 0.0
|
||||
count := columns.count * rows.count
|
||||
if cells.count < count { count = cells.count }
|
||||
for i: 0..count-1 {
|
||||
value := cells[i]
|
||||
if value.missing || !Finite.Finite64(value.value) { continue }
|
||||
size := ifx value.value < 0.0 then -value.value else value.value
|
||||
if size > span { span = size }
|
||||
}
|
||||
HeatLegend(session, *view, span)
|
||||
dx := view.plot.width / cast(float32)columns.count
|
||||
dy := view.plot.height / cast(float32)rows.count
|
||||
for col: 0..columns.count-1 { ChartCategory(session, view, columns[col], col, columns.count, false) }
|
||||
for row: 0..rows.count-1 {
|
||||
ChartCategory(session, view, rows[row], row, rows.count, true)
|
||||
for col: 0..columns.count-1 {
|
||||
at := row * columns.count + col
|
||||
box := Rectangle.{view.plot.x + cast(float32)col * dx,
|
||||
view.plot.y + cast(float32)row * dy, dx, dy}
|
||||
if dx > 3.0 && dy > 3.0 { box.width -= 1.0; box.height -= 1.0 }
|
||||
missing := at >= cells.count || cells[at].missing || !Finite.Finite64(cells[at].value)
|
||||
color := view.grid
|
||||
if !missing { color = HeatColor(view, cells[at].value, span) }
|
||||
PaintRoundedFill(session, view.node, box, 0.0, 0, color)
|
||||
if missing && box.width >= 7.0 && box.height >= 7.0 {
|
||||
PaintLine(session, view.node, Rectangle.{box.x + 3.0, box.y + box.height - 3.0,
|
||||
box.width - 6.0, 6.0 - box.height}, view.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
if view.pointed { hit = HeatmapHit(view.plot, columns.count, rows.count, cells, view.mouse.x, view.mouse.y) }
|
||||
if hit.active { ChartTipValue(session, view, columns[hit.index], rows[hit.series], hit.y, hit.missing) }
|
||||
return hit
|
||||
}
|
||||
|
||||
WaterfallSpan :: struct { start: float64; finish: float64; valid: bool }
|
||||
|
||||
#program_export
|
||||
WaterfallApply :: (running: float64, step: WaterfallStep) -> WaterfallSpan {
|
||||
if step.missing || !Finite.Finite64(step.value) { return WaterfallSpan.{running, running, false} }
|
||||
start := ifx step.total then 0.0 else running
|
||||
finish := start + step.value
|
||||
if !Finite.Finite64(finish) { return WaterfallSpan.{running, running, false} }
|
||||
return WaterfallSpan.{start, finish, true}
|
||||
}
|
||||
|
||||
#program_export
|
||||
WaterfallChart :: (session: Session, props: ChartProps, steps: []WaterfallStep) -> ChartHit {
|
||||
view := ChartStart(session, props, 78.0)
|
||||
hit := ChartNoHit()
|
||||
if view.plot.width <= 0.0 || view.plot.height <= 0.0 { return hit }
|
||||
observed := ChartDomain.{0.0, 0.0, true}
|
||||
running: float64 = 0.0
|
||||
has_data := false
|
||||
for step: steps {
|
||||
span := WaterfallApply(running, step)
|
||||
running = span.finish
|
||||
if span.valid { has_data = true; ChartDomainInclude(*observed, running) }
|
||||
}
|
||||
domain := ChartDomainResolve(observed, props.y_min, props.y_max)
|
||||
ChartAxes(session, view, domain)
|
||||
ChartZeroLine(session, view, domain, false)
|
||||
running = 0.0
|
||||
previous := Rectangle.{}
|
||||
connect := false
|
||||
for index: 0..steps.count-1 {
|
||||
step := steps[index]
|
||||
ChartCategory(session, view, step.label, index, steps.count, false)
|
||||
span := WaterfallApply(running, step)
|
||||
running = span.finish
|
||||
if !span.valid { connect = false; continue }
|
||||
mark := ChartBarBounds(view.plot, domain, index, steps.count, 0, 1, span.start, span.finish)
|
||||
if connect && !step.total && ChartInDomain(span.start, domain) {
|
||||
y := ChartYPosition(view.plot, domain, span.start)
|
||||
edge := previous.x + previous.width
|
||||
PaintLine(session, view.node, Rectangle.{edge, y, mark.x - edge, 0.0}, view.text)
|
||||
}
|
||||
color := ifx step.value < 0.0 then view.negative else view.positive
|
||||
if step.total { color = view.accent }
|
||||
zero := span.start == span.finish && ChartInDomain(span.start, domain)
|
||||
ChartPaintBar(session, view, mark, zero, false, color)
|
||||
if ChartPickBar(view, mark, zero, false) {
|
||||
hit = .{.active = true, .index = index, .series = 0, .x = cast(float64)index, .y = step.value}
|
||||
}
|
||||
previous = mark
|
||||
connect = true
|
||||
}
|
||||
if !has_data { ChartEmpty(session, view) }
|
||||
if hit.active {
|
||||
step := steps[hit.index]
|
||||
ChartTipValue(session, view, step.label, ifx step.total then "Total" else "Change", hit.y, false)
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
TimeCandleValid :: (bar: Candle.PriceBar64) -> bool {
|
||||
return Finite.Finite64(bar.open) && Finite.Finite64(bar.close) &&
|
||||
Finite.Finite64(bar.high) && Finite.Finite64(bar.low) && bar.high >= bar.low &&
|
||||
bar.open >= bar.low && bar.open <= bar.high && bar.close >= bar.low && bar.close <= bar.high
|
||||
}
|
||||
|
||||
TimeCandleTip :: (session: Session, view: ChartFrame, domain: ChartDomain, bar: Candle.PriceBar64) {
|
||||
if view.props.hide_tooltip { return }
|
||||
date: Text = ChartXText(view, domain, cast(float64)bar.timestamp, true)
|
||||
x := ChartXPosition(view.plot, domain, cast(float64)bar.timestamp) + 9.0
|
||||
ChartTooltip(session, view, x, view.plot.y + 5.0, date)
|
||||
labels: [4]string = .{"Open", "High", "Low", "Close"}
|
||||
values: [4]float64 = .{bar.open, bar.high, bar.low, bar.close}
|
||||
for i: 0..3 {
|
||||
y := view.plot.y + 28.0 + cast(float32)i * 23.0
|
||||
if y + 23.0 > view.clip.y + view.clip.height { break }
|
||||
value: Text = ChartFormat(values[i], view.props.y_unit)
|
||||
out := Vec(u8).{}
|
||||
BuilderPrint(*out, "% · %", labels[i], TextView(value))
|
||||
tip: Text = BuilderFinish(out)
|
||||
ChartTooltip(session, view, x, y, tip)
|
||||
}
|
||||
}
|
||||
|
||||
ChartResolveX :: (domain: ChartDomain, props: ChartProps) -> ChartDomain {
|
||||
if props.date_x && domain.valid && domain.low == domain.high && !(props.x_min < props.x_max) {
|
||||
return ChartDomain.{domain.low - 0.5, domain.high + 0.5, true}
|
||||
}
|
||||
return ChartDomainResolve(domain, props.x_min, props.x_max)
|
||||
}
|
||||
|
||||
TimeCandleAt :: (bars: []Candle.PriceBar64, legacy: []Candle.PriceBar, index: s64) -> Candle.PriceBar64 {
|
||||
if index < bars.count { return bars[index] }
|
||||
bar := legacy[index - bars.count]
|
||||
return Candle.PriceBar64.{.timestamp = bar.timestamp, .open = cast(float64)bar.open,
|
||||
.high = cast(float64)bar.high, .low = cast(float64)bar.low, .close = cast(float64)bar.close}
|
||||
}
|
||||
|
||||
DrawTimeCandles :: (session: Session, props: ChartProps, bars: []Candle.PriceBar64,
|
||||
legacy: []Candle.PriceBar) -> ChartHit {
|
||||
props.date_x = true
|
||||
view := ChartStart(session, props, 78.0)
|
||||
hit := ChartNoHit()
|
||||
if view.plot.width <= 0.0 || view.plot.height <= 0.0 { return hit }
|
||||
domains: XYDomains
|
||||
count := bars.count + legacy.count
|
||||
for i: 0..count-1 {
|
||||
bar := TimeCandleAt(bars, legacy, i)
|
||||
ChartDomainInclude(*domains.x, cast(float64)bar.timestamp)
|
||||
if !TimeCandleValid(bar) { continue }
|
||||
ChartDomainInclude(*domains.y, bar.low)
|
||||
ChartDomainInclude(*domains.y, bar.high)
|
||||
}
|
||||
domains.x = ChartResolveX(domains.x, props)
|
||||
domains.y = ChartDomainResolve(domains.y, props.y_min, props.y_max)
|
||||
ChartAxes(session, view, domains.y)
|
||||
ChartTimeAxis(session, view, domains.x)
|
||||
if count == 0 || !domains.y.valid || !domains.x.valid { ChartEmpty(session, view); return hit }
|
||||
width := view.plot.width / cast(float32)count * 0.62
|
||||
if width > 13.0 { width = 13.0 }
|
||||
if width < 1.0 { width = 1.0 }
|
||||
pick := view.pointed && ChartInside(view.plot, view.mouse.x, view.mouse.y)
|
||||
nearest := view.plot.width + 1.0
|
||||
has_data := false
|
||||
for i: 0..count-1 {
|
||||
bar := TimeCandleAt(bars, legacy, i)
|
||||
timestamp := cast(float64)bar.timestamp
|
||||
if !TimeCandleValid(bar) || !ChartInDomain(timestamp, domains.x) ||
|
||||
bar.low > domains.y.high || bar.high < domains.y.low { continue }
|
||||
has_data = true
|
||||
x := ChartXPosition(view.plot, domains.x, timestamp)
|
||||
color := ifx bar.close < bar.open then view.negative else view.positive
|
||||
low := ChartYPosition(view.plot, domains.y, ChartClamp(bar.low, domains.y))
|
||||
high := ChartYPosition(view.plot, domains.y, ChartClamp(bar.high, domains.y))
|
||||
PaintLine(session, view.node, Rectangle.{x, high, 0.0, low - high}, color)
|
||||
lower := ifx bar.open < bar.close then bar.open else bar.close
|
||||
upper := ifx bar.open > bar.close then bar.open else bar.close
|
||||
bottom := ChartYPosition(view.plot, domains.y, ChartClamp(lower, domains.y))
|
||||
top := ChartYPosition(view.plot, domains.y, ChartClamp(upper, domains.y))
|
||||
if bottom - top < 1.0 { top -= 0.5; bottom += 0.5 }
|
||||
if upper >= domains.y.low && lower <= domains.y.high {
|
||||
body := RectangleIntersection(view.plot, Rectangle.{x - width / 2.0, top, width, bottom - top})
|
||||
PaintRoundedFill(session, view.node, body, 0.0, 0, color)
|
||||
}
|
||||
distance := view.mouse.x - x
|
||||
if distance < 0.0 { distance = -distance }
|
||||
if pick && distance < nearest {
|
||||
nearest = distance
|
||||
hit = .{.active = true, .index = i, .series = 0, .x = timestamp, .y = bar.close}
|
||||
}
|
||||
}
|
||||
if !has_data { ChartEmpty(session, view) }
|
||||
if props.link_hover && ChartInDomain(props.hover_x, domains.x) {
|
||||
ChartCrosshair(session, view, domains.x, props.hover_x)
|
||||
if !props.hide_tooltip {
|
||||
for i: 0..count-1 {
|
||||
bar := TimeCandleAt(bars, legacy, i)
|
||||
if cast(float64)bar.timestamp == props.hover_x && TimeCandleValid(bar) {
|
||||
TimeCandleTip(session, view, domains.x, bar)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if hit.active {
|
||||
ChartCrosshair(session, view, domains.x, hit.x)
|
||||
TimeCandleTip(session, view, domains.x, TimeCandleAt(bars, legacy, hit.index))
|
||||
}
|
||||
return hit
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
// Chronological OHLC panes align with XYChart using the same left edge,
|
||||
// width and x range. Supply the active pane's hit.x to peers.
|
||||
#program_export
|
||||
TimeCandleChart :: (session: Session, props: ChartProps, bars: []Candle.PriceBar) -> ChartHit {
|
||||
empty: []Candle.PriceBar64
|
||||
return DrawTimeCandles(session, props, empty, bars)
|
||||
}
|
||||
|
||||
#program_export
|
||||
TimeCandleChart64 :: (session: Session, props: ChartProps, bars: []Candle.PriceBar64) -> ChartHit {
|
||||
empty: []Candle.PriceBar
|
||||
return DrawTimeCandles(session, props, bars, empty)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Plot :: #import "Plot";
|
||||
using Surface :: #import "PlotWidget";
|
||||
Math :: #import "std/math";
|
||||
#import "kryon/geometry"
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
area := Rectangle.{10.0, 20.0, 400.0, 200.0}
|
||||
selection: [4]Plot.XYPointValue = .{.{0.0, 100.0, false}, .{1.0, 104.0, false},
|
||||
.{6.0, 0.0, true}, .{8.0, 110.37, false}}
|
||||
benchmark: [2]Plot.XYPointValue = .{.{0.0, 100.0, false}, .{8.0, 293.58, false}}
|
||||
series: [2]Plot.XYSeries = .{.{.name = "Selected", .points = selection[:]},
|
||||
.{.name = "Buy and hold", .points = benchmark[:]}}
|
||||
shared := Plot.XYChartDomains(.{}, series[:])
|
||||
focus := Surface.XYChartDomains(.{}, series[0:1])
|
||||
if shared.y.low != 100.0 || shared.y.high != 293.58 || focus.y.high != 110.37 { return 1 }
|
||||
if Plot.ChartXPosition(area, shared.x, 1.0) != 60.0 { return 2 }
|
||||
hit := Plot.XYChartHit(area, shared, series[:], 60.0, 216.0)
|
||||
if !hit.active || hit.series != 0 || hit.index != 1 || hit.x != 1.0 || hit.y != 104.0 { return 3 }
|
||||
linked := Plot.XYChartHit(area, shared, series[:], 310.0, 216.0, true)
|
||||
if linked.active || linked.index != -1 { return 4 }
|
||||
invalid: [3]Plot.XYPointValue = .{selection[0], .{1.0, Math.NotANumber(), false}, .{8.0, Math.Infinity(), false}}
|
||||
invalid_series: [1]Plot.XYSeries = .{.{.points = invalid[:]}}
|
||||
focus = Plot.XYChartDomains(.{}, invalid_series[:])
|
||||
if focus.y.low != 98.0 || focus.y.high != 102.0 { return 5 }
|
||||
if Plot.XYChartHit(area, focus, series[0:1], 60.0, 19.0).active { return 6 }
|
||||
one := Plot.XYChartDomains(.{}, series[0:0])
|
||||
if one.x.valid || one.y.valid { return 7 }
|
||||
single: [1]Plot.XYSeries = .{.{.points = selection[0:1], .mark = .XYPoint}}
|
||||
one = Plot.XYChartDomains(.{.date_x = true}, single[:])
|
||||
if one.x.low != -0.5 || one.x.high != 0.5 { return 8 }
|
||||
if !Plot.XYChartHit(area, one, single[:], 210.0, 120.0).active { return 9 }
|
||||
if Plot.XYChartHit(area, one, single[:], 210.0, 160.0).active { return 10 }
|
||||
|
||||
good: [1]Plot.ChartValue = .{.{10.37, false}}
|
||||
bad: [2]Plot.ChartValue = .{.{-64.2, false}, .{500.0, true}}
|
||||
groups: [2]Plot.BarSeries = .{.{.values = good[:]}, .{.values = bad[:]}}
|
||||
domain := Plot.BarChartDomain(.{}, 2, groups[:])
|
||||
if domain.low != -64.2 || domain.high != 10.37 { return 11 }
|
||||
rising := Plot.ChartBarBounds(area, domain, 0, 2, 0, 2, 0.0, 10.37)
|
||||
falling := Plot.ChartBarBounds(area, domain, 0, 2, 1, 2, 0.0, -64.2)
|
||||
if rising.y != area.y || rising.y + rising.height != falling.y ||
|
||||
rising.x + rising.width >= falling.x || falling.y + falling.height != 220.0 { return 12 }
|
||||
side := Plot.ChartBarBounds(area, domain, 0, 2, 1, 2, 0.0, -64.2, true)
|
||||
if side.x != area.x || side.width <= 0.0 || side.height <= 0.0 { return 13 }
|
||||
pp: Text = Plot.ChartFormat(good[0].value - bad[0].value, "pp")
|
||||
if TextView(pp) != "74.57 pp" { return 14 }
|
||||
compact: Text = Plot.ChartFormat(-1550021.0, "USD")
|
||||
if TextView(compact) != "-1.55M USD" { return 15 }
|
||||
percentage: Text = Plot.ChartFormat(10.37, "%")
|
||||
if TextView(percentage) != "10.37%" { return 16 }
|
||||
unavailable: Text = Plot.ChartFormat(invalid[1].y)
|
||||
if TextView(unavailable) != "No data" { return 17 }
|
||||
|
||||
matrix: [3]Plot.ChartValue = .{.{0.0, false}, .{0.0, true}, .{-7.15, false}}
|
||||
zero := Plot.HeatmapHit(area, 2, 2, matrix[:], 150.0, 60.0)
|
||||
hole := Plot.HeatmapHit(area, 2, 2, matrix[:], 300.0, 60.0)
|
||||
red := Plot.HeatmapHit(area, 2, 2, matrix[:], 150.0, 175.0)
|
||||
tail := Plot.HeatmapHit(area, 2, 2, matrix[:], 410.0, 220.0)
|
||||
if !zero.active || zero.missing || !hole.active || !hole.missing ||
|
||||
red.series != 1 || red.index != 0 || red.y != -7.15 || !tail.missing { return 18 }
|
||||
|
||||
start := Plot.WaterfallApply(4.0, .{"Start", 20.0, true, false})
|
||||
drop := Plot.WaterfallApply(start.finish, .{"Expenses", -25.0, false, false})
|
||||
gap := Plot.WaterfallApply(drop.finish, .{"Missing", 100.0, false, true})
|
||||
total := Plot.WaterfallApply(gap.finish, .{"Total", 8.0, true, false})
|
||||
if start.start != 0.0 || drop.start != 20.0 || drop.finish != -5.0 ||
|
||||
gap.valid || gap.finish != -5.0 || total.start != 0.0 || total.finish != 8.0 { return 19 }
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Drive the cookbook's native and ZX windows on a private X display."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from PIL import Image, ImageChops
|
||||
|
||||
|
||||
OUTPUT = Path("build/dashboard-render").resolve()
|
||||
HEIGHT = 840
|
||||
|
||||
|
||||
def render(command, profile):
|
||||
with (OUTPUT / f"{profile}.log").open("wb") as log:
|
||||
app = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
try:
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline and app.poll() is None:
|
||||
window = subprocess.run(
|
||||
["xdotool", "search", "--onlyvisible", "--name", "^plot$"],
|
||||
capture_output=True, text=True, timeout=3,
|
||||
).stdout.splitlines()
|
||||
if window:
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise AssertionError(f"{profile} window did not open; see {log.name}")
|
||||
window = window[0]
|
||||
subprocess.run(["xdotool", "windowmove", window, "0", "0"], check=True, timeout=5)
|
||||
|
||||
def move(x, y):
|
||||
subprocess.run(["xdotool", "mousemove", "--window", window, str(x), str(y)],
|
||||
check=True, timeout=5)
|
||||
|
||||
def capture(name):
|
||||
path = OUTPUT / f"{profile}-{name}.png"
|
||||
subprocess.run(["import", "-window", window, "PNG32:" + str(path)], check=True, timeout=5)
|
||||
with Image.open(path) as image:
|
||||
return image.convert("RGB")
|
||||
|
||||
for width in (550, 1200):
|
||||
subprocess.run(["xdotool", "windowsize", "--sync", window, str(width), str(HEIGHT)],
|
||||
check=True, timeout=5)
|
||||
move(3, 3)
|
||||
time.sleep(0.6)
|
||||
before = capture(str(width))
|
||||
assert before.size == (width, HEIGHT), (profile, before.size)
|
||||
card_width = (width - 36) / 2
|
||||
card_height = (HEIGHT - 54) / 4
|
||||
# The second series uses the fallback amber color. Its down-year
|
||||
# bars are solid, so this counts painted pixels, not antialiasing.
|
||||
returns = before.crop((90, 270, int(card_width), 375))
|
||||
colors = {color: count for count, color in returns.getcolors(returns.width * returns.height)}
|
||||
assert colors.get((227, 154, 67), 0) > 100, profile
|
||||
# The actual strategy/benchmark hover must change the card raster.
|
||||
move(125, 130)
|
||||
time.sleep(0.5)
|
||||
hovered = capture(f"{width}-hover")
|
||||
changed = ImageChops.difference(before, hovered).getbbox()
|
||||
assert changed and changed[0] >= 12 and changed[2] <= card_width + 13, (profile, changed)
|
||||
# Moving into OHLC changes the peer pane as well via linked x.
|
||||
move(125, int(9 + 3 * (card_height + 12) + 86))
|
||||
time.sleep(0.5)
|
||||
linked = capture(f"{width}-linked")
|
||||
peer = (int(card_width) + 25, 668, width - 12, 825)
|
||||
assert ImageChops.difference(before.crop(peer), linked.crop(peer)).getbbox(), (profile, width)
|
||||
print(f"{profile}: {width}px native raster, grouped bars, shared hover and linked hover")
|
||||
finally:
|
||||
if app.poll() is None:
|
||||
os.killpg(app.pid, signal.SIGTERM)
|
||||
try:
|
||||
app.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(app.pid, signal.SIGKILL)
|
||||
app.wait(timeout=8)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) == 2:
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
env = os.environ.copy()
|
||||
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "ICEAUTHORITY",
|
||||
"DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER", "DESKTOP_SESSION",
|
||||
"XDG_SESSION_ID", "XDG_SESSION_TYPE", "KRYON_TEST_DRIVER"):
|
||||
env.pop(key, None)
|
||||
env.update(HARMONY_DESKTOP_RECOVERY="0", YUE_DESKTOP_RECOVERY="0", SDL_VIDEODRIVER="x11")
|
||||
return subprocess.run(
|
||||
["xvfb-run", "-a", "-s", "-screen 0 1280x1024x24", sys.executable,
|
||||
__file__, sys.argv[1], "--private"], env=env, timeout=310,
|
||||
).returncode
|
||||
assert sys.argv[2:] == ["--private"] and os.environ["HARMONY_DESKTOP_RECOVERY"] == "0"
|
||||
render([str(Path("build/plot-cairo").resolve())], "cairo")
|
||||
render([sys.argv[1], "tool", "kryon", "run", "--profile", "portable"], "zx")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+11
-11
@@ -46,15 +46,6 @@
|
||||
"ref": "f5f186bb13569ef13338f81366ff63fb9b9282f6",
|
||||
"url": "https://github.com/ziranlang/avif.git"
|
||||
},
|
||||
{
|
||||
"commit": "9ea1567980771a061e7a9f78d7ab8b660e20bcf9",
|
||||
"dependencies": {"audio": "p59deb49c7f103127", "avif": "p3ed49c5d0912e411", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
|
||||
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "f5f186bb13569ef13338f81366ff63fb9b9282f6", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
|
||||
"id": "p439f82a30e97c7fa",
|
||||
"name": "kryon",
|
||||
"ref": "9ea1567980771a061e7a9f78d7ab8b660e20bcf9",
|
||||
"url": "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
},
|
||||
{
|
||||
"commit": "1aadfad932c98c069a1204261b1856f81f3bc199",
|
||||
"dependencies": {},
|
||||
@@ -108,6 +99,15 @@
|
||||
"source": true,
|
||||
"url": "https://github.com/videolan/dav1d.git"
|
||||
},
|
||||
{
|
||||
"commit": "facaace35051336a2a993d90d1bb7d7396543852",
|
||||
"dependencies": {"audio": "p59deb49c7f103127", "avif": "p3ed49c5d0912e411", "image_codec": "p69c0e968ae5735d9", "libaom": "p74ab3cb6eb3b86fa", "libavif": "p57c0272208aae8db", "libwebp": "p3b3c785a0e17e605", "sdl3": "p16cd0434af3dff7b", "webp": "p2af20e0c835b1c63"},
|
||||
"dependency_refs": {"audio": "1b2f35b7b39df6fb9af7a52324b4b7cf18e98df2", "avif": "f5f186bb13569ef13338f81366ff63fb9b9282f6", "image_codec": "360553150917f352e49e1beb78917370792ccaef", "libaom": "b141d9c45db236335351c8a4b2a14b3ade27c937", "libavif": "1aadfad932c98c069a1204261b1856f81f3bc199", "libwebp": "1844042d1ca751e62e61df7617dba19c98588339", "sdl3": "829a65d769d935c4852f8159e964312c0957260a", "webp": "ec6ed304767e10c125ab2820f3b01d6fd773e147"},
|
||||
"id": "pd2c26aeaec4cd5b9",
|
||||
"name": "kryon",
|
||||
"ref": "facaace35051336a2a993d90d1bb7d7396543852",
|
||||
"url": "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
},
|
||||
{
|
||||
"commit": "ddbe48383984d56acd9e1ab6a090c54ca6b735a6",
|
||||
"dependencies": {},
|
||||
@@ -119,8 +119,8 @@
|
||||
}
|
||||
],
|
||||
"root": {
|
||||
"dependencies": {"kryon": "p439f82a30e97c7fa"},
|
||||
"dependency_refs": {"kryon": "9ea1567980771a061e7a9f78d7ab8b660e20bcf9"},
|
||||
"dependencies": {"kryon": "pd2c26aeaec4cd5b9"},
|
||||
"dependency_refs": {"kryon": "facaace35051336a2a993d90d1bb7d7396543852"},
|
||||
"name": "plot"
|
||||
},
|
||||
"toolchain": {
|
||||
|
||||
+6
-2
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "plot"
|
||||
entry = "src/app.zi"
|
||||
module_roots = ["src", "tests"]
|
||||
module_roots = ["src", "examples", "tests"]
|
||||
bridge_modules = ["app"]
|
||||
|
||||
[toolchain]
|
||||
@@ -10,7 +10,7 @@ ref = "9432a110709c4a4f72c4f732fcfc368e15213a54"
|
||||
|
||||
[dependencies.kryon]
|
||||
git = "https://git.waozi.xyz/kryonlabs/kryon.git"
|
||||
ref = "9ea1567980771a061e7a9f78d7ab8b660e20bcf9"
|
||||
ref = "facaace35051336a2a993d90d1bb7d7396543852"
|
||||
|
||||
[exports]
|
||||
# Public module is Plot; the lowercase export is retained for older imports.
|
||||
@@ -28,3 +28,7 @@ default_profile = "cairo"
|
||||
|
||||
[tool.kryon.profiles.cairo]
|
||||
backend = "desktop"
|
||||
|
||||
[tool.kryon.profiles.portable]
|
||||
backend = "desktop"
|
||||
codegen = "zx"
|
||||
Reference in new issue
Block a user