Introducing a new way to review your PRs.

Read the announcement

nklmilojevic / sofka

A Kubernetes TUI, reimagined in Rust - built on kube-rs and ratatui, async-first from the ground up.

View on GitHub

19 documents · Updated Nov 4, 2026

docs / terminal-rendering-and-input

Terminal rendering and input

Terminal rendering and input form the UI boundary of sofka. The terminal layer owns screen modes and command hand-off. The renderer turns application state into readable views. The input layer turns terminal events into actions that change that state. Read this page with Interactive terminal application for the product flow and Application event loop and navigation for state movement outside the terminal boundary.

Terminal session

The terminal session gives the application a full-screen workspace while keeping shell use safe. Startup enters raw mode and the alternate screen. The main loop then presents frames. Shutdown restores mouse capture, the screen, and the cursor so the user's shell receives a normal terminal.

When sofka runs an interactive command, it temporarily gives the terminal back to that command. It releases raw mode and the alternate screen before the command starts. It restores them and clears the terminal before the UI resumes. This keeps shell input and UI input from sharing terminal modes.

flowchart LR
    A[Start application] --> B[Enter alternate screen and raw input]
    B --> C[Render UI frames]
    C --> D{Interactive command queued?}
    D -- No --> C
    D -- Yes --> E[Restore normal terminal for command]
    E --> F[Run command with inherited input and output]
    F --> G[Re-enter UI terminal modes]
    G --> C
    C --> H[Quit]
    H --> I[Restore shell terminal]

The main loop redraws after input, resize, and relevant state changes. It batches background updates and limits their frame rate, while key events redraw without waiting so typed input stays responsive. A resize causes a fresh layout before later input uses the new dimensions. src/main.rs coordinates this lifecycle and src/terminal.rs owns the temporary command boundary.

References: src/main.rs• L549-566 src/main.rs• L1008-1043 src/main.rs• L1046-1165 src/terminal.rs• L9-35

Rendering model

The renderer presents one coherent frame from the current App state. It chooses the layout, draws the active base view, adds overlays, and sends the result as one synchronized terminal update. Resize handling draws a fresh frame before the next event uses the new geometry. This prevents users from seeing partial frames or acting on stale dimensions.

The normal layout has a header, a main view, an optional prompt, and a status line. The header carries context, cluster, namespace, resource, count, and action hints. Resource tables can also show a compact guide for actions that apply to the current kind. Compact mode reduces this chrome to a single header while keeping prompt input visible. Fullscreen logs and documents remove borders and surrounding UI so terminal selection produces clean text. The header gives up its logo before its action hints as the terminal narrows. If the hint column cannot fit, the header keeps the context information and leaves the full guide to help.

Overlays keep the view that opened them underneath when that context helps the user understand the pending action. A palette, confirmation, prompt, directory browser, or PVC action therefore does not replace the relevant table or document. Transient activity is drawn above the base view. Plugin activity can show progress, diagnostics, follow mode, and a final result without hiding the rest of the UI permanently. A command-failure popup is added after the base view so an error remains visible until the user dismisses it.

The main view types serve different reading and operating needs:

ViewPurposeMain reading behavior
Resource tableBrowse live resourcesRow selection, sorting, filters, marked rows, status signals, and horizontal column movement
Document, diff, or event viewRead resource text and change historyVertical and horizontal scroll, search matches, syntax cues, and optional wrapping
Log viewFollow or inspect streamed logsFiltering, follow mode, timestamps, source labels, ANSI colors, JSON display, wrapping, and fullscreen reading
Picker, directory browser, or popupChoose a resource, local manifest, context, namespace, action, or optionSelection, type-to-filter input, and a focused result list
Help or specialized viewExplain actions or show focused operational dataSearch, scrolling, compact summaries, and view-specific panels
flowchart TD
    S[Application state] --> L[Choose responsive layout and base mode]
    L --> B[Draw header and base view]
    B --> V[Table, document, logs, or specialized view]
    V --> O[Draw active prompt or overlay]
    O --> A[Draw activity or failure feedback]
    A --> P[Present one synchronized frame]

Tables use terminal-cell width rather than byte length. The renderer keeps the name and selection area anchored while other columns move through a narrow viewport. Configured columns can set width and alignment, while the remaining columns share available space according to their display role. Resource status and metric thresholds add semantic color without changing the table's role. Resource rows also show active port forwards and matched filter characters across visible cells where those signals help scanning. Document and log views use the same visible-row idea for wrapping and scrolling. The log view also keeps an indexed display-row position so large paused buffers remain usable. Long log lines can move sideways when wrapping is off.

