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 3. Component Contracts and Handler Functions

The application in Chapter 2 runs because the two sides happen to line up, yet nothing in the code guarantees it. Split takes two strings, and inputs holds two Textboxes. The count and the types are hard-coded separately, with no check in between.

Switch to three inputs, or make one of them a number, and it no longer necessarily holds. What type a component passes to the handler function, which component a return value is written into, and what happens when the counts don’t match. These are the contracts this chapter makes clear. Once the contracts are clear, you can write the signature straight from a requirement, without trial and error.

This chapter’s example is a line-wrapping tool. A piece of text, a character count per line, and a switch; it outputs the wrapped Body, the Statistics, and the Notice. The business rules live in a class library that does not reference Gradio.NET, and the UI project is responsible only for components and type conversion.

3.1 Component Factories and value

First look at the code on the UI layer.

using Chapter03.Core;
using Gradio.Net;

const string SampleText = """
Wrapping looks simple,
but first settle a few small rules.
Trim each line ending,
Skip all blank lines
Then count lines and characters.
""";

var source = gr.Textbox(label: "Source text", value: SampleText, lines: 8);
var width = gr.Number(label: "Characters per line", value: 30);
var keepEdits = gr.Checkbox(label: "Keep my edited body", value: false);

var body = gr.Textbox(label: "Body", lines: 12, interactive: true);
var stats = gr.Textbox(label: "Statistics", lines: 2, interactive: false);
var notice = gr.Textbox(label: "Notice", lines: 3, interactive: false);

(object, string, object) Layout(string text, double? width, bool keepEdits)
{
    var result = TextLayout.Wrap(text, width);

    var report = result.Report;

    object bodyValue = keepEdits ? gr.Skip() : result.Text;

    var statsValue = $"{report.Lines} lines, {report.Characters} characters, longest line {report.LongestLine} characters";

    object noticeValue = report.Warnings.Count == 0
        ? "No issues to report"
        : gr.Update() with
        {
            Label = $"Notice ({report.Warnings.Count} items)",
            Value = string.Join("\n", report.Warnings),
        };

    return (bodyValue, statsValue, noticeValue);
}

var demo = gr.Interface(
    Layout,
    inputs: [source, width, keepEdits],
    outputs: [body, stats, notice],
    title: "Line Wrapping and Cleanup",
    description: "Wrap a piece of text by the character count per line, and also report the line count, the character count, and the longest line.",
    submitBtn: "Clean up",
    flaggingMode: "never",
    apiName: "layout");

demo.Launch();

Calls like gr.Textbox(...), gr.Number(...) and gr.Checkbox(...) are called component factories. Write one, get one component object; all the arguments are named and can be omitted. You can build one without writing any, like gr.Textbox(), and an empty box with no label appears on the page. It works, but nobody knows what to fill in. That is what label is for.

The six component objects go into variables first, then into inputs and outputs. This step is not required; you can also write inputs: [gr.Textbox(...), gr.Number(...)], putting the factory calls straight into the collection. The only benefit of writing them as variables is that it reads clearly. Who sits in which position can be matched at a glance across the two list lines.

A component object is a declaration, and also an object you can reference again.

It is a declaration because it tells the framework “there is an input box here on the page, labeled Source text, taking 8 lines”. Its position in inputs decides which input it is; its position in outputs decides which output it is.

Here we need to be clear about what a component object is. Writing gr.Textbox(...) produces a description: what the type is, what the label is, how many lines it takes, what the initial value is. The real input box is drawn by the browser from that description. So “using the same component object twice” is “asking for the same description to be drawn twice”. The framework rejects the latter, because a description and a position on the page are one-to-one.

value is a property of a component, but it has two identities. At construction time it is the initial value, the content pre-filled in the box when the page opens. Once running it is the current value: when the user changes it, it changes along; when the handler function returns a new value, it is replaced. So value is “the value this component holds at this moment”. It just happens that you can supply one at construction time. Chapter 2 said the initial value does not trigger a run when the page opens — that was about triggering; the value itself has always been this value.

