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 19. Themes and Appearance

The first eighteen chapters built up the UI structure and the interactions: seven pages, a dozen or so containers, and over a hundred bindings. They still look like Gradio’s default. A light gray background, orange-red buttons, six-pixel corners.

This chapter’s tools run from coarse to fine: the theme (pick a built-in one, adjust a few shared parameters, then change a few variables), the stylesheet, and head injection; plus binding-level frontend scripts, which are not about appearance — they change “what this one click submits”.

What the four layers share is that none of them touch the structure. The components inside using and the handler functions in the bindings need not change by a single line. If changing appearance really required changing business code, that means styling has leaked into the structure.

The example is still that workbench, with an eighth page, “Appearance”, added to put every tool on the same page; there is also a separate theme experiment project, where the same set of components is photographed once under each of several themes for comparison.

19.1 Choosing a Built-in Theme

A theme is an object; assign it to Blocks.Theme and it takes effect.

var demo = gr.Blocks(title: "Personal Local Workbench");
demo.Theme = new SoftTheme();

That is the whole line. The buttons, input boxes, sliders, accordions, and tab bar on the page all change together. They all read from the same set of CSS variables, and a theme is one set of values for that batch of variables.

The built-in themes have twelve names: base, default, ember, glass, monochrome, neon, soft, origin, citrus, ocean, mario, cyberpunk. There are two ways to get one, and they are equivalent.

demo.Theme = new SoftTheme();              // a typed class
demo.Theme = ThemePresets.Get("soft");     // look it up by name

ThemePresets.BuiltInNames is the list of those twelve names. A misspelled name does not silently fall back to the default — Get throws an exception. That is easier to track down than “waiting until the page has rendered only to find nothing changed”.

What does a theme actually do? Open /theme.css to see. This address returns the current theme’s stylesheet, which holds over three hundred CSS custom properties.

--primary-500: #6366f1;
--neutral-50: #f9fafb;
--spacing-md: 6px;
--radius-lg: 8px;
--text-md: 14px;
--body-background-fill: var(--background-fill-primary);
--color-accent: var(--primary-500);

Every component on the page reads from this batch of variables. A button’s background is --button-primary-background-fill, which points to --primary-500; an input box’s corner radius is --input-radius, which points to --radius-lg. Changing the theme means changing the values of this batch of variables; the components themselves are unaffected.

Figure 19-1 The default theme

Figure 19-2 Soft: the same components, looser letter spacing, larger corners

Figure 19-3 Glass: translucent panels, a background leaning cool

Figure 19-4 Monochrome: the primary color recedes to grayscale, leaving only tonal layers

Figure 19-5 Ocean: blue-green primary color

The components are identical in all five figures: a text box, a slider, a checkbox, a group of radio buttons, two buttons, and one accordion. The differences are entirely in color, text size, spacing, and corner radius.

How do you choose? Two practical considerations.

First, projection and printing. Glass’s translucent layers often blur into a smear on a projector, while Monochrome shows the clearest tonal layers when printed. Choose the former for a presentation people watch, the latter for figures in a document people read.

Second, how much it fights the content. The more saturated the primary color, the more the UI grabs attention and the further the main text recedes. The workbench’s main text is what the user wrote, so the theme should step back; low-saturation primaries like soft and ocean fit better. neon and cyberpunk suit demo pages and event pages, not a tool you stare at for long stretches.

One more thing to be clear about. A theme changes appearance only, not behavior. The button is still that button, the click is still that click. So you can change the theme at the very last moment of development without affecting any binding. But the reverse holds too. A theme cannot rescue a UI with a muddled structure: if two columns are crammed together, ten themes later they are still crammed.

Component properties and the theme are two separate layers. The variant in gr.Button("Clean up", variant: "primary") chooses “which step from the theme to use” — the primary-color step or the secondary step; it does not name a color. So the same line of code is indigo under SoftTheme, dark gray under Monochrome, and blue-green under Ocean. That is also why changing the theme needs no change to component code. The code only says “this is a primary button”; the theme decides the color.

