sealed-surface 0.2.0

Non-extractable data surface: tables and timeseries as glyphs, never DOM text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Timeseries layout on the sealed painter (no JS series, no SVG text).

use crate::error::Error;
use crate::host::{ClipboardPayload, HostProjection, HostText};
use crate::layout::{CellBox, HitKind, HitMap, MAX_PIXMAP_AXIS, PAD};
use crate::model::{CellValue, Column, ColumnId, Grid, Row, RowId};
use crate::raster::Pixmap;
use crate::surface::{Frame, FrameRequest, Surface};

/// Identifier for a series. Opaque to the host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SeriesId(pub u32);

/// One sample. `x` is the independent axis (time or category index).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SeriesPoint {
    /// Independent axis.
    pub x: f64,
    /// Dependent axis.
    pub y: f64,
}

impl SeriesPoint {
    /// Construct.
    #[must_use]
    pub const fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}

/// Named polyline.
#[derive(Debug, Clone, PartialEq)]
pub struct Series {
    /// Opaque id.
    pub id: SeriesId,
    /// Legend / schema label. Painted as glyphs. Not a datum in sealed host text.
    pub name: String,
    /// Samples in x order (caller should sort).
    pub points: Vec<SeriesPoint>,
}

impl Series {
    /// Construct.
    #[must_use]
    pub fn new(id: u32, name: impl Into<String>, points: Vec<SeriesPoint>) -> Self {
        Self {
            id: SeriesId(id),
            name: name.into(),
            points,
        }
    }
}

/// Timeseries chart. Scatter/treemap stay [`Error::UnsupportedLayout`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SeriesLayout {
    series: Vec<Series>,
}

impl SeriesLayout {
    /// Empty layout.
    #[must_use]
    pub fn new() -> Self {
        Self { series: Vec::new() }
    }

    /// One or more series.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidGrid`] when `series` is empty.
    pub fn try_new(series: Vec<Series>) -> Result<Self, Error> {
        if series.is_empty() {
            return Err(Error::InvalidGrid("at least one series is required"));
        }
        Ok(Self { series })
    }

    /// Series as supplied (pre-lens).
    #[must_use]
    pub fn series(&self) -> &[Series] {
        &self.series
    }

    /// Paint a timeseries on `surface` (same PNG / host contract as tables).
    ///
    /// # Errors
    ///
    /// Raster failure or empty layout.
    pub fn render(&self, surface: &Surface, request: &FrameRequest) -> Result<Frame, Error> {
        surface.render_series(self, request)
    }

    /// Reserved. Scatter is 0.3.
    ///
    /// # Errors
    ///
    /// Always [`Error::UnsupportedLayout`].
    pub fn render_scatter(
        &self,
        _surface: &Surface,
        _request: &FrameRequest,
    ) -> Result<Frame, Error> {
        Err(Error::UnsupportedLayout("scatter"))
    }
}

