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 10. Charts and Galleries

The table in the previous chapter spread the tasks into cells: Tag, Content, Character count, Due, Done. Cells are good for reading one at a time, not for seeing at a glance “which tag has the most characters” or “whether the character count rises over time”. Questions like that need to be drawn as charts.

This chapter adds two blocks to the workbench. One draws the task table as six charts; the other arranges six cards into a wall. The first is about “how data becomes a chart”, the second about “how images are laid out into a surface”. The two don’t look related, but they tell the same story about division of labor: the business side shapes the data into the form the component wants, and the component does the drawing.

Either you assemble the chart JSON yourself and write it into the component, and the component only passes it to the front end unchanged; or you hand over a few columns of data and let the component compute coordinates and group them itself. The first is flexible, the second is convenient.

The gallery side covers a different set of parameters: how many images per row, how many rows, how an image fits into its cell, and which one is shown first on load. Plus three events: what you do and don’t get when you click an image, open the preview, and close the preview.

10.1 Plot and Chart Data Passthrough

Plot takes a PlotData. Two fields: a library name and that library’s own drawing.

plotly = gr.Plot(
    value: new PlotData("plotly", TaskChart.PlotlyBars(rows)),
    label: "Hand-built Plotly");

The first field is the library name, one of four: plotly, bokeh, altair, matplotlib. The front end uses that name to find the matching plotting library and passes the second field to it unchanged. The second field is the JSON that library recognizes: plotly wants a plotly figure, altair wants a vega-lite spec, matplotlib accepts a base64-encoded image. The component doesn’t interpret a single byte.

That’s all “passthrough” means. It doesn’t care what’s drawn inside, only about delivering the string. The upside is a high ceiling: anything plotly can draw, you can draw here, including 3D, maps, and animations that the component itself can’t make. The downside is a low floor too: axes, colors, aggregation, sorting — all of it has to be computed on the business side and written into that JSON.

The Plotly bar chart in the sample draws “how many tasks each tag has”. Counting that number uses a business-side method.

    public static IReadOnlyList<(string Tag, int Count)> CountByTag(IEnumerable<TableRow> rows) =>
    [
        .. rows.GroupBy(row => row.Tag).Select(group => (group.Key, group.Count())),
    ];

After counting, it still has to be assembled into JSON. The sample doesn’t hand-write the string; it serializes an anonymous object instead.

    public static string PlotlyBars(IEnumerable<TableRow> rows)
    {
        var counts = CountByTag(rows);

        var figure = new
        {
            data = new[]
            {
                new
                {
                    type = "bar",
                    x = counts.Select(pair => pair.Tag).ToArray(),
                    y = counts.Select(pair => pair.Count).ToArray(),
                    marker = new { color = "#1d4ed8" },
                },
            },
            layout = new
            {
                title = new { text = "Tag counts (Plotly)" },
                height = 300,
                margin = new { t = 40, r = 20, b = 50, l = 50 },
            },
        };

        return JsonSerializer.Serialize(figure);
    }

The anonymous object’s field names become the JSON keys, so they’re all lowercase here: data, layout, type, marker. Change one to uppercase Data and plotly won’t recognize it — nothing appears, and no error is reported. That’s the easiest trap when assembling JSON: C# compiles fine and the UI is a blank space.

A wrong library name behaves the same. new PlotData("chartjs", json) goes through, the server doesn’t stop it, and the front end gets a library name it doesn’t know, so the chart area stays empty. The four names are a hard constraint; there is no fifth.

The left-hand path in Figure 10-1 is exactly that: the business side counts, assembles JSON, wraps it in PlotData, the component passes it to the front end unchanged, and the front end picks the library by name. The right-hand path is next section’s NativePlot. Both routes reach the same place in the front end; the only difference is “who computes”.

Figure 10-1 Plot passthrough and NativePlot direct drawing: one gives JSON, the other a table

Plot has no title, xTitle, or the like. Its parameter list is short: value, format, label, every, container, scale, minWidth, visible, plus the few that every component has. What text appears on the chart and what the axes are called all live in the JSON’s layout — the sample’s title.text and margin do exactly that. On the passthrough route, the chart’s appearance belongs to the JSON; the component only passes the JSON to the front end unchanged.