There is only one moment to assign it: demo.Theme = ... has to be written before Launch. Chapter 4 explained that the page is sealed on the first request; changing the theme after that seal has no effect. It raises no error, the page simply keeps the old set. The example puts it at the very top, alongside Queue and the upload directory settings, precisely so that the order “configure first, build the UI next, launch last” is visible in the code.

In /config the theme leaves only a name, a theme_hash, and four body_css rules (the light and dark pairs of the page background and main-text color); the actual three-hundred-plus variables live in /theme.css. The benefit of the split is that the browser can cache the stylesheet. If the theme has not changed, the hash does not change, and the stylesheet need not be downloaded again.

Changing a theme is something people look at, so acceptance is by looking too. Same page, same viewport, content unchanged, only the theme swapped, three shots in a row. If in any one of the three a button is hard to read or a block of text is crammed together, that theme cannot be used. No need to compare parameters one by one; let your eyes go over it first.

There is one rule for taking comparison shots. Viewport, content, and zoom all stay fixed; only the theme changes. Change the viewport and column widths and line wrapping change, so the two shots cannot be compared; change the content (one more line of text, one more accordion opened) and the height changes, again no comparison. The example’s eight theme comparison shots are all 1440×700, the same content, the same set of components.

A theme should appear only once in the code. The example puts it at the top of Program.cs, in the three lines before using (demo): construct, Set, assign. Do not write it again in every page method. Blocks has only one Theme; write it in two places and the later one overwrites the earlier one, while someone reading the code assumes both take effect.

What design hands you is usually a set of concrete numbers: “primary color #7c3aed, corner radius 8 pixels, main text 14 pixels”. Landing it takes three steps. Find the closest hue (the 500 step of violet happens to be #8b5cf6, close but not exact), pick the step (radius_lg), and make up the remaining difference with Set. The order of the three steps cannot be reversed. Picking the hue first and then patching the color is less work than Set-ing a pile of colors first and only then discovering the hue is wrong.

19.2 Theme Tuning Parameters

A built-in theme is not necessarily exactly right. When it is off by a little, you do not have to build one from scratch; just change a few parameters.

var skin = new SoftTheme(
    primaryHue: Colors.Find("violet"),
    radiusSize: Sizes.Find("radius_lg"));

BaseTheme and its eleven subclasses all accept the same set of parameters, eight in all (of the twelve built-in names, base is the base class itself).

ParameterAcceptsVariables changedChange in the UI
primaryHuea hue--primary-50 through --primary-950primary buttons, links, sliders, selected state, focus ring
secondaryHuea hue--secondary-*secondary emphasis (selection highlight on some components)
neutralHuea hue--neutral-*page background, borders, main-text color
textSizea text size step--text-xxs through --text-xxltext in the main body, labels, and buttons
spacingSizea spacing step--spacing-xxs through --spacing-xxlpadding, gaps between components
radiusSizea corner-radius step--radius-xxs through --radius-xxlcorner radius of input boxes, buttons, and blocks
fonta font list--fonttypeface of the main text and headings
fontMonoa font list--font-monomonospaced typeface in Code

Hues and sizes do not accept strings; they accept the objects returned by Colors.Find(...) and Sizes.Find(...). Names use lowercase with underscores: Colors.Find("violet"), Sizes.Find("radius_lg"). Write "Violet" or "RadiusLg" and you get null; then the parameter is null, the theme is still built, and only that one path falls back to the default. No error is raised — unlike a misspelled name in Get("soft").

Here is what “expanding into a color scale” concretely looks like. Give it a hue and the theme generates eleven levels, --primary-50 through --primary-950, from very light to very dark. Each component takes what it needs. A button at rest uses 500, on hover 600, when pressed 700, and a light background uses 50. So what you give is one hue, and what lands is eleven levels; changing the hue swaps all eleven together, and every “shade of the primary color” in the UI follows at once.

