Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 8. Display Components

Every component in the first seven chapters takes input: text boxes take text, dropdowns take options, sliders take numbers. This chapter switches to a different kind, drawing only, taking nothing.

The workbench needs such things too. When a filter finishes, the result is a pile of data; dumping it into a read-only text box is readable but not good-looking. A score should be drawn as a bar, a structure should be collapsible, tagged source text should have color, a piece of explanation should have a heading and a list, and a conclusion should be wrapped in a card.

Figure 8-1 Five display components, five kinds of content

The sample adds a fourth block to the shell, the display area. It reads the filter result and presents it once in each of five ways.

Figure 8-2 The display area, five slots each holding one block

Click “Render” and all five blocks fill with content at once.

Figure 8-3 After rendering: report, raw data, tag distribution, annotation, card

The five blocks from top to bottom map exactly onto the five components. This chapter goes through each one’s quirks. Every one has at least one place where “writing it any other way breaks it”.

The display area takes two inputs, the raw items and the filtered result. The report has to state “how many in total, how many left”; the denominator has to be counted from the raw items and the numerator from the filtered result, so one input can’t supply both numbers. The five components share these two sets of data, each taking the part it needs. Label only counts tags, HighlightedText only splits lines, and JSON only holds a few summary fields.

Markdown is the most used one and the easiest to underestimate. It takes a string and draws it as headings, lists, bold text, links, and code blocks according to Markdown syntax.

            var report = gr.Markdown("Not rendered yet.", label: "Report");

The sample’s report is assembled dynamically.

    var formula = $"$$\\frac{{{kept.Length}}}{{{total}}}$$";
    var top = counts.OrderByDescending(pair => (double)pair.Value).First().Key;

    var report = $"""
        ### This Filter

        There are **{total}** items in total, **{kept.Length}** left after filtering, retention rate {formula} ({ratio:P0}).

        - Tag types: {counts.Count}
        - Highest share: {top}
        """;

Whatever you write in the string is what appears on the page. Headings, bold, lists — all follow the syntax. That is one way it beats a read-only text box. With the same piece of text, adding ** makes it bold and adding - makes it a list, with no HTML to assemble.

The {ratio:P0} in the report writes 0.375 as 38%. P is the percent format and 0 is the number of decimal places. Don’t multiply by 100 again in the interpolation expression — P has already done that, and you’d get 3750%. How a number displays is decided by string interpolation; the formula only handles layout.

Here are the common ones, run through once.

SyntaxRenders as
# Heading, ## SubheadingLevel-one and level-two headings (more # means smaller)
**bold**, *italic*Bold, italic
- one itemUnordered list (1. is an ordered list)
> a paragraphBlock quote, with a vertical line on the left
`code`Inline monospace
Wrapped in three backticksCode block, with an optional language
[text](address)Link
![caption](address)Image
Several lines separated by vertical barsTable

This list is enough to draw most results. What it can’t cover is “precise layout”. Column widths, spacing, rounded corners, hover effects — Markdown syntax can’t express those.

One practical suggestion. For report-style content, use the three-part form of “heading + a paragraph + a list”. The heading says what it is, the paragraph gives the conclusion, the list gives the details. It reads better than one long stretch of text and is easier to write than a pile of tables.

Heading levels have to line up with the page structure. The sample’s page header uses # for the site name, the four blocks’ subheadings use ###, and the report’s subheading also uses ###. There should be only one # on a page; use # everywhere and every block is as large as the page header, so the hierarchy is gone.

Tables have one hard requirement: the separator row can’t be omitted. Write only a header and a few data rows and it won’t render as a table, just as a paragraph of text with vertical bars. The separator row’s column count also has to match the data; one column short and the later columns are dropped.

Nested lists rely on indentation: a child item gets two more spaces than its parent. Not enough indentation and the child is treated as a sibling.

Formulas

There are two easy mistakes with formulas, both about delimiters.

By default only $$...$$ is recognized. Write $E = mc^2$ and the page shows those characters verbatim instead of rendering a formula. For inline formulas you have to state explicitly what the delimiters are.