format is for images and defaults to "webp". The matplotlib route hands the component an image, and the component handles it in that format. The sample goes through plotly, where the format is irrelevant, so it’s left alone.

Give it an empty value and the chart area sits empty. The sample’s “Clear” button returns six empty values, and all six charts vanish together — the blocks remain, blank inside. It’s the same idea as a cleared table keeping only its header: the space stays, so the user knows something belongs here.

So when should you take this route? Three cases to consider. One, the chart you need is one the component can’t draw — 3D, maps, Sankey diagrams and the like. Two, you already have a piece of plotly JSON on hand, exported from somewhere or generated by a script. Three, the styling is fine-grained down to the width of each line and the font of each tick, beyond what the component’s few parameters can cover.

For everyday charts beyond those, the three components in the next section are less work.

10.2 LinePlot, BarPlot, and ScatterPlot

NativePlot is the other route. Instead of JSON you give it a table, tell the component “which column is the x-axis, which is the y-axis, which decides the color”, and it computes the rest itself.

Three factory methods correspond to three chart types: LinePlot for lines, BarPlot for bars, ScatterPlot for points.

            var line = gr.LinePlot(
                value: series,
                x: "Due",
                y: "Character count",
                color: "Tag",
                title: "Due and character count per task",
                xTitle: "Due",
                yTitle: "Character count",
                xAxisFormat: "%m-%d",
                xLabelAngle: 45,
                yLim: new double?[] { 0, 40 },
                height: 260,
                label: "Line chart");

The three factories’ parameter lists are nearly identical; go through them one by one and they line up. All have value, x, y, color, title, xTitle, yTitle, colorTitle, xBin, yAggregate, xLim, yLim, xAxisFormat, yAxisFormat, xLabelAngle, height, tooltip, caption.

There’s only one difference: what gets drawn. At runtime all three types are the same component, with a mark field in the value — line for the line chart, bar for the bar chart, point for the scatter plot. Apart from that field, the data the three send to the front end is identical.

That explains why their parameter lists can look the same: the three charts are the same thing, with only the final stroke drawn differently. It also explains why changing one parameter often works for all three. color means grouping in a line chart, side-by-side bars in a bar chart, and point color in a scatter plot — the meaning is consistent.

value can be one of two things. One is a “column name → values” dictionary, which is what the sample uses.

    public static IReadOnlyDictionary<string, object?[]> Series(IEnumerable<TableRow> rows)
    {
        var points = Points(rows);

        return new Dictionary<string, object?[]>
        {
            ["Tag"] = [.. points.Select(point => (object?)point.Tag)],
            ["Character count"] = [.. points.Select(point => (object?)point.Chars)],
            ["Due"] = [.. points.Select(point => (object?)point.Due)],
            ["Order"] = [.. points.Select(point => (object?)point.Order)],
        };
    }

Four columns, eight values; one task takes one slot in each column. The dictionary keys are the column names, and the “Due” in x: "Due" is exactly one of those keys. A misspelled key doesn’t error — you just get an empty chart. Like a wrong headers, the mistake is in the name and the UI only looks “a bit off”.

The other is NativePlotData, with four fields: Columns, Data, Datatypes, Mark. It’s the dictionary flattened out; the component converts the dictionary into it and sends it to the front end. To specify a column’s type yourself (say, treating a column of numbers as categories), you have to construct it directly — the dictionary route leaves no opening for that.

The component infers a column’s type from its values, by three rules.

  • Numeric values are quantitative, drawn to a numeric scale;
  • Date values are temporal, drawn on a time axis;
  • Everything else is nominal, drawn as categories.

Booleans count as numeric, because they work as 0 and 1. An empty column counts as categorical, because such a column has no members at all.

The sample’s four columns come out as: Tag categorical, Character count quantitative, Due temporal, Order quantitative. That’s why the line chart’s x-axis becomes a time axis and the bar chart’s x-axis is laid out as equal-width slots. The component inferred these types from the values.

One detail to know up front about the date type: what it sends to the front end is a millisecond count, not a string. The tooltip in Figure 10-4 reads 2026-03-02 08:00:00. The business-side DateTime is midnight on March 2, and the extra eight hours on the chart come from the time zone. The date column in Chapter 9 behaves the same way. Server and front end understand “an instant” one time zone apart, so keep that in mind when reading the values.