A component object can go in only once. Put the same Textbox into inputs twice and constructing Interface throws an exception.

System.InvalidOperationException: 'Textbox' is not waiting to be rendered by this application;
it was never added here, belongs to another render root, or has already been rendered.

The meaning is simple. A component has only one position on the page; once rendered, it is gone. If you want two input boxes that look the same, create two component objects; if you want two inputs to share one configuration, extract a method that builds one each time, rather than stuffing the same object in twice.

One more thing: components in outputs are generally non-editable by default. This chapter’s body writes interactive: true, and that is what makes it editable by hand; stats and notice don’t write true, so they are grayed out.

Why are outputs read-only by default? Because they show the result of the handler function, not an input. Let people edit them and the edited content is not sent back, and it is overwritten again on the next run. This chapter’s body is an exception. This tool is used by “first wrapping automatically, then fixing a few lines by hand”, so it needs to be editable, and the “Keep my edited body” switch is there so the next run does not wipe out the manual edits. The Skip part is covered in 3.4.

Launch the example and the UI looks like this.

Figure 3-1 The initial UI of the example

Three inputs on the left, three outputs on the right, and a “Clean up” button in the middle. Source text already has an initial value, and all three outputs are empty. As in Chapter 2, opening the page does not run once.

3.2 Handler Function Parameters and Component Data Types

Layout’s signature is the core of this chapter.

(object, string, object) Layout(string text, double? width, bool keepEdits)

The three parameters correspond to the Textbox, Number and Checkbox in inputs, exactly one each.

The component decides the type; the handler function can only accept what it is given. The correspondence is listed in this table.

ComponentParameter type passed to the handler functionNotes
TextboxstringAn empty string when blank, not null
NumberdoubleCan be declared as int, decimal, double?; the framework converts according to the declaration
SliderdoubleSame as above
CheckboxboolOnly two possible values
DropdownstringA single value for single-select; the multi-select form is covered in Chapter 7

The Number row needs expanding. What the component itself passes to the handler function is a double. A number comes from the browser as a number in JSON and is read into C# as a double-precision floating-point value. You can declare the parameter as int or decimal and the framework converts once more according to your declaration; if it cannot convert, it reports an error rather than silently truncating. The example declares it as double? to tell “not filled in” apart from “filled with 0”. More on this in 3.5.

The declared type has to hold the value the component gives. A Textbox’s string fits into string and object; a Number’s double fits into double, float, int, long, decimal, double? and object; a Checkbox’s bool fits only into bool and object. The reverse does not fit. Stuff a Textbox’s string into an int and you get an exception. object always fits, so it is the most convenient while debugging and the least useful in everyday code, because the compiler can no longer help you.

Which numeric type to declare depends on whether you want decimals and whether you want precision. Use int for counts, double for ordinary measurements, and decimal for values like amounts of money that cannot have binary error. Number converts once according to the type you declared; if it cannot convert, it reports an error and does not round for you.

Parameters correspond by position. Layout’s first parameter is called text only because it sits first and corresponds to the first component in inputs; rename the parameter to content and everything stays the same. But the name is not entirely useless: it appears in the interface documentation. In this chapter’s /gradio_api/info, the parameter_name of the three parameters are text, width and keepEdits. What people see is label; what callers see is the parameter name.

That interface documentation can also answer “what does the framework think this component is”. In the same response, every parameter carries its type and component, {"type": {"type": "string"}, "component": "Textbox"}. When the signature is wrong and the UI shows only “Error”, look here first. It tells you which type the framework has computed for which component, which is faster than guessing in the code.

How do you know what type the component you wrote actually passes? You can wait until Chapter 6, when the components are covered one by one, and note them down; or temporarily write the parameters as object and print their runtime types inside the function.

static string Probe(object? a, object? b, object? c)
    => $"{(a?.GetType().Name ?? "null")} / {(b?.GetType().Name ?? "null")} / {(c?.GetType().Name ?? "null")}";