pub(crate) fn render_timeseries(
    surface: &Surface,
    layout: &SeriesLayout,
    request: &FrameRequest,
) -> Result<Frame, Error> {
    if layout.series.is_empty() {
        return Err(Error::InvalidGrid("at least one series is required"));
    }
    let viewed_series = surface.lens().apply_series(&layout.series);
    let placeholder = surface.lens().style.glyph_str();
    let theme = surface.theme();

    let vp = request.viewport;
    let pixmap_w = vp.width.clamp(1, MAX_PIXMAP_AXIS);
    let pixmap_h = vp.height.clamp(1, MAX_PIXMAP_AXIS);
    let mut pm = Pixmap::new(pixmap_w, pixmap_h, theme.background)?;

    let left = 52u32;
    let right = 10u32;
    let top: u32 = if request.caption.is_some() { 18 } else { 10 };
    let bottom = 22u32;
    let plot_x0 = left;
    let plot_y0 = top;
    let plot_w = pixmap_w.saturating_sub(left.saturating_add(right)).max(8);
    let plot_h = pixmap_h.saturating_sub(top.saturating_add(bottom)).max(8);

    if let Some(caption) = &request.caption {
        pm.text(PAD, 4, caption, theme.accent, pixmap_w.saturating_sub(PAD));
    }

    let (xmin, xmax, ymin, ymax) = bounds(&viewed_series);
    let xticks = axis_ticks(xmin, xmax, 5);
    let yticks = axis_ticks(ymin, ymax, 5);

    pm.fill_rect(plot_x0, plot_y0, plot_w, plot_h, theme.header);
    pm.hline(plot_x0, plot_y0, plot_w, theme.grid);
    pm.hline(
        plot_x0,
        plot_y0.saturating_add(plot_h.saturating_sub(1)),
        plot_w,
        theme.grid,
    );
    pm.vline(plot_x0, plot_y0, plot_h, theme.grid);
    pm.vline(
        plot_x0.saturating_add(plot_w.saturating_sub(1)),
        plot_y0,
        plot_h,
        theme.grid,
    );

    let mut buf = String::with_capacity(16);
    let mut boxes = Vec::new();

    for (i, t) in yticks.iter().enumerate() {
        let py = map_y(*t, ymin, ymax, plot_y0, plot_h);
        pm.hline(plot_x0, py, plot_w, theme.grid);
        buf.clear();
        fmt_num(*t, &mut buf);
        let tw = crate::font::measure(&buf).saturating_add(4);
        let tx = plot_x0.saturating_sub(tw.min(plot_x0));
        pm.text(tx, py.saturating_sub(3), &buf, theme.text, tw);
        boxes.push(CellBox {
            row_index: None,
            col_index: i as u32,
            row: RowId(0),
            col: ColumnId(i as u32),
            x: tx,
            y: py.saturating_sub(4),
            w: tw.max(8),
            h: 12,
            header: false,
            kind: HitKind::TickY,
        });
    }
    for (i, t) in xticks.iter().enumerate() {
        let px = map_x(*t, xmin, xmax, plot_x0, plot_w);
        pm.vline(px, plot_y0, plot_h, theme.grid);
        buf.clear();
        fmt_num(*t, &mut buf);
        let tw = crate::font::measure(&buf).saturating_add(2);
        let ty = plot_y0.saturating_add(plot_h).saturating_add(4);
        pm.text(px.saturating_sub(tw / 2), ty, &buf, theme.text, tw);
        boxes.push(CellBox {
            row_index: None,
            col_index: i as u32,
            row: RowId(0),
            col: ColumnId(i as u32),
            x: px.saturating_sub(tw / 2),
            y: ty,
            w: tw.max(8),
            h: 10,
            header: false,
            kind: HitKind::TickX,
        });
    }

    let palette = [theme.series, theme.accent, theme.crosshair];
    for (si, series) in viewed_series.iter().enumerate() {
        let color = palette[si % palette.len()];
        let mut prev: Option<(i32, i32)> = None;
        for (pi, pt) in series.points.iter().enumerate() {
            let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
            let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
            let xi = px as i32;
            let yi = py as i32;
            if let Some((ax, ay)) = prev {
                pm.line(ax, ay, xi, yi, color);
            }
            prev = Some((xi, yi));
            let hit_w = 6u32;
            boxes.push(CellBox {
                row_index: Some(pi as u32),
                col_index: si as u32,
                row: RowId(pi as u32),
                col: ColumnId(series.id.0),
                x: px.saturating_sub(hit_w / 2),
                y: py.saturating_sub(hit_w / 2),
                w: hit_w,
                h: hit_w,
                header: false,
                kind: HitKind::Sample,
            });
        }
        let legend_y = plot_y0.saturating_add(4);
        let legend_x = plot_x0
            .saturating_add(6)
            .saturating_add((si as u32).saturating_mul(80));
        pm.fill_rect(legend_x, legend_y, 8, 4, color);
        pm.text(
            legend_x.saturating_add(12),
            legend_y.saturating_sub(1),
            &series.name,
            theme.text,
            70,
        );
    }

    let mut nearest: Option<(usize, usize, u32, u32, f64)> = None;
    if let Some(p) = request.pointer {
        if p.x >= plot_x0 && p.y >= plot_y0 && p.x < plot_x0 + plot_w && p.y < plot_y0 + plot_h {
            for (si, series) in viewed_series.iter().enumerate() {
                for (pi, pt) in series.points.iter().enumerate() {
                    let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
                    let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
                    let dx = i64::from(p.x) - i64::from(px);
                    let dy = i64::from(p.y) - i64::from(py);
                    let d2 = (dx * dx + dy * dy) as f64;
                    let better = match nearest {
                        None => true,
                        Some((_, _, _, _, best)) => d2 < best,
                    };
                    if better {
                        nearest = Some((si, pi, px, py, d2));
                    }
                }
            }
        }
    }

    if let Some((_, _, px, py, _)) = nearest {
        pm.vline(px, plot_y0, plot_h, theme.crosshair);
        pm.hline(plot_x0, py, plot_w, theme.crosshair);
        pm.fill_rect(
            px.saturating_sub(2),
            py.saturating_sub(2),
            5,
            5,
            theme.crosshair,
        );
    }

    let hits = HitMap { boxes };
    let tooltip_png = match (request.pointer, nearest) {
        (Some(_), Some((si, pi, _, _, _))) => {
            series_tooltip(&viewed_series, si, pi, placeholder, theme)?
        }
        _ => None,
    };

    let viewed = series_to_grid(&viewed_series)?;
    let n = viewed.rows.len() as u32;
    let host = series_host(surface, request, &viewed_series);

    let png = pm.to_png()?;
    Ok(Frame {
        png,
        hits,
        host,
        tooltip_png,
        viewed,
        content_width: pixmap_w,
        content_height: pixmap_h,
        visible_row_start: 0,
        visible_row_end: n,
    })
}