Which of the three to pick depends on the question you’re answering.

QuestionUseWhy
How it changes over timeLinePlotLines join the points, so the trend is visible at a glance
Who has more, who has lessBarPlotBar lengths are easier to compare than angles
How two numbers relateScatterPlotPoints spread over a plane, so correlation or its absence shows

The sample feeds the same data to six charts so you can see “one data set, six questions”. All six share a single series; none of them computes it a second time.

With six charts side by side, one more thing depends on label. In Figure 10-2 each chart has a line of small text in its top-left corner (“Line chart”, “Total”, “Count”, “Binned”, “Scatter”) — that’s the component’s label, not the chart’s title. The title sits at the top of the chart and says what the chart draws; the label sits at the block’s corner and says which component this block is. Both are set so the six charts can be told apart when placed together. showLabel: false hides the label; the title can’t be hidden — it lives in the JSON or the title parameter.

When the data is empty, the six charts are six blank blocks, with no error and no message. To see what “no data” looks like, click “Clear”.

Figure 10-2 The chart area: the same task table, one line chart plus three bar charts

The line chart in Figure 10-2 has only three line segments, yet the legend lists five tags. Nothing was lost: after grouping by color, each group gets its own line, and a group with a single point can’t form a line. The sample’s eight tasks spread over five tags, two of which have only one task each, so those two are left with just a name in the legend. To make a single point visible you need a scatter plot — a scatter plot draws points, and one point still gets drawn.

10.3 Coordinates, Grouping, and Aggregation

x and y are both column names. Give two columns and the points are laid out on those two. The sample’s line chart uses “Due” for the x-axis and “Character count” for the y-axis, so each task becomes a point in the plane whose x-coordinate is its due date and y-coordinate its character count.

Give a wrong column name, or one that doesn’t exist, and the chart is empty — no exception, no message.

color is also a column name, but it governs “splitting by this column”. Split a line chart by tag and each tag gets a line and a color; split a scatter plot by tag and the point color follows the tag. Omit color and all points count as one family — one connected line, one color for every point.

Grouping has two consequences. First, the legend lists the values of that column — five tag names in the sample. Second, each group’s points form their own line. That’s why “a single point can’t draw a line” from 10.2 shows up.

yAggregate decides “how multiple values at the same x-coordinate collapse into one”. Three settings: "sum" adds them, "count" counts entries, "mean" takes the average. The sample draws three bar charts; the first two share the tag as their x-axis and differ only in aggregation.

                sum = gr.BarPlot(
                    value: series, x: "Tag", y: "Character count", yAggregate: "sum",
                    title: "Total character count per tag", height: 300, label: "Total");

                count = gr.BarPlot(
                    value: series, x: "Tag", y: "Character count", yAggregate: "count",
                    title: "Number of entries per tag", height: 300, label: "Count");

                bin = gr.BarPlot(
                    value: series, x: "Character count", xBin: 2, y: "Character count", yAggregate: "count",
                    title: "Character count in two-character bins", height: 300, label: "Binned");

The two charts have identical data and both label their y-axis “Character count”, yet what they draw is completely different. Compute the same data once for each of the three settings and the results look like this.

AggregateTo-doIn ProgressDoneTo ConfirmArchived
sum121610108
count22211
mean685108

sum adds the character counts of the same tag, count counts “how many entries this tag has”, and mean is “the average characters per entry”. One column of data, three questions, three answers. The mean row in the table isn’t drawn as a chart — it’s not among the three charts; the algorithm is the same, so you can compute the values yourself against it.

count has one oddity: it doesn’t use the y-column’s values, yet that column still has to be written. Write x: "Tag" with yAggregate: "count" and no y — the server accepts it, but the front end errors while drawing and the chart area is left blank. All three bar charts in the sample dutifully write y: "Character count", even though count never looks at it.

Now look at the y-axis ticks. The Total chart runs from 8 to 16, the Count chart from 1.0 to 2.0. The counts are plainly integers, yet the ticks carry decimals. Because that column was inferred as quantitative, the axis is drawn as a numeric axis and decides its own tick spacing — it doesn’t switch to integer ticks just because “the values happen to be integers”. To make it tidy you’d have to turn the column into a categorical one, but then bar heights would no longer be compared by value.