Text size, spacing, and corner radius work the same way, with seven levels: xxs, xs, sm, md, lg, xl, xxl. textSize gives the “baseline”, and the theme derives the whole scale proportionally; the difference between Sizes.Find("text_lg") and Sizes.Find("text_md") is “the baseline of the whole text scale raised one step”, so the main text, labels, and button text all change together.

Parameters are a starting point, not a contract. The same primaryHue looks different under different built-in themes. Soft’s buttons are solid fills, Glass’s are translucent. So a request like “change it to ocean’s blue” has to settle the theme at the same time. Pick a base first (Soft, Glass, Monochrome), then tune parameters on top of it; do it the other way — tune parameters, then swap the base — and the earlier tuning is wasted.

secondaryHue and neutralHue are often confused. The difference is in what they are for. neutral decides the base (page background, borders, the color of main-text letters; change it and the whole UI’s light/dark and warm/cool balance shifts; secondary decides the second emphasis) used when some components need a contrasting color besides the primary. When in doubt, change only primaryHue and neutralHue first — those two decide nine tenths of the look.

Colors holds about twenty colors (slate, gray, red, orange, amber, green, teal, sky, blue, indigo, violet, pink, …), and Sizes holds three groups: radius_*, spacing_*, text_*. A hue expands into an eleven-level color scale once it comes in; a text size expands into seven levels. So what you pass is a “hue” and a “step”, not a concrete color value.

Figure 19-6 Only radiusSize, spacingSize, and textSize changed: the buttons turned into capsules, line spacing widened, and the text grew one size

Figure 19-7 Only primaryHue and neutralHue changed: buttons, sliders, and the selected radio change color together, and the background goes from cool gray to warm gray

Viewed side by side, the two figures show the division of labor among the tuning parameters. In Figure 19-6 the colors did not move, only sizes did; in Figure 19-7 the sizes did not move, only colors did. The eight parameters each own one segment and do not cross into the others. That is the difference between “tuning parameters” and “variable overrides”. The former changes a whole color scale at once; the latter changes a single point.

font accepts a list of Font, of three types: GoogleFont, LocalFont, and Font.

new SoftTheme(font: [new LocalFont("Source Han Sans SC"), new Font("system-ui")]);

The three font types land differently; one try is enough to tell them apart.

  • LocalFont("Source Han Sans SC") generates an @font-face whose src points to static/fonts/SourceHanSansSC/SourceHanSansSC-Regular.woff2. You have to place the file into the static directory at that path yourself; otherwise loading fails and it falls back to the next font in the list.
  • GoogleFont("Inter") only writes the name into --font ('Inter', 'system-ui'); it generates no @font-face and has no address pointing at Google, so the font has to be one already installed on the system.
  • Font("Georgia") likewise writes only the name and uses a system font.

The fonts shipped with the built-in themes take the first path. Soft’s stylesheet has an @font-face pointing to static/fonts/Montserrat/...; the file comes with the package and /static/fonts/... serves it directly. So “changing the font” means either putting the font file into the static directory and pointing LocalFont at it, or accepting a system font.

The fonts shipped with the built-in themes are local files. Soft uses Montserrat and IBM Plex Mono; the stylesheet points an @font-face at static/fonts/..., fetched on demand as the page loads. The most visible difference before and after changing the font is character width. For the same main text, Montserrat is a little wider than the system sans-serif, so a line holds fewer characters and the line count goes up. So after changing the font, check line wrapping and height again, especially for text boxes with a fixed number of lines (ones like lines: 2); a wider font can bring on a scrollbar.

Tuning parameters has an order. Settle the hue first (it decides the character), then text size and spacing (they decide the density), and corner radius last (it decides hard versus soft). Changing the hue means re-checking the most components, so settling it first saves going back and forth.

How do you verify after changing? Three actions.

One, print a few values: skin.GetValue("primary_500"), GetValue("radius_lg"), GetValue("spacing_md") — confirm you got the step you thought you did. When a parameter is passed null, the original value shows up here, which is faster than staring at the button on the page and guessing.

