rs-rich-web 0.0.7

Serve rs-rich intuiTUIve apps, or any terminal program on a PTY, to a web browser over a WebSocket, drawn by a vendored xterm.js or as accessible DOM
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! The DOM renderer's side of the wire: what the server sends a page that
//! draws an app itself ([`Renderer::Dom`](crate::Renderer::Dom)), as a grid
//! of styled spans with the app's accessibility tree laid over it as ARIA.
//!
//! # Protocol, version 1
//!
//! The page and the server talk over the same WebSocket, opened at
//! `/ws?token=…&cols=…&rows=…&renderer=dom`.
//!
//! **From the page**, text messages, as the xterm.js page sends them: `d`
//! and the bytes an xterm sends for keys, SGR mouse reports and bracketed
//! pastes (decoded by [`input::decode`](crate::input::decode)); `r` and
//! `columns,rows` when its size changes; `c` and `number:1` (or `:0`) when
//! the clipboard took (or refused) a copy.
//!
//! **From the server**, text messages, each a JSON object whose `t` names
//! it:
//!
//! - `{"t":"hello","protocol":1}`, first. A page that speaks another
//!   version stops.
//! - `{"t":"frame","cols":C,"rows":R,"styles":[[id,css],…],
//!   "lines":[[y,[run,…]],…],"cursor":[x,y]|null}` after each frame: the
//!   lines that changed (every line after a resize), each as runs of
//!   `[text, style]`, or `[text, style, 2]` for one wide grapheme. A style
//!   is a number; `0` is the page's own colours, and each other is sent,
//!   as CSS declarations, in the first frame that uses it. `cursor` is
//!   where the focused text box's caret is ([`Driver::cursor`]).
//! - `{"t":"tree","focus":id|null,"nodes":[node,…]}` when the
//!   accessibility tree changed: [`Driver::accessibility`], outermost
//!   first, each node `{"id","depth","rect":[x,y,w,h],"attrs":[[name,
//!   value],…],"text"}` and, for a widget of items (a list, a table, a
//!   tree, tabs, a menu, a grid), `"item":{"role","attrs","text"}` for its
//!   selected item. `attrs` are [`AccessNode::aria_attributes`], with the
//!   states of the selected item (`aria-selected`, `aria-expanded`,
//!   `aria-checked`, `aria-posinset`, `aria-setsize`) on the item. `text`
//!   is what the element reads: [`AccessNode::describe`] for text and a
//!   status, a text box's value, the selected item's text. The page nests
//!   each node in the nearest node before it of a smaller depth, and
//!   focuses the focused node (its item, if it has one).
//! - `{"t":"say","text":"…","urgent":bool}` for each announcement
//!   ([`Driver::take_announcements`]), for an `aria-live` region:
//!   assertive when urgent, else polite.
//! - `{"t":"copy","n":number,"text":"…"}` when the app copies text; the
//!   page answers `c` as above.
//!
//! The session ends with a WebSocket close.
//!
//! [`Driver::cursor`]: intuituive::Driver::cursor
//! [`Driver::accessibility`]: intuituive::Driver::accessibility
//! [`Driver::take_announcements`]: intuituive::Driver::take_announcements
//! [`AccessNode::aria_attributes`]: intuituive::a11y::AccessNode::aria_attributes
//! [`AccessNode::describe`]: intuituive::a11y::AccessNode::describe

use std::collections::HashMap;

use intuituive::Driver;
use intuituive::a11y::{AccessNode, Announcement, Role};
use intuituive::rich::{Color, ColorTriplet, Style, TerminalTheme};
use serde_json::{Value, json};

/// The protocol's version, sent in `hello`.
pub const PROTOCOL: u32 = 1;