The renderer distinguishes live data from a static snapshot in the status area. A table or event view can show live or syncing state. A document, diff, explanation, volume browser, or local directory listing shows static state instead, so the UI does not imply that a one-time result is still updating. Directory browsing presents manifests and subdirectories as a focused list. Its action hints expose navigation, refresh, edit, apply, and delete operations, while a manifest preview adds apply to the document-view hints.

References: src/ui.rs• L91-120 src/ui.rs• L205-512 src/ui.rs• L557-841 src/ui.rs• L1225-1637 src/ui.rs• L1702-1858 src/ui.rs• L1878-2024 src/ui.rs• L2000-2185 src/ui.rs• L2191-2387 src/ui.rs• L3969-4044 src/ui.rs• L5944-5976 src/ui.rs• L6111-6129

Configurable resource views

Resource views describe how a Kubernetes object becomes a readable table row. A view can add or replace columns, choose an initial sort, define display width and alignment, and describe how a row relates to another resource. The view system selects the most specific configuration for the resource and namespace, then supplies the renderer with display values and sort values.

Unknown custom resources can still gain useful columns from their Kubernetes custom-resource printer columns. This gives the table a readable fallback without requiring a built-in view for every resource kind. Invalid view settings become warnings and do not stop the UI from starting.

References: src/views.rs• L1-11 src/views.rs• L99-149 src/views.rs• L291-299 src/views.rs• L644-675 src/views.rs• L1052-1118

Theme and semantic styles

The theme system gives the UI a named palette and shared semantic styles. Views ask for roles such as title, border, selected row, dim text, status, and severity instead of choosing unrelated colors at each draw site. This keeps resource state readable across tables, documents, popups, and status messages.

The active skin comes from configuration. sofka supports named dark and light palettes, plus per-swatch color overrides. If no skin is named, it makes a best-effort dark or light terminal check and selects a matching default. Unknown skin names, swatch names, and malformed colors produce warnings while the UI keeps a usable fallback. The background fill is separate, so the UI can either preserve the terminal background or paint the skin's base color. Popup clearing respects that choice and repaints the skin background when needed.

Status colors express meaning rather than raw field names. Healthy rows use the normal row tint. Transitional rows use a warning tint. Failures use red. Completed rows fade. Terminating rows use a separate end-of-life tint. Threshold-based CPU, memory, restart, and utilization warnings use the same semantic severity roles. Embedded standard ANSI colors in logs are mapped into the active skin, while explicit indexed and true colors remain available for source output.

A skin can change while the application runs. Palette readers refresh after a skin or context change, so later frames do not mix colors from two skins.

References: src/theme.rs• L36-111 src/theme.rs• L117-153 src/theme.rs• L263-339 src/theme.rs• L358-480 src/theme.rs• L487-675 src/ui.rs• L205-221 src/ui.rs• L1460-1539 src/ui.rs• L2261-2589 src/ui.rs• L2722-2799

Key mapping

Key mapping separates an action from the key that invokes it. An action has a name and description. Each UI mode has a scope with its own effective chords. Shared global, navigation, and text-input bindings can be changed as groups. Shared changes apply before explicit mode settings, so a mode-specific setting takes precedence and can replace or disable one binding. The default map also accepts shifted forms of arrow, paging, and home/end navigation where they do not conflict with table range selection, and provides half-page actions wherever paging is available.

The action catalog covers resource operations, document and log controls, picker navigation, structured log display, timestamps, and resource-specific changes such as image or Helm chart version updates. The keymap records which resource kinds support actions that only make sense for those kinds. If a key invokes such an action on another kind, user bindings such as bookmarks, workspaces, or plugins get the first chance to handle it. If no binding handles the key, the UI can report the kinds where the built-in action applies instead of running an operation that cannot work on the current resource.

The keymap compiles configuration before it becomes active. It accepts plain keys, named keys, function keys, and modifier forms. Explicit completion bindings in the command palette take priority over text-editing and cancel bindings when they overlap. Shared paging bindings yield to text editing or a mode's existing binding unless the mode explicitly sets them. Inherited Ctrl-H backspace is also released when another binding claims it. The compiler rejects unknown scopes, unsupported actions, invalid chords, and conflicts. If compilation fails, sofka keeps the default or previous working map rather than installing a partial map.

The same effective labels drive behavior, help text, header hints, prompts, and popup footers. These views therefore show the binding that works after user overrides instead of a hard-coded default. Resource-table hints are filtered by the active resource kind and include actions such as the namespace resource list or a Helm chart version change only when they apply. Narrow headers reduce their hint set when the terminal cannot fit the full per-kind action guide. The directory browser uses its own navigation hint set, and a local-manifest diff exposes the apply action alongside document navigation.