Two, compare screenshots. Same page, same viewport, only the theme swapped, the two shots side by side. That is how the example’s two sets of screenshots were made. Not a single component changed; only the BOOK_THEME environment variable was swapped.

Three, narrow the window and look again. Once spacing and text size grow, the stacking point set by minWidth arrives earlier. In the “480 + 320 + 16” example from Chapter 4, the columns stack when the available width drops below 816; enlarge the spacing and the width actually needed is larger, so the two side-by-side columns stack sooner. On a wide desktop screen you see no problem; only on a narrow screen do you find two columns have become one.

19.3 Overriding Theme Variables

Tuning parameters change “a whole color scale” or “a whole step of sizes”. Sometimes the difference is a single point. The primary color one step lighter is exactly right, but changing primaryHue moves the whole scale; an eight-pixel corner radius is exactly right, but radiusSize has only a few steps.

Then change a single variable directly.

var skin = new SoftTheme(primaryHue: Colors.Find("violet"), radiusSize: Sizes.Find("radius_lg"));
skin.Set("primary_500", "#7c3aed");
demo.Theme = skin;

Set takes two string parameters, a variable name and a value, returns the theme itself, and can be chained. A variable name is the CSS variable name with the two leading hyphens removed and hyphens replaced by underscores: --primary-500 becomes primary_500, and --radius-lg becomes radius_lg.

A mistake throws on the spot; it does not silently do nothing.

System.ArgumentException: '--primary-500' is not a theme variable.
The theme has 325 of them, all of which ThemeOptions declares. (Parameter 'variable')

The “start with --” spelling shown in the message is not accepted, and that is the most common source of this error. The same theme has over three hundred variables, and --primary-500 is one of them, yet Set wants primary_500.

Three naming rules.

In CSSIn SetNote
--primary-500primary_500drop --, hyphens to underscores
--radius-lgradius_lgsame as above
--button-primary-background-fillbutton_primary_background_filllong names follow the same rule

Levels in a name are joined with underscores, not dots and not hyphens.

You can also use Css to write a :root { --primary-500: … } block for the same effect, but that is “adding another layer on the outside”. The stylesheet the theme generates still holds the old value, and your override has to guarantee its own priority. Set changes it at the source. What comes out of /theme.css is the new value, and every component that references it follows along. Where both can be changed, prefer Set.

Whether an override took effect can be seen in two places. One is GetValue; the other is fetching /theme.css directly and searching it for the value you wrote. Find it and the stylesheet the server generated already holds the new value; fail to find it and it was not written in (a misspelled name, or overwritten by a later Set).

To know the current value of one variable path, use GetValue.

Console.WriteLine(skin.GetValue("primary_500"));   // #7c3aed
Console.WriteLine(skin.GetValue("radius_lg"));     // 8px

It prints the value exactly as it is, including indirect references like var(--...). GetValue does no resolving. To turn an indirect reference into a concrete value, use GetComputedValue.

Besides Set one variable at a time, there is a strongly typed path, ThemeOptions.

demo.Theme = ThemePresets.Get("default").Set(new ThemeOptions
{
    ColorAccent = "#0f766e",
    RadiusLg = "2px",
});

Every property of ThemeOptions maps to one variable, which suits “change a batch at once and want the property names checked at compile time”. It and Set("name", value) change the same batch of variables; the only difference is the notation, one by string, the other by property.

Figure 19-8 Default theme + primary_500 changed to dark green + radius_lg changed to 2px: only two points changed

This figure and Figure 19-1 use the same components and the same theme, differing by only two variables. Notice where the change lands. The buttons and slider turned dark green, and the corners of the input boxes and buttons went from round to sharp; text size, spacing, and layout did not move anywhere.

There is a side effect here that the screenshot cannot show. Change one step and the others stay old. The example’s override sample changes primary_500 to dark green, so the button is dark green at rest; move the mouse over it and the color becomes primary_600, which is still the default theme’s orange. The rest and hover states no longer match, and the button looks broken.