gr.Markdown("Inline $E = mc^2$", latexDelimiters: new[] { new LatexDelimiter("$", "$", false) });

LatexDelimiter has three parameters: the left delimiter, the right delimiter, and whether it is block-level (display). false means inline, with the formula on the same line as the text; true means block-level, with the formula on its own line, centered and in a larger font. The sample uses block-level $$...$$, so the retention-rate fraction is shown on a line of its own.

Why isn’t $ recognized by default? Because $ is too common in ordinary text: amounts, variable names, command prompts all contain it. Recognizing only $$ by default trades “recognizing a little less” for “no false positives”. If you really want inline formulas, declare the delimiters once, and from then on every $...$ in that component is treated as a formula.

Don’t write % inside a block-level formula. LaTeX treats % as a comment marker, so 100% renders as just 100. That’s why the sample puts the percentage outside the formula (“retention rate [fraction] (100%)”) and leaves only the fraction inside. This one is subtle: the code is right, the rendering is right, and a single character is simply missing.

With headerLinks on, each heading gets a link icon in front of it that appears only on hover; clicking it makes the address bar jump to #h-heading-text. It suits long documents. With a dozen or so subsections on a page, giving each one a copyable address is useful.

gr.Markdown("# A heading with a link", headerLinks: true);

It only means something when there are headings. For a stretch of text with no #, on or off makes no difference.

What It’s Not For

Markdown isn’t for “precise layout control”. It can make text look good, but you can’t say “this box is 300 pixels wide, with 12 pixels of left padding and 4-pixel rounded corners”. For that kind of control, use Html.

It’s also not for drawing structured data. An object written out in Markdown is just a lump of text, while JSON can collapse it and show the hierarchy.

8.2 Markdown’s HTML Sanitizing and Height

Markdown lets you mix HTML into the text, which raises a question: where does that HTML come from?

If you wrote all of it yourself, no problem. If any of it is user input (say you splice a user-supplied title into a report), there’s a risk. A user puts an image with onerror in the title and that script runs when the image fails to load; put in an <iframe> and the page gains a chunk of content from somewhere else.

sanitizeHtml is what handles this; it defaults to true.

TagSanitizing on (default)Sanitizing off
<b>, <i>KeptKept
<span style="color:red">KeptKept
<img src onerror>Tag kept, event attribute removedAll kept
<iframe>RemovedKept
<div onclick>Tag kept, onclick removedAll kept
<script>RemovedKept

This table leads to one conclusion. What it blocks is “things that execute”, not “all HTML”. Bold, color, images — things that only affect display — stay; scripts, embedded pages, event attributes — things that can run code — are removed.

Turning it off (sanitizeHtml: false) means all of the above is output exactly as written. When should you turn it off? When the HTML is generated entirely by your code and you genuinely need things like <iframe> that get stripped. If there’s even a trace of user input in the content, don’t turn it off.

Be precise about what happens after you turn it off. A <script> tag stays on the page, but browsers don’t execute scripts inserted via innerHTML; event attributes like onerror do execute instead. So with sanitizing off, the worry about someone slipping in a script is smaller than you’d think — what you actually have to guard against is an image with onerror. Judge the risk by whether an event is attached, not by the tag name.

When does this come up? The most common case is splicing user input into Markdown. The sample’s report has no user input, so leaving sanitizing on changes nothing. But if the report contains a line like “Result name. {name}” and name is user-supplied, a user typing <img src=x onerror=...> puts that straight into the page’s HTML. With sanitizing on, onerror is removed; with it off, it stays on the page and the script runs as soon as the image fails.

The boundary needs stating clearly here. Sanitizing reduces risk; it isn’t a security guarantee. It filters tags and attributes against a list, and anything outside that list, differences in how browsers parse, and combined bypass tricks are all outside what it promises. To really render untrusted content onto a page, you have to handle it on the server first. That’s a web-security topic, not something a component parameter can solve.

So the right attitude has two layers. Keep user input out of HTML where you can (for example, escape a title to plain text before splicing it in), and only when you really must let it in, fall back on sanitizing — while knowing it doesn’t cover every case.