/// The colours styles resolve to: xterm.js's default palette on the page's
/// background, so an app looks the same drawn either way.
pub const THEME: TerminalTheme = TerminalTheme {
    background: ColorTriplet::new(0x10, 0x10, 0x10),
    foreground: ColorTriplet::new(0xd0, 0xd0, 0xd0),
    ansi: [
        ColorTriplet::new(0x2e, 0x34, 0x36),
        ColorTriplet::new(0xcc, 0x00, 0x00),
        ColorTriplet::new(0x4e, 0x9a, 0x06),
        ColorTriplet::new(0xc4, 0xa0, 0x00),
        ColorTriplet::new(0x34, 0x65, 0xa4),
        ColorTriplet::new(0x75, 0x50, 0x7b),
        ColorTriplet::new(0x06, 0x98, 0x9a),
        ColorTriplet::new(0xd3, 0xd7, 0xcf),
        ColorTriplet::new(0x55, 0x57, 0x53),
        ColorTriplet::new(0xef, 0x29, 0x29),
        ColorTriplet::new(0x8a, 0xe2, 0x34),
        ColorTriplet::new(0xfc, 0xe9, 0x4f),
        ColorTriplet::new(0x72, 0x9f, 0xcf),
        ColorTriplet::new(0xad, 0x7f, 0xa8),
        ColorTriplet::new(0x34, 0xe2, 0xe2),
        ColorTriplet::new(0xee, 0xee, 0xec),
    ],
};

/// The states that belong to a widget's selected item.
const ITEM_STATES: [&str; 5] = [
    "aria-selected",
    "aria-expanded",
    "aria-checked",
    "aria-posinset",
    "aria-setsize",
];

/// What the page was last sent, so only changes go.
#[derive(Debug, Default)]
pub struct Dom {
    /// Each style's CSS, by the number the page knows it by.
    styles: HashMap<String, u32>,
    /// Each line as last sent.
    lines: Vec<Value>,
    size: (u16, u16),
    cursor: Option<(u16, u16)>,
    /// The tree as last sent, as the driver gave it.
    tree: Option<Vec<AccessNode>>,
    /// The driver's frame count when the page was last brought up to it:
    /// rows the frames since damaged are compared, and only they.
    frame: Option<u64>,
}

impl Dom {
    pub fn new() -> Dom {
        Dom::default()
    }

    /// The first message.
    pub fn hello(&self) -> String {
        json!({"t": "hello", "protocol": PROTOCOL}).to_string()
    }

    /// The messages that bring the page up to `driver`'s last frame: a
    /// `frame` when a line or the caret changed, and a `tree` when the
    /// accessibility tree did.
    pub fn update(&mut self, driver: &Driver) -> Vec<String> {
        let mut out = Vec::new();
        let frames = driver.stats().frames;
        if let Some(frame) = self.frame(driver) {
            out.push(frame.to_string());
        }
        self.frame = Some(frames);
        // The tree's JSON is made only when the tree changed (the focus can
        // move with no frame drawn).
        let nodes = driver.accessibility();
        if self.tree.as_ref() != Some(&nodes) {
            out.push(tree(&nodes).to_string());
            self.tree = Some(nodes);
        }
        out
    }

    fn frame(&mut self, driver: &Driver) -> Option<Value> {
        let screen = driver.screen();
        let area = screen.area();
        let size = (area.width, area.height);
        if size != self.size {
            self.size = size;
            self.lines.clear();
        }
        // The rows to compare: those the frames since the last update
        // damaged; every row the first time, after a resize, or when the
        // driver no longer remembers that far back.
        let mut rows = vec![self.lines.len() < area.height as usize; area.height as usize];
        match self.frame.and_then(|frame| driver.damage_since(frame)) {
            Some(damage) => {
                for rect in damage {
                    let rect = rect.intersection(area);
                    for y in rect.y..rect.bottom() {
                        rows[y as usize] = true;
                    }
                }
            }
            None => rows.iter_mut().for_each(|row| *row = true),
        }
        let mut new_styles = Vec::new();
        // Each screen style's number, for this frame.
        let mut known = HashMap::new();
        let mut changed = Vec::new();
        for y in (0..area.height).filter(|&y| rows[y as usize]) {
            let mut runs: Vec<Value> = Vec::new();
            let mut run = String::new();
            let mut current = 0;
            for x in 0..area.width {
                let cell = screen.cell(x, y);
                if cell.is_continuation() {
                    continue;
                }
                let id = *known.entry(cell.style).or_insert_with(|| {
                    let css = screen.style(cell.style).map(css).unwrap_or_default();
                    self.style_number(css, &mut new_styles)
                });
                if cell.width >= 2 {
                    if !run.is_empty() {
                        runs.push(json!([std::mem::take(&mut run), current]));
                    }
                    runs.push(json!([cell.text(), id, 2]));
                    continue;
                }
                if id != current && !run.is_empty() {
                    runs.push(json!([std::mem::take(&mut run), current]));
                }
                current = id;
                run.push_str(cell.text());
            }
            if !run.is_empty() {
                runs.push(json!([run, current]));
            }
            let line = Value::Array(runs);
            let y = y as usize;
            if self.lines.get(y) != Some(&line) {
                changed.push(json!([y, line.clone()]));
                if y < self.lines.len() {
                    self.lines[y] = line;
                } else {
                    self.lines.push(line);
                }
            }
        }
        let cursor = driver.cursor();
        if changed.is_empty() && new_styles.is_empty() && cursor == self.cursor {
            return None;
        }
        self.cursor = cursor;
        Some(json!({
            "t": "frame",
            "cols": size.0,
            "rows": size.1,
            "styles": new_styles,
            "lines": changed,
            "cursor": cursor.map(|(x, y)| json!([x, y])),
        }))
    }