Measured values: at rest rgb(15, 118, 110), on hover rgb(234, 88, 12).

So single-point overrides have two uses, each with a cost.

  • Change the hue (primaryHue) recomputes all eleven levels, with the light/dark relationships built in, at the cost of changing the whole scale;
  • Change one step (Set("primary_500", ...)) moves a single point, at the cost of having to fill in the neighboring steps yourself.

If you really want a single-point override, change the commonly used steps together: primary_500 for rest, primary_600 for hover, primary_700 for pressed, primary_50 for a light background. Write the four lines together so someone reading the code can tell “this swaps the primary color for another set”.

Single-point overrides suit variables that have no neighboring steps needing to follow. radius_lg, spacing_md, embed_radius, body_text_size — changing one changes all of it.

Order. Construct the theme first (with tuning parameters), then Set the variables. Writing it the other way raises no error either, but the tuning parameters recompute the color scale and overwrite the values you Set earlier. Read in code it is one line after another; in reality it is “set the big direction first, then turn the small screws”.

A finished theme can be saved.

skin.Dump("skin.json");                    // save a copy, with all variables
var same = Theme.Load("skin.json");        // read it back, values identical

Dump writes the current values of those three-hundred-plus variables, and Load reads them back into a complete theme object, names and values intact. It suits two cases: the theme has to travel with the project into version control, or you let a design colleague edit a JSON file while the code only has to read it.

Saving as JSON has one more use. The difference between two themes can be diffed directly. Whatever Set changed shows up as those few extra lines in the file.

ThemeOptions or Set? For a batch of changes where you want property names checked by the compiler, use ThemeOptions; for just one or two points, or when the variable names were copied from elsewhere (a JSON from design, /theme.css), use Set. The two can be mixed. The example’s main app fixes the hue and corner radius with constructor parameters first, then Sets one primary_500. Watch the order when mixing: constructor parameters are computed first, Set writes later, and the later write wins.

19.4 Custom Stylesheets and Head Injection

The theme governs “that batch of variables”. Changes that variable overrides cannot reach (adding a vertical line to one block, turning one line of small text all-uppercase) have to be written in CSS.

There are two places to write it, inline and in a file.

demo.CssPaths = [Path.Combine(AppContext.BaseDirectory, "assets", "skin.css")];
demo.Css = """
    .card { border-left: 6px solid var(--primary-500); padding-left: 14px !important; }
    .badge { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--primary-600); }
    """;

CssPaths accepts a set of file paths, read in when the config is fetched; Css accepts a string. The two are concatenated in the end into the css field of /config, which the frontend injects into the page. So the following two things both hold.

  • The order is “inline first, file second”; for rules with the same name the later one wins, that is, the file’s version wins;
  • When writing the file you need not worry about how the path is delivered. It does not go through the static file service; it is read into memory and joined into the string.

CSS is global: write button { ... } and you hit every button on the page. To change just one spot, you first have to give that spot a hook. Two hooks are given when the component is constructed.

gr.Markdown("# Appearance", elemId: "hero-title");            // becomes id="hero-title"
using (gr.Column(elemClasses: "card")) { ... }          // becomes class="card"

elemId is a unique id, and elemClasses can hold several classes (separated by spaces). Give class names a prefix (the example uses card and badge); do not use ones like button, input, or prose. When they collide with class names the framework or theme ships, the range you hit grows larger than you expect. Both work on containers and on components. gr.Column(elemClasses: "card") hits the whole column, gr.Markdown(..., elemClasses: "badge") hits that one segment. The example’s assets/skin.css relies on exactly these two hooks.

.card { border-left: 6px solid var(--primary-500); padding-left: 14px !important; }
.badge { font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--primary-600); }

Figure 19-9 The “Appearance” page: the vertical line on the left of the card and that line of all-uppercase small text are both done by skin.css

Notice the buttons and input boxes inside the card. Their background, corner radius, and text size come from the theme; the vertical line and the small text come from the stylesheet. The two are managed separately, so changing the theme does not touch the stylesheet, and changing the stylesheet does not touch the theme.