One more easy-to-miss point. Markdown’s sanitizing applies only to HTML fragments, not to Markdown syntax itself. A link like [click me](javascript:alert(1)) written by a user doesn’t go through the HTML path. Validating link targets belongs in the business layer. That’s the division of labor between “sanitizing” and “validation”: the former handles tags, the latter handles content.

Line Breaks and Height

lineBreaks handles line breaks. It defaults to false, with Markdown following the standard syntax: a single newline is merged into a space, and you need a blank line to start a paragraph. Set it to true and a single newline becomes a <br>.

When do you need it? For text pasted in from elsewhere — say a list arranged line by line with none of Markdown’s blank lines. Default rendering squeezes it into one paragraph; with lineBreaks on, the lines stay separate.

There are three height parameters: height, maxHeight, minHeight. height is a fixed height, scrolling when content overflows; maxHeight is “grow at most this tall”, and the box shrinks when there’s less content; minHeight is the reverse. Give none of them and the height follows the content.

How to pick depends on whether the content can grow.

ContentUseReason
A fixed few lines of stable lengthNone of themThe box follows the content, no more and no less
Reports, logs, varying lengthmaxHeightShort content doesn’t take up space; long content doesn’t push what’s below away
A fixed-size panelheightPosition doesn’t jump; overflow scrolls

The price of a fixed height is blank space when content is short and a scrollbar when it’s long. For a stable layout that price is worth paying; if you’re only worried about content getting too long, use maxHeight.

To confirm sanitizing really does something, put an <iframe> into a piece of Markdown and it won’t be on the page; put onclick into a <div> and clicking does nothing. Turn sanitizeHtml off and look again, and both stay on the page. Judgments like this have a direct way to be checked: change one parameter and compare whether those two things are on the page.

What You Can Embed

What sanitizing blocks are things that execute (scripts, event attributes, inline frames); layout tags and inline styles aren’t affected. There’s still plenty you can use for layout. Three common ones.

Collapsing. Use <details> and <summary> to fold long content away, visible only when clicked open.

gr.Markdown("<details><summary>Expand for details</summary>\n\nContent inside the fold.\n\n</details>");

Attaching a stretch of raw data or a log to a report — both suit folding. The main text stays short, and anyone who needs to check opens it themselves.

Small blocks side by side. Markdown syntax has no “horizontal arrangement”; use a div with flex.

gr.Markdown("<div style=\"display:flex;gap:8px\"><span style=\"padding:2px 8px;background:#eef2ff;border-radius:10px\">Badge one</span><span style=\"padding:2px 8px;background:#eef2ff;border-radius:10px\">Badge two</span></div>");

For things like badges and status labels, this looks better than a string of **.

Native tables. Markdown’s table syntax can’t express merged cells; when you need them, write a <table> directly.

All three stay on the page, which means they aren’t on the list. What the list blocks are <script>, <iframe>, and on* attributes. There’s just one criterion: will this HTML execute code?

8.3 Html: Template Substitution and Default Styles

Html sits one level below Markdown: it outputs HTML directly. Two parameters decide what it outputs. value is the data, htmlTemplate is the template, and ${value} in the template is replaced by the data.

            var card = gr.HTML("Not rendered yet.", label: "Card",
                htmlTemplate: "<div style=\"padding:12px;border-left:4px solid #3366cc;background:#f6f7f9\">Kept <b>${value}</b></div>");

This template wraps value in a light-colored block with a left border. The handler function returns "8 items (out of 8)", and that sentence appears wrapped in the box on the page (the bottom block in Figure 8-3).

The default of htmlTemplate is ${value}. In other words, if you don’t write a template, value itself is output directly as HTML. The sample’s template adds a layer of wrapping, so the data (a plain-text sentence) and the layout (that bordered div) are separated. Changing the layout doesn’t touch the handler function, and changing the data doesn’t touch the template.

The template replaces only this one placeholder, ${value}. Names like ${color} or ${title} aren’t replaced with anything. They don’t exist in the template’s scope, the whole block errors out, and all that’s left on the page is a line reading Error rendering HTML: color is not defined. To pass several values, assemble them into one HTML string in the handler function and write the whole thing into value.