The scatter plot uses the “Order” column on its y-axis, and not for looks. Among the eight tasks, character count has only seven distinct values from 4 to 10; when two numbers match, two points overlap and it looks like one is missing. Put “which entry” on the y-axis and each task gets its own row, so all eight points spread out. A scatter plot shows the relation between two numeric columns; pick a y-column where “every row differs” and the points won’t coincide — and Order is exactly such a column.

xBin cuts the x-axis column into bins and then aggregates. The sample’s third chart uses xBin: 2, so the axis is split two characters per bin: four to six, six to eight, eight to ten. Each bin gets one bar whose height is how many entries fall in it.

                bin = gr.BarPlot(
                    value: series, x: "Character count", xBin: 2, y: "Character count", yAggregate: "count",
                    title: "Character count in two-character bins", height: 300, label: "Binned");

Binning is a bar-chart-only technique; line and scatter plots don’t use it, since their x-axis is continuous to begin with. xBin gives the bin width, not the bin count. Write 2 and it’s two characters per bin: eight character counts between 4 and 10 naturally fall into three bins. Change it to 10 and all eight numbers land in the “zero to ten” bin, leaving a single bar.

color and aggregation can be used together. Then color splits by the color column, each bar gets its own color, and the legend still lists that column’s values. To assign colors yourself, use colorMap — a “value → color” dictionary: give a few values their colors and the rest use the default. The sample doesn’t set it, so all five bars are one color, which doesn’t affect comparing lengths; to really tell “Done” and “To-do” apart, colorMap is easier to distinguish than the default palette.

All three bar charts in the sample set the aggregation explicitly. Leave it out and how multiple values at one x-coordinate are placed depends on the chart’s own default — not something you can reliably guess. If you want merging, write sum, count, or mean clearly; don’t leave it to the default.

Placing the three bar charts side by side serves one more purpose: seeing what “the x-axis changed” means. The first two use the tag as the x-axis, the third uses character count. Same data, and switching the x-axis changes the story the chart tells. That’s also the first step in choosing a chart: decide which column goes on the x-axis.

Figure 10-3 Scatter plot and Plotly: on the left the component draws, on the right you assemble it yourself

The right-hand chart in Figure 10-3 is the passthrough from 10.1: the bar heights are entry counts computed by the business side per tag, the color is hard-coded in the JSON, and even the margins are filled in by hand. In the left-hand scatter plot, coordinates, legend, and axes are all computed by the component from four columns of data. Put them side by side and the difference between the two routes needs no further explanation.

10.4 Titles, Ranges, and Tooltips

title is the chart’s title, drawn centered above it. xTitle, yTitle, colorTitle are the three axis names — x-axis, y-axis, legend. The sample’s line chart sets all four, so “Due and character count per task” sits at the top and “Due”, “Character count”, “Tag” sit against their axes.

All four are plain text: whatever you write is what shows, and they take no part in computation. Omit title and the space above the chart is empty but takes no room; omit an axis name and the axis edge is empty. With many charts, titles are indispensable — six charts side by side with no titles can’t be told apart.

xLim and yLim are each a two-number array, lower bound and upper bound. The sample’s line chart pins the y-axis to 0 to 40.

                yLim: new double?[] { 0, 40 },

Pinning means points outside the range aren’t drawn. The sample’s character counts max out at 10, far from 40, so in practice this setting only stretches the y-axis and squeezes the three lines into the lower half. With a data set whose counts reach 60, the points above 40 disappear — they’re still there, just outside the window.

A range and “truncated data” are two different things. Truncation means data is missing; a range only means it isn’t drawn. Remove yLim and the blocked points come straight back, because the data was always there — only the window changed.

The range parameter is meant for continuous axes. The sample pins only the line chart’s y-axis, which is a numeric axis — the only kind where pinning makes sense. When the x-axis is dates or categories, pinning a range means “only look at this stretch”, but those slots are labels, not numbers, so what to pin depends on the data itself.

The most common use of a fixed range is “several charts sharing one ruler”. If each of six charts sets its own y-axis from its own data, one bar reaches 16 and another 2, and side by side they look eight times apart; pin them all to 0 to 20 and the lengths become comparable. The sample doesn’t do this, because the six charts have different x-axes and their bar lengths weren’t directly comparable anyway.