Return values have to be caught too. Output components have their own types as well; the rule is the same as on the input side, only the direction is reversed, and a component can only display values of its own kind. Textbox accepts strings, Checkbox accepts true/false, Dropdown accepts one of its options; give Number a string and it throws at runtime

System.ArgumentException: A number field's value is a number; the handler returned a System.String.

The input types are decided by the components, the output types are decided by the components, and the handler function sits in between, so the types on both ends must match. Once they match, the code in the middle is just ordinary C#. Not one line in this chapter’s Layout deals with type conversion; the conversion is all done on the component side.

3.3 inputs, outputs, and Multiple Return Values

Three inputs, three outputs, and the handler function returns a three-tuple. The correspondence is simply one-to-one in order.

Figure 3-2 Three inputs become three parameters, and three return values land back in the three outputs

Launch the example and click “Clean up”.

Figure 3-3 After clicking “Clean up”

The Body is wrapped to 30 characters per line, Statistics reports “7 lines, 109 characters, longest line 30 characters”, and Notice says “No issues to report”. The three return values each land in their own place, in the right order.

Inputs and outputs need not be equal in number. One input feeding three outputs is common, and three inputs feeding one output works too; there is no constraint on count, only on order.

A wrong position does not report an error either, it just computes wrong. Swap the order of the three output components in outputs and statistics text appears in the Body’s place. The types are all string, so any of them can accept it, and the UI just “looks a bit off”. This kind of error can be avoided by one thing only: the order of outputs and the order of the handler function’s returns are the same sentence in your head.

If you really suspect you got the order wrong, there is a clumsy but effective method. Have the handler function return three obvious markers, like ("one", "two", "three"), run once, and see which word appears in which box. It is faster than staring at the code and more reliable than guessing.

A tuple can also carry names, like (string Body, string Stats, object Notice). Names do not affect the correspondence; they just make the returned line read like a sentence. The example does not name them because it already splits them into variables in the function body; when one of your functions returns four or five values, names become useful.

Back to the example’s return type (object, string, object). Why are the first and third object? Because those two positions may hold something that is not a string. The first may be the update returned by gr.Skip(), and the third may be an Update. When one position has to hold two kinds of things, you can only fall back to their common parent type. The second position is always a string, so it honestly says string.

This chapter needs object in only this one place, and only in the either-or position of “value or update”. Do not carry this habit elsewhere; write a concrete type wherever you can.

3.4 Contract Differences Between Return Values, Update, and Skip

The three return values of Layout each handle one thing. The following is a sketch; ... is detail left out, and the full code is in 3.1.

object bodyValue = keepEdits ? gr.Skip() : result.Text;
var statsValue = $"...";                       // a string
object noticeValue = report.Warnings.Count == 0
    ? "No issues to report"                     // a string
    : gr.Update() with { Label = ..., Value = ... };   // an Update

An output can be filled by three kinds of things: a value, an Update, or Skip.

A value is a replacement. stats is replaced wholesale every time, and no trace of the old statistics remains.

Update is “change only the named properties”. notice normally returns a string, and returns an Update when there are warnings, with only Label and Value written. The label becomes “Notice (1 item)”, and the content is replaced with the warnings. The other properties (height, whether editable, visibility) are all untouched, because they were not written.

Skip is “don’t touch it this time”. body returns gr.Skip() after “Keep my edited body” is checked. The Body stays as it is, while Statistics and Notice update as usual.

Figure 3-4 Clean up after checking “Keep my edited body”

In Figure 3-4, the Body is “This line is one I edited myself”, but Statistics has already become “5 lines, 109 characters, longest line 35 characters”. The statistics were recomputed at 60 characters per line, yet the Body was not overwritten. In a single run, some outputs are skipped and others replaced, each going its own way.

Update carries only the properties it wrote, and there is finer evidence of this on the UI. Fill in 5 for the characters per line and click “Clean up” once more.