That’s the path the sample’s card takes. The template only handles the border; the content is assembled by the handler function.

    var card = $"{kept.Length} items (out of {total})";

The <b>${value}</b> in the template thus becomes “Kept 8 items (out of 8)”. The bold comes from the template, the numbers from the handler function. If you later want to add an “updated at” time, you change only that one line in the handler function and not a word of the template. Data belongs to data and layout to layout; that’s the only value of the template parameter.

It Doesn’t Sanitize

Markdown has a layer of sanitizing; Html doesn’t. Whatever you write in value goes into the page as-is.

No need to guess at this; two lines show it. Put onerror on an image and that script still runs when the image fails to load; write an <iframe> and it’s embedded in the page, border styles and all. Both get through.

So Html’s boundary sits further out than Markdown’s, and the risk is greater too. If even one character in the content comes from a user, you have to escape it yourself.

var safe = System.Net.WebUtility.HtmlEncode(title);
var card = $"<b>{safe}</b>";

HtmlEncode turns <, >, &, and quotes into entities, so the browser shows them as text instead of structure. No component covers this step for you; whoever assembles the string is responsible for escaping it.

applyDefaultCss defaults to true and adds a basic set of styles (font size, spacing, margins) to tags like h1–h6, p, ul, table, so bare HTML doesn’t look bad. Set it to false and the styling comes entirely from your own HTML — use that when you want to control layout from scratch — at the cost of headings, paragraphs, and lists all falling back to browser defaults, with line height and spacing yours to write again.

A middle-ground use: keep the default globally and override it with inline styles only on the section that needs special layout. The sample’s card does exactly that — applyDefaultCss is left alone, and the style in the template makes that left border.

Html’s typical uses are all cases where “the layout is itself the content”: cards with a left border, status badges, progress bars, embedded players. You can’t write those in Markdown; with Html they’re a few lines of string.

How to choose between Html and Markdown? Look at the content itself. If the content contains formatting syntax (Markdown), use Markdown; if it’s a piece of HTML whose layout you need to control precisely, use Html. Using them the other way round is awkward. Put Markdown syntax into Html and it won’t render — the page shows the asterisks and hash marks verbatim; push a large chunk of HTML into Markdown and <iframe>, on*, and the like get stripped by sanitizing.

8.4 Html: Load Scripts

Html has one more parameter, jsOnLoad, which runs a piece of JS after the component loads. Its default is a single line.

element.addEventListener('click', function() { trigger('click') });

It means “click this block and its click event fires”. That’s what lets Html bind Click (Chapter 5). Set it to null or an empty string and the block is just a static block: even with Click bound, nothing fires.

The element in the script is the container holding the template content, not the whole component’s frame. The sample’s card doesn’t set jsOnLoad, so it gets that default line, which means that besides displaying, it could also bind Click; the sample doesn’t bind it, so clicking does nothing.

When you write your own, element works the same way — for example, to make some spot in the block show something the script computed.

gr.HTML("Original text", htmlTemplate: "<div class=\"w\">${value}</div>",
    jsOnLoad: "element.querySelector('.w').textContent = 'Changed by script'");

What the page shows is “Changed by script”, not “Original text”. The script runs after the template renders and changes the content.

It runs only once, at mount time. Afterwards, when the handler function updates value and the template substitutes again, the script doesn’t rerun. Wire that block up to a button, click once to swap in a new value, and the display goes back to the new sentence — the content the script changed is gone. If you want “every piece of data to pass through the script”, this parameter can’t do it. It executes once at mount, and the template takes over from there.

This parameter suits “small widgets”. A piece of HTML that needs initialization before it works (a chart library, a map, a player) can have its init function called in jsOnLoad. The code you write runs in the browser, so only put your own code in it — don’t splice in user input. That’s the same line as escaping in the previous section: whatever you put in must either be trusted or processed first.