xAxisFormat controls how dates are written on the axis. The default writing is two lines: the time on top, the date below. All of this sample’s data falls at the same instant, so every slot on the top line reads “12 PM” — it looks broken, and you have to read the date from the line below.

Change it to "%m-%d" and only month and day remain, written on a single line.

                xAxisFormat: "%m-%d",

This parameter governs the writing, not the spacing. How many ticks there are is decided by the axis from the range. The sample’s due dates span fourteen days, and the axis picked a half-day interval, so each date appears twice — March 2, March 3, another March 3, March 4… Those repeated dates correspond to one midnight tick and one noon tick, and once the format hides the time, the two ticks look identical.

When they crowd together, tilt the labels.

                xLabelAngle: 45,

Tilted, each label takes less horizontal width, so twenty-odd dates fit. The cost is taller rows — space has to be left at the bottom of the chart.

tooltip is the hover box. Its default is "axis". Hover anywhere on the chart and it finds the nearest point and lists that point’s values for every column. Figure 10-4 shows the mouse resting on the first point.

Figure 10-4 The hover tooltip: character count, due, and tag columns are all there

The tooltip has three lines: Character count 7, Due 2026-03-02 08:00:00, Tag To-do. It lists “this point’s value in every column”, not “the few values you care about”. The eight-hour offset on the Due column shows up most clearly here.

To show only a few columns you can give tooltip a list of column names. The sample once wrote ["Tag", "Character count"], and on hover all three columns were still listed. The parameter doesn’t narrow the columns — with or without it, all three show — so the sample leaves the default "axis" and doesn’t set it again. "none" turns the tooltip off, "data" lists data without the axis; both are useful when you only want to look at the chart and not check numbers.

The tooltip on a bar chart is a different matter. Hover over the “Done” bar and it shows Character count 10. Ten is that tag’s total character count, yet the tooltip still writes the column name “Character count”, not “Total”. That’s because the tooltip lists “this cell’s values in each column”, and the aggregated number lands in the Character count column with its name unchanged. When reading it, know you’re looking at an aggregate, not one row’s character count.

height is the block’s height in pixels. It isn’t the same as the chart’s own height. The chart draws at its own size, and if the block is shorter, the bottom gets cut off. The sample’s bar charts started at 240, which clipped the bar bottoms and the x-axis labels; setting them all to 300 made the charts whole. This parameter adjusts “how much space is left”, not “how big the chart is”.

caption is the explanatory text below the chart — plain text, not part of the tooltip. It and title sit one above, one below: one says “what this chart draws”, the other “where this chart came from”. The sample doesn’t use it; the figure captions live in the book, and an extra line on the UI would only crowd it. In a product, caption suits notes like “data current as of”.

Clearing the charts follows the old path from Chapter 3: the handler function returns empty values and the components go empty.

(object, object, object, object, object, object) ClearCharts()
    => (null!, null!, null!, null!, null!, null!);

Click “Clear” and all six charts vanish together, blocks still there and empty inside. Click “Draw charts” and all six come back.

(object, object, object, object, object, object) Draw(string items)
{
    var rows = TaskTable.FromLines(items.Split('\n'));
    var series = TaskChart.Series(rows);

    return (series, series, series, series, series, new PlotData("plotly", TaskChart.PlotlyBars(rows)));
}

Six outputs for six components; the first five are the same dictionary. Those five charts read the same data, so there’s no reason to compute it five times. The sixth is the Plotly chart, which wants a PlotData, so it gets wrapped separately. The items input is the content of the “Filter” text box on the left. Edit a few lines, click “Draw charts”, and all six charts change with them. Where a chart’s data comes from and when it’s recomputed is still the Chapter 3 rule.

Gallery takes a sequence of entries. An entry can be a path, a URL, an image object, bytes, a stream, or a combination of “image and caption”. The sample uses GalleryEntry.

static GalleryEntry[] Entries(IEnumerable<GalleryCard> cards) =>
[
    .. cards.Select(card => new GalleryEntry(ImageBook.PathOf(card), card.Caption)),
];

Two fields: image and caption. The caption shows below the image and stays with it when enlarged. Each of the sample’s six cards has a caption — “Line wrapping rules”, “Event table”, “Screenshot list”. Those words aren’t in the image; the entry carries them.