    /// The number `css` goes by, sending it the first time.
    fn style_number(&mut self, css: String, new_styles: &mut Vec<Value>) -> u32 {
        if css.is_empty() {
            return 0;
        }
        if let Some(&id) = self.styles.get(&css) {
            return id;
        }
        let id = self.styles.len() as u32 + 1;
        new_styles.push(json!([id, css]));
        self.styles.insert(css, id);
        id
    }
}

/// `style` as CSS declarations, in [`THEME`]'s colours. Reverse video with
/// a colour left to the terminal swaps in the theme's, so a focused row
/// drawn in reverse shows.
pub fn css(style: &Style) -> String {
    // Attribute 6 is reverse (as `Style::get_html_style` reads it).
    let reverse = style.attr(6) == Some(true);
    let mut style = style.clone();
    if reverse {
        let rgb = |t: ColorTriplet| Color::from_rgb(t.red, t.green, t.blue);
        if style.color().is_none() {
            style = style.with_color(rgb(THEME.foreground));
        }
        if style.bgcolor().is_none() {
            style = style.with_bgcolor(rgb(THEME.background));
        }
    }
    style.get_html_style(&THEME)
}

/// The role a widget of items gives its selected item.
fn item_role(role: Role) -> Option<&'static str> {
    Some(match role {
        Role::List => "listitem",
        Role::Table => "row",
        Role::Tree => "treeitem",
        Role::TabList => "tab",
        Role::Menu | Role::MenuBar => "menuitem",
        Role::Grid => "gridcell",
        Role::RadioGroup => "radio",
        Role::ComboBox => "option",
        _ => return None,
    })
}