There’s also a head parameter that puts content into the page’s <head>. Use it to pull in an external script or stylesheet. It affects the whole page, not this one component. Write a <style> in there and every element on the page matching the selector is affected, including other components. Know that you’re changing globals when you use it, and keep selectors as narrow as possible.

gr.HTML("<p class=\"hh\">Look at the color</p>", head: "<style>.hh { color: #c00; }</style>");

That <style> really does go into <head>, but the color has no effect. The component’s own paragraph-color rule has higher priority; you need !important to override it.

head: "<style>.hh { color: #c00 !important; }</style>"

The benefit is not having to cram styles into value; the cost is that the class name becomes global, the component’s own rules still sit on top of it, and you have to think about priority when writing styles.

8.5 JSON: Collapsing and Height

JSON takes an object and draws it as a structure with line numbers that can be collapsed.

            var data = gr.JSON(null, height: 220, label: "Raw data");

The sample’s handler function returns an anonymous object, and the page shows its structure.

    var data = new
    {
        total,
        kept = kept.Length,
        ratio = Math.Round(ratio, 3),
        tags = counts.Keys.ToArray(),
    };

open controls the initial expansion. By default it expands to the third level; deeper levels collapse to a single line Object(n) that you click to see. Set it to true and everything expands. Don’t expand everything when the data is deeply nested — a screen full of braces hides the structure instead of showing it.

The sample gives it an anonymous data object with no defined type. Fed to this one component, it can be drawn from the structure of property names and values; JSON doesn’t read type names. If that data also has to go elsewhere (say to Label at the same time), define a record instead of assembling it twice in two places — assemble it twice and sooner or later the two won’t match.

showIndices adds indices to array elements. When objects in an array all look alike, only an index tells you which one you’re looking at. It does this by turning elements into keyed items: [1, 2] displays as two lines, "0": 1 and "1": 2, with the index as the key. Quotes on keys are a JSON rule; keys can only be strings, so don’t mistake them for fields of the data itself when reading.

height and maxHeight work the same as in Markdown. JSON especially needs them: a slightly complex object runs to dozens of lines, and without a height limit it pushes the whole page down. The sample gives height: 220, and the overflow scrolls.

The sample’s value starts as null, so the page shows an empty box. That’s more honest than stuffing in fake data: an empty box says plainly “no data yet”, while fake data makes people think it’s the result.

What is JSON for? Debugging and checking. Whether the structure returned by the handler function is right, whether a field name is misspelled, whether an array is empty, whether a number got rounded down to 0. You can’t see those in assembled text; in a structure they’re separate fields.

Then from Chapter 5 has a handy use here. The main step gives the user the finished result; in Then you give the same batch of raw data to a JSON. The user sees the result, you see the data, and the two don’t get in each other’s way. When it actually ships, delete that JSON from Then.

The other way round, JSON isn’t for end users. A screen of braces is something no one but a developer wants to read; if you really need to show users a structure, rearrange it with a Markdown table or list.

8.6 Label: Presenting Classification Scores

Label takes a set of “tag → confidence” pairs and draws them as percentage bars. It was originally made for classification models: a model outputs a bunch of probabilities, and this component shows the highest one enlarged, with the rest arranged as bars in proportion.

            var distribution = gr.Label(null, label: "Tag distribution");

The sample uses it to show the tag distribution.

    var counts = all.Lines
        .Select(line => line.Split(' ')[0])
        .GroupBy(tag => tag)
        .OrderByDescending(group => group.Count())
        .ToDictionary(group => group.Key, group => (object)Math.Round((double)group.Count() / all.Shown, 3));

There’s one detail you have to know here. The dictionary’s value type must be object, not double. Write new Dictionary<string, double> and it throws at runtime.

