Chapter 18. Advanced Layout and Multi-Page Navigation
The previous chapter’s UI had fifteen blocks: text cleanup, segments, filtering, display, tables, charts, galleries, images, media, files, chat, state, queues, streaming, and tasks. Scrolling to the bottom takes several screens, and finding a button means first remembering which block it is in. No functionality is missing, but “cannot find it” is itself already a defect.
This chapter fixes it. Tabs, accordions, and the sidebar tuck things away on the same page; what cannot be tucked away gets split into several pages, each with its own address, reached through the navbar.
The order matters. Tuck away what you can first; split only what you cannot. Tucking away is free — the user stays on the same page and the address does not change; splitting pages has a price. Referencing components across pages gets awkward, the navbar has to be written once on every page, and users may bookmark the wrong page. So this chapter explains how to tuck away first, then how to split.
The example is still that workbench, but the page structure has changed. One page becomes seven, and the seventh is the layout page, set up specifically to put the four containers side by side for comparison. Not a single module was deleted; they were just reassigned to new positions.
18.1 Tabs and Tab Selection Switching
Tabs cut a region into several screens. Only one is drawn at a time, and a row of buttons beside it switches screens.
Tabs tabs;
using (tabs = gr.Tabs(selected: "one"))
{
using (gr.Tab("Overview", id: "one"))
{
using (gr.Group())
{
gr.Markdown("**Overview** three lines of one result, joined into a block with `Group`.");
gr.Textbox(label: "Body", lines: 2, interactive: false);
gr.Textbox(label: "Statistics", lines: 1, interactive: false);
gr.Textbox(label: "Notice", lines: 1, interactive: false);
}
}
using (gr.Tab("Details", id: "two")) { gr.Markdown("**Details** Switching tabs changes only this block."); }
using (gr.Tab("Notes", id: "three")) { gr.Markdown("**Notes** Switch away and back, the values are still there."); }
}
tabs.Select((SelectData data) => $"**Tab** Selected '{data.Value}', number {data.Index + 1}.", [], [tabNote]);
Tabs is a container, Tab is its child element, and you put other things inside a Tab. The syntax is exactly the same as Row/Column: using opens a level and the braces close it. The indentation tells you everything, and the layout tree in /config is read the same way.
selected only recognizes the Tab’s id. Give a tab a short id and write that id in selected; omit selected and it defaults to the first screen.
So either give every tab a short id and have selected use it, or do not write selected. The example writes selected: "one" because the first tab’s id is "one". When the UI comes up empty, check this first.
There are two selection events, Select and Change. Both fire; the difference is the payload. Select gives you a SelectData, Change gives you nothing. SelectData has three fields: Value is this tab’s label text (in the example, “Overview”), Index is the position counted from 0, and Selected is a flag. So to ask “which one did the user pick,” use Select; do not count on Change.
When both are bound, whichever arrives last decides what gets written. The example binds only Select, precisely so Change cannot overwrite the line that carries data. Binding both is not wrong either, you just have to accept “the last line wins.” When debugging and the status stops at the Change line, do not assume Select never ran.
Figure 18-1 Switching tabs replaces the whole content block; the status line reads “Selected ‘Overview’, number 1”
What does switching screens cost? Two things.
First, the screen you switch away from is unmounted. The components inside an unselected tab are not on the page; inspect the DOM and you find they are simply not there, not hidden. Switching back draws them again, but the values are still there, because values live in the server-side session (Chapter 14), not in the DOM. The three boxes on the example’s first screen are read-only, so you cannot see this; switch to editable input boxes, switch away and back, and the text you just typed is still there. This is easy to misread. See no such box in the DOM and you assume the value is lost.
Second, the address does not change. Switching tabs sends no request to the router and does not change the address bar. So “this page is complex, separate it with tabs” solves the scrolling problem, not the problem of “sending a link that points at that screen.” For the latter you need one page per screen (18.5), or a deep link (18.7).
What happens when the tabs do not fit? overflowBehavior handles that, with two values.
menu(default). What does not fit is tucked into the⋯on the right; click it for a dropdown;wrap. What does not fit wraps to a second row and the tab bar grows taller.
Figure 18-2 The viewport narrowed to 780 pixels: on the left it tucks into ⋯, on the right it wraps to a second row
The same set of seven tabs, menu on the left and wrap on the right. When the window is wide the two look identical; only narrowing reveals the difference. menu saves space at the price of half the tabs being invisible — the user does not know there are “Files” and “Chat” screens. wrap shows everything at the price of the tab bar taking two rows and pushing content down. Weighing the two harms, with five tabs or fewer either works; beyond five, if you need the user to see them all, wrap is safer.
This comparison also shows one thing. The number of tabs is a design decision, not an implementation detail. Stuff seven tabs into one page and no matter how they overflow, the user has to read through all the tab names before knowing where to go. At the scale of seven, the more likely answer is that the page should be split (18.5), not that you should change overflow strategy. The example keeps them on one page only so both overflow behaviors can be compared in a single figure.
How do you decide to use tabs? Only when both conditions hold. The blocks are parallel (none depends on any other), and they do not need to be seen at the same time (the user cares about one at a time). For two blocks that need side-by-side comparison, use Row to split them left and right, not tabs — people cannot remember the numbers from the previous screen.
Another easy confusion: a tab is not a radio button. Radio (Chapter 7) selects a value, and that value goes into inputs and is read by the handler function; a tab selects a screen of content, goes into no inputs at all, and only decides which block is drawn. So use Radio for “let the user pick a format,” and tabs for “let the user switch among three views.” Using the wrong one still runs, it is just semantically off. Make format selection a tab and the user will think picking it takes effect, when in fact they still have to click a button.
18.2 Accordion and Sidebar Expand and Collapse
Tabs tuck away horizontally, accordions tuck away vertically. One title, one click, and the content collapses or expands.
Accordion rules;
using (rules = gr.Accordion("Wrapping rules", open: true))
{
gr.Markdown("Wrap by character count, not by words; strip trailing whitespace and drop blank lines.");
}
Accordion events;
using (events = gr.Accordion("Event conventions", open: false))
{
gr.Markdown("The order of `inputs` in a binding decides the parameter order; the order of `outputs` decides where each return value goes.");
}
rules.Expand(() => "**Fold** 'Wrapping rules' expanded.", null, [foldNote]);
rules.Collapse(() => "**Fold** 'Wrapping rules' collapsed.", null, [foldNote]);
events.Expand(() => "**Fold** 'Event conventions' expanded.", null, [foldNote]);
events.Collapse(() => "**Fold** 'Event conventions' collapsed.", null, [foldNote]);
Three parameters control the appearance. label is the text on the title, open decides whether it is expanded when opened, and height/maxHeight set how tall the content area can get. The default is open: true, so to “have it collapsed by default” you must write false explicitly. That is what the example’s second accordion does.
There are two events, Expand and Collapse, and both carry no payload. Note that. The handler function’s signature is “no parameters,” not “receives an object saying which one it was.” To know which one was clicked you have to bind them one by one. The example uses four lambdas, each with the name written in directly. Two accordions means four bindings — sounds clumsy, but it is more reliable than guessing which one it was at runtime.
One substantial difference between accordions and tabs: collapsed content is still in the DOM, just not displayed. Tabs unmount, accordions hide. So collapse an input box inside an accordion and expand it again, and the value is right there, not even redrawn. Conversely, components inside an accordion still take up session state and can still be referenced by events. Hiding a “not needed for now” block inside an accordion is a clean way to tuck it away.
The sidebar is the third kind. It is not in the main text flow but clings to one side of the page, collapsed by default, with an arrow left at the page edge.
Sidebar side;
using (side = gr.Sidebar(label: "How to use this page", open: false, width: 260, position: "right"))
{
gr.Markdown("### How to use this page");
gr.Markdown("""
1. Click a tab to switch screens;
2. Click an accordion title to expand or collapse it;
3. Click the arrow on the right edge of the page to bring up these instructions.
""");
gr.Button("Button in the sidebar");
var sideNote = gr.Markdown("**Sidebar** has not been opened yet.");
side.Expand(() => "**Sidebar** opened.", null, [sideNote]);
side.Collapse(() => "**Sidebar** collapsed.", null, [sideNote]);
}
label is its name, but it is not displayed on the page. It is only there for the code and the config. All the user sees is that arrow. width is the panel width (260 pixels in the example), and position is left or right. The example puts it on the right, because there is already a column of content on the left and the sidebar would cover it.
An expanded sidebar covers the main text, which is different from an accordion. An accordion pushes the content below it down; the sidebar floats on top. So the sidebar suits things you “open to consult at any time and put away when done”: usage instructions, a table of contents, filter criteria. Do not put must-see content in it — users will forget it is there.
One practical point. The sidebar width is given in pixels, 260 in the example. On a narrow screen that is not a small number. A phone is a little over eight hundred pixels wide, so a 260-pixel sidebar takes up a third of it. Keep sidebar content short: three to five lines of instructions, a set of links, one button — do not stuff a table in there. If you need a table, it is not “auxiliary content” anymore and deserves a proper place on the page.
Figure 18-3 “Event conventions” expanded and the sidebar open; both status lines were written by events
All three containers are called “folding” in one way or another, but each covers a different scenario. There are three criteria.
| Container | What it holds | When to use it | Cost |
|---|---|---|---|
Tabs | Several parallel screens of content | See one at a time, blocks are peers | Switching unmounts components, address unchanged |
Accordion | Segments within the same page | Segments have an order, you may view two at once | Content stays on the page, just not displayed |
Sidebar | Auxiliary content outside the main text | Instructions, contents, filters — things called up at any time | Floats over the main text and covers content |
Choosing among the three is not a matter of taste; ask in this order. Is this content on the same level as the main text? On the same level and mutually exclusive, use tabs; on the same level but to be seen together, use Row. Is it part of the main text? Then use an accordion, divided by section. Is it not part of the main text at all? Then it is a sidebar.
Here is a counterexample: collapsing something you “must see.” The example’s accordions hold rule explanations and event conventions — the kind of thing you read carefully the first time and look back at occasionally afterward. That is exactly what folding suits. But fold the “Result” away and the user clicks a button, sees nothing, and has to click a title open as well — that turns folding into an obstacle. Results, errors, and current status should never be inside an accordion; what you may fold are instructions, options, history, and secondary settings.
The height and maxHeight parameters control the content area’s height; the example does not use them because they have to be tuned to the content length. When content exceeds maxHeight, the accordion scrolls internally instead of growing taller. For a block holding twenty lines of log, maxHeight: 240 fits better than letting it grow to a full screen. But it also brings a hidden risk: there is more content below and you cannot see it at a glance. For “must read to the end” things like logs, better to let it grow taller.
An accordion has one more detail that is the opposite of tabs: at page load it all exists at once. Two accordions both open means two blocks of content drawn together, just separated by their titles. So folding does not save server work, only vertical space. If you really want “compute only one block at a time,” that is a tab’s job.
18.3 Group Parameters and Nesting
Chapter 4 covered how to use Group. It joins several child elements into one block with a shared outer frame and no gaps in between. This section adds two things: its parameters, and its place among containers.
gr.Group() has six optional parameters: visible, elemId, elemClasses, render, key, and preservedByKey. In the config the parameter names are written in snake case (elem_id, elem_classes, and so on), and /config’s props keeps only the fields that are used. What the example’s Group writes in is visible: true, empty elem_classes and preserved_by_key, plus a name: "group". The example passes not a single parameter.
using (gr.Group())
{
gr.Markdown("**Overview** three lines of one result, joined into a block with `Group`.");
gr.Textbox(label: "Body", value: "The wrapped body goes here.", lines: 2, interactive: false);
gr.Textbox(label: "Statistics", value: "Six lines, 128 characters, longest line 20 characters.", lines: 1, interactive: false);
gr.Textbox(label: "Notice", value: "No blank lines and no overlong lines.", lines: 1, interactive: false);
}
You cannot leave out the using level. When the factory creates the Group it also makes it the current rendering scope; only when that scope ends do the components inside get attached in the right place. This also explains why Group and Row/Column are not peers. Those two set direction, while Group decides “whether this counts as one thing”; it has no scale or minWidth of its own, and how wide it is comes from the layer outside it (Chapter 4).
Of the six, the first three are used most. visible controls whether the whole block is drawn. When hidden it does not appear on the page, but the block still stays in the config; elemId and elemClasses leave hooks for stylesheets, and Chapter 19 uses them to land custom CSS on one specific block. The remaining three relate to the component tree and re-rendering, and the example never passes them. Most of the time Group is simply a container whose parameters you do not need to tune.
Group carries no value of its own and emits no signal; in the component tree it is just a node. It does not change the ownership of the components inside it and cannot be used as an input or output. Being placeable at any level is its other trait — inside tabs, accordions, or the sidebar, all fine. The example’s “Overview” tab uses it to hold three lines of results, and the task panel in Chapter 17 uses it to join steps, result, and status into one block.
Nesting works too, but keep it in check. Put a Row inside a Group, a Column inside that Row, and after three levels each level draws its own frame: three nested rectangles on the page, with no telling which edge belongs to which. The rule of thumb is one Group level plus one direction container; beyond that, split it into two modules.
18.4 Step-by-Step Guidance with Walkthrough
The containers in the previous sections do not restrict where the user can click; Walkthrough is the opposite — you can only go forward.
Walkthrough walk;
using (walk = gr.Walkthrough(selected: 0))
{
using (gr.Step("Preparation", id: 0))
{
gr.Markdown("**Step 1** First see how tabs switch screens, then click an accordion title.");
var next = gr.Button("Next", variant: "primary");
next.Click(() => GoStep(1), null, [walk], apiName: "Go to step 2");
}
using (gr.Step("Processing", id: 1))
{
gr.Markdown("**Step 2** Open the instructions in the sidebar, then come back.");
var next = gr.Button("Next", variant: "primary");
next.Click(() => GoStep(2), null, [walk], apiName: "Go to step 3");
}
using (gr.Step("Wrap up", id: 2))
{
gr.Markdown("**Step 3** Done. Switch to the 'Data' page to see tabs used in a real UI.");
var again = gr.Button("Back to step 1");
again.Click(() => GoStep(0), null, [walk], apiName: "Back to step 1");
}
}
// Switching steps means writing the target step number into an Update and passing it to Walkthrough.
static Update GoStep(int step) => new() { Selected = step };
Walkthrough looks a lot like Tabs: both “draw one screen at a time” and both have selected. But three differences affect how you use it.
selected recognizes the Step’s id, not its ordinal. This is the same idea as Tabs recognizing id, but the consequence here is more direct. If a Step has no id, whatever you write in selected comes up empty. If the example dropped id: 0, not one screen of the three steps would show.
Only the current step is drawn. Reach step two and step one’s content is removed from the page. That is the exact opposite of an accordion: folding hides, a walkthrough replaces.
Steps you have not reached cannot be clicked. The dots for steps two and three are gray and the buttons carry disabled, so the user cannot get in. Steps you have passed get a check mark and are no longer gray. So the “order” is locked at the control level.
You write the step change yourself. Walkthrough has no “Next” button of its own. That is where it differs from a typical wizard component. The example puts an ordinary button in each step; after a click the handler function returns new Update { Selected = 1 }, the outputs names this Walkthrough, and the framework changes the step accordingly.
Why design it that way? Because “whether you may go to the next step” usually needs checking. Form not filled in, file not selected, validation not passed — you should not let the user through then. Since the handler function performs the step change, it gets a chance to block it. If validation fails, return an error and leave Selected unchanged. If the framework shipped its own “Next,” that check would have to be crammed in somewhere else.
There are two events, with a division of labor somewhat different from tabs; let me take them separately.
Changefires when the step number changes, with no payload. When the program advances viaUpdate, this is the one that fires;Selectfires only when the user clicks a completed step, carrying aSelectDatawhoseValueis that step’s title and whoseIndexis the position counted from 0. After the click it goes back to that step and the content block is swapped back.
The case where both fire is “the user clicks back”: first Select (with data), then Change (without). So to know “which step the user went back to,” bind Select; to know only “the step number changed,” bind Change. The example logs the two events separately. One line writes “changed a step,” the other writes “clicked back to ‘Preparation’, number 1.” Logging them separately keeps the later one from overwriting the earlier one.
One more thing. Clicking the current step fires nothing. No change means no event; do not take it as evidence that “the user clicked but nothing moved.”
Figure 18-4 Step two: step one has a check mark, step three is still gray, and the content is swapped to step two
When should you use Walkthrough? One condition only: the order is rigid and a later step depends on the result of an earlier one. Installing configuration, importing data, first-time setup — all fit. Conversely, use tabs when “the user may look at any block in any order,” and an accordion when “the user decides what to do first.”
18.5 Splitting a Single Page into Multiple Pages
The four containers above solve “one page is too long.” They do not solve a different case: the things on this page should not be together.
Three questions decide “should it be split,” asked in order.
- Which blocks are used in one session? If two are never used together, they should not share a page;
- Do they share the same input? If they do, keep them on the same page; if not, separate them;
- Do you need an address you can send on its own? If so, you must split — tabs cannot produce an address.
Question 1 splits the fifteen blocks into six groups in the example: Text, Data, Media, Chat, Run, Layout. Then question 2 reveals one adjustment. Data and its four views below it share the “item source,” so the item source and filtering stay outside the tabs and the four views go into tabs. Skip this question and after splitting you find “the chart page cannot get the filter results.”
Figure 18-5 No modules lost, more addresses: the home page stays at the root and the other six pages each take a suffix
The split itself is small: four steps.
One, group them on paper first, without writing code. Copy the fifteen block names, connect the ones “used together,” and a closed loop of connections is one group. Get this step wrong and everything after has to be redone — and it costs nothing.
Two, give each group an address segment. Short, English, and showing its purpose: text, data, media, chat, ops, layout. Do not use page1, page2. The address shows up in users’ bookmarks; it has to stand up to being looked at.
Three, fold each group’s “build components + bind events” into one method. This is mechanical work, but there is a rule: the method and the components it uses must be in the same scope. Do not think “declare the components outside so two methods can share them.”
Four, open the pages in order at the root, writing the navbar at the top of each (18.6).
using (demo)
{
// The home page is the content at the root: it is not written into any page, and its address is /.
Home();
using (demo.Route("Text", "text")) { TextPage(); }
using (demo.Route("Data", "data")) { DataPage(); }
using (demo.Route("Media", "media")) { MediaPage(); }
using (demo.Route("Chat", "chat")) { ChatPage(); }
using (demo.Route("Run", "ops")) { OpsPage(); }
using (demo.Route("Layout", "layout")) { LayoutPage(); }
}
Except for moving the small “Sharing” block from the end of the page to below the result, the code inside every page method was carried over verbatim. BuildInput(), BuildResult(), and the bindings like arrange.Then(...) were not changed by a single line. That is the payoff of Chapter 4’s “write regions as methods”: when splitting pages you move method calls, not hundreds of lines of component code.
One thing cannot be moved: you cannot reference components across pages. Events can only bind components on the same page, and outputs can only name components on the same page. The old cross-module wiring like “the filter button also updates the display panel” breaks after the split. The example handles it by keeping them on one page (the Data page’s filter and four views), or by letting each mind its own business.
So splitting is not free. For every cross-page dependency, either merge two pages or turn the dependency into an “in-page” one — pass the value through state, or have the user click again. Thinking this through before splitting is less trouble than figuring it out afterward.
Do not call it done right after splitting; run through this checklist.
- Open each page. Visit every page once, looking for blank pages and errors;
- Type the address directly. Try the kind of address from a bookmark first, not by clicking in from the home page;
- Refresh. Press F5 on page two and still be on page two;
- Cross-page dependencies. Are those “click A changes B” wires still connected? Repair the broken ones;
- Navbar. It is at the top of every page, the current page is highlighted correctly, and clicking “Home” returns to the root.
Of these five, missing the fourth raises no error. That button does nothing when clicked — exactly the same symptom as “forgot to bind the event” — but for a completely different reason.
The Data page is a real example of “tabs holding modules.”
Figure 18-6 The Data page: item source and filtering above, four tabs below holding display, table, chart, and gallery
This page uses two containers in different positions. The tabs hold “the four views” because they are parallel, mutually exclusive, and need not be seen together; filtering stays outside the tabs because all four views read its result. Choose the wrong position and the code tells you first: a variable goes out of scope and you cannot reach it.
The home page looks like this.
Figure 18-7 The home page: one navbar and six entries with addresses
The home page holds no modules, just one line of explanation and a list. That is deliberate. After the split, the home page’s job changes from “the UI where work happens” to “telling you where the work happens.” If the home page still piles up modules, it is as if you never split at all.
18.6 Routing and the Navbar
demo.Route(...) means “open a page.” It returns something Dispose-able; close the using and that page ends, with the following components back at the root (or in the next page).
Three parameters: name, path, and showInNavbar.
path is the address suffix; text becomes /text. If you omit path, the framework derives one from name — but it only accepts letters and digits, so a name with spaces or non-ASCII characters derives no usable suffix and throws immediately.
System.ArgumentException: The route 'Text' derives no URL suffix;
give it a name of letters and digits, or pass the path explicitly.
The message is clear enough. That is why the example pairs a display name with a short ASCII path: the name is for the user to see, the path for the address bar. The two need not match, and you should not force them to. Non-ASCII paths get escaped by all sorts of tools when copied and pasted; short ASCII words are safer.
path has a few hard rules; break any one and it throws on the spot.
| What you write | Result |
|---|---|
A route the app owns, like config or gradio_api | Rejected — the app already occupies that address segment |
Spaces or slashes (my page, a/b) | Rejected — a suffix may contain only letters, digits, and -._~!$&'()*+,;=:@[] |
A duplicate of an earlier page (both written as text) | No error — the later page is quietly renamed to _text |
The third does not raise an error. Two pages with the same name are not stopped; at startup the later page is hung on _text, still reachable but not at the address you wrote. The link in the navbar still says text, so clicking it always shows the earlier page. That is where “I clearly clicked page two” comes from. When you find “clicking leads to a different page,” first count whether Route has a duplicate path.
The navbar is another thing to make clear: two facts, one line of code.
// The navbar lists every page automatically (the home page is named with mainPageName), so you do not list them yourself.
// It is a component: it appears only on the page where it is written, so every page has to write it once at the top.
void Top() => gr.Navbar(mainPageName: "Home");
First fact: it lists all the pages by itself. Every page with showInNavbar set to true enters the bar in declaration order, the home page is named with mainPageName, and the current page is highlighted automatically. Tried with a small three-page example. Put only one NavbarLink("Text", "text") in value, and the bar still shows four entries: Home, Text, Data, Media. The links in value are appended, not a “whitelist.” So you do not need to assemble a page list yourself, and doing so would not make it more complete.
Second fact: it is a component, not a property of the page. It appears only on the page where it is written. That is why the example calls Top() once at the top of every page. What if you write it only on the home page? The home page has the bar, clicking into /text loses it, and the user cannot get back. That is not a defect; it matches the component model — components belong to pages, and so does the navbar.
NavbarLink is therefore used in only two cases: adding an external link (write an absolute address as the second parameter), or making one page appear in the bar under a different name. The example adds none, and all six pages are there automatically. Adding an external link works: new NavbarLink("Docs", "https://www.gradio.app") appears in the bar and clicking it jumps straight out. A local-machine app does not need this, but an app delivered to others often wants one.
The third parameter, showInNavbar, decides whether this page goes into the navbar. A page written with false still has its address and can still be opened by address, it just is not in the bar. The example omits this parameter, so all six pages use the default true and all appear. When do you turn it off? Two cases. One is a debug or temporary page you do not want users clicking by mistake; the other is a page “entered from somewhere else,” whose entry point is a button rather than the navigation. This has nothing to do with permissions. It is simply not listed in the navbar — anyone who knows the address can still open it, so do not treat it as access control (Chapter 20).
A page having its own address means three things hold at once.
- Open
/datadirectly and land on the Data page without going through the home page first; - Refresh and still be on the Data page, not back at the home page;
- Bookmark it, send the link, paste it into a document — all point at this page.
The difference between multiple pages and tabs rests on these three things. Tabs are view switching under one address; multiple pages give each view its own address. When a user wants to “send the chart page to a colleague,” only multiple pages can do it.
After splitting, there is one more place to verify that “the pages really are separate”: open /config and /config?page=text and compare. The former is the whole application’s config, with every page’s components listed; the latter lists only this page’s components and bindings. If some event is missing from /config?page=text, it was bound on another page — exactly the mistake splitting leaves behind. Checking the config pins down ownership directly. In code you have to trace through the using nesting; in the config it is a flat list of ids.
18.7 Deep Links and Session State
Multiple pages solve “send an address to a certain page,” but not “after sending it, the content matches what is here.” A colleague opens /text and sees their own empty input.
gr.DeepLinkButton() fills this gap. It draws as a button, and one click does three things: ask the server for a token, append the token to the address, and copy the whole address to the clipboard.
gr.Markdown("### Sharing");
gr.Markdown("Click the button below and a `deep_link` segment appears in the address bar; when the copied link opens in a new window, the input box still holds these same characters.");
gr.DeepLinkButton("Copy link with state");
The first parameter is the text on the button; the second, copiedValue, is the text temporarily swapped in after a successful copy. The example writes “Copied”; omit it and the default Link Copied! is used. It lights up for a little over a second, then switches back to the original line. Checking it takes a quick hand — look right after clicking; wait three seconds and you only see the restored version.
After the click, it goes through a very short chain.
- The frontend requests
GET /gradio_api/deep_link?session_hash=…with the session id; - The server takes a snapshot of the component values recorded for this session and gives that snapshot a short token (the example gets
RVKOw2ohFG8, eleven characters); - The frontend appends
?deep_link=RVKOw2ohFG8to the current address and copies it to the clipboard.
Figure 18-8 The token is only eleven characters; it points at that snapshot in the server’s memory
When someone else opens this link, the server first finds the snapshot by token, fills the component values back in, and then renders the page. What opens is a new session (a new session id), but the page shows the old session’s values. That is what “the ‘Source text’ in the two browser frames in Figure 18-8 is identical” means.
Two things need telling apart here: the session id and the token. The session id identifies this page; it changes on every refresh and the server recognizes the user by it. It is not in the address and the user never sees it. The token is the short segment in the deep link, pointing at “a snapshot of a certain session at a certain moment.” One session can issue many tokens (one per share click), each pointing at the snapshot from its own moment; conversely, a token only goes back to its own snapshot and does not follow later changes to the session.
Put another way, the session id is a house number and the token is a photograph. The house number points to who lives there now; the photograph freezes the moment it was taken.
Figure 18-9 The Text page before sharing: source text, cleaned result, and statistics are all in the session
Testing turned up four things, noted one by one.
First, the token is a reference, not the content. Eleven characters cannot hold several paragraphs of main text; it only says “go fetch snapshot number so-and-so from the server.” So the link is valid only on the same server, within the same process run. Change the port or restart once and the token points at nothing.
Second, an invalid token raises no error and falls back to defaults. Change deep_link to random characters and the page opens as usual with the input boxes at their initial values — the same as having no parameter. That is better than popping up “link expired”; the user can at least still use the page.
Third, the token is a snapshot from the moment it was created. Share first to get token A, then change the input and share again to get token B; opening with A still shows the old values. It is “the photograph from back then.” To get the latest content, you have to click share again.
Fourth, if the last write-back is a property, the value cannot come along. This one is counterintuitive and is often misread as “the deep link is broken.”
The example’s “Source text” box has a Change bound to it (the character count from Chapter 5). While the user types it changes the label to “Source text (23 characters)” and returns gr.Update() with a new label — no value. So after that run, what the server records for this box is a “label-only” property update. Click share then, and the link opens on a box whose label is right but whose value is empty.
Click “Clean up” once and then share, and source text, body, and statistics are all there. What is the difference? “Clean up” reads the source text once as an input and writes the body and statistics back, so the last write carries values.
So the correct statement is this: the link carries away “what the server remembers for this session,” not “what the UI currently shows.” Every run records an entry for the components it used — reads are recorded as values, writes as what was written. But if the last write-back is an Update that only changes properties, that value gets pushed aside by this update. This is the normal result of “a property update overwriting a value.”
The way to judge is plain: before sharing, let the button that actually does the work run once; do not stop at the “only changed the label” step.
One word on security too. The token is a reference: whoever gets the link can see that snapshot. In the example it is the wrapped body, nothing sensitive; swap in a piece of configuration carrying a secret and you should not use this button. Deep links suit “sharing the result of one operation,” not “sharing data in an account.”
One more usage note. Deep links are for people, not for programs. To “pass state between programs,” reading the /gradio_api/... endpoints is more reliable than assembling links (Chapter 22). Links are for people to copy and paste. /text?deep_link=RVKOw2ohFG8 is easier to recognize than a long string of JSON, and the /text in the link plainly marks which page it is.
18.8 Chapter Summary
Tuck away what you can first; split only what you cannot.
Tucking away on the same page, the three containers divide the work clearly. Tabs hold “several screens that are parallel and mutually exclusive,” unmounting components on a switch while values stay in the session; accordions hold “segments within the same page,” where collapsing only hides them and the content remains; the sidebar holds “auxiliary content outside the main text,” floating on the page and callable at any time. The order of judgment: on the same level as the main text → tabs or Row; part of the main text → accordion; not part of the main text at all → sidebar.
All three folding containers have events, but only Tabs.Select carries a payload (Value is the tab’s label text, Index counts from 0). Accordion and Sidebar’s Expand/Collapse take no parameters; to know which one it was, bind them one by one.
selected recognizes id, not text. Tabs and step-by-step guidance are the same; getting it wrong raises no error, it just shows no screen at all. Walkthrough has three more traits: it draws only the current step (not cumulative); step changes must be returned by the handler function as Update { Selected = n }; and it has no “Next” button of its own. Its events come in two kinds: Change covers “the step number changed,” and Select covers only “the user clicked back to a step” (with title and ordinal).
Splitting pages is decided by three questions: which blocks are used in one session, whether they share the same input, and whether you need an address you can send on its own. After splitting, each page has its own address and direct opening, refresh, and bookmarking all work; the price is that cross-page component references do not work and events can only bind components on the same page.
Routing uses demo.Route(name, path, showInNavbar), and the content at the root is the home page. A name that is not plain ASCII letters must be given a path; path cannot occupy a route the app owns, cannot contain spaces or slashes, and cannot duplicate another page (a duplicate raises no error, the later page is renamed to _text) — that one you can only catch by counting.
The navbar is a component and must be written once on every page; it lists all pages by itself (the home page named with mainPageName, the current page highlighted), and NavbarLink is only for appending external links or giving a page a different name.
Deep links use gr.DeepLinkButton(); one click gets a token, appends it to the address, and copies it. The token is eleven characters and points at a snapshot in the server’s memory; an invalid token falls back to defaults; the snapshot is from the moment of creation, not live; and it is valid only on the same server. Last, this one: the link carries what the server remembers, not what the UI shows. If the last write only changed properties, the value carried over is empty.
Finally: if you can tuck it away, do not split; once split, stop thinking about cross-page references; if you want to share, share the result of one run, not “the text being typed.”
The next chapter changes direction: with the UI structure settled, the next step is making it look good. Themes, colors, fonts, custom stylesheets — all work that “changes appearance without changing structure.”