A path can be relative or absolute. The sample gives absolute paths, built from the output directory’s assets.

    /// <summary>The images ship with the app; at runtime they are looked up under assets in the output directory.</summary>
    public static string Folder => Path.Combine(AppContext.BaseDirectory, "assets");

The image files ship with the project, so at runtime there’s no looking elsewhere. Point the path at a file that doesn’t exist and the UI shows a broken-image frame, with no error — the same behavior as an <img> tag.

There are three ways to write an entry, all with the same effect: give just a path and no caption shows under the image; give a two-tuple (image, caption); or give a GalleryEntry. The sample uses the third, because named fields tell you which is the image and which is the caption when you read the code.

Once an image is handed to the gallery, the file is copied into the app’s own cache directory. The sample’s six PNGs go across unchanged, byte count intact; the gallery doesn’t re-encode, it just moves the file to a directory the front end can fetch from. The gallery doesn’t re-encode — it treats “something already an image” as a file to move and sends it to the front end as-is.

type decides what the handler function receives; it defaults to "filepath", which gives a path string. The sample only puts images into the gallery and never reads them back, so it uses the default "filepath".

Layout is set by three parameters: columns, rows, height.

columns is how many images per row. The sample’s wall sets 3, so six images form three columns and two rows. rows is the maximum number of rows; leave it out and it’s computed from the entry count — six images in three columns naturally make two rows. The sample’s “six in one row” block sets rows to 1, squeezing all six into a single row.

height is the block’s height. Together with rows it decides how big each cell is: block height divided by row count is one cell’s height. Give 500 with three columns and each cell is about 250 wide by 250 tall; give 180 with one row and each cell is only 180 tall, so the images are flattened.

When the three parameters don’t work together, the most common result is cropping. The block height is fixed, so the cells are fixed too, but the image isn’t necessarily that aspect ratio. That’s when you look at objectFit.

  • "cover" scales the image up to fill the cell and crops the excess;
  • "contain" shrinks the image to fit inside the cell and leaves the leftover space blank.

The sample’s wall uses cover: the image fills the cell and its edges are cropped. The color band on the card’s left and the number on its right remain, while the text in the middle may be cut a little. The sample’s strip uses contain: the whole image shrinks in, leaving a white margin on each side.

Figure 10-5 is the arrangement of these three blocks: a three-column wall at the top, six in one row in the middle, and a block that has the third card selected on load at the bottom, with three callback panels right below the wall.

Figure 10-5 The gallery area: a three-column wall, six in one row, plus three callback panels

Each arrangement has its place. When images are only placeholders and their content isn’t read, use cover (full cell, tidy, no blank space); when the content has to be readable, use contain — not a single word can be lost. Mix two aspect ratios in one gallery and cover crops them all to the same size while contain leaves them different sizes. The first is tidy, the second complete; pick one.

There’s one more parameter, fitColumns, which defaults to true: column widths are split evenly across the container and the images follow their cells. The sample leaves it alone. Even column widths are what most cases want — six images sit neatly in the container.

gr.Gallery is interactive by default, with toolbar buttons for upload, delete, download, and so on on the block. The sample doesn’t use them: the images come from the business side, so users don’t need to upload any. Those buttons don’t affect display, and being there does no harm.

The gallery and the previous chapter’s table are alike in one way: both are handed a whole batch of things and both lay them out in cells. The difference is what each cell holds. A table holds values, a gallery holds images. Table cells can be edited; gallery cells can only be viewed (or opened larger).

Figure 10-6 Two other arrangements of the same images: six in one row, and the third card selected on load

10.6 The Selected Item and the Preview Switch

selectedIndex is “which card to show first on load”, counted from 0. The sample’s third block sets selectedIndex: 2, so as soon as the page opens the third card is in the large view.

This parameter does more than its name suggests. Omit it and the gallery is a grid; set it and the gallery opens as “one large image + a strip of thumbnails”. The large image is the selected one, the thumbnails are all of them, and below sits a row of buttons for download, fullscreen, share, and close.

            var pick = gr.Gallery(
                value: Entries(Cards),
                columns: 3,
                selectedIndex: 2,
                height: 300,
                label: "Third card selected on load");