References: src/keymap.rs• L141-229 src/keymap.rs• L245-293 src/keymap.rs• L656-772 src/keymap.rs• L775-917 src/keymap.rs• L951-1017 src/keymap.rs• L1057-1115 src/ui.rs• L805-1223 src/ui.rs• L6013-6159

Input processing

Input processing maps a terminal event to the current mode's action and then applies that action to application state. The mode selects the key scope, so the same key can mean navigation in a table, editing in a prompt, or scrolling in a document. Global actions and special overlays are handled before mode-specific dispatch.

Text entry uses shared editing behavior across the command palette, filters, prompts, and pickers. Plain character events append to the active buffer. Enter accepts the current input. Escape returns or cancels. Backspace removes one character. Ctrl-U clears the line. Word-rubout removes trailing whitespace and the preceding word. The command palette also updates suggestions as the buffer changes.

The main input paths are:

  1. The event loop accepts a key or mouse event and repairs split alternate-scroll escape sequences when mouse capture is off.
  2. The app resolves the event against the active key scope.
  3. The mode handler changes selection, text, scroll state, or a pending operation.
  4. The app performs cleanup for overlays, streams, child tasks, and suspended commands.
  5. The next frame shows the new state.

Filters provide live local feedback. Resource label and field selectors take effect on Enter because they change the server-side watch. Document searches keep the source view visible and highlight matches in place. Log filters and follow mode change what the log viewport reads without changing the resource view below it. Prompts raised from logs, context pickers, the PVC browser, or the directory browser keep the relevant base view visible so the requested action remains clear. The directory browser accepts a path, shows local manifests and directories, and uses its preview or list as the base for apply and delete actions.

References: src/main.rs• L1046-1165 src/…/input.rs• L19-124 src/…/input.rs• L127-232 src/…/input.rs• L235-273 src/…/input.rs• L549-587 src/…/input.rs• L1136-1169 src/…/input.rs• L1435-1525 src/…/helpers.rs• L206-225 src/ui.rs• L329-512 src/ui.rs• L3969-4044 src/ui.rs• L5739-5819

Text helpers

Text helpers protect the UI at terminal boundaries where byte length and display width are different. The shared ellipsis helper truncates by Unicode character and adds one ellipsis cell when needed, so multi-byte API values do not cause invalid byte slicing. The renderer separately measures terminal display columns for table widths, clipped cells, popup sizing, and visible text.

Document, diff, help, and log views use display-cell width for wrapping and horizontal clipping. Their scroll positions count the same display rows that the renderer draws. Wide Unicode characters take the space they need. ANSI escape sequences do not take display cells. Log helpers remove control sequences from screen text while preserving useful embedded color, source labels, timestamps, severity colors, and search highlights. Horizontal log scrolling clips by display columns and preserves styles at the scroll edge.

These rules keep names, revisions, errors, headers, file names, and other variable text inside their available area without corrupting UTF-8. They also support stable wrapping and horizontal movement when text includes wide Unicode characters or colored log output.

References: src/text.rs• L1-19 src/ui.rs• L1712-1796 src/ui.rs• L1829-1913 src/ui.rs• L1936-1998 src/ui.rs• L2000-2185 src/ui.rs• L2191-2387 src/ui.rs• L2606-2799 src/ui.rs• L5591-5819

Terminal title

The terminal title identifies the active sofka context and namespace outside the application window. When enabled, it follows the form sofka: context/namespace; all-namespaces mode uses all. Control characters are removed before the title reaches the terminal.

Title updates are change-driven. The UI loop writes a title only when the computed value differs from the last value. It clears the title when the feature is disabled or the application exits. Context changes and command suspension refresh the title so the shell window does not keep stale session information.