System.ArgumentException: The Label output expects one of: a string label, an int label,
a float label, or a dictionary whose keys are labels and values are confidences;
got a System.Collections.Generic.Dictionary`2[System.String,System.Double].

The message says it accepts “a dictionary whose keys are labels and values are confidences”, but it doesn’t recognize the specific type you gave. Switch to Dictionary<string, object> and it passes. The values are still double; only the container’s generic parameter differs. This is this chapter’s first case of “the type looks right but isn’t”.

Values are rendered as percentages, with 0.25 shown as 25%. So what you pass in should be proportions, not raw counts — the sample divides by the total first. Pass counts in and you get absurd numbers: a category with 2 items, passed straight as 2, shows as 200% on the page.

The denominator has to be picked correctly too. The sample uses all.Shown (the total before filtering), not the count after filtering. This block shows “how much each tag accounts for in all the data”, so all the data is naturally the denominator. If you want “how much each tag accounts for in the filtered result”, change the denominator to the post-filter count. The two sentences sound almost the same, but the numbers on the chart differ a lot.

You also have to decide how many decimal places to keep. The sample uses Math.Round(..., 3), and 0.125 passed in displays as 13%. Percentages show as integers, so decimals aren’t visible. Three decimal places is already finer than the display precision; going finer is pointless. The length of a bar can only ever give a rough idea anyway.

numTopClasses limits how many items are shown. By default all are shown; set it to 2 and only the top two remain, with the rest not drawn. Use it when there are many tag types and you only want people to see the top ones.

showHeading defaults to true and shows the highest item enlarged on its own at the top. If the highest item doesn’t matter, or you’ve already explained it in a heading, set it to false and keep only the bars.

color changes the background of that enlarged block at the top, using a hex color value. The bars themselves follow the theme and aren’t affected.

When should you use it? When a set of numbers needs “who’s bigger at a glance”. The same five tag counts written as a Markdown table are five rows of numbers the reader has to compare mentally; drawn as bars, the longest one is given by its length, with no need to compare numbers one by one. It isn’t for precise reading: 25% and 24% are almost the same length on the chart, so pair it with a table if you need exact values.

Label isn’t limited to classification models either. Any “set of named proportions” (tag distribution, share of error types, time spent at each stage) can go here. What it wants is proportions, not the status of being “a classification”.

Besides a dictionary, it also accepts a single string or a single integer; then the page has only one label and no bars to arrange.

8.7 HighlightedText: Segments and Legend

HighlightedText takes a series of “text + category” segments, colors each segment by its category, and joins them into one continuous stretch of source text.

            var marked = gr.HighlightedText(null, showLegend: true, label: "Annotation",
                colorMap: new Dictionary<string, string>
                {
                    ["To-do"] = "#c2410c",
                    ["In Progress"] = "#1d4ed8",
                    ["Done"] = "#15803d",
                    ["To Confirm"] = "#7c3aed",
                    ["Archived"] = "#6b7280",
                });

The sample splits each filtered line into two segments, one for the tag and one for the content.

    var tokens = kept
        .SelectMany(line =>
        {
            var space = line.IndexOf(' ');
            var tag = space < 0 ? line : line[..space];
            var rest = space < 0 ? "" : line[space..];
            return new[] { new HighlightedToken(tag, tag), new HighlightedToken(rest + "\n", null) };
        })
        .ToArray();

There’s one more type requirement here: segments have to be HighlightedToken. Pass a tuple array directly, writing new[] { ("To-do", "todo") }, and it throws.

System.ArgumentException: A highlighted text is made of tokens, pairs, or a text with its entities;
it was handed a System.ValueTuple`2[System.String,System.String][].

HighlightedToken has two parameters: the text and the category. A segment whose category is null isn’t colored (in the sample the content segment is null, so only the tags get color).

That code does one thing: it splits each line at the first space, with the tag in front and the content behind. Splitting the tag out is so it can be colored. Treat the whole line as one segment and the color covers the entire line, so readers can’t tell which part is the tag. SelectMany here flattens “two segments per line” into one big array; Select would give an array of arrays, which the component doesn’t accept.

This splitting has a precondition: the first column of the filtered result is the tag. The sample’s “Which columns to show” has “Tag” checked by default, so it holds; uncheck that column and the first word of the content gets colored as a tag. Display components accept strings, and what format those strings carry has to be agreed on between upstream and downstream.

colorMap assigns a color to each category: the key is the category name, the value the color.

gr.HighlightedText(tokens, colorMap: new Dictionary<string, string> { ["To-do"] = "#c2410c" });