There are three practical lessons when writing CSS.

First, prefer variable values, do not hard-code colors. border-left: 6px solid var(--primary-500) follows the theme when it changes color; writing #7c3aed nails it down. Theme variables live on :root and can be referenced anywhere in the stylesheet.

Second, use !important sparingly. The one padding-left: 14px !important in the example is there because the component’s own rule is more specific and cannot be overridden without it. If a more specific selector can win the priority, do not add !important. Add one and the next override can only add another, until the page is full of exclamation marks. The usual way to raise priority is to stack a selector: .card .prose { ... } is more specific than .prose { ... }.

Third, do not forget printing. Dark backgrounds, gradients, and shadows on screen often print as a solid black blob. If you really need printing, add a block to skin.css.

@media print {
  body { background: #fff !important; }
  button, .card { box-shadow: none !important; }
}

The example does not include this block, because the example does not print. Whether to write it depends on whether the app will be “printed to PDF and sent out”.

Files in CssPaths do not go through the static file service. The page makes no request for skin.css; its content is read on the server and joined into the css field of config. That one fact decides three things. The file can live at any path, with no need to move it into a publicly served directory; it is read as plain text, with no HTTP caching; and every config fetch re-reads it, so after editing the file a page refresh shows the change with no restart.

Beyond the stylesheet there is one more place, Head.

demo.Head = """
    <style>
      #hero-title {
        font-family: "Songti SC", "SimSun", Georgia, serif;
        letter-spacing: 0.06em;
        display: inline-block;
        padding-bottom: 4px;
        border-bottom: 2px solid var(--primary-500);
      }
    </style>
    <meta name="book-chapter" content="19" />
    """;

Head accepts a piece of HTML that goes into <head> verbatim. What it adds over Css is not just styles: <meta>, <link>, <script>, and <base> can all go in. The example puts in two, a <style> block and a <meta> tag.

Figure 19-10 The Songti typeface and that bottom border come from the <style> in Head; the <meta> is not displayed but did go into <head>

The division of labor among the three can be remembered like this.

WhereWhat it isScopeWhat to put there
Theme variablesCSS custom propertiesWhole page, components read by variableColors, text sizes, spacing, corner radius
Css/CssPathsA set of CSS rulesWhole page, hit by selectorSupplementary rules, spacing tweaks, decorative lines, print styles
HeadHTML that goes into <head> verbatimThe whole documentmeta, external link, inline script, font declarations

All three can change appearance; the difference is “which layer they change”. The theme changes variables, the stylesheet adds rules, head injection adds document-level things. So “make the buttons rounded” is the theme’s job, “add a line to one block” is the stylesheet’s job, and “make a search engine read the page as a different title” is head injection’s job.

Head is more dangerous than the other two because it can carry <script>. A script injected there executes in this page’s source, can read things on the page, and can send requests. So do not do two things. Do not write secrets or internal addresses into Head or Css (they are all in /config and the page source, visible to anyone who opens them), and do not paste in scripts from unknown sources.

One more thing is easily confused with Head: demo.Js. It accepts a piece of JS function source that runs once after the page finishes loading, and acts on the whole document; a <script> stuffed into Head is script text the browser parses verbatim. The example uses Js to put a data-themed marker on <html>, to confirm this script really ran. It does not change appearance; it is only used to check that the loading chain is intact.

Css and Head overlap in effect: a <style> block works on either side. Divide them by “is it a document-level thing”: for page styles only, write it into Css/CssPaths, where it is managed together with the other rules; only reach for Head to add meta, an external link, or script.

19.5 The Boundaries of Binding-Level Frontend Scripts

The fourth item is not entirely about appearance. You can attach a piece of JS to a binding, and it runs once before the request is sent out.

Func<string, object> echo = value => "**Edit Input** Server received '" + value + "'.";
edit.Click(echo, [text], [editNote], apiName: "Frontend edits input",
    js: "(t) => { return [t + '(added in the browser)']; }");

js accepts a piece of JS function source. Its parameters are this event’s inputs (one text box in the example, so one string parameter), and the return value has to be written as an array whose elements are the edited inputs. What the server receives is exactly this edited copy.

There is one point that is easy to misread. The array you return is inputs, not outputs. It is not written straight into the result cell. The result still comes from the server-side handler function. Make it return a string you want displayed directly and what appears on the page is still the server’s line. What you put in the returned array depends on how many inputs there are and what components they are.

These parameters correspond one-to-one with inputs (the injection contract covered in Chapter 17), so if you change the order of inputs, the parameter order in js has to change with it. Returning undefined or returning nothing means “leave the inputs alone”, and the request is sent as usual.

This source goes verbatim into the dependency list in /config. Anyone who opens the page can read it, and during debugging you can confirm from there “whether the piece you wrote actually took effect”. So do not put decision logic, secrets, or endpoint addresses into it — they become public.

Figure 19-11 The input box contains “Wrapping text”; the server received “Wrapping text(added in the browser)”

This is its most practical use: patch the format once. Strip the invisible characters a user pasted in, remove spaces from a phone number, normalize lowercase to uppercase. Doing these in the browser costs a few milliseconds, and the server does not have to run an extra pass for them.

The second piece of JS demonstrates something else.

Func<object> serverSays = () => "**Edit Page** The server ran too.";
dom.Click(serverSays, null, [domNote], apiName: "Frontend edits the title",
    js: "() => { document.title = 'Title changed by the frontend'; }", jsRunsInBrowser: true);

This JS only changes the browser title and returns nothing. After the click the browser title changes, and the server still ran once.

The name jsRunsInBrowser sounds like “runs only in the browser, not sent to the server”. It is not. Open /config and the dependencies contain only two fields, js and js_implementation; js_runs_in_browser is not there at all. The parameter is merely accepted, not passed on. So writing true and writing false behave the same.

To “complete an interaction entirely on the frontend”, the way is to bind no server-side handler function and attach the event listener yourself with Head or Js. The binding route cannot avoid the request.

The third piece demonstrates the boundary.

check.Click(accept, [text], [checkNote], apiName: "Frontend edit plus validation",
    js: "(t) => { return [t + '(added in the browser)']; }",
    validator: (Func<string, string?>)OnlyOk);

The frontend edits the input, and the server validates as before. The validator sees the edited copy and rejects it if it does not recognize it.

Figure 19-12 The frontend added a suffix, the validator only accepts ok, the request was rejected, and the status line did not move

Put the three together and the boundary becomes clear.

  • It can change what is submitted. The return value of js becomes this request’s inputs, and the server gets the edited copy;
  • It can change the page. DOM, title, style classes — anything the browser can touch;
  • It cannot change “whether it is accepted”. Validation, permissions, and idempotency live on the server; nothing the frontend does gets around them;
  • It cannot compute for the server. No js return value means no output, and the server-side handler function runs as usual; to skip the request you have to write a separate script.

So frontend scripts suit three things. Patch the format once (strip whitespace, normalize case, turn full-width commas into half-width), give instant feedback (gray it out on click, change the title first, do not make the user wait), and block one obvious mistaken action (do not send the request on empty input). The three share one trait: getting them wrong is not fatal, because the server checks again.

What they do not suit is just as clear: business rules (“can an order still be placed this month”), permission checks (“may this person edit”), and idempotency (“has this charge already gone through”). Writing these into js is putting the rules in the browser to execute. Switch clients or send one curl and the rules are gone.

When js is used with a validator, the order is fixed. The frontend script runs first, the validator runs second. The example’s third line does exactly that. js adds a suffix to the input, and the validator sees the suffixed copy, so “Wrapping text” becomes “Wrapping text(added in the browser)”, the “ok” rule no longer matches, and the request is rejected. This order is why js cannot be used to “fool validation”. It changes the very thing the validator looks at; changing it only makes rejection more likely.

There is one more syntactic limit you will hit while writing. A binding with js needs a delegate variable; you cannot put the lambda directly in the parameter slot.

Func<string, object> echo = value => ...;      // declare it first
edit.Click(echo, [text], [editNote], js: "...");  // then pass it in

Writing edit.Click(v => ..., [text], [note], js: "...") directly raises CS1593. The compiler assigns the lambda to a different overload that has no inputs; that overload’s first parameter is Func<object?>, which cannot accept a lambda with parameters. Switch to a method group or an explicitly typed delegate variable and it works.

19.6 Chapter Summary

Appearance has four layers, each covering one segment.

Built-in themes take one line, demo.Theme = new SoftTheme(), or a lookup by name, ThemePresets.Get("ocean"). Twelve names, in essence twelve sets of CSS variables; /theme.css shows the current set directly.

Tuning parameters are eight parameters: three hues, two size steps (text size, spacing), one corner-radius step, and two font lists. Each expands into a color scale or a set of sizes, so changing one parameter moves a whole region. Hue governs color, text size governs text, spacing governs padding and gaps, and corner radius governs how hard or soft the edges are.

Variable overrides are Set("primary_500", "#7c3aed"): drop the -- from the name and turn hyphens into underscores; a mistake throws ArgumentException on the spot; GetValue reads the current value, Dump/Load save and load a whole theme, and Set(ThemeOptions) is the strongly typed form. In order, construct the theme with tuning parameters first, then override point by point.

Stylesheets take two routes, inline and file, finally joined into the css field; rules are page-wide and hit specific components through elemId and elemClasses; when writing rules use theme variables rather than hard-coded colors. Head injection goes into <head> verbatim, adding over the stylesheet the document-level things: meta, link, script.

Frontend scripts hang on bindings. With no js return value they can only change the page; with a return value they change this request’s inputs. jsRunsInBrowser never reaches the config, so writing it changes no behavior; validation, permissions, and business rules all live on the server, beyond the frontend’s reach. A binding with js needs a delegate variable; you cannot stuff the lambda into the parameter slot.

Here are the places this chapter easily goes wrong, gathered together to check against as you write.

  • Theme written after Launch: no effect, and no error;
  • Colors.Find("Violet"): wrong case, returns null, and the theme quietly falls back to the default color;
  • Set("--primary-500", ...): Set does not accept the CSS spelling, only primary_500;
  • Changing only primary_500: rest correct, hover still the old color;
  • Hard-coding #7c3aed in Css: this rule does not follow when the theme changes;
  • Selecting components in the stylesheet without writing elemClasses: the range hit is larger than you intended;
  • Writing a lambda directly in a binding with js: CS1593; catch it with a delegate variable first.

After changing appearance, run a regression. Pick three to five key bindings and click through them once, confirming the buttons are still wired to their original handler functions. Changing a theme should not move behavior, but “should not” is a design intent, not a guarantee. A wrong script in Head, or CSS that covers a button so it cannot be clicked, turns an “appearance change” into a “functional failure”.

The relation of the four layers is laid out in one figure, ordered from global to local.

Figure 19-13 The scope of the four layers, and the things they cannot change

The column in the lower-right of the figure is a different matter: the structure of the component tree, which handler function a binding connects to, whether the validator accepts, and business rules and permissions. None of these four are in the hands of the four layers. They are the content of Chapters 4 through 17, living on the server and inside using. Aiming appearance tools at these four only gets you “looks fixed, problem still there”.

Beyond these four layers, a component’s own parameters can change appearance too: variant, size, scale, minWidth, elemClasses. These say “what this one spot should look like”, while the theme says “what the global default looks like”. When the two conflict, the component parameter wins, because it is the nearer one. So when tracking down “why does this button look different from the others”, look at its own parameters first, then the stylesheet, and only then the theme.

Appearance is the last layer and the one most often revisited. It touches neither structure nor behavior, so getting it wrong only makes things ugly. That is why it belongs after the functionality has stabilized, followed by a check that the key bindings are still there.

The next chapter settles “who is allowed in to look”: authentication and access control.