References: src/…/mod.rs• L44-57 src/terminal_title.rs• L5-36 src/main.rs• L1027-1043 src/main.rs• L1071-1079 src/main.rs• L559-566

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the renderer's mode layout and the input mode-to-scope mapping aligned. A new view or overlay can otherwise draw correctly but receive the wrong bindings.
  • Keep keymap labels and help generation based on the same effective map. Hard-coded hints can become false after configuration overrides.
  • Keep shared key groups applied before explicit mode overrides. File order must not change which binding wins.
  • Keep command-palette completion bindings distinct from text-editing and cancel bindings. An override can otherwise change which action receives an overlapping key.
  • Keep shared paging changes aligned with text editing and mode-specific bindings. A new inherited paging key can silently consume line editing input.
  • Keep kind-specific action declarations aligned with fallback dispatch, header hints, and hidden-key warnings. A stale supported-kind list can block plugins or report the wrong resource kinds.
  • Keep terminal mode hand-off paired. Every path that releases raw mode, mouse capture, or the alternate screen must restore it before the next UI frame.
  • Keep compact, fullscreen, and normal layout conditions aligned with prompt placement. A new mode can otherwise hide the input line or draw an overlay over the wrong base view.
  • Keep overlay order explicit. Activity and error panels must remain above the base view without hiding a prompt or the view that gives the action context.
  • Keep wrapping, display-row counts, ANSI handling, horizontal clipping, and scroll handlers based on the same width rules. A mismatch can make follow mode or paging jump to the wrong place.
  • Keep live-versus-static status labels aligned with the data source. A snapshot view must not claim that it is still watching the cluster.
  • Keep title updates and context-switch state aligned so a disabled setting clears an old title and a new context does not display stale namespace data.
  • Keep semantic theme roles stable when adding view states. Status and severity colors are shared signals across table cells, rows, prompts, and diagnostics.
  • Keep directory list, preview, and action hints aligned. A local-manifest mode can otherwise show the wrong base view or expose an action that does not apply to the selected entry.

Important failure modes

TriggerConsequenceGuard
A configured key scope, action, or chord is invalid or conflicts with another bindingThe new map is rejected and the default or previous working map remains activeKeymap compilation validates scopes, actions, chords, and overlaps before replacement
A mode override is applied before shared bindingsA shared setting can silently replace a more specific mode choiceCompilation applies shared groups first and explicit mode settings second
Completion keys in the command palette overlap with text editing or cancel keysA typed key can edit or close the palette instead of completing the selected suggestionExplicit completion settings remove overlapping lower-priority input bindings
A shared paging key overlaps with text editing or a mode bindingA text command can page instead of editing, or a mode can lose its own actionShared half-page keys yield to editing and existing mode bindings unless explicitly set
A kind-specific action is treated as valid for every resource kindA built-in action can consume a key that should reach a plugin, or report an operation failure on an unsupported resourceEach restricted action declares its supported kinds before fallback dispatch and hint generation
An interactive command exits while the UI still owns raw mode or mouse captureCommand input can generate signals for the parent or leave terminal escape sequences in the shellThe suspend path releases terminal modes first and restores them after the child exits
An activity or error overlay is drawn below a later full-frame widgetThe user cannot see progress or the command failure that should explain the current stateThe frame draws transient overlays after the base view and keeps their context-specific order
A view renders wrapped rows with different width or ANSI rules from its scroll stateThe visible text and scroll position disagreeDocument and log views calculate viewport rows with the same wrapping logic used for rendering
A long log line is scrolled by bytes or a capped terminal offsetWide characters can split or the user cannot reach the end of the lineLog rows use display-column clipping and keep horizontal offsets in an unbounded size
A live view is labeled as static or a snapshot is labeled as liveThe user can trust stale data or wait for updates that cannot arriveThe status indicator classifies the current view and its return mode before drawing
A title value contains control characters or becomes stale after disabling title updatesThe terminal title can contain unsafe control data or show an old contextTitle construction removes control characters and change tracking clears the title when inactive
A live skin change leaves cached colors at an older paletteSome parts of a frame use old colors after a skin switchPalette changes advance the cache epoch before later color reads
A directory browser is treated as a live watch or its preview loses its directory contextThe user can expect updates that do not arrive or apply an action to the wrong manifest setDirectory mode is marked static and keeps the directory list or preview under its prompts and actions

Key files

FileWhy to read it
src/main.rsShows terminal startup and shutdown, the event loop, redraw timing, mouse capture, title updates, and command suspension.
src/terminal.rsDefines the boundary between the full-screen UI and an interactive child command.
src/ui.rsDefines synchronized frame presentation, responsive layouts, tables, documents, logs, prompts, help, popups, activity panels, directory browsing, key hints, text treatment, and terminal-cell layout.
src/theme.rsDefines palette selection, skin overrides, background behavior, live skin changes, and semantic state colors.
src/keymap.rsDefines action scopes, supported resource kinds, default bindings, shared overrides, completion priority, conflict checks, inherited binding rules, and effective labels.
src/keys.rsDefines the accepted key-chord language and terminal event matching rules.
src/…/input.rsConnects key scopes and actions to mode-specific behavior, text entry, filtering, scrolling, and cleanup.
src/…/helpers.rsDefines shared line-edit operations used by text input modes.
src/views.rsDefines the high-level contract for configurable resource columns and fallback views.
src/text.rsDefines Unicode-safe text truncation used at narrow terminal boundaries.
src/terminal_title.rsDefines change-aware terminal title writes and clearing.