Leave it out and a default palette is used. The defaults are distinct enough, but may not match your theme. The sample gives each of the five tags its own color, and in Figure 8-3 the legend’s color swatches line up one-to-one with the colors in the text.

One thing to note when setting it: what the legend shows is the category name itself. Write category names like “todo” or “in-progress” and those are exactly the words in the legend, so the reader has to translate them first. The sample uses the tag names directly as category names (new HighlightedToken(tag, tag)), so the legend and the text match, with no guessing.

showLegend decides whether the legend is drawn. With it on, category names are listed above the text (the row of colored squares in Figure 8-3); with it off, the category name travels with each segment (showInlineCategory, true by default). Both are ways of “letting people know what a color means”; the difference is one is concentrated and the other spread out. Use a legend when there are many categories; inline saves space with two or three.

combineAdjacent merges adjacent segments of the same category into one, separated by adjacentSeparator. A tokenizer often outputs one word per segment; when adjacent words share a category, merging them reads more smoothly.

One more thing: you have to put the line breaks in yourself. A segment breaks only if it contains \n; without it, everything runs on in one line. The sample appends \n to each line’s content segment, so the eight tasks each take one line; remove it and the eight lines collapse into a single paragraph.

showWhitespaces defaults to true and keeps the whitespace before and after a segment. Segments from a tokenizer often carry spaces; turn it off and each segment is trimmed, so the spaces are gone. Text without spaces has no use for it; splitting English words does.

What is HighlightedText for? Source text with annotations. Named-entity recognition marking people and places, tokenization results marking parts of speech, a proofreading tool flagging suspect segments. What they share is “the source text can’t change; only some segments are tagged”. It isn’t for showing classification statistics (that’s Label’s job), nor for long documents (it has no notion of headings or paragraphs).

8.8 Updating Five Components at Once

The sample’s “Render” button updates all five blocks at once. The binding is written as in Chapter 5; here we only look at how it relates to the display components.

    show.Run.Click(Render,
        [filter.Items, filtered.Lines],
        [shown.Report, shown.Data, shown.Distribution, shown.Marked, shown.Card],
        apiName: "Render");

The handler function returns five values, in the same order as the line above.

    return (report, data, counts, tokens, card);

The order of the return values is the order of the outputs. The first goes to Report, the second to Data, and so on. That contract was covered in Chapter 3. Getting the order wrong doesn’t necessarily error (report and card are both strings, so swapping them still runs); a wrong type is what throws at runtime (giving tokens to Label).

Five-to-five is easy to misalign, so the sample puts the five components into a record (ShowView), lists them by field order when binding, and changes both sides together so your eyes can line them up.

There’s one more trade-off. The five values have different types, so the return is written as (object, object, object, object, object). They’re all reference types to begin with, so converting to object copies no data; the price is that type checking moves to runtime, and a mismatch in order or type only shows up as an error at runtime. What you get in exchange is “one click updates the whole display area together”. Splitting it into several events, each handling one or two components, also works, but then one click sends several requests. For a display area where “changing together is what makes sense”, one update is the better deal.

If any one of the five outputs errors, the whole event fails. The rule from Chapter 5 holds here too: if the handler function throws, none of the five components update and the UI shows only one error. So the lines that assemble the data have to be solid. A zero denominator, an empty array, a missing field — all blocked inside the handler function. The sample’s total == 0 ? 0 : ... is exactly the move that guards the denominator; without it, an empty item list produces something that isn’t a percentage.

8.9 How to Choose Among the Five Components

All five components can “display”; choosing wrong throws no error, it just feels off. The order of decision: first look at what the content is, then at whether you need precise layout.

ContentComponentKey parameters
Formatted text, reports, explanationsMarkdownlatexDelimiters, headerLinks, lineBreaks
A piece of HTML whose layout you need to control preciselyHtmlhtmlTemplate, applyDefaultCss, jsOnLoad
An object, a batch of raw dataJSONopen, showIndices, height
A set of named proportionsLabelnumTopClasses, showHeading, color
Source text that can’t change, with only some parts taggedHighlightedTextcolorMap, showLegend, combineAdjacent