fn pairs(attrs: &[(&'static str, String)]) -> Value {
    Value::Array(
        attrs
            .iter()
            .map(|(name, value)| json!([name, value]))
            .collect(),
    )
}

/// One node of the `tree` message.
pub fn node(node: &AccessNode) -> Value {
    let attrs = node.aria_attributes();
    let item = item_role(node.role).zip(node.value.as_ref());
    let text = match node.role {
        Role::Text | Role::Status => node.describe(),
        Role::TextBox => node.value.clone().unwrap_or_default(),
        _ => String::new(),
    };
    let rect = node.rect;
    let mut out = json!({
        "id": node.id,
        "depth": node.depth,
        "rect": [rect.x, rect.y, rect.width, rect.height],
        "text": text,
    });
    match item {
        Some((role, value)) => {
            // A combo box's open state is its own; its current option is
            // the selected one.
            let combo = node.role == Role::ComboBox;
            let (mut on_item, own): (Vec<_>, Vec<_>) = attrs.into_iter().partition(|(name, _)| {
                ITEM_STATES.contains(name) && !(combo && *name == "aria-expanded")
            });
            if combo {
                on_item.insert(0, ("aria-selected", "true".to_string()));
            }
            out["attrs"] = pairs(&own);
            out["item"] = json!({"role": role, "attrs": pairs(&on_item), "text": value});
        }
        None => out["attrs"] = pairs(&attrs),
    }
    out
}

/// The `tree` message for `nodes`.
pub fn tree(nodes: &[AccessNode]) -> Value {
    let focus = nodes.iter().find(|n| n.focused).map(|n| n.id);
    json!({
        "t": "tree",
        "focus": focus,
        "nodes": nodes.iter().map(node).collect::<Vec<_>>(),
    })
}

/// The `say` message for `announcement`.
pub fn say(announcement: &Announcement) -> String {
    json!({"t": "say", "text": announcement.text, "urgent": announcement.urgent}).to_string()
}

/// The `copy` message for copy `number` of `text`.
pub fn copy(number: u64, text: &str) -> String {
    json!({"t": "copy", "n": number, "text": text}).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use intuituive::rich::Style;

    #[test]
    fn styles_become_css() {
        let parse = |s: &str| Style::parse(s).unwrap();
        assert_eq!(css(&Style::new()), "");
        assert_eq!(
            css(&parse("bold red")),
            "color: #cc0000; text-decoration-color: #cc0000; font-weight: bold"
        );
        // Reverse with nothing set still shows: the theme's colours swap.
        assert_eq!(
            css(&parse("reverse")),
            "color: #101010; text-decoration-color: #101010; background-color: #d0d0d0"
        );
        assert_eq!(css(&parse("on #123456")), "background-color: #123456");
    }

    #[test]
    fn items_take_the_item_states() {
        use intuituive::a11y::AccessState;
        use intuituive::screen::Rect;
        let list = AccessNode {
            depth: 0,
            id: 7,
            role: Role::List,
            name: "Files".into(),
            value: Some("b.txt".into()),
            focused: true,
            disabled: false,
            state: AccessState::item(1, 3),
            rect: Rect::new(0, 1, 10, 3),
            error: None,
        };
        let json = node(&list);
        assert_eq!(
            json["attrs"],
            json!([["role", "list"], ["aria-label", "Files"]])
        );
        assert_eq!(
            json["item"],
            json!({
                "role": "listitem",
                "attrs": [["aria-selected", "true"], ["aria-posinset", "2"], ["aria-setsize", "3"]],
                "text": "b.txt",
            })
        );
        assert_eq!(json["rect"], json!([0, 1, 10, 3]));
        // A radio group's chosen option is a checked radio.
        let group = AccessNode {
            role: Role::RadioGroup,
            name: "Size".into(),
            value: Some("Medium".into()),
            state: AccessState {
                checked: Some(true),
                position: Some((2, 3)),
                ..AccessState::default()
            },
            ..list.clone()
        };
        let json = node(&group);
        assert_eq!(json["item"]["role"], "radio");
        assert_eq!(
            json["item"]["attrs"],
            json!([
                ["aria-checked", "true"],
                ["aria-posinset", "2"],
                ["aria-setsize", "3"]
            ])
        );
        // A combo box's current option is a selected option; whether it
        // is open stays on the combo box.
        let combo = AccessNode {
            role: Role::ComboBox,
            name: "Theme".into(),
            value: Some("Dark".into()),
            state: AccessState {
                expanded: Some(false),
                position: Some((2, 3)),
                ..AccessState::default()
            },
            ..list.clone()
        };
        let json = node(&combo);
        assert_eq!(json["item"]["role"], "option");
        assert_eq!(json["item"]["text"], "Dark");
        assert_eq!(
            json["item"]["attrs"],
            json!([
                ["aria-selected", "true"],
                ["aria-posinset", "2"],
                ["aria-setsize", "3"]
            ])
        );
        assert!(
            json["attrs"]
                .as_array()
                .unwrap()
                .contains(&json!(["aria-expanded", "false"]))
        );
        // A button keeps its own attributes and reads by its label.
        let button = AccessNode {
            role: Role::Button,
            name: "Save".into(),
            value: None,
            state: AccessState::default(),
            ..list.clone()
        };
        let json = node(&button);
        assert_eq!(
            json["attrs"],
            json!([["role", "button"], ["aria-label", "Save"]])
        );
        assert!(json.get("item").is_none());
        assert_eq!(json["text"], "");
        // Text reads as linear mode writes it.
        let text = AccessNode {
            role: Role::Text,
            name: "Hello".into(),
            ..button
        };
        assert_eq!(node(&text)["text"], "Hello");
    }
}