Figure 3-5 Enter 5 for the line width and the Notice label becomes “Notice (1 item)”

The Notice’s label changed, its value changed, and the Body and Statistics updated as usual. This time the Update wrote two items, so only those two moved on the UI; height, whether editable, and visibility all stay as they were.

To verify “an item you didn’t write won’t change”, change one line. Delete the Label line in the example’s gr.Update() with, rebuild, and click once more. The label stays as it was (if it has not been changed yet, that is “Notice”), and the value is still replaced with the new one, because this time the Update wrote only Value and the client merges only that one item.

That is the whole difference between Update and “returning a value”. A value replaces the entire displayed content of the component; Update merges only the few items you wrote out.

Update can change quite a few properties; these are the common ones.

PropertyWhat it changes
ValueThe value the component holds
LabelThe label above the component
VisibleWhether it is shown or hidden
InteractiveWhether it can be edited
PlaceholderThe hint text in an empty box
InfoThe description below the component

The remaining properties (options, numeric range, size) are covered when their components come up; Update has an item of the same name for each. Properties not listed in Update fall back to Props, which accepts any property by its name in the configuration. This escape hatch is reserved for properties not yet modeled; you do not need it day to day, but when you meet a property that “exists in the component properties but not in Update”, you can use it.

How to choose? See whether this output has “something to preserve”. Statistics is a brand-new piece of text every time, and the old value has no worth keeping, so returning a value directly is the least trouble. Notice is different. Its label has to follow the content, while the label is normally “Notice” and is “Notice (2 items)” when there are warnings. The value changes every time, and the label sometimes changes and sometimes does not. Writing it with Update expresses exactly “which items changed this time”; writing it with a return value means computing the label every time too, and one wrong write leaves the label unable to go back.

One step further. If you do not even want to change the value and only want an output to stay as it is, that is Skip. This chapter’s body is exactly that case. The user may have fixed a few lines by hand, and the handler function has no right to overwrite it.

The three return styles correspond to three intentions: redo everything, change only a few items, change not a single item. Choosing wrong does not report an error; it only makes changes appear on the UI that you did not intend.

Value has one special value, Update.Clear. It means “write this item as null”. Leaving a property blank means “don’t touch”, and Value = null also means “don’t touch”, so to clear an output you must write Value = Update.Clear explicitly. This difference does not show up in the “replace everything at once” style of Chapter 2; you only meet it when using Update.

Skip is really “an Update with nothing written in it”. The object returned by gr.Skip() is the same thing as gr.Update(); when the framework sends it to the browser, it looks like this.

{"__type__": "update"}

An empty update, merged by the client, amounts to no merge at all. So Skip is a degenerate case of Update. This also explains why using it on one output while the others update as usual is not a contradiction.

There is one more, used less often: returning the component itself. Return the body object directly and the client receives all the properties from when the component was constructed. Value, label, line count, whether editable — all reset to their factory state at once. It suits operations like “restore defaults”: for example, a “Reset” button restores all the outputs to how they looked when just opened, and the handler function returns the component objects one by one without having to copy every default value again. It does not suit everyday updates. You want to change one value, but you also knock the label and editability back.

The four styles divide by purpose: return a value by default; use Update to change only appearance; use Skip when you do not want to overwrite someone else’s work; return the component itself only to get back to the initial state.

3.5 Empty Values and Type Boundaries

An input box is cleared; what does the handler function receive?

A text box gives the empty string "", not null. A number box gives null. These two differences are not small. string text will never become null because of “not filled in”, while double? width will become null because it was not filled in.

This chapter’s example works precisely because of this. width is declared as double?; after the number box is cleared it is null, TextLayout.Wrap recognizes “not filled in”, handles it with the default 30, and gives a warning.

Characters per line not filled in, using 30

What if it is declared as double (without the question mark)? null is converted to 0, with no error. TextLayout.Wrap receives 0, clamps it to the minimum 10 by its rules, and so you get a Body wrapped at 10 characters per line and a warning “at least 10 characters per line”. That 0 came out of null; the user filled in nothing.