A few pairs that are easy to confuse, taken separately.

Markdown and Html. The difference isn’t which is more powerful, it’s “who controls the layout”. In Markdown, layout is decided by syntax: ** gives you bold, but you can’t write “300 pixels wide, 12 pixels on the left”. In Html, you decide the layout — whatever you write is what you get. So when content leads and layout follows, use Markdown; when layout is itself the requirement (cards, badges, bordered quote blocks), use Html.

JSON and Label. One shows developers the structure, the other shows users the proportions. For the same batch of data, JSON holds total, ratio, and the tags array, while Label holds five bars of differing lengths. Who it’s for decides which one to use.

HighlightedText and Markdown. Both are “a stretch of text”; the difference is that the former’s every segment carries a category and can be colored or given a legend, while the latter’s text is one whole block with only syntax-level emphasis like bold and italic. For information about “what this segment is”, use HighlightedText; to just bold a few words, use Markdown.

The last point is about direction: don’t use input components for read-only things. A Textbox from Chapter 6 set to interactive: false can display text too, but it carries the shell of an input box and focus styling, so readers think they can edit there. Display is display — use this chapter’s five components. The result areas of the first three modules in the sample are still read-only text boxes. That’s how Chapters 4 through 7 wrote them; this chapter doesn’t go back and change them, and the newly added display area uses this chapter’s components.

For layout, the sample puts the display area in the wider right column (scale: 2), wraps the five components in a Group (covered in Chapter 4; Group adds a border around a set of components), and stacks them top to bottom, each with its label. No Row is used. Each block of content should fill the width; side by side they’d be squeezed into a strip.

The order matters too. The report is at the top (the conclusion comes first), raw data next (look down when you need to check), then proportions, annotation, and card. A reader scanning downward goes from conclusion to detail.

When you look at this table, first ask “what does the reader want to do with this block” — read text, compare sizes, see structure, or see which segment is tagged. Once that’s answered, the component is decided.

8.10 Chapter Summary

None of the five components collects user input; they only draw. Which one you pick depends on the content itself: Markdown for text, Html for precise layout, JSON for structured data, Label for proportions, HighlightedText for annotated source text.

Markdown recognizes only block-level $$...$$ formulas by default; inline formulas need latexDelimiters stated explicitly. A % inside a formula is treated by LaTeX as a comment, so write percentages outside the formula. headerLinks adds anchors to headings. lineBreaks turns a single newline into <br>, which text pasted in from elsewhere needs.

sanitizeHtml is on by default and blocks “things that execute”. Scripts, embedded pages, and event attributes are removed; bold, color, and images stay. It reduces risk, it isn’t a security guarantee — don’t turn it off when there’s user input.

Html substitutes ${value} in htmlTemplate and recognizes only that one placeholder; to pass several values, assemble them into one string in the handler function. applyDefaultCss gives bare tags a basic set of styles; jsOnLoad runs JS once at mount, and the default line makes the block clickable, while later updates to value don’t rerun it. Html doesn’t sanitize. onerror still runs, <iframe> still embeds, so if the content contains user input you have to HtmlEncode it yourself.

JSON’s open controls the initial expansion, showIndices turns array elements into keys like "0" and "1", and height limits the height. A large object has to have a height limit. It’s a debugging tool, not a display for people.

Label’s dictionary value type must be object; pass proportions, not counts, and pick the denominator correctly. numTopClasses limits the number of bars, showHeading controls that enlarged label at the top.

HighlightedText’s segments are HighlightedToken, not tuples; put \n in the segments yourself for line breaks. showLegend and showInlineCategory are the two ways of drawing a legend, and the legend shows the category name verbatim; combineAdjacent merges adjacent segments of the same category.

This chapter has two cases of “the type looks right but isn’t”: Label’s dictionary and HighlightedText’s segments. They’re an extension of the same contract from Chapter 3. The component decides what types it accepts; get it wrong and it fails at runtime, with only “Error” on the UI.

The next chapter is about tables. One component holding dozens of rows and dozens of columns, and editable too.