The bottom block in Figure 10-6 is that one. Same images, same columns; one extra selectedIndex changes the whole presentation. This suits a “detail page” that lands on one image immediately and lets the user flip left and right.

allowPreview decides “whether clicking one opens it”. It defaults to true: click an image and the gallery switches from grid to large view; click the cross in the top-right and it goes back to the grid. Set it to false and clicking does nothing.

“Does nothing” is meant literally. The sample’s “six in one row” block sets allowPreview: false: click the third card and nothing on the image changes, and the three callback panels below don’t move either — not even select fires. This is the exact opposite of a table’s interactive: a read-only table blocks editing but not selection, while a read-only gallery blocks selection along with it.

Why? Because in a gallery, “selecting” and “opening” are two sides of the same thing. Click a thumbnail and the gallery first puts it in the large view, then reports “this card was selected”. Without that large-view step there is no “selected” state and nothing to report. If you want something clickable but not enlarged, this component can’t do it — you’d have to assemble an Image with buttons yourself (Chapter 11).

You can remember the three parameters this way: allowPreview governs “whether it can be opened”, selectedIndex governs “which card it lands on at load”, and columns/rows/height govern “how it’s laid out while not opened”.

Put the two switches allowPreview and selectedIndex together and three combinations show up in the sample.

allowPreviewselectedIndexOn loadClicking one
truenot setGridSwitches to large view; both select and preview_open fire
truesetLarge view + thumbnail stripSwitches the large view; only select fires
falsenot setGridNothing happens

The difference between the first and second rows is “how many events fire”. Both can be opened; one opens from the grid (two events), the other is already in the large view (only select). This table clears up one easy misconception: selectedIndex isn’t the state of “which card is selected”, it’s only “which card to show first on load”. Real selection comes from the user’s click and is reported by select.

Figure 10-7 Click the third card: the wall switches to the large view, and “Select” and “Preview open” fire together

10.7 Callbacks for Opening and Closing the Preview

The gallery has six events: select, upload, change, delete, preview_open, preview_close. The sample uses three of them, exactly the chain of “click one”, “open”, “close”.

The three events share the same signature.

string OnPick(IReadOnlyList<GalleryEntry> entries, SelectData pick)
{
    var index = pick.Index ?? -1;
    var caption = index >= 0 && index < entries.Count ? entries[index].Caption : "(no such card)";

    return $"""
        **Select** card {index} · chosen from {entries.Count} cards

        Caption: {caption}
        """;
}

The first parameter is the whole sequence of entries, not “this one”. The second, SelectData, is injected by type. The Chapter 5 rule holds here too: it takes no slot in inputs, so the binding lists only one input, [wall.Wall], while the handler function has two parameters.

The difference among the three events is entirely in that second parameter.

select brings back the index. pick.Index is this card’s position in the whole sequence, counted from 0. In Figure 10-7 the “Select” panel reads “card 2” — the third card, index 2. Use that index on entries[index] to get the entry, and the caption and path are both in hand. It reports whichever card you click; of the three events it’s the only one that can pinpoint a specific card.

preview_open brings no index. It fires when the large view opens; the first parameter is still the whole sequence, but SelectData.Index is empty.

string OnPreviewOpen(IReadOnlyList<GalleryEntry> entries, SelectData pick)
    => $"""
        **Preview open** {entries.Count} cards on the wall

        Which card was opened: it does not say (index {pick.Index ?? -1})
        """;

That panel in Figure 10-7 writes exactly this: “6 cards on the wall, which card was opened — it does not say (index -1)”. It can tell you “someone is looking”, but not “which card they’re looking at”.

preview_close also brings no index. Click the cross in the top-right and it fires once, bringing back the whole sequence of entries.

string OnPreviewClose(IReadOnlyList<GalleryEntry> entries)
    => $"""
        **Preview close** {entries.Count} cards on the wall

        Which card was closed: it does not say either
        """;

After closing, it looks like Figure 10-8. The wall goes back to a grid, the “Preview close” panel changes one line, and “Select” and “Preview open” stay where they were. Closing doesn’t undo the open; it just fires once more.

Figure 10-8 Close the preview: the wall returns to a grid, and the three panels each log their own

Figure 10-9 The three events: when they fire, what they bring back, and what to do with it

