JFLib

32. Markdown / HTML viewer and lists with rows of different heights#

The document view shows Markdown or HTML: help pages, README-like content, release notes, chat output, pages of a browser (read-only but for the fields of forms; images the app fetches; HTML changed through its elements as page scripts do, styled by a subset of CSS). MdDoc is its model -- blocks of formatted text -- read from Markdown (CommonMark with GitHub's tables, task lists, strikethrough and bare links) or from HTML (the reader of the rich-text editor, extended by rules, images, preformatted code and tables). ui.markdown_view / ui.html_view draw it; the app keeps an MdViewState (layouts, images, scroll position, selection).

// state: self.help = MdViewState::new(); self.help.base = String::from("app://help/");
// per frame: the text is parsed again only when it changes (the state keeps a hash of it)
ui.next_size(-1, -1);
let ev = ui.markdown_view(ID_HELP, &mut self.help, &self.page, 0);
if let Some(url) = ev.link {                 // a click on a link, Enter on the focused one
    if url.starts_with("#") { self.go_to(&url) } else { ui.open_url(&url); }
}
self.status = ev.hover.unwrap_or_default();   // the link under the pointer
// HTML instead: ui.html_view(ID_NOTES, &mut self.notes, &html, MV_NO_FRAME)
// a document built once: st.set_markdown(s) / set_html(s) / set_doc(MdDoc::markdown(s)),
// then ui.doc_view(id, &mut st, flags)
  • Markdown: ATX and setext headings, paragraphs (lazy continuation lines), block quotes, bullet and ordered lists (start numbers, tight / loose spacing, [ ] / [x] task items), fenced and indented code, thematic breaks, tables with alignment (\| in cells), HTML blocks (through the HTML reader), link reference definitions; emphasis by CommonMark's delimiter rules, ~~strike~~, code spans, inline / reference / auto links and bare https:// and www. addresses, images, hard and soft breaks, entities, backslash escapes, a little inline HTML (br, b, i, s, u, code, kbd, a href, img). HTML: what RichDoc::from_html reads (headings h1 .. h6, paragraphs, lists, quotes, formats, colours, links) and hr, img (width / height), pre / code class="language-x", tables (th, thead, alignment), forms (below).

  • Layout: the blocks in a column; quotes indented with a bar, list markers in front (bullets by depth, numbers, task boxes), headings 2 / 1.5 / 1.25 / 1 / 0.875 / 0.85 times the body text (h1 / h2 underlined), code blocks in the monospace font with the code editor's highlighting (Highlighter::for_name of the fence's language, ui.code_theme() colours), tables with column widths from their cells (wrapped to fit), images at their size in DIP (scaled down to the column; SVGs through lib/img_svg, sharp at every size). Text wraps at text::segment's line breaks. A paragraph's direction comes from its first strong character: Hebrew and Arabic run right to left, shaped and reordered by text_shape (with the fallback font that has the script); the document's direction (indents, markers) is that of its first strong character unless MV_RTL / MV_LTR says otherwise -- a German page stays left to right in a mirrored window, a Hebrew one runs right to left in any window.

  • Long documents: only the blocks in view are laid out (cached per width, dpi, text scale and fonts) and drawn; scrolling is anchored at the first visible block, so blocks laid out for the first time never move what is shown. 50 000 blocks scroll in about a millisecond per frame. scroll_to_end() (and scrolling to the end of a long document) keeps the end in view while the document grows -- chat output.

  • Mouse: drag selects (the view scrolls at its edges), Shift + press extends, a double click selects a word, a click on a link activates it. Keys: Up / Down scroll by a line, PgUp / PgDn and Space / Shift+Space by a view, Home / End, Tab / Shift+Tab through the links and fields (the focused link is framed, a field gets the focus, scrolled into view; past the last one the focus moves on), Enter activates the focused link, Esc drops it, Ctrl+A, Ctrl+C / Ctrl+Insert copy text (list markers, cells by tabs, images as their alt texts) and HTML. MdViewState also gives selection(), selected_text(), selected_html(), select_all(), scroll_to_block(i).

  • Clicks on an HTML document: MdEv::click names the element a click on the text hit: the inline element around the character under the pointer, else the block's element, beside the blocks the document's root; none after a drag; Enter on a link gives its element. A field's widget keeps its own clicks (MdEv::field, submit). MdDoc::element_at(block, byte) finds such an element for any place of a block's text.

  • Links are reported, not opened: MdEv::link carries the target; with MV_OPEN_LINKS the view also hands it to open_url (whose scheme rules and the app's url permission apply) -- only after the user's click or Enter, never by itself.

  • Images: names of the VFS (app://, data:// ...) and paths -- relative ones after st.base -- are read when first shown and kept in the state; the view never fetches http(s) and data: addresses itself. By default (st.images = MI_LOCAL) they show their alt text in a frame. With MI_ASK the app supplies them (VFS names and paths are still read), with MI_APP the app supplies every image (the view reads no file: pages from the network). The view asks once per address for the images it lays out; until the bytes come a frame with the alt text stands in (at the width / height the HTML gives), then the block is laid out again at the picture's size without moving the view:

    // state: st.images = MI_ASK (or MI_APP); per frame:
    for (addr, bytes) in self.fetched.drain(..) {        // what the app's downloads brought
        st.set_image(&addr, bytes.as_deref());           // None: failed -> the alt text stays
    }
    let ev = ui.html_view(ID_PAGE, &mut st, &self.html, 0);
    for addr in st.image_requests() {                    // the addresses the view waits for
        self.start_download(addr);                       // (each one once)
    }
    // bytes that come outside a frame: set_image, then ui.invalidate() for a frame

    set_image decodes at once with the library's decoders (SVG through img_svg, the rest through img_core); bytes it cannot decode count as a failure.

  • Forms (HTML, also in Markdown's HTML blocks): <form action method>, <input> (text and the other text types, password, checkbox, radio, hidden, submit, image, reset, button), <textarea>, <select> / <option>, <button>, <label> (around a field or for= its id) become fields in the text flow -- the library's own text boxes, check boxes, radios, drop-down lists and buttons, so the style, high contrast, text scale, HiDPI and a mirrored window apply. doc.forms() / doc.fields() hold what the page says (MdForm, MdField: kind MF_*, name, first value, label, options, size ...); the current values live in the state (field_text(i), field_checked(i), field_selected(i) and their setters). A document without fields reads exactly as before.

    let ev = ui.html_view(ID_PAGE, &mut st, &self.html, 0);
    if let Some(i) = ev.field { /* field i changed (or a plain button was pressed) */ }
    if let Some(s) = ev.submit {                         // Enter in a field, a submit button
        // s.action, s.method ("get" / "post"), s.fields: [(name, value)], s.button
        self.navigate(&s.action, &s.method, &s.fields);
    }

    Keys: Tab / Shift+Tab go through links and fields in reading order (a group of radios is one stop: the checked one; the arrows choose inside it), Space toggles, Enter in a text field, check box or radio sends the form with its first submit button (nothing when that is disabled), Enter / Space press a button, Esc in a text field returns to the view, PgUp / PgDn on a field scroll the view. form_data(form, button) gives the pairs a browser would send (named, enabled fields; checked boxes and radios; a list's chosen value; only the submitting button), reset_form(form) (also the reset button) the first values. Password fields show dots, never copy, and give screen readers dots and the protected state. Each field has its record (K_TEXTBOX, K_CHECKBOX, K_RADIO, K_COMBO, K_BUTTON) named by its <label>, aria-label, title or placeholder; the widget ids are md_field_id(view_id, i). Not supported: JavaScript, file inputs (they are text fields), several choices in one list.

  • CSS (HTML, a subset; rich_html.rs "Style sheets"): <style> elements (media screen / all), style= attributes and <link rel="stylesheet"> elements whose text the app gives: the view reads nothing by itself, doc.sheet_links() names the addresses as written (in document order, each once, also a link a script added) and doc.set_sheet(href, Some(css)) hands a text over, which counts where its link stands among the <style> elements, from the next update on (None takes it back, a page without links costs nothing). doc.style_of(node) says what the cascade gives an element (property:value;, without what it inherits). Selectors: tag, *, #id, .class, [attr], [attr=v] (also ~= |= ^= $= *=), descendant and child combinators, lists; the cascade takes specificity, then source order, then the style attribute, !important above them. Properties: color, background(-color), font-weight, font-style, text-decoration, text-align, white-space: pre, display: none (and the hidden attribute); the text's properties are inherited; a link keeps the link colour unless a rule for it gives one. Block elements (p, div, h1, li, table, tr ..., also ul, ol, nav, form, body) get boxes (MdDoc::boxes(), MdBox, MdBlock::boxes): margin, padding, border (width -- px, pt, em, thin / medium / thick -- a visible style drawn solid, colour; shorthands, per side and -width / -style / -color) and a background around their blocks; margins and padding grow with the text scale, a margin CSS gives at a box's top or bottom takes the place of the gap between blocks (p { margin: 2px 0 } sets paragraphs close). On a box's background, text without a colour of its own takes one that reads on it, fields get the theme's background behind them; high contrast drops the page's colours and backgrounds and draws borders in the text's colour; left and right stay physical in a right-to-left document. Unknown properties, at-rules (@media, @import), pseudo-classes and sibling combinators are left out; font-size is read but not shown, of font-family only monospace (as code). Deliberately not: a box model of its own (widths, heights, floats, flexbox, grid, positioning), collapsing margins, inline boxes. Rules are indexed by the id, class or tag their subject needs; matching costs at most a budget proportional to the page and its sheets. Changes of the elements (above) apply the sheets again, also a changed <style>. The page's text colours stay as given in a dark theme.

  • Changing the document (HTML; what a page script does -- the script host itself is the app's): an HTML document keeps its element tree (md_dom.rs). MdNode handles stay the same across changes (raw() / MdNode::from_raw turn them into numbers for a script's objects); a freed node's handle refers to nothing.

    let d = st.doc_mut();                             // st: the view's MdViewState
    if let Some(n) = d.select_first("#stand b") {     // tag, .class, #id, [attr=v], a b, a > b
        d.set_text(n, "3");                           // in place: that paragraph alone again
    }
    if let Some(list) = d.by_id("liste") {
        let li = d.create_element("li");
        let t = d.create_text("Neuer Eintrag");
        d.insert(li, None, t);
        let first = d.children(list).first().copied();
        d.insert(list, first, li);                    // before its first child (None: at the end)
    }
    for n in d.select("p.hinweis") { d.toggle_class(n, "neu"); }
    // the view takes the changes at its next frame (st.update(): now)

    Queries: root(), by_id(id) (an index), select(sel) / select_first / select_in(n, sel) / matches(n, sel) in document order, parent / children / next_sibling / prev_sibling, tag(n) ("" a text), attr / attrs / has_class, text_of(n) (as textContent), inner_html(n), alive / attached. Changes: set_text, set_attr / remove_attr, add_class / remove_class / toggle_class, create_element / create_text (not in the document yet), insert(parent, before, n) (moves an attached node), remove(n) (out of the document, kept), free(n), set_inner_html(n, html). Selectors: compounds of a tag or *, #id, .class, [attr], [attr=v] (also ~= |= ^= $= *=) joined by blanks (descendant) and > (child), lists with commas; pseudo-classes and sibling combinators match nothing. Elements with the hidden attribute or display:none are not shown. The blocks follow at MdDoc::update() (the view calls it every frame): a change inside a block element that shows one paragraph of formatted text by itself (text, inline elements, their attributes and classes) redoes that block alone; any other derives all blocks again in linear time (about a parse of the page; no layout). The view keeps the layouts and heights of the blocks that stay, shows the block it showed (scrolling is anchored there), moves the selection and the focused link with their blocks, and keeps the fields' values by their elements: what the user typed, checked or chose (or the app set) stays, a field the user left alone follows its document value; a focused field keeps the focus when fields come or go before it. MdBlock::node, MdField::node, MdForm::node name the elements, field_of(n) finds a field, element_at(block, byte) the element at a place of a block's text, dom_size() gives the nodes and bytes of the tree (for a host that limits what others write into it). A new document (set_html with another text) starts afresh. Markdown documents have no elements. The tree is capped (256 open elements, 2^20 nodes), a query's work is bounded by the tree's size.

  • Accessibility: the view is a K_BOX (label st.label, default "Dokument"; value: the scroll position in DIP); per visible block a K_HEADING record (new kind; value: the level), K_TEXT (paragraphs, code, table cells), K_LISTITEM (value: the item's number), K_CHECKBOX (a task's box, checked), K_LINK per link, K_IMAGE (label: the alt text). Scripts select them as heading:"Title", link:"Docs" ... Screen readers get the headings as headings with their level on every platform (section 19): heading navigation jumps through the document's visible blocks.

  • Robustness: malformed input never panics and takes linear time -- container nesting is capped at 32 (the HTML reader's at 64 open elements), the inline parser has a scan budget for link destinations and tags, code spans find their closing run through an index, nested images collapse as they form; 16 MB of input at most.

Lists with rows of different heights (ui.vlist_begin, vlist.rs) virtualize like list_begin, but every row has a height of its own: the app emits the rows the list asks for, each in a box whose natural height is measured.

// state: self.vl = VListState::new();
ui.next_size(-1, -1);
let (first, end) = ui.vlist_begin(ID_LOG, &mut self.vl, self.msgs.len());
for i in first..end {
    ui.vlist_item_begin(i);                      // the row's box (BOX_V, the list's width)
    ui.text(TS_BODY_STRONG, &self.msgs[i].from);
    ui.text(TS_BODY | TX_WRAP, &self.msgs[i].text);
    ui.vlist_item_end();                         // measured: the rows below follow it
}
let ev = ui.vlist_end(&mut self.vl);            // EV_ACT: selection, EV_DOUBLE: Enter / double click
// older messages arrived at the top: tell the list, the view stays where it is
self.msgs.splice(0..0, older);
self.vl.insert(0, n);
  • Heights: measured as the rows are built (a changed row is measured again the next time it is built; invalidate(i) / invalidate_all() force it), or given by the app with set_height(i, dip). Rows not measured yet count with estimate (DIP; by default the mean of the measured rows). The heights sit in Fenwick trees: positions and the row at a position cost O(log n), 100 000 rows scroll in about a millisecond per frame.
  • Scrolling is anchored at the first visible row: rows above it may change their height, be inserted (insert(at, n)) or removed (remove(at, n)) without moving what is shown; the selection stays on its row. reveal(i) scrolls a row fully into view (exactly, once the rows on the way are measured), scroll_to(i) shows it at the top, first_visible(), scroll_pos() / set_scroll_pos(px), total_height().
  • Keys: Up / Down, PgUp / PgDn (a view of rows), Home / End move the selection and reveal it; Enter reports EV_DOUBLE. The wheel scrolls smoothly, the scroll bar drags. Records: K_LIST (value: the selection, max: the count), K_LISTITEM per row (id + 1 + i).
  • The document view scrolls its blocks with the same height cache (Rows).

Tests: apps/mdviewtest (--test unit: the parser -- blocks, inline parts, HTML, text and HTML of ranges, forms -- adversarial input with time limits, the list's height cache, the headings and the fields in the accessibility tree, images the app supplies, the element tree and its changes (groups dom, dom changes, dom view, dom cost), the style sheets (css); doc_shots.uis light / dark / high contrast / HTML / Hebrew, doc_rtl.uis (mirrored window), doc_scale.uis (150 % text), doc_links.uis, doc_select.uis, doc_keys.uis (also 50 000 blocks), vlist.uis (100 000 rows); with --page form a form page: form_keys.uis, form_mouse.uis, form_images.uis, form_scale.uis (150 %), form_rtl.uis; with --page dom a page the app changes step by step: dom_steps.uis; with --page css a page with a style sheet: css_shots.uis (light, dark, high contrast, mirrored), css_scale.uis (150 %); all with --verify-dirty).

Source: docs/GUIDE.md in the JFLib repository.