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 5. Events and Interaction Bindings

The page in Chapter 4 has a button that does nothing when you click it. This chapter wires it up.

An event is the line between a “component” and a “handler function”. Chapter 3 covered what a handler function should look like, but not how to connect this line; Interface connects it for you, while in Blocks you connect it yourself. This chapter follows the bindings in the sample: trigger conditions, which components to read and write, how repeated clicks are coalesced, and how several steps are chained together.

This chapter’s sample adds two “playgrounds” on top of the skeleton. They exist for this chapter and are separate from the workbench itself. One uses a single input box to show the difference between four events; the other uses three buttons to show coalescing and dropping under repeated clicks. After this chapter you can delete both blocks wholesale without affecting the workbench itself.

Figure 5-1 The UI with events wired up: inputs on the left, results on the right, two playgrounds at the bottom

The page is much longer than in Chapter 4, but the structure is still those three parts: title, main body, footer. The two columns in the main body haven’t changed; what has changed is that they now respond to actions. The two blocks at the bottom are this chapter’s playgrounds; everything from “Event Playground” down can be deleted.

5.1 Trigger Differences Between Click, Change, Input, and Submit

Of the four events, Click is the easiest to understand: a button is clicked once. The other three are all on input boxes, and the difference lies in “what counts as one trigger”.

Start with the conclusion. The figure below shows which events four actions trigger on the same single-line input box.

Figure 5-2 The same input box, and which events each of the four actions triggers

You can read three rules out of the figure.

Input only recognizes user actions. Keystrokes and pressing Enter both fire it; a program writing a value in does not. It answers “did the user touch it?”.

Change only recognizes whether the value changed. Type a key and the value changes, so it fires; a button writes a value in and the value changes too, so it fires just the same. It answers “did the value move?”.

Submit is only on single-line boxes. Press Enter in a single-line input box and it fires; press Enter in a multi-line input box and it’s a newline, so it does not fire. Bind Submit to a multi-line box, put the cursor in it, and press Enter: you only get one more empty line, and the Submit cell doesn’t budge.

The difference between Click and the others is not the trigger condition but the trigger source. The first three come from inside the input box; Click comes from a button. So “the user typed something” and “the user clicked a button” are two kinds of events and shouldn’t be understood together.

The table alone isn’t enough; you have to see it in motion. The sample’s “Event Playground” does exactly that. A single-line box called “Try it”, with four events each writing to its own cell.

Figure 5-3 Type three characters in “Try it”, and both Input and Change move

Type three characters and both the Input and Change cells read “3 characters”. At this point they look identical; the difference comes in the next step.

Figure 5-4 Click “Write example”: Change follows, Input stays at 3 characters

The “Write example” button does one thing: it writes that sample text into “Try it”. That’s a program changing the value, with nobody touching the keyboard. The result is unambiguous. Change becomes 139 characters, Input stays at 3 characters.