fn series_tooltip(
    series: &[Series],
    si: usize,
    pi: usize,
    placeholder: &str,
    theme: crate::theme::Theme,
) -> Result<Option<Vec<u8>>, Error> {
    let Some(s) = series.get(si) else {
        return Ok(None);
    };
    let Some(pt) = s.points.get(pi) else {
        return Ok(None);
    };
    let mut label = String::new();
    label.push_str(&s.name);
    label.push_str(": ");
    fmt_num(pt.y, &mut label);
    if s.points.is_empty() {
        label.push_str(placeholder);
    }
    let tw = crate::font::measure(&label).saturating_add(16).max(48);
    let mut pm = Pixmap::new(tw.max(40), 22, theme.tooltip)?;
    pm.fill_rect(0, 0, pm.width(), 1, theme.accent);
    pm.text(6, 7, &label, theme.text, pm.width().saturating_sub(8));
    Ok(Some(pm.to_png()?))
}

fn series_host(surface: &Surface, request: &FrameRequest, series: &[Series]) -> HostProjection {
    if surface.mode().is_sealed() {
        return HostProjection::sealed();
    }
    let mut text_nodes = Vec::new();
    if let Some(caption) = &request.caption {
        text_nodes.push(HostText {
            kind: "caption",
            text: caption.clone(),
        });
    }
    let mut tsv = String::from("series\tx\ty\n");
    for s in series {
        for p in &s.points {
            tsv.push_str(&s.name);
            tsv.push('\t');
            fmt_num(p.x, &mut tsv);
            tsv.push('\t');
            fmt_num(p.y, &mut tsv);
            tsv.push('\n');
        }
    }
    HostProjection {
        text_nodes,
        clipboard: Some(ClipboardPayload::Tsv(tsv)),
    }
}

fn series_to_grid(series: &[Series]) -> Result<Grid, Error> {
    let columns = vec![
        Column::new(0, "series"),
        Column::new(1, "x"),
        Column::new(2, "y"),
    ];
    let mut rows = Vec::new();
    let mut id = 0u32;
    for s in series {
        for p in &s.points {
            let mut xs = String::new();
            let mut ys = String::new();
            fmt_num(p.x, &mut xs);
            fmt_num(p.y, &mut ys);
            rows.push(Row::new(
                id,
                vec![
                    CellValue::text(s.name.clone()),
                    CellValue::text(xs),
                    CellValue::text(ys),
                ],
            ));
            id += 1;
        }
    }
    if rows.is_empty() {
        rows.push(Row::new(
            0,
            vec![
                CellValue::Redacted,
                CellValue::Redacted,
                CellValue::Redacted,
            ],
        ));
    }
    Grid::try_new(columns, rows)
}

fn bounds(series: &[Series]) -> (f64, f64, f64, f64) {
    let mut xmin = f64::INFINITY;
    let mut xmax = f64::NEG_INFINITY;
    let mut ymin = f64::INFINITY;
    let mut ymax = f64::NEG_INFINITY;
    for s in series {
        for p in &s.points {
            xmin = xmin.min(p.x);
            xmax = xmax.max(p.x);
            ymin = ymin.min(p.y);
            ymax = ymax.max(p.y);
        }
    }
    if !xmin.is_finite() {
        return (0.0, 1.0, 0.0, 1.0);
    }
    if (xmax - xmin).abs() < 1e-9 {
        xmax = xmin + 1.0;
    }
    if (ymax - ymin).abs() < 1e-9 {
        ymax = ymin + 1.0;
    }
    (xmin, xmax, ymin, ymax)
}

fn axis_ticks(min: f64, max: f64, n: usize) -> Vec<f64> {
    let n = n.max(2);
    let span = max - min;
    (0..n)
        .map(|i| min + span * (i as f64) / ((n - 1) as f64))
        .collect()
}

fn map_x(x: f64, xmin: f64, xmax: f64, x0: u32, w: u32) -> u32 {
    let t = ((x - xmin) / (xmax - xmin)).clamp(0.0, 1.0);
    x0 + ((t * f64::from(w.saturating_sub(1))) as u32)
}

fn map_y(y: f64, ymin: f64, ymax: f64, y0: u32, h: u32) -> u32 {
    let t = ((y - ymin) / (ymax - ymin)).clamp(0.0, 1.0);
    y0 + (((1.0 - t) * f64::from(h.saturating_sub(1))) as u32)
}

fn fmt_num(v: f64, out: &mut String) {
    use std::fmt::Write as _;
    let _ = write!(out, "{v:.2}");
    while out.contains('.') && out.ends_with('0') {
        out.pop();
    }
    if out.ends_with('.') {
        out.pop();
    }
}