universal-dependencies-visualizer / docs /GRADIO_DESIGN_GUIDE.md
Simon Clematide
fix: align navigation typography for v1.0.2
23643fa
|
Raw History Blame Contribute Delete
27.3 kB
# Designing restrained, professional Gradio applications
Use this guide to adapt Gradio prototypes into restrained, professional applications. It applies to editors, model demonstrations, analysis tools, media processors, and other interactive workflows. Choose the patterns that fit the task; a small tool does not need the navigation or workspace complexity of a larger application.
The aim is a calm working environment: clear tasks, readable content, predictable interactions, and enough visual distinction to make important states obvious. Gradio provides the components; the application should provide the hierarchy.
## 1. Set the design direction
Gradio applications often accumulate emphasis as features are added: colored badges, decorative emoji, prominent containers, repeated headings, numerous status details, and controls competing for attention. Users may have to assemble the workflow from disconnected controls and help panels.
Establish information flow and correctness first, then refine presentation. Use neutral surfaces, consistent typography, selective line icons, compact toolbars, and progressively disclosed detail. Examples should include their dependencies. Status and actions should follow application state. Automatic updates should preserve the user's focus and working position.
| Area | Starting tendency | Resulting principle |
| --- | --- | --- |
| Visual emphasis | Several colors and badges compete | Use hierarchy first; reserve color for meaning |
| Containers | Nested boxes and shaded regions | Give the main work areas boundaries; keep their contents light |
| Headings | Titles and metadata repeated across containers | Display each piece of information where it is useful |
| Controls | Large buttons and scattered utilities | Group controls by task and size them to their content |
| Status | Readiness, metrics, and technical details compete | Show essentials; disclose supporting detail |
| Examples | Sample inputs require extra setup | Supply a complete, runnable example, including media |
| Help | Instructions leave gaps between workflow stages | Explain the full workflow in the order users need it |
| Preview | Updates interrupt the user or show stale results | Update deliberately while preserving focus and position |
| Branding | Release-stage label adds another signal | Show release information only when it helps users |
A professional interface is achieved when each distinction has a purpose. Establish hierarchy before changing colors: remove competing emphasis before removing useful identity. A restrained accent color is acceptable when used consistently. Preserve deliberately prominent content, such as a sentence input used for teaching, when its size serves the task.
## 2. Organize around the user's work
Give each page or tab a clear job. A larger application might separate the main workspace, asset management, and reference material. A small application may work best on one page. Add navigation when it reduces cognitive load, rather than to give every component its own destination.
Keep the primary workflow easy to describe: provide input, configure what matters, run or preview, inspect the result, then use or download it. Adapt this sequence to the task; continuous editors and explicit model runs need different interaction patterns. Navigation labels should name tasks or destinations consistently. Help should support this sequence rather than introduce a second vocabulary.
At the entry point, provide:
- A product name and one sentence explaining its purpose.
- An obvious entry into the main workspace.
- A small set of examples that demonstrate real capabilities.
- Brief workflow guidance, with longer explanations available on demand.
- Quiet version and release-date information when useful for support.
Avoid turning the entry page into a wall of documentation. A separate Home page is optional. Let users start working immediately when little explanation is needed. Example details can live in a collapsed disclosure while the action to load the example remains visible. Renaming a collapsed section “Try an example” does not by itself provide a visible example action.
Navigation should normally change the destination only. Actions that also execute processing should say so, such as **Parse an example**. Avoid hiding model execution behind a generic navigation label.
## 3. Establish a restrained visual foundation
### Typography
Use one sans-serif family for interface text and documentation, with a reliable fallback stack. A suitable example is **Source Sans 3**, followed by Source Sans Pro, Arial, and sans-serif; an established system sans-serif stack is also appropriate. Use a monospace stack for editable source and code examples.
Navigation labels should match the normal body text size unless there is a
specific reason to differ. Use regular weight and distinguish the active tab
through an underline and color, rather than larger or heavier text. Define the
size consistently with body prose, using a shared typography token where
practical. Scope tab styling to a stable application hook, and verify both
computed font sizes and the rendered navigation, including long labels and
narrow layouts.
Create hierarchy through size, weight, spacing, and placement. Keep the number of distinct text styles small. Product titles can be larger; section headings should be modest; metadata should recede without becoming difficult to read. Avoid bolding every label and adding a badge to every value.
The following values are a starting point to tune against actual content, devices, and font metrics:
| Role | Starting point |
| --- | --- |
| Product title | Approximately 1.8rem, medium to semibold |
| Section heading | Approximately 1.05–1.08rem, semibold |
| Introductory prose | Approximately 1.05rem, line height 1.6 |
| Toolbar and status text | Approximately 0.9–0.95rem |
| Source editor | Approximately 0.92rem, monospace, programming ligatures disabled |
| Documentation | Line height approximately 1.65 |
Use relative sizing where practical and check readability at browser zoom. Do not shrink necessary instructions to make a layout fit. Shorten the text or improve the layout. Check font fallback behavior as well as the preferred font.
### Color and surfaces
Start with white surfaces and slate text. Use a dark slate primary action and white secondary actions with light borders. Use subtle separators and small corner radii. Remove routine button shadows and unnecessary shaded panels.
An example light-theme palette:
| Purpose | Reference color |
| --- | --- |
| Main headings | `#0f172a` |
| Body text | `#1e293b` |
| Primary action | `#334155` |
| Supporting text | `#475569` or `#64748b` |
| Light divider | `#e2e8f0` |
| Subtle reference surface | `#f8fafc` |
Keep semantic color where it conveys correctness, an error, a warning, or an interactive distinction such as selected image regions or distinct data series. Routine categories usually need readable names rather than a rainbow of badges. Reserve error styling for failed operations or invalid inputs. Model disagreement, alternative interpretations, and detected differences are analytical findings; present them neutrally unless a separate criterion establishes an error. This distinction is especially important in teaching applications, where disagreement can be the learning opportunity. Pair semantic color with text or another recognizable cue. Keep data visualization palettes separate from interface decoration: plots may need multiple colors to distinguish series. If dark mode is supported, define equivalent semantic roles and check every state in that mode rather than applying light-theme colors unchanged.
### Spacing and boundaries
Use spacing to establish groups before adding a border. Main input and result panes benefit from clear boundaries; each nested label, status, and toolbar does not need its own card.
Use a small, repeated spacing scale. Gaps around 8, 12, and 16 pixels and radii around 4–5 pixels are reasonable starting points. Align related labels and controls consistently. Remove empty wrappers and excess padding that create unexplained gaps.
Give the application a consistent outer inset. Unless the layout intentionally
requires otherwise, match the top padding to the left and right padding;
16 pixels on all sides is a useful starting point. Check the navigation as well
as the content: tabs should not sit flush against the top edge while the rest
of the interface is inset horizontally.
Apply page padding to the outer application wrapper only. Avoid broad selectors
such as `.wrap`, which can also affect Gradio loading overlays and nested
components. Inspect the rendered structure and scope the rule to the page
wrapper; verify it again after changing Gradio versions. Keep width calculations
compatible with the inset, for example using `box-sizing: border-box`.
Verify the outer spacing in the actual hosting context, including the direct
Space URL and its enclosing Hugging Face page. Host chrome, iframe boundaries,
and browser zoom can make spacing differences more apparent than in a local
preview. Check computed padding and the rendered result; do not infer equal
visible margins solely from the CSS declaration.
## 4. Make controls explain their purpose
### Actions and emphasis
Choose the primary action for the current task and state. Avoid giving every button equal visual weight.
For example, **Run analysis** can be primary before a result exists. Once the current result is ready, **Download results** may become primary and **Run again** secondary. If inputs change, clearly mark the previous result as outdated. Keep actions in stable locations as their state changes.
Use concise, specific verb phrases: **Upload image**, **Load example**, **Run analysis**, **Download CSV**, **Copy result**. Match these names in documentation and tooltips. A tooltip may explain a consequence; the label should still be understandable without it.
Size routine buttons to their content. Full-width actions are useful when the layout or device warrants them, but should not be the default for every utility. In Gradio, explicitly review `scale` and `min_width`; intrinsic component widths can otherwise force overflow or awkward wrapping.
### Icons
Use one coherent icon family. Simple SVG line icons work well for upload, download, copy, expand, and edit, and for distinctions such as input versus output or view versus edit mode.
Keep icons that improve recognition or scanning. Remove decorative emoji from routine headings and buttons when they add visual noise. Do not mix several icon styles within the same toolbar.
Prefer an icon with a visible text label for unfamiliar or consequential actions. An icon-only fullscreen control can work when it has an accessible name and an accurate tooltip. Decorative icons should be hidden from assistive technology; meaningful icons need an accessible equivalent.
### Toolbars
Put controls beside the content they affect. For example, result display options, expand/collapse, and fullscreen controls belong in the result header. Avoid duplicating these controls in a second toolbar inside the result content.
Keep desktop toolbars compact and allow deliberate wrapping on narrow screens. Labels must remain readable; never accept one-word-per-line or syllable-level wrapping as a responsive design.
## 5. Separate essential state from supporting analysis
Show the facts users need to act: input readiness, processing progress, result availability, and result freshness. Put optional metrics and heuristic advice behind a clearly named disclosure, such as **Quality checks**.
Distinguish blocking errors from warnings and advisory checks. A successfully processed input can still require human review. A heuristic warning must not imply that processing failed or that a model judgment is certain.
Keep success messages short and local. Avoid displaying an elaborate success panel for every routine operation. Detailed filenames and explanations can be secondary text or tooltips when they do not affect the next decision.
For long-running work, show a clear running state and useful progress when available. Prevent accidental duplicate submissions. On failure, preserve recoverable inputs and give a specific next step; show technical diagnostics separately from the user-facing explanation.
Empty states should explain the next useful action. Hide empty workspace content and unnecessary disclosures where they create dead space. Ensure a collapsed panel's label tells users what they will find inside it. When moving content into a disclosure, preserve a visible cue to the capability and its purpose. Verify that a first-time user can discover examples, contextual help, and interactive features without reading the full documentation.
## 6. Make updates predictable
Choose an update model that matches the task:
| Task | Appropriate starting pattern |
| --- | --- |
| Lightweight formatting or local preview | Automatic updates; debounce disruptive navigation |
| Expensive inference or analysis | Explicit Run action with progress and a clear completion state |
| Repeated parameter exploration | Debounced or explicit updates, depending on cost and latency |
| Long-running processing | Progress, cancellation where supported, and durable result access |
Avoid triggering costly work on every keystroke. Explain whether changing a setting immediately updates the result or requires another run. Keep previous results available when useful, but identify them as outdated if their inputs have changed. Prevent older requests from overwriting newer results.
A result belongs to a specific combination of input and processing settings. Track that combination explicitly. Mark retained results as outdated whenever a relevant value changes, and verify freshness again when asynchronous processing completes. Apply the same contract to examples, shared-link loading, retries, and ordinary submissions. Treat the visualization, tables, raw output, summaries, and exports as parts of the same result. An outdated-result notice should supplement, rather than erase, relevant failure information.
Prefer one execution model within a workspace. If examples execute immediately while manual edits require **Run**, communicate that before selection and make replacement behavior clear. Choose immediate execution only when its benefit warrants this difference; otherwise let examples initialize the controls and use the ordinary primary action to execute.
For linked editors and previews:
- Use compact summaries with enough identity to navigate.
- Reveal full titles when expanded without repeating them in the body.
- Suppress redundant headings while retaining instructions and warnings.
- Preserve meaningful document or result groups.
- Keep supporting detail available without dominating each item.
- Preserve expansion, selection, and scroll state across ordinary updates where possible.
- Make modes explicit when they change what users see or can do.
About **one second of inactivity** can be a useful starting point for source-to-preview navigation. Each new input resets the delay. Tune the delay to the task; explicit navigation can synchronize immediately.
The interaction contract matters more than the exact timeout:
1. Preserve input focus, selection, and caret position.
2. Identify the result corresponding to the current input position.
3. Scroll only when the relevant context is outside the visible pane.
4. Scroll the relevant pane without unexpectedly moving the whole page.
5. Wait for a result corresponding to the current input; do not navigate using stale content.
6. Cancel pending navigation when focus leaves the input.
7. Respect input-method composition and synchronize after composition ends.
Treat content updates, expensive computation, and viewport movement as separate decisions. They need not use the same timing policy.
## 7. Make documentation part of the product
### Explain the complete path
Documentation should answer, in order: what the tool does, how to start, what input is accepted, which settings matter, how to interpret the result, and how to save or use it. Include downstream steps when the application produces files for another tool.
Put consequential choices before the steps that depend on them. For example, explain the choice between processing modes before upload or execution if it changes accepted formats, runtime, or output interpretation.
Explain what each validation layer checks and where its limits are. Distinguish previews and estimates from final results. For integrations, explain any relevant differences in the destination tool and how users can verify the transferred result.
### Use complete examples
Start with a small, complete example users can load and run. Follow it with format details and advanced variations. Give each example a clear purpose, such as the simplest workflow, a representative real case, or an advanced capability.
Bundle all required assets: images, audio, sample tables, configuration, or companion files. Loading an example should initialize the relevant controls and dependencies together. Offer downloads when users need to inspect or reuse those assets. An example should demonstrate a working workflow without hidden setup.
State when loading an example replaces existing work. Ensure examples replace or initialize all relevant state consistently so that unrelated old files or results cannot mislead users.
### Verify technical claims
Run examples through the actual processing path. Verify target-platform instructions against authoritative documentation and the actual supported integration. Be careful with accepted formats, units, escaping, defaults, model limitations, and version-specific behavior.
Do not infer the behavior of a bundled engine solely from a newer specification. Check the installed version and actual runtime behavior when defaults affect the result. Displayed code must preserve literal backslashes and other syntax after Markdown rendering.
Use exact current button and page names throughout help. When a control is renamed, search documentation, examples, tooltips, and empty states for the old name.
### Present reference material quietly
Use descriptive headings, short paragraphs, and tables for genuine comparisons. Prefer light horizontal table separators and a subtle header background to a heavy grid. Use monospace for literal syntax and restrained code-block backgrounds. Put long explanations behind disclosures only when users can discover them from a meaningful label.
Keep application help, repository documentation, and downloadable instructions aligned. Assign a clear home to each explanation so that duplicated guidance does not drift.
## 8. Work with Gradio deliberately
Use the theme for shared typography, palette, and component defaults. A restrained base theme with neutral hues and consistent label styling is a useful foundation. Add application CSS for layout and details that the theme does not express adequately.
Use stable `elem_id` and `elem_classes` hooks for application styling. Prefer explicit hooks over selectors tied to incidental generated markup. Keep shared visual rules centralized and reuse icon and control helpers across rendered HTML and Gradio components.
Gradio wrappers can add padding, minimum widths, scrolling, or flex behavior that is not obvious from Python code. Inspect the rendered layout. A component that looks correct in isolation may overflow when placed beside status text or inside a toolbar.
Use browser-side behavior for local interaction when appropriate, but account for asynchronous backend rendering. Avoid duplicate event handlers after rerenders and use an explicit notion of render freshness for interactions that depend on the current content.
During a redesign, a final CSS override layer can help establish the new hierarchy. That is a practical migration technique, not a reason to keep accumulating contradictory rules indefinitely. Future maintenance should consolidate superseded styles when doing so is safe and reviewable.
## 9. Validate the experience, not just the code
Review the deployed app after deployment as well as a local build during implementation. A source-level review cannot reveal every wrapper, scrollbar, font, or responsive-layout issue.
Use this review sequence:
1. **Information flow:** Can a first-time user identify the next action and complete the workflow?
2. **Correctness:** Do labels, examples, validation claims, and import instructions match behavior?
3. **Visual hierarchy:** Does the working content receive more attention than its controls and metadata?
4. **Interaction:** Do editing, previewing, expansion, navigation, and export states behave predictably?
5. **Responsive layout:** Do controls wrap intentionally without horizontal overflow or clipped labels?
6. **Accessibility:** Are names, focus indicators, keyboard behavior, and non-color cues usable?
Check the workspace at a normal desktop size and a narrow mobile width, for example 390 pixels. Also check long labels, large inputs, and browser zoom. Exercise empty, invalid, ready, running, successful, failed, and outdated-result states where applicable. Include cancellation and retry if supported. Inspect representative text, tabular, and media content for the application.
Use focused automated tests for consequential state transitions and timing behavior. For example, test result freshness, asynchronous request ordering, and delayed synchronization, including composition input when editing is supported. Avoid tests that merely freeze incidental markup or decorative choices.
Record validation evidence: identify the workflows, viewport sizes, failure states, and deployment contexts actually checked, along with material gaps. A desktop fixture pass does not establish mobile usability, live-service availability, or hosted export behavior.
Browser verification must include real input events: changing a textarea's DOM value alone may not trigger Gradio's normal update path. Confirm both the visible result and the relevant application state.
## 10. Acceptance checklist for future changes
- The main task and next action are obvious.
- Fonts, spacing, borders, and icons follow the shared system.
- Color communicates a meaningful state or distinction.
- Buttons have concise names and appropriate emphasis for the current state.
- Related controls share a toolbar or local action group.
- Headings and content are not needlessly repeated.
- Essential status is visible; optional detail is discoverable.
- Results track their input and settings; changes and late completions cannot silently present an outdated analysis as current.
- Navigation and execution are distinct, or their combination is explicit.
- Analytical disagreement is visually distinguished from processing failure.
- Editing preserves focus and does not cause unexpected page movement.
- Examples are complete and include their required assets.
- Help follows the workflow and matches current behavior and labels.
- Desktop and narrow layouts remain readable and usable.
- Outer top and side spacing is consistent, including navigation, and has been checked in the hosted context.
- Keyboard focus and accessible names survive visual simplification.
- Relevant behavioral checks and a rendered UI review have been completed, with their scope and gaps recorded.
- The deployed application version identifies the reviewed release, separately from framework and model versions.
## 11. Adapt an existing application in stages
1. **Map the task.** Write down the intended user, the primary outcome, and the shortest complete workflow. Identify consequential choices and common points of confusion.
2. **Inventory the interface.** List pages, controls, states, examples, and documentation. Mark duplicated information and features that are advanced or rarely needed.
3. **Repair information flow.** Reorder controls around the workflow, clarify labels, complete examples, and correct help before polishing appearance.
4. **Define the visual system.** Choose typography, neutral surfaces, action hierarchy, semantic colors, spacing, and a single icon family. Centralize these choices.
5. **Simplify the workspace.** Reduce nested containers, consolidate toolbars, and move optional detail into discoverable disclosures. Preserve necessary functionality.
6. **Review interaction behavior.** Define when work runs, how progress and stale results appear, what persists across updates, and when automatic navigation is appropriate.
7. **Verify representative tasks.** Complete a first-use workflow, a repeat-use workflow, and a failure-and-recovery workflow on desktop and a narrow viewport.
8. **Consolidate.** Remove superseded styles and obsolete labels, align documentation, and keep a short acceptance checklist for future additions.
For a model demonstration, prioritize meaningful defaults, clear input examples, explicit execution when computation is costly, and honest result interpretation. For an analysis tool, prioritize data readiness, configuration, traceable result state, and useful downloads. For an editor, prioritize space for content, stable focus, linked previews, and unobtrusive validation.
Use this guide as a design brief rather than a fixed template. Keep the shared principles consistent while letting the application's task determine its structure.
## 12. Versioning and release traceability
Maintain the application version and release date in one source of truth.
Display them quietly in About or the footer, without a promotional badge.
Keep necessary metadata readable and avoid repeating it across the interface.
Use semantic versioning (`MAJOR.MINOR.PATCH`) and a dedicated bump script:
- **Patch:** fixes that preserve supported behavior and interfaces.
- **Minor:** backward-compatible features.
- **Major:** incompatible changes to supported workflows or public APIs.
Update the release date when preparing a release and use a documented timezone
consistently. Keep application versions distinct from framework, model, dataset,
and renderer or asset versions. A framework version in deployment metadata is
not an application release identifier.
The bump script should update version metadata only. Prepare and commit the
version change explicitly before publishing; avoid automatic version commits
inside push hooks. Such hooks can change the local history during publication
and make it harder to establish which commit was actually deployed.
Review the release diff, run the relevant checks, and create the release commit.
Tag that commit when tags are part of the release workflow. Publish the same
reviewed commit to each deployment remote, then verify the displayed version
in the deployed app. If the host creates additional build commits, retain a
traceable mapping to the reviewed source commit.
Distinguish clearly between **implemented locally**, **committed**, **pushed**,
and **deployed** when reporting completion. A successful push establishes source
publication; deployment is complete only after the host finishes building and
the running app has been checked.