This is a quiet error, more troublesome than throwing an exception. An exception at least stops; this one keeps running and even gives you an output that looks reasonable. The rule is simple. For any parameter where “not filled in” and “a value was filled in” need to be treated differently, declare it as a nullable type. This applies to numbers, booleans and dates; strings do not need it, because the empty string already means “not filled in”. Unless the empty string itself has meaning in your business logic, in which case you need a different marker.

The return side has empty values too. Returning null to an output component clears it. In 3.3, when one fewer value is returned, that position receives null, and the UI shows that cell empty. So “clear an output” has two ways of writing it. Return null, or return an Update with Value = Update.Clear. The former replaces the whole component with an empty value along the way; the latter changes only the value and leaves the other properties alone. Use the latter when you need to keep the label and height.

Finally, type boundaries. You saw two kinds of failure earlier: the input type cannot hold it, and the return type cannot hold it. What they share is that you cannot see them at compile time; at runtime the server throws an exception, and the UI shows only “Error”.

This feedback is weak, so spend ten extra seconds when writing. Check every type in the signature against the table in 3.2; check the return types against every component in outputs once more. After these two passes, that runtime failure can basically be avoided.

There is one boundary that is not about type but about count. With too few inputs, the missing parameters get their type’s default value — string is null, int is 0; with too many inputs, the extra ones are ignored. These two, like the return side, do not report an error either. So “three inputs, three parameters” is something you have to check for yourself too.

There is a very practical diagnostic for this situation. When some parameter is mysteriously null inside the function, first count how many components are in inputs and how many non-injected parameters are in the signature. Once you have counted, you will most likely have found it. Either one component too few was placed, or one parameter too many was written.

The last thing is about where to put these boundaries. This chapter’s TextLayout.Wrap never throws an exception. When the text is empty, it returns an empty result plus a warning; when the line width is out of range, it clamps to the valid range and adds a warning; when there are too many lines, it truncates and adds a warning. All the “not ideal but can continue” cases become one line in LayoutReport.Warnings, and the UI decides how to display it.

The benefit of this is that the boundary exists in only one place. The UI layer does only two things. It hands the components’ values to the business logic, and it puts the business result back into the components. It does not judge “whether the text is empty”, nor “whether the line width is valid”. Those judgments are all in core, traveling with the business rules. If one day you want to run the same set of rules on the console, this whole UI layer can be dropped as a block, and what remains still works.

This chapter’s example is split into two projects. core/Core.csproj does not reference Gradio.NET and has no idea what a Textbox is; Chapter03.csproj references core and handles only components, types, and the three return styles. The boundary between the two projects is the boundary between “business” and “UI”.

3.6 Chapter Summary

A component factory writes once and produces one component object, which is both a position on the page and an object you can reference again later. This chapter needs that second reference only in “returning the component itself” in 3.4. value is the value it holds at this moment, and the one given at construction time is the initial value. A component object can go in only once, and output components are non-editable by default.

The component decides the type. Textbox gives string, Number gives double (can be declared as int, decimal or double?), Checkbox gives bool. Parameters correspond by position; if they cannot hold the value it fails at runtime, the UI shows only “Error”, and the reason is in the console.

Multiple return values land in multiple outputs in order. With too few, the missing positions are cleared; with too many, the extras are dropped; neither reports an error, so write the return type as a tuple whenever possible and let the compiler count for you.

An output can be filled by three kinds of things: a value, Update, Skip. A value replaces, Update merges only the named properties, and Skip is an empty Update. Returning the component itself is a fourth, used for resets. To clear a value, use Update.Clear and do not count on null.

An empty text box gives "", an empty number box gives null; if you do not want “not filled in” mixed up with 0, declare the parameter as a nullable type.

The next chapter switches to a different way of organizing things. No longer one function plus a set of inputs and outputs, but several areas laid out on one page.