Figure 10-9 sets the three events out in three columns. The middle column is the easiest to misread: “Preview open” sounds like “the user opened the third card”, but it only says “the user opened the preview”. For “which card”, you have to record it with select first. select and preview_open fire at the same instant — select carries the index, preview_open doesn’t.

Record it where? In a state that survives across events. The sample only writes the index onto a panel, so the next event can’t read the previous value. To actually “mark this card as seen when the preview closes”, you need a variable that persists across events — that’s state in Chapter 14. This chapter first gets clear on “who carries the index and who doesn’t”.

Two more boundaries are worth stating.

One: with allowPreview: false, none of the three events fire. No preview means no preview_open or preview_close, and select is gone too, because selection follows opening. Making a read-only gallery report “which one was clicked” isn’t possible.

Which of the three to pick works backwards from “what you want to know”.

  • To know which card the user clicked, bind select. It carries the index and is the most useful.
  • To know “someone opened the preview”, bind preview_open. It has no index and only suits things that don’t need to know which card — counting, analytics, pausing other actions.
  • To wrap up after closing, bind preview_close. It also has no index; what it can do is “restore things when closed”.
  • To know “which card changed to which”, none of the three is enough. select carries one index each time, so you have to store two consecutive values and compare them. Where to store them is that same question — across events, it takes Chapter 14.

upload and delete are for galleries where users upload images themselves. An upload completing and a card being deleted each fire once, and they also bring back the whole sequence of entries. The sample’s images come from the business side, so those two events aren’t bound. change fires when the value is replaced from code. The sample’s “Switch to two” takes that route: it replaces six entries with two, and the wall shortens accordingly.

10.8 Chapter Summary

Charts have two routes. Plot is passthrough: PlotData(library name, JSON), with the name one of four (plotly, bokeh, altair, matplotlib) and the JSON that library’s own drawing — the component doesn’t interpret a single byte. It’s flexible, but coordinates, colors, and aggregation all have to be computed yourself; a wrong library name or a wrong JSON key leaves the chart area empty, with no error.

NativePlot draws directly. Give it a “column name → values” dictionary, say which columns x, y, color take, and the component computes the rest. The three factories LinePlot, BarPlot, ScatterPlot share one parameter list and differ only in mark: line, bar, point. Column types are inferred from values — numbers are quantitative, dates temporal, everything else categorical; Booleans count as numeric and empty columns as categorical. Dates are sent to the front end as milliseconds, so the tooltip shows an extra eight-hour time-zone offset.

color is grouping: a line chart splits by it, one line per group, and a group with a single point can’t form a line. yAggregate has three settings — sum adds, count counts entries, mean takes the average — three questions over one column. count requires y; omit it and the chart area goes empty. xBin cuts a numeric column at a fixed bin width; it gives the width, not the bin count.

title, xTitle, yTitle, colorTitle are plain text. xLim, yLim are display ranges: points outside aren’t drawn, but the data isn’t gone. xAxisFormat changes only how dates are written, not tick spacing; when labels crowd, tilt them with xLabelAngle. tooltip defaults to "axis", listing a whole point’s values across all columns on hover. height is the block height; smaller than the chart’s own height and the bottom gets clipped. Clearing the charts returns empty values and all six go blank together.

Gallery’s value is a sequence of entries; an entry can be a path, a URL, bytes, a stream, or “image + caption”. columns sets how many per row, rows the maximum rows, height the block height — the three together decide how big each cell is. objectFit decides how an image fits its cell: cover crops to fill, contain leaves margins.

selectedIndex is which card to show first on load; set it and the gallery opens as “one large image + a thumbnail strip”, not a grid. allowPreview decides whether it can be opened; set it to false and clicking does nothing, not even firing select. In a gallery, selecting and opening are the same thing.

All three events bring back the whole sequence of entries. select adds an index (counted from 0) that pinpoints a specific card; preview_open and preview_close have an index of -1 and only say “opened” or “closed”, not which one. For “which card”, you have to record it with select, in a state that survives across events — that’s for a later chapter.

What’s in the charts and the gallery can’t be saved either. Refresh and the six charts go back to their initial data, the gallery back to six cards. The two swapped-in images and the opened preview all live on the page and don’t persist. Saving has to wait for state in Chapter 14.

The next chapter switches to heavier content: images, audio, video, and 3D models, each with their own sources, types, and formats.