Behind these two cells are two bindings; the whole playground has six in total, plus two small functions.

    events.Probe.Input((string s) => Echo("Input", s), [events.Probe], [events.OnInput], triggerMode: TriggerMode.AlwaysLast, apiName: "Try Input");
    events.Probe.Change((string s) => Echo("Change", s), [events.Probe], [events.OnChange], triggerMode: TriggerMode.AlwaysLast, apiName: "Try Change");
    events.Probe.Submit((string s) => Echo("Submit", s), [events.Probe], [events.OnSubmit], apiName: "Try Submit");
    events.Probe.Focus((string s) => Echo("Focus", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Focus");
    events.Probe.Blur((string s) => Echo("Blur", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Blur");
    events.Write.Click(() => SampleText, null, [events.Probe], apiName: "Try Write");
static string Echo(string what, string value)
    => value.Length == 0 ? $"{what} · empty" : $"{what} · {value.Length} characters";

Five of the bindings look much alike: the same input box, the same Echo, each writing to its own cell. The last one is different. It’s the Click of the “Write example” button, writing the sample text into “Try it” to create the “program changes the value” scenario.

That’s the entire disagreement between Input and Change. Which one you pick depends on whether you want to follow “values changed by a program”.

  • Only care about user input? Use Input. For example, feedback that follows your hands like “prompt as you type”.
  • Need to sync whenever the value changes? Use Change. For example, a program backfilling a value, loading a sample, or another component changing the value.

In the sample, the “Source text” box is bound to Change, not Input, and the reason is right here. Next to it is a “Load example” button that replaces the whole source text. If you bound only Input, the character-count label and button state wouldn’t update with it, and the user would see the previous character count.

    input.Text.Change(Count, [input.Text], [input.Text, input.Run], triggerMode: TriggerMode.AlwaysLast, apiName: "Character count");

The triggerMode parameter in this line is covered in 5.4; for now, just remember it has to do with fast typing.

There’s a misconception carried over from web development; let’s dispel it first. Change does not “fire only on blur.” The browser’s native change event does work that way: you edit an input box, click elsewhere, and it fires once. Gradio’s Change doesn’t — it fires on every keystroke. So “bind a Change to query the database” turns into one query per character typed. To prevent that, use the triggerMode covered in 5.4, or simply don’t do heavy work inside Change.

Submit has a narrower place; it only makes sense on single-line boxes. The typical single-line scenario is “enter a name, an address, press Enter to submit”. The user doesn’t have to go looking for a button. Multi-line boxes don’t bind Submit, because Enter there is a necessity (writing the Body needs newlines). If you want “Enter to submit” on a multi-line box, Submit can’t help; you need another approach (more on that in Chapter 6, when we cover Textbox’s button parameters).

Click and Submit often come as a pair: press Enter in a single-line box, or click the button next to it, and the same thing happens. To support both, bind twice — write the same set of inputs and outputs twice, with the same handler function. Whether to give the two bindings different apiName values depends on whether you want to tell them apart in the API; on the UI they do the same thing, so the two bindings can share one name.

One more detail about Click: a button click carries no extra event data. You can’t ask in the handler function “which button was just clicked”. If you want to know “what was in the input box when it was clicked”, list the input box in inputs. Input boxes, on the other hand, can get event data, covered at the end of 5.3.

5.2 Use Cases for Blur and Focus

The two focus events are one in, one out. Focus is the cursor coming in, Blur is the cursor leaving.

In Figure 5-4, the Focus cell reads “Blur · 3 characters”. That’s because clicking “Write example” moves the cursor out of “Try it”, and clicking a button counts as leaving too.

Focus events suit three kinds of things.

Editing-state hints. Show “Editing” when the cursor comes in and “Saved” when it leaves. This kind of hint doesn’t need to know what the value is, only whether the person is there.

Validation on leave. The user fills in one cell and clicks to the next; that’s the most natural moment to validate. It neither interrupts typing nor waits until submit to find a problem.

Drafts. Save the current value on leave, and show “you left off halfway last time” when they come back. For real persistence you have to wait for state in Chapter 14.

It’s not suited to being used as “the value is done changing”. The user may just switch windows or click elsewhere without changing a single character, and Blur still fires. To judge “the value really changed”, use Change.

These two are often used together. Take the “Characters per line” cell: the user enters 5, and you need to tell them “at least 10 characters per line”. The validation itself goes in Change (recompute as soon as the value changes), while the hint’s display timing can go in Blur (only remind them when they leave the cell, without interrupting typing). The benefit of separating them is that the user isn’t chased by red text while still editing, and what needs saying still gets said on leave.

Focus has one other use. It’s the only event that reflects “getting here with the keyboard Tab key”. For keyboard accessibility, Click can’t help; Focus can.

In the sample, both events write to the same cell, so you see the result of the last one. Going in writes “Focus”, coming out writes “Blur”. In real features you’d usually write them into two separate components.

There’s one more side effect of focus to know: clicking a button blurs the input box. In Figure 5-4, clicking “Write example” turns the Focus cell into “Blur” — that’s what this click causes. So a single “click a button” action can send the server two events, first Blur, then Click. If your Blur does heavy work, the user waits extra every time they click a button.

You can also use this the other way around. To keep “save on leave” from blocking a click, put the save in Blur and write the result elsewhere with Update; the click still happens, and neither side waits for the other.

5.3 inputs, outputs, and Handler Function Signatures

One event binding has to state three things: whose event it is, which components to read, and which components to write.

    var arrange = input.Run.Click(Arrange,
        [input.Name, input.Text, input.Width, input.Keep],
        [result.Body, result.Stats],
        apiName: "Clean up");

The first line is “whose event”: the Click of the input.Run button. The second is “which to read”: Result name, Source text, Characters per line, and Keep my edited body. The third is “which to write”: Body and Statistics.

The contract from Chapter 3 still holds here, unchanged down to the letter. However many components are in inputs, the handler function has that many parameters; however many are in outputs, it returns that many values.

What happens when they don’t match is covered in Chapter 3. Too few inputs: the missing parameters get the type’s default value. Too few return values: the missing outputs are cleared. Too many: they’re dropped. None of it raises an error; on the UI it’s just “the result is wrong”. This chapter on events merely moves that into the binding’s two arrays. Get an array wrong and the symptom is exactly the same as a wrong handler function, and harder to spot, because it isn’t in the function signature. After writing a binding, it’s best to check these counts against each other: the number of inputs, the number of parameters, the number of outputs, and the number of return values.

(object, string) Arrange(string name, string text, double? width, bool keep)
{
    if (TextLayout.NameError(name) is { } error)
    {
        throw new ArgumentException(error);
    }

    var result = TextLayout.Wrap(text, width);

    object body = keep ? gr.Skip() : result.Text;

    return (body, Stats(result.Report));
}

Four parameters for four inputs, two return values for two outputs. The reasoning behind the object body line was covered in Chapter 3. That position can be a string or Skip, so it has to fall back to the common parent type.

apiName is new in this chapter. It gives the binding a name that appears in /gradio_api/info and in the public API; if you don’t give one, the framework uses the handler function’s name (the line-wrapping tool in Chapter 2 has endpoints called /lambda or /Split). The sample gives each binding an explicit name such as Clean up. Spaces work in an endpoint name too, so /gradio_api/call/Clean up is valid.

One Kind of Parameter Doesn’t Take an inputs Slot

There is another kind of parameter that isn’t written into inputs: event data. To find out what this trigger brought back, put SelectData in the signature.

    // Illustration: this binding is not in the sample
    text.Change((string s, SelectData d) => $"value={s} Source text={d.Raw}", [text], [outBox], apiName: "with_data");

Two parameters in the signature, only one component in inputs. SelectData doesn’t count as an input slot; the framework fills it in by type. Type abc in the box and the d.Raw the handler function gets is abc.

Different components give different event data. SelectData carries the selected item and index (used most with selection components, met again in Chapter 7), KeyUpData carries the pressed key and current value, LikeData carries the like state. If you don’t need it, don’t write it. Writing it doesn’t take an input slot, but the signature looks more complex than it really is.

The same “what to read, what to write” can hang off multiple events. In the sample, “Clean up” hangs only off Click, but if you want both “click the button” and “press Enter” to clean up, bind once more with Submit and write the same set of inputs and outputs again. From Chapter 6 on you’ll see that one handler function hanging off two or three events is common.

Look at all the bindings in the sample together and you get a fairly useful map.

    // Clean up: the button runs the main step, then records, and finally picks Pass or Fail.
    var arrange = input.Run.Click(Arrange,
        [input.Name, input.Text, input.Width, input.Keep],
        [result.Body, result.Stats],
        apiName: "Clean up");
    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");
    arrange.Success(Pass, [input.Name, result.Stats], [result.Notice], apiName: "Pass");
    arrange.Failure(Fail, [input.Name], [result.Notice], apiName: "Fail");

    // When the source text changes, update the label and button state; both manual typing and "Load example" must keep up.
    input.Text.Change(Count, [input.Text], [input.Text, input.Run], triggerMode: TriggerMode.AlwaysLast, apiName: "Character count");
    input.Load.Click(() => SampleText, null, [input.Text], apiName: "Load example");

Six bindings, all read the same way: whose event, which to read, which to write. The input.Load.Click one has no inputs (null), because “Load example” doesn’t need to read anything. It returns a constant. The handler function is a lambda, one line long; a handler function that short doesn’t need a name of its own.

The null position can also be written as an empty array []; the two forms are equivalent. The sample uses null because it states more clearly that “this event reads no components” rather than “reads zero components”, even though the two are the same thing inside the framework.

A component can be an input and an output at the same time. The sample’s “Run log” does exactly that.

    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");

Record reads three things (result name, statistics, the old run log) and writes back into the run log. Read the old, write the new — this pattern is the only way to make output “accumulate” before there’s state (state isn’t covered until Chapter 14).

string Record(string name, string stats, string log)
    => $"{DateTimeOffset.Now:HH:mm:ss} {name.Trim()} · {stats}\n{log}";

A new line of record is added in front of the old ones, so the newest is on top. This function references no components; it only concatenates strings. The boundary between business logic and UI stays where it was.

The Sample’s Code Structure Changed

The Chapter 4 sample is flat: one using nested inside another, with all the components written inside. That won’t do in this chapter, because a binding uses components from the left and the right at the same time. The “Clean up” button is in the left column, Body and Statistics in the right; when you write the binding, both components have to still be in scope.

So the sample changed to one method per area (BuildInput, BuildResult, BuildEventLab, BuildClickLab), each returning the components it builds.

    InputArea input;
    ResultArea result;
    using (gr.Row())
    {
        input = BuildInput();
        result = BuildResult();
    }

BuildInput still has those using blocks, except that at the end it does return new InputArea(name, text, width, keep, run, load). InputArea is a record; its six fields are those six components. The bindings are written together at the top, accessed as input.Name, result.Body, and so on.

That’s the “write areas as methods” from Section 4.3 of Chapter 4.

InputArea BuildInput()
{
    using (gr.Column(scale: 2, minWidth: 480))
    {
        gr.Markdown("### Text Cleanup");

        var name = gr.Textbox(label: "Result name", value: "Wrapped text", interactive: true);
        var text = gr.Textbox(label: "Source text", lines: 8, value: SampleText, interactive: true);
        var width = gr.Number(label: "Characters per line", value: DefaultColumns, interactive: true);
        var keep = gr.Checkbox(label: "Keep my edited body", value: false);

        Button run;
        Button load;
        using (gr.Row())
        {
            run = gr.Button("Clean up", variant: "primary");
            load = gr.Button("Load example");
        }

        return new InputArea(name, text, width, keep, run, load);
    }
}

Compared with the flat code in Chapter 4, there are only two differences: a method wrapped around the outside, and one extra return at the end. The “declare first, assign inside the using” style of Button run; exists because both buttons have to sit in one Row, and variables inside a using block cease to exist once you leave the block.

The record definition is as follows.

sealed record InputArea(Textbox Name, Textbox Text, Number Width, Checkbox Keep, Button Run, Button Load);

It has no methods; it only bundles a few components and carries them out. The field names are exactly the ones used in the bindings, input.Name, input.Run.

5.4 triggerMode and Concurrent Triggers

What about repeated clicks? It’s a question every UI with buttons has to answer.

The sample’s “Repeated Clicks Compared” area has three buttons that do the same thing: wait 600 milliseconds, then report which run this is. Each button has a different triggerMode; click each one four times in a row and the result looks like this.

Figure 5-5 Four repeated clicks each: Default runs once, Last runs twice, All runs four times

Three lines of text, three behaviors.

Default (no triggerMode) runs once. The first click starts the run; the next three arrive before it finishes and are dropped outright.

AlwaysLast runs twice. The first runs immediately, the middle two are dropped, and the last is kept; once the first finishes, that last one is added.

Multiple runs four times. All four run, one after another. The queue lets only one through at a time, so four runs are four 600-millisecond stretches.

Why is the default “drop” rather than “queue”? Because the most common scenario is “the user’s hand slipped and clicked too many times”, not “the user really wants five runs”. A ten-second task clicked five times would queue up fifty seconds of running, and the user would just think the program is broken.

The semantics of AlwaysLast take a little more thought. It guarantees “the last state is always computed”. The user changes parameters a few times, clicks repeatedly, and you want the final result to correspond to the last click, not the first. Use AlwaysLast for that scenario.

Multiple is used less, but it isn’t useless: it’s for occasions where every click should leave a trace. Take a “Record” button — five clicks should produce five records.

What does the user see for the clicks that get dropped? The button is still clickable, and clicking gives no feedback at all. While a 600-millisecond run is in progress, the button is still clickable; clicking it just does nothing. This isn’t a defect. If the button were disabled during the run, the user would think the program froze; keeping it clickable at least avoids the feeling of “I can’t click it”. The cost is that the user may not know their click was ignored. Fixing that takes progress display (Chapter 16) and button state (Interactive in 5.7).

The three modes differ in how they handle repeated clicks. Default holds in exactly one case: repeated clicks should not repeat the run. To guarantee “the final result corresponds to the last click”, use AlwaysLast; to leave a trace every time, use Multiple. When you can’t decide, ask first: the user clicks five times — how many runs do they want?

ScenarioWhich to useReason
Ordinary submit, queryDefaultExtra clicks from a slipping hand shouldn’t cause extra runs
Change a few parameters, then submitAlwaysLastThe final result must correspond to the last click
Every time needs a recordMultipleFive clicks should give five records
Input / Change on an input boxAlwaysLastDon’t let the result stop halfway

One more emphasis on the last row. The first three rows of the table are about “the user clicks a button”; the last row is about “the user types”. The two look like the same thing (both are high-frequency triggers), but typing is denser, so the default “drop” makes the UI visibly lag. In the sample, both high-frequency events Input and Change are written with AlwaysLast; Submit and the focus events are low-frequency to begin with, so they aren’t.

One more thing to make clear: triggerMode is not throttling. Throttling is “run at most once every 200 milliseconds”, and merges the intervening triggers into an average; triggerMode either drops later ones (default), waits for the current run to finish and then adds the last one (AlwaysLast), or runs every time (Multiple). It doesn’t make judgments like “wait until the user stops”. If you want to query after input has stopped for 300 milliseconds, you have to wait in the handler function yourself, or use Textbox’s input throttling parameter (covered in Chapter 6). For this chapter you only need to know that it governs “how repeated triggers are handled”, not “how often to run”.

static class Runs
{
    private static int once;
    private static int last;
    private static int all;

    public static string Once() => Run("Default", ref once);

    public static string Last() => Run("Last", ref last);

    public static string All() => Run("All", ref all);

    private static string Run(string label, ref int counter)
    {
        Thread.Sleep(600);
        return $"{label} · run {Interlocked.Increment(ref counter)}";
    }
}

The three methods differ only in the counter and the wording. Thread.Sleep(600) is deliberate. Real line wrapping takes only tens of milliseconds — so fast that four clicks wouldn’t overlap at all, and you’d never see the coalescing. Slowing it down is what makes the coalescing visible.

The counters sit in static fields only so this chapter can show “how many runs happened”. They belong to the process, not to any one user; real session state is covered in Chapter 14.

The three buttons’ bindings differ by only one parameter.

    clicks.Once.Click(Runs.Once, null, [clicks.OnceLog], apiName: "Repeated Clicks Default");
    clicks.Last.Click(Runs.Last, null, [clicks.LastLog], triggerMode: TriggerMode.AlwaysLast, apiName: "Repeated Clicks Last");
    clicks.All.Click(Runs.All, null, [clicks.AllLog], triggerMode: TriggerMode.Multiple, apiName: "Repeated Clicks All");

triggerMode has one more use, unrelated to repeated clicks: high-frequency events.

Input and Change fire once per keystroke in an input box. A fast typist can hit five or six keys a second, and the default “drop” leaves the UI stuck on the result of the first keystroke. In the sample, both events on “Try it” are written with AlwaysLast, precisely so fast typing doesn’t leave the result halfway. Omit this parameter and a reader typing quickly will see “3 characters” after typing 5, then assume the count is wrong.

5.5 The queue Parameter and Immediate Events

Events go through a queue by default. The queue is a pipe: events come in, line up, and run one at a time (only one runs at a time by default). queue: false turns that pipe off, so the request goes straight to the handler function.

To compare queued and non-queued, use four buttons: two queued, two not, with every handler function waiting 600 milliseconds, then use a tool to click both in the same group at almost the same time.

Queued: A 16352–16964ms, B 16984–17588ms
Not queued: A 18881–19482ms, B 18889–19497ms

The queued group runs one after the other. B starts 20 milliseconds after A ends, so the two stretches barely overlap; the two intervals in the non-queued group almost completely overlap. From the first click to the second result, the queued group takes 1236 milliseconds and the non-queued group 616 milliseconds — exactly double.

When should you turn the queue off?

Turn it off for actions that are quick and must happen immediately. The two focus events in the sample have the queue off. The cursor moving in and out shouldn’t be queued behind typing, or the hint would take ages to appear.

Don’t turn it off for work that writes files, uses CPU, or calls external services. With it off there’s no queue protection, so a few repeated clicks really do run concurrently several times. The whole point of the queue is to line that kind of work up.

Here’s a counterintuitive point to know first. No queue doesn’t mean you can click repeatedly. Click a non-queued button four times and the handler function runs only once. After the click it ignores you for a while, and only recovers when the result comes back. So turning off the queue doesn’t let the same button “run more times”; what it changes is a different thing — whether two different events can run at the same time.

    events.Probe.Focus((string s) => Echo("Focus", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Focus");
    events.Probe.Blur((string s) => Echo("Blur", s), [events.Probe], [events.OnFocus], queue: false, apiName: "Try Blur");

To see the queue with your own eyes, open the browser’s network panel and click “Clean up”. You’ll first see a POST to queue/join, then a persistent queue/data (an SSE stream), with the result pushed back over that stream. Non-queued requests don’t take this path; they go straight to an immediate endpoint. This difference comes up again in Chapter 16 on streaming output. There, the queue/data stream pushes not just one result but a series of them.

What does the queue mean for the user? It means “after you click, you wait”. When several requests come in, the UI shows a queued or running state (that little spinning icon), and runs the next only after the previous finishes. This is also why the default triggerMode is “drop”. If repeated clicks all queued up, the user would see a long string of waits when they really only wanted one run.

The cost of turning off the queue needs to be clear: there is no queue protection. When two different events trigger the same handler function at once, the two really do run at the same time. If that function writes the same file or changes the same static variable, they’ll collide. In the sample, the only events with the queue off are the two focus ones, and they do only one thing: write a string into a cell, which doesn’t interfere with anything.

If running this action twice would cause trouble, don’t turn off the queue; use triggerMode to block repeats. If running twice does no harm and it must happen immediately, turn it off.

Queue limits, concurrency limits, and per-group throttling belong to Chapter 15. This chapter’s rule is: queue by default, and turn it off only when you’re sure “this action must happen immediately and is quick”.

5.6 Dependency and Chained Steps

One click can set off a chain of things.

Click “Clean up” in the sample and three steps actually run: first wrap the lines and write Body and Statistics, then add a record to the run log, and finally write a notice based on success or failure.

    arrange.Then(Record, [input.Name, result.Stats, result.Log], [result.Log], apiName: "Record");
    arrange.Success(Pass, [input.Name, result.Stats], [result.Notice], apiName: "Pass");
    arrange.Failure(Fail, [input.Name], [result.Notice], apiName: "Fail");

The return value of Click is a Dependency, representing “this one binding”. The chained steps hang off it, with the three methods each handling one segment.

  • Then runs after Click succeeds and before Success;
  • Success runs only when nothing before it went wrong;
  • Failure runs only when an exception was thrown before it.

Each step has its own inputs and outputs, independent of the others. Then reads the result name, statistics, and old log; Success reads the result name and statistics; Failure reads only the result name. They don’t share the main step’s return value. To use the main step’s result, you have to list that component in your own inputs.

On success the UI looks like this.

Figure 5-6 Click “Clean up”: the main step writes Body and Statistics, Then records, Success writes the notice

Failure looks different. Clear the result name, then click Clean up again.

Figure 5-7 Clean up again after clearing the result name: the main step throws, and only the Failure step writes a notice

Read the two figures side by side and you can draw three conclusions.

On success the order is main → Then → Success. In Figure 5-6, the run-log line was written by Then and the notice line by Success; both are there, which means the record was made before the notice was written.

On failure only Failure runs. In Figure 5-7 the run log is empty; Then didn’t run. The Body and Statistics positions are marked “Error” — that’s left by the main step’s exception, not written by Then or Success.

Failure can’t read the main step’s result. It lists only the result name, so what it gets is the empty string left after clearing; if it tried to read Statistics, it would get the value left over from the last success, or empty.

Those two red “Error” marks are added automatically by the framework. When the main step throws, the two positions it would have written are marked as errors, and the message is only two characters long. That feedback is weak: the user can’t tell what went wrong. So the Failure step has to write a sentence in plain language (in the sample it’s “Cleanup failed, the result name can’t be empty”). Turning exceptions into plain language is covered in more detail in Chapter 17. There you get the Error component, runtime prompts like gr.Error, and the ability to tell cancellation, timeout, and real failure apart.

Behind the third conclusion is an easy trap. When the main step throws, its outputs are not cleared. In Figure 5-7, Body and Statistics are marked “Error” because they were empty to begin with; if the previous run succeeded, the values in those two positions are still there, just covered by a red “Error” on the UI so they look gone. Turn that mark off or look from another position and the old values are still there. So in Failure, don’t treat the main step’s outputs as “this run’s result” — they’re always the old ones.

One more thing to add. Success and Failure look only at the main step, not at the steps after it. Make Then throw an exception itself and here’s what happens.

Normal:         Main=main:hi     Then=then:main:hi    Success=success:main:hi   Failure=
Then throws:  Main=main:boom   Then=then:main:hi    Success=success:main:boom  Failure=

In the second line, Then threw an exception (the cell it writes stayed at the previous value then:main:hi), yet Success still ran and Failure didn’t. The reason is that Success / Failure judge the main step’s success or failure, not the whole chain’s. So don’t expect “Then failing will go to Failure”. An error inside Then just means its own cell wasn’t written; everything else goes on as usual.

This rule affects how you split steps. If a later action’s failure must be visible to the user, don’t put it in Then and expect Failure to catch it; either move it back into the main step (make it “part of the main step”) or write the error into one of its own outputs inside that step.

There’s one more thing visible in the browser. One click, and the server receives three jobs. Click “Clean up” and the network panel shows three queue requests. The chain is three jobs queued one after another; the next one’s turn comes only after the previous finishes.

This has two practical effects. One is latency: three steps mean three round trips, a little slower than one run. The other is that each step is an independent event, so each has its own triggerMode, queue, and apiName; the parameter lists of Then and Success are identical to the main step’s, and they aren’t just for show. The sample doesn’t set these parameters and uses the defaults, because none of the three steps is heavy and none needs its own rate limiting; when a step does need separate control over concurrency or the queue, the parameters are given explicitly right here.

So why three steps? Because the three things have different responsibilities.

  • The main step only “computes the result”, with no record-keeping and no notice;
  • Record-keeping is something done “only after success”, so it goes in Then;
  • The notice has two tones, one line for success and one for failure, so it’s split into Success and Failure.

Stuff all three into the main step and the handler function ends up with mixed logic — “first compute, then build the log, then check for an exception and build the notice” — and once an exception is thrown, the code after it is never reached, so the notice can never be written. Chained steps take “the things that still have to happen after an error” out of the main step.

One limitation: a chain hangs only off “that one binding”. If the same handler function is bound to two events (say a button and Enter), the chain has to be hung once on each; it can’t be shared.

5.7 Linking Output Components to Inputs

By now events can fire, read, write, and chain. One common task remains. When an input changes, make other components change with it.

There’s one in the sample. The label above the source-text box shows the current character count; when the source text is cleared, the “Clean up” button turns gray.

Figure 5-8 Clear the source text: the label becomes “Source text (0 characters)”, the Clean up button turns gray, and the results on the right are left as is

Both changes come from the same handler function.

(object, object) Count(string text)
    => (gr.Update() with { Label = $"Source text ({text.Length} characters)" },
        gr.Update() with { Interactive = !string.IsNullOrWhiteSpace(text) });

It returns two Update values: one for the source text (label only), one for the Clean up button (interactivity only).

Why must you use Update here instead of returning a value? Chapter 3 covered it. A return value replaces the component’s displayed content wholesale; Update merges only the properties you name. In this scenario the difference becomes concrete.

  • Return a string to the source-text box and every keystroke replaces the input box’s whole content. What the user is typing gets wiped, and the cursor jumps to the end.
  • Return Update to change only the label, and neither the characters in the input box nor the cursor moves.

Figure 5-8 has one more piece of evidence: none of the four boxes in the result area on the right changed. If this handler function returned “redraw the whole page”, the result area would be cleared or redrawn; it didn’t, because Update touches only the two properties it names. That’s the “no wholesale redraw” from the start of this section. That’s simply Update’s semantics.

Interactive on a button means “can it be clicked”, on an input box “can it be edited”. In Figure 5-8, the orange Clean up button turns pale — that’s the effect of Interactive = false. This isn’t the same thing as the visible from Section 4.6. visible is whether it’s drawn; interactive is whether it can be operated.

There are three common kinds of linking, each with a bigger effect than the last.

Change the label. This is the sample’s kind. Change “Source text” into “Source text (112 characters)”. It moves one property and the rest of the page stays as it is. Good for “letting the user know the current state”.

Toggle a button. Use Interactive. Turn the submit button off when the content is empty and back on when there’s content. That’s friendlier than letting the button throw an error when clicked. The user can see “you can’t click this yet”. You can also use it the other way around: turn it off while a run is in progress and back on when it finishes (used in Chapter 16 on progress).

Hide a block. Use Visible. The advanced area in Chapter 4, hidden by default, is opened from false with Visible. Write gr.Update() with { Visible = true } to make it appear and false to make it disappear. Note the difference from Interactive: Visible = false means it isn’t drawn, Interactive = false means it’s drawn but can’t be operated.

    // Click to expand the advanced area (illustration, this binding is not in the sample)
    return gr.Update() with { Visible = true };

One thing to watch: the fewer properties in Update, the better. Every property you write is another merge on the client; five properties means changing five places at once. The sample writes only two because it really only needs to change two. When you’re tempted to “refresh everything”, ask first: did everything really change? Don’t write the ones that didn’t.

One limitation: Update can change a component’s properties, but not the structure. It can’t conjure up a component out of nothing, and it can’t move a component from one container to another. To change the structure you have to rebuild the page (Chapter 18 on multiple pages has other ways).

Looking back, the choice between Update and “returning a value” was settled in Chapter 3: a value replaces, Update merges. In this chapter on events the difference becomes more practical. A return value is only right for “this component’s content is exactly this run’s result”, like Body and Statistics; as soon as a component carries other state (label, interactivity, visibility), you have to use Update, otherwise you’d have to rewrite all those properties every time, and miss one and you lose one.

5.8 Chapter Summary

Click, Input, Change, and Submit are four different trigger semantics. Input only counts user actions, so programmatic value changes don’t fire it; Change only cares whether the value changed, so anyone changing it fires it; Submit fires only on Enter in a single-line box; Click comes from a button. Focus and Blur handle the cursor moving in and out, good for editing hints and validation on leave, but not for “the value is done changing”.

One binding has to state three things: whose event, which components to read, which components to write. The contract is the same as Chapter 3: number of inputs matches parameters, number of outputs matches return values. A component can be an input and an output at once — that’s how you let output accumulate before there’s state. One handler function can hang off multiple events, and a chain has to be hung once on each.

triggerMode has three settings. Default drops later triggers, AlwaysLast keeps the last one, Multiple runs them all. The default drop is to guard against a slipping hand; AlwaysLast suits “the final state must be right” scenarios, Multiple suits scenarios where every time must leave a trace. High-frequency events should also set AlwaysLast, or fast typing leaves the result halfway.

The queue is on by default, so events run one at a time; queue: false makes it execute directly, and two non-queued events can run at the same time. Turn the queue off only for actions that are “quick and must happen immediately”. No queue doesn’t mean you can click repeatedly: clicking the same button repeatedly still runs only once.

Chained steps. On success it’s main → Then → Success; on failure only Failure runs. Then runs only after the main step succeeds, and Failure can’t read the main step’s result from this run. Splitting “do the work”, “keep the record”, and “report the error” apart is what lets the main step only compute.

Update does linking: it changes only the properties you name and leaves everything else alone. It’s the only way that dares to write back to a component inside an Input event. A return value replaces the whole content; Update doesn’t.

Before writing a binding, ask three questions.

  1. Which event? Only when the user touches it (Input), whenever the value changes (Change), pressing Enter (Submit), clicking a button (Click), or the cursor moving in and out (Focus / Blur).
  2. What to read, what to write? The handler function’s parameters and return values correspond one-to-one with those two arrays.
  3. What about repeated clicks? Default drop, AlwaysLast, Multiple, or turning off the queue.

Answer the three questions and the binding is written. If you can’t, it’s usually the second question you haven’t thought through. Not knowing what to read usually means not knowing at which step to do the work. The three questions work in reverse too: read a binding someone else wrote, break it down along these three lines, and in a few seconds you can see what it does.

This chapter’s sample is much longer than Chapter 4’s, but the structure hasn’t changed: inputs on the left, results on the right, and two playgrounds at the bottom for this chapter. Delete those two playground blocks and what’s left is the workbench itself. It’s already usable. Change the source text, click Clean up, see the result, repeated clicks won’t run five times, and clearing the source text turns the button gray.

The next chapter starts on the components themselves. It begins with text and numeric inputs, filling in the workbench’s input area piece by piece.