bots-garden/razorbillpublic Fork
⑂ 96dad58
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#54 step 2: TUI shell — AppState, screen routing, frame renderer, list and form widgets

F1-F4 select Chat / Dashboard / Models / Settings, Ctrl-T the next one,
Ctrl-C / Ctrl-Q quit. The status bar says what to do for each connection
problem. ListView and FormView (TextField, Tab/Shift-Tab focus, secrets).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-26T23:03:59+01:00 Browse files
96dad58 parent: b971e1f
added Sources/RazorbillTUI/AppRenderer.swift +97 -0
new file mode 100644
@@ -0,0 +1,97 @@
1+import Foundation
2+
3+/// Draws the frame of `rzb tui` around a screen's body: the tabs on the first row, the status
4+/// bar on the last, the body in between.
5+///
6+/// ```swift
7+/// let renderer = AppRenderer(style: Style(colors: false))
8+/// let screen = renderer.render(state, body: ["hello"], rows: 24, columns: 80)
9+/// screen.lines.first // " F1 Chat F2 Dashboard F3 Models F4 Settings …"
10+/// ```
11+public struct AppRenderer: Sendable {
12+ public var style: Style
13+
14+ public init(style: Style) {
15+ self.style = style
16+ }
17+
18+ /// `body` is cut or padded to the rows between the bars. `cursor` is a position within the
19+ /// body (row, column); without it the cursor is hidden.
20+ public func render(
21+ _ state: AppState, body: [String], cursor: (row: Int, column: Int)? = nil, rows: Int,
22+ columns: Int
23+ ) -> Screen {
24+ let width = max(columns, 20)
25+ let bodyHeight = max(rows, 3) - 2
26+ var lines = Array(body.prefix(bodyHeight)).map { TextLayout.truncate($0, width: width) }
27+ lines += Array(repeating: "", count: bodyHeight - lines.count)
28+ let screen = [tabBar(state, width: width)] + lines + [statusBar(state, width: width)]
29+ guard let cursor, cursor.row < bodyHeight else {
30+ return Screen(lines: screen, hidesCursor: true)
31+ }
32+ return Screen(lines: screen, cursorRow: cursor.row + 1, cursorColumn: cursor.column)
33+ }
34+
35+ /// ` F1 Chat F2 Dashboard F3 Models F4 Settings`, the current screen in reverse video.
36+ func tabBar(_ state: AppState, width: Int) -> String {
37+ var bar = ""
38+ var used = 0
39+ for screen in AppScreen.allCases {
40+ let tab = " F\(screen.rawValue) \(screen.title) "
41+ guard used + tab.count <= width else { break }
42+ bar += screen == state.screen ? style.reverse(tab) : tab
43+ used += tab.count
44+ }
45+ return bar
46+ }
47+
48+ /// The connection on the left, the keys on the right when there is room.
49+ func statusBar(_ state: AppState, width: Int) -> String {
50+ let keys = "Ctrl-T next · Ctrl-Q quit"
51+ let (mark, text) = connectionText(state)
52+ let left = TextLayout.truncate(text, width: max(0, width - 2))
53+ let room = width - 2 - left.count - keys.count - 1
54+ let right = room >= 0 ? String(repeating: " ", count: room + 1) + style.dim(keys) : ""
55+ return mark + " " + left + right
56+ }
57+
58+ private func connectionText(_ state: AppState) -> (mark: String, text: String) {
59+ let url = state.serverURL
60+ switch state.connection {
61+ case .connecting:
62+ return (style.dim("…"), "connecting to \(url)")
63+ case .connected(let version):
64+ var parts = ["rzb \(version) at \(url)"]
65+ if let model = state.model { parts.append(model) }
66+ if let memory = state.memory {
67+ let used = Self.gigabytes(memory.used)
68+ parts.append("memory \(used) / \(Self.gigabytes(memory.limit))")
69+ }
70+ return (style.green("●"), parts.joined(separator: " · "))
71+ case .unreachable:
72+ return (style.red("○"), "no server at \(url) — start one with: rzb serve")
73+ case .unauthorized:
74+ return (style.red("✕"), "\(url) refused the API key — check --api-key-env")
75+ case .notLocal:
76+ let text = "\(url) is another machine — rzb tui needs a server on this one"
77+ return (style.red("✕"), text)
78+ }
79+ }
80+
81+ /// `12.3 GB`, one decimal, 1 GB = 2³⁰ bytes like the server's own messages.
82+ static func gigabytes(_ bytes: Int64) -> String {
83+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
84+ }
85+
86+ /// The body of a screen whose content is not built yet, naming the ticket that brings it.
87+ public static func placeholder(for screen: AppScreen) -> [String] {
88+ let ticket: String =
89+ switch screen {
90+ case .chat: "#55"
91+ case .dashboard: "#56"
92+ case .models: "#57"
93+ case .settings: "#58"
94+ }
95+ return ["", " \(screen.title): coming with \(ticket)."]
96+ }
97+}
new file mode 100644
@@ -0,0 +1,97 @@
1+import Foundation
2+
3+/// Draws the frame of `rzb tui` around a screen's body: the tabs on the first row, the status
4+/// bar on the last, the body in between.
5+///
6+/// ```swift
7+/// let renderer = AppRenderer(style: Style(colors: false))
8+/// let screen = renderer.render(state, body: ["hello"], rows: 24, columns: 80)
9+/// screen.lines.first // " F1 Chat F2 Dashboard F3 Models F4 Settings …"
10+/// ```
11+public struct AppRenderer: Sendable {
12+ public var style: Style
13+
14+ public init(style: Style) {
15+ self.style = style
16+ }
17+
18+ /// `body` is cut or padded to the rows between the bars. `cursor` is a position within the
19+ /// body (row, column); without it the cursor is hidden.
20+ public func render(
21+ _ state: AppState, body: [String], cursor: (row: Int, column: Int)? = nil, rows: Int,
22+ columns: Int
23+ ) -> Screen {
24+ let width = max(columns, 20)
25+ let bodyHeight = max(rows, 3) - 2
26+ var lines = Array(body.prefix(bodyHeight)).map { TextLayout.truncate($0, width: width) }
27+ lines += Array(repeating: "", count: bodyHeight - lines.count)
28+ let screen = [tabBar(state, width: width)] + lines + [statusBar(state, width: width)]
29+ guard let cursor, cursor.row < bodyHeight else {
30+ return Screen(lines: screen, hidesCursor: true)
31+ }
32+ return Screen(lines: screen, cursorRow: cursor.row + 1, cursorColumn: cursor.column)
33+ }
34+
35+ /// ` F1 Chat F2 Dashboard F3 Models F4 Settings`, the current screen in reverse video.
36+ func tabBar(_ state: AppState, width: Int) -> String {
37+ var bar = ""
38+ var used = 0
39+ for screen in AppScreen.allCases {
40+ let tab = " F\(screen.rawValue) \(screen.title) "
41+ guard used + tab.count <= width else { break }
42+ bar += screen == state.screen ? style.reverse(tab) : tab
43+ used += tab.count
44+ }
45+ return bar
46+ }
47+
48+ /// The connection on the left, the keys on the right when there is room.
49+ func statusBar(_ state: AppState, width: Int) -> String {
50+ let keys = "Ctrl-T next · Ctrl-Q quit"
51+ let (mark, text) = connectionText(state)
52+ let left = TextLayout.truncate(text, width: max(0, width - 2))
53+ let room = width - 2 - left.count - keys.count - 1
54+ let right = room >= 0 ? String(repeating: " ", count: room + 1) + style.dim(keys) : ""
55+ return mark + " " + left + right
56+ }
57+
58+ private func connectionText(_ state: AppState) -> (mark: String, text: String) {
59+ let url = state.serverURL
60+ switch state.connection {
61+ case .connecting:
62+ return (style.dim("…"), "connecting to \(url)")
63+ case .connected(let version):
64+ var parts = ["rzb \(version) at \(url)"]
65+ if let model = state.model { parts.append(model) }
66+ if let memory = state.memory {
67+ let used = Self.gigabytes(memory.used)
68+ parts.append("memory \(used) / \(Self.gigabytes(memory.limit))")
69+ }
70+ return (style.green("●"), parts.joined(separator: " · "))
71+ case .unreachable:
72+ return (style.red("○"), "no server at \(url) — start one with: rzb serve")
73+ case .unauthorized:
74+ return (style.red("✕"), "\(url) refused the API key — check --api-key-env")
75+ case .notLocal:
76+ let text = "\(url) is another machine — rzb tui needs a server on this one"
77+ return (style.red("✕"), text)
78+ }
79+ }
80+
81+ /// `12.3 GB`, one decimal, 1 GB = 2³⁰ bytes like the server's own messages.
82+ static func gigabytes(_ bytes: Int64) -> String {
83+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
84+ }
85+
86+ /// The body of a screen whose content is not built yet, naming the ticket that brings it.
87+ public static func placeholder(for screen: AppScreen) -> [String] {
88+ let ticket: String =
89+ switch screen {
90+ case .chat: "#55"
91+ case .dashboard: "#56"
92+ case .models: "#57"
93+ case .settings: "#58"
94+ }
95+ return ["", " \(screen.title): coming with \(ticket)."]
96+ }
97+}
added Sources/RazorbillTUI/AppState.swift +105 -0
new file mode 100644
@@ -0,0 +1,105 @@
1+/// The four screens of `rzb tui`, in tab order. F1–F4 select them.
2+public enum AppScreen: Int, CaseIterable, Sendable {
3+ case chat = 1
4+ case dashboard
5+ case models
6+ case settings
7+
8+ public var title: String {
9+ switch self {
10+ case .chat: "Chat"
11+ case .dashboard: "Dashboard"
12+ case .models: "Models"
13+ case .settings: "Settings"
14+ }
15+ }
16+
17+ /// The screen after this one, wrapping around (Ctrl-T).
18+ public var next: AppScreen {
19+ AppScreen(rawValue: rawValue % AppScreen.allCases.count + 1) ?? .chat
20+ }
21+}
22+
23+/// Whether the TUI can talk to the server, as the status bar shows it.
24+public enum Connection: Sendable, Equatable {
25+ /// No answer yet.
26+ case connecting
27+ /// The server answered `/rzb/status`.
28+ case connected(version: String)
29+ /// Nothing listens at the URL; `rzb serve` is not running there.
30+ case unreachable
31+ /// The server wants an API key, or another one (401).
32+ case unauthorized
33+ /// The server is on another machine: `/rzb/` routes answer this machine only (403).
34+ case notLocal
35+}
36+
37+/// What the TUI shows, independent of the terminal: the current screen and what the status bar
38+/// says. Keys change it through ``handle(_:)``; ``AppRenderer`` draws it.
39+///
40+/// ```swift
41+/// var state = AppState(serverURL: "http://127.0.0.1:7920")
42+/// state.handle(.function(3)) // .redraw — the Models screen is current
43+/// state.handle(.control("q")) // .quit
44+/// ```
45+public struct AppState: Sendable, Equatable {
46+ /// What the app does after a key.
47+ public enum Action: Sendable, Equatable {
48+ /// Nothing changed.
49+ case none
50+ /// The state changed: draw again.
51+ case redraw
52+ /// Leave the TUI.
53+ case quit
54+ }
55+
56+ public var screen: AppScreen
57+ /// The server's base address, without `/v1`: `http://127.0.0.1:7920`.
58+ public var serverURL: String
59+ public var connection: Connection = .connecting
60+ /// The model the status bar names: the one chat uses, or the last one loaded.
61+ public var model: String?
62+ /// The engine's memory, when the server reports it.
63+ public var memory: MemoryUse?
64+
65+ /// Starts on the Dashboard, the screen that has content before the chat exists (#55).
66+ public init(serverURL: String, screen: AppScreen = .dashboard) {
67+ self.serverURL = serverURL
68+ self.screen = screen
69+ }
70+
71+ /// F1–F4 select a screen, Ctrl-T goes to the next one, Ctrl-C and Ctrl-Q quit. Other keys
72+ /// belong to the current screen.
73+ public mutating func handle(_ key: Key) -> Action {
74+ switch key {
75+ case .function(let number):
76+ guard let wanted = AppScreen(rawValue: number) else { return .none }
77+ return select(wanted)
78+ case .control("t"):
79+ return select(screen.next)
80+ case .control("c"), .control("q"):
81+ return .quit
82+ case .resize:
83+ return .redraw
84+ default:
85+ return .none
86+ }
87+ }
88+
89+ private mutating func select(_ wanted: AppScreen) -> Action {
90+ guard wanted != screen else { return .none }
91+ screen = wanted
92+ return .redraw
93+ }
94+}
95+
96+/// Bytes of memory in use out of a limit.
97+public struct MemoryUse: Sendable, Equatable {
98+ public var used: Int64
99+ public var limit: Int64
100+
101+ public init(used: Int64, limit: Int64) {
102+ self.used = used
103+ self.limit = limit
104+ }
105+}
new file mode 100644
@@ -0,0 +1,105 @@
1+/// The four screens of `rzb tui`, in tab order. F1–F4 select them.
2+public enum AppScreen: Int, CaseIterable, Sendable {
3+ case chat = 1
4+ case dashboard
5+ case models
6+ case settings
7+
8+ public var title: String {
9+ switch self {
10+ case .chat: "Chat"
11+ case .dashboard: "Dashboard"
12+ case .models: "Models"
13+ case .settings: "Settings"
14+ }
15+ }
16+
17+ /// The screen after this one, wrapping around (Ctrl-T).
18+ public var next: AppScreen {
19+ AppScreen(rawValue: rawValue % AppScreen.allCases.count + 1) ?? .chat
20+ }
21+}
22+
23+/// Whether the TUI can talk to the server, as the status bar shows it.
24+public enum Connection: Sendable, Equatable {
25+ /// No answer yet.
26+ case connecting
27+ /// The server answered `/rzb/status`.
28+ case connected(version: String)
29+ /// Nothing listens at the URL; `rzb serve` is not running there.
30+ case unreachable
31+ /// The server wants an API key, or another one (401).
32+ case unauthorized
33+ /// The server is on another machine: `/rzb/` routes answer this machine only (403).
34+ case notLocal
35+}
36+
37+/// What the TUI shows, independent of the terminal: the current screen and what the status bar
38+/// says. Keys change it through ``handle(_:)``; ``AppRenderer`` draws it.
39+///
40+/// ```swift
41+/// var state = AppState(serverURL: "http://127.0.0.1:7920")
42+/// state.handle(.function(3)) // .redraw — the Models screen is current
43+/// state.handle(.control("q")) // .quit
44+/// ```
45+public struct AppState: Sendable, Equatable {
46+ /// What the app does after a key.
47+ public enum Action: Sendable, Equatable {
48+ /// Nothing changed.
49+ case none
50+ /// The state changed: draw again.
51+ case redraw
52+ /// Leave the TUI.
53+ case quit
54+ }
55+
56+ public var screen: AppScreen
57+ /// The server's base address, without `/v1`: `http://127.0.0.1:7920`.
58+ public var serverURL: String
59+ public var connection: Connection = .connecting
60+ /// The model the status bar names: the one chat uses, or the last one loaded.
61+ public var model: String?
62+ /// The engine's memory, when the server reports it.
63+ public var memory: MemoryUse?
64+
65+ /// Starts on the Dashboard, the screen that has content before the chat exists (#55).
66+ public init(serverURL: String, screen: AppScreen = .dashboard) {
67+ self.serverURL = serverURL
68+ self.screen = screen
69+ }
70+
71+ /// F1–F4 select a screen, Ctrl-T goes to the next one, Ctrl-C and Ctrl-Q quit. Other keys
72+ /// belong to the current screen.
73+ public mutating func handle(_ key: Key) -> Action {
74+ switch key {
75+ case .function(let number):
76+ guard let wanted = AppScreen(rawValue: number) else { return .none }
77+ return select(wanted)
78+ case .control("t"):
79+ return select(screen.next)
80+ case .control("c"), .control("q"):
81+ return .quit
82+ case .resize:
83+ return .redraw
84+ default:
85+ return .none
86+ }
87+ }
88+
89+ private mutating func select(_ wanted: AppScreen) -> Action {
90+ guard wanted != screen else { return .none }
91+ screen = wanted
92+ return .redraw
93+ }
94+}
95+
96+/// Bytes of memory in use out of a limit.
97+public struct MemoryUse: Sendable, Equatable {
98+ public var used: Int64
99+ public var limit: Int64
100+
101+ public init(used: Int64, limit: Int64) {
102+ self.used = used
103+ self.limit = limit
104+ }
105+}
added Sources/RazorbillTUI/FormView.swift +120 -0
new file mode 100644
@@ -0,0 +1,120 @@
1+/// One line of editable text with a cursor.
2+///
3+/// ```swift
4+/// var field = TextField(text: "abc")
5+/// field.handle(.arrowLeft) // cursor 2
6+/// field.handle(.character("x")) // "abxc"
7+/// ```
8+public struct TextField: Sendable, Equatable {
9+ public private(set) var text: String
10+ /// Position of the cursor, in characters, from 0 to `text.count`.
11+ public private(set) var cursor: Int
12+
13+ public init(text: String = "") {
14+ self.text = text
15+ cursor = text.count
16+ }
17+
18+ /// Edits with characters, Backspace, Delete, the arrows, Home and End. Returns whether the
19+ /// key was one of those.
20+ @discardableResult
21+ public mutating func handle(_ key: Key) -> Bool {
22+ var characters = Array(text)
23+ switch key {
24+ case .character(let character):
25+ characters.insert(character, at: cursor)
26+ cursor += 1
27+ case .backspace where cursor > 0:
28+ characters.remove(at: cursor - 1)
29+ cursor -= 1
30+ case .delete where cursor < characters.count:
31+ characters.remove(at: cursor)
32+ case .arrowLeft: cursor = max(0, cursor - 1)
33+ case .arrowRight: cursor = min(characters.count, cursor + 1)
34+ case .home, .control("a"): cursor = 0
35+ case .end, .control("e"): cursor = characters.count
36+ case .backspace, .delete: break
37+ default: return false
38+ }
39+ text = String(characters)
40+ return true
41+ }
42+}
43+
44+/// Labelled text fields, one per line, with one focused field.
45+///
46+/// ```swift
47+/// var form = FormView(fields: [.init(label: "Port", text: "7920"), .init(label: "Host")])
48+/// form.handle(.tab) // .none, focus on Host
49+/// form.handle(.enter) // .submit
50+/// form.values // ["7920", ""]
51+/// ```
52+public struct FormView: Sendable, Equatable {
53+ /// One labelled field.
54+ public struct Field: Sendable, Equatable {
55+ public var label: String
56+ public var input: TextField
57+ /// Shown as dots (an API key).
58+ public var secret: Bool
59+
60+ public init(label: String, text: String = "", secret: Bool = false) {
61+ self.label = label
62+ input = TextField(text: text)
63+ self.secret = secret
64+ }
65+ }
66+
67+ /// What a key did to the form.
68+ public enum Action: Sendable, Equatable {
69+ case none
70+ /// Enter: the caller reads ``values``.
71+ case submit
72+ /// Escape: the caller drops the edits.
73+ case cancel
74+ /// Not a form key: the caller may use it.
75+ case ignored
76+ }
77+
78+ /// A position in the rendered lines: row, then column.
79+ public typealias Cursor = (row: Int, column: Int)
80+
81+ public private(set) var fields: [Field]
82+ public private(set) var focus = 0
83+
84+ public init(fields: [Field]) {
85+ self.fields = fields
86+ }
87+
88+ public var values: [String] { fields.map(\.input.text) }
89+
90+ /// Tab, Shift-Tab and the vertical arrows move the focus; Enter submits; Escape cancels; the
91+ /// focused field takes the editing keys.
92+ public mutating func handle(_ key: Key) -> Action {
93+ guard !fields.isEmpty else { return .ignored }
94+ switch key {
95+ case .tab, .arrowDown: focus = (focus + 1) % fields.count
96+ case .backtab, .arrowUp: focus = (focus + fields.count - 1) % fields.count
97+ case .enter: return .submit
98+ case .escape: return .cancel
99+ default: return fields[focus].input.handle(key) ? .none : .ignored
100+ }
101+ return .none
102+ }
103+
104+ /// One line per field, `label: value`, labels aligned; the focused line in bold. The cursor
105+ /// position (row within these lines, column) goes with it.
106+ public func render(width: Int, style: Style) -> (lines: [String], cursor: Cursor) {
107+ let labelWidth = (fields.map(\.label.count).max() ?? 0) + 2
108+ var lines: [String] = []
109+ for (index, field) in fields.enumerated() {
110+ let shown =
111+ field.secret
112+ ? String(repeating: "•", count: field.input.text.count) : field.input.text
113+ let line = TextLayout.fit(field.label + ":", width: labelWidth) + shown
114+ let fitted = TextLayout.truncate(line, width: width)
115+ lines.append(index == focus ? style.bold(fitted) : fitted)
116+ }
117+ let column = min(labelWidth + (fields.isEmpty ? 0 : fields[focus].input.cursor), width - 1)
118+ return (lines, (focus, max(0, column)))
119+ }
120+}
new file mode 100644
@@ -0,0 +1,120 @@
1+/// One line of editable text with a cursor.
2+///
3+/// ```swift
4+/// var field = TextField(text: "abc")
5+/// field.handle(.arrowLeft) // cursor 2
6+/// field.handle(.character("x")) // "abxc"
7+/// ```
8+public struct TextField: Sendable, Equatable {
9+ public private(set) var text: String
10+ /// Position of the cursor, in characters, from 0 to `text.count`.
11+ public private(set) var cursor: Int
12+
13+ public init(text: String = "") {
14+ self.text = text
15+ cursor = text.count
16+ }
17+
18+ /// Edits with characters, Backspace, Delete, the arrows, Home and End. Returns whether the
19+ /// key was one of those.
20+ @discardableResult
21+ public mutating func handle(_ key: Key) -> Bool {
22+ var characters = Array(text)
23+ switch key {
24+ case .character(let character):
25+ characters.insert(character, at: cursor)
26+ cursor += 1
27+ case .backspace where cursor > 0:
28+ characters.remove(at: cursor - 1)
29+ cursor -= 1
30+ case .delete where cursor < characters.count:
31+ characters.remove(at: cursor)
32+ case .arrowLeft: cursor = max(0, cursor - 1)
33+ case .arrowRight: cursor = min(characters.count, cursor + 1)
34+ case .home, .control("a"): cursor = 0
35+ case .end, .control("e"): cursor = characters.count
36+ case .backspace, .delete: break
37+ default: return false
38+ }
39+ text = String(characters)
40+ return true
41+ }
42+}
43+
44+/// Labelled text fields, one per line, with one focused field.
45+///
46+/// ```swift
47+/// var form = FormView(fields: [.init(label: "Port", text: "7920"), .init(label: "Host")])
48+/// form.handle(.tab) // .none, focus on Host
49+/// form.handle(.enter) // .submit
50+/// form.values // ["7920", ""]
51+/// ```
52+public struct FormView: Sendable, Equatable {
53+ /// One labelled field.
54+ public struct Field: Sendable, Equatable {
55+ public var label: String
56+ public var input: TextField
57+ /// Shown as dots (an API key).
58+ public var secret: Bool
59+
60+ public init(label: String, text: String = "", secret: Bool = false) {
61+ self.label = label
62+ input = TextField(text: text)
63+ self.secret = secret
64+ }
65+ }
66+
67+ /// What a key did to the form.
68+ public enum Action: Sendable, Equatable {
69+ case none
70+ /// Enter: the caller reads ``values``.
71+ case submit
72+ /// Escape: the caller drops the edits.
73+ case cancel
74+ /// Not a form key: the caller may use it.
75+ case ignored
76+ }
77+
78+ /// A position in the rendered lines: row, then column.
79+ public typealias Cursor = (row: Int, column: Int)
80+
81+ public private(set) var fields: [Field]
82+ public private(set) var focus = 0
83+
84+ public init(fields: [Field]) {
85+ self.fields = fields
86+ }
87+
88+ public var values: [String] { fields.map(\.input.text) }
89+
90+ /// Tab, Shift-Tab and the vertical arrows move the focus; Enter submits; Escape cancels; the
91+ /// focused field takes the editing keys.
92+ public mutating func handle(_ key: Key) -> Action {
93+ guard !fields.isEmpty else { return .ignored }
94+ switch key {
95+ case .tab, .arrowDown: focus = (focus + 1) % fields.count
96+ case .backtab, .arrowUp: focus = (focus + fields.count - 1) % fields.count
97+ case .enter: return .submit
98+ case .escape: return .cancel
99+ default: return fields[focus].input.handle(key) ? .none : .ignored
100+ }
101+ return .none
102+ }
103+
104+ /// One line per field, `label: value`, labels aligned; the focused line in bold. The cursor
105+ /// position (row within these lines, column) goes with it.
106+ public func render(width: Int, style: Style) -> (lines: [String], cursor: Cursor) {
107+ let labelWidth = (fields.map(\.label.count).max() ?? 0) + 2
108+ var lines: [String] = []
109+ for (index, field) in fields.enumerated() {
110+ let shown =
111+ field.secret
112+ ? String(repeating: "•", count: field.input.text.count) : field.input.text
113+ let line = TextLayout.fit(field.label + ":", width: labelWidth) + shown
114+ let fitted = TextLayout.truncate(line, width: width)
115+ lines.append(index == focus ? style.bold(fitted) : fitted)
116+ }
117+ let column = min(labelWidth + (fields.isEmpty ? 0 : fields[focus].input.cursor), width - 1)
118+ return (lines, (focus, max(0, column)))
119+ }
120+}
modified Sources/RazorbillTUI/Key.swift +3 -0
@@ -4,6 +4,8 @@ import Foundation
44 public enum Key: Sendable, Equatable {
55 case character(Character)
66 case enter, backspace, delete, tab, escape
7+ /// Shift-Tab (`ESC [ Z`).
8+ case backtab
79 case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown
810 /// A function key, `F1` = `.function(1)` … `F12` = `.function(12)`.
911 case function(Int)
@@ -73,6 +75,7 @@ public struct KeyDecoder: Sendable {
7375 guard bytes.count >= 3 else { return nil }
7476 let simple: [UInt8: Key] = [
7577 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end,
78+ 90: .backtab,
7679 ]
7780 if let key = simple[bytes[2]] {
7881 return (key, 3)
@@ -4,6 +4,8 @@ import Foundation
4 public enum Key: Sendable, Equatable {4 public enum Key: Sendable, Equatable {
5 case character(Character)5 case character(Character)
6 case enter, backspace, delete, tab, escape6 case enter, backspace, delete, tab, escape
7+ /// Shift-Tab (`ESC [ Z`).
8+ case backtab
7 case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown9 case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown
8 /// A function key, `F1` = `.function(1)` … `F12` = `.function(12)`.10 /// A function key, `F1` = `.function(1)` … `F12` = `.function(12)`.
9 case function(Int)11 case function(Int)
@@ -73,6 +75,7 @@ public struct KeyDecoder: Sendable {
73 guard bytes.count >= 3 else { return nil }75 guard bytes.count >= 3 else { return nil }
74 let simple: [UInt8: Key] = [76 let simple: [UInt8: Key] = [
75 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end,77 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end,
78+ 90: .backtab,
76 ]79 ]
77 if let key = simple[bytes[2]] {80 if let key = simple[bytes[2]] {
78 return (key, 3)81 return (key, 3)
added Sources/RazorbillTUI/ListView.swift +71 -0
new file mode 100644
@@ -0,0 +1,71 @@
1+/// The selected row of a list and the first row shown, kept within bounds as the list changes.
2+///
3+/// ```swift
4+/// var list = ListView(count: 30)
5+/// list.handle(.arrowDown, pageSize: 10) // selected 1
6+/// list.handle(.end, pageSize: 10) // selected 29, offset 20
7+/// list.render(rows, width: 40, height: 10, style: style) // 10 lines, row 29 highlighted
8+/// ```
9+public struct ListView: Sendable, Equatable {
10+ /// Rows in the list.
11+ public private(set) var count: Int
12+ /// The highlighted row; 0 when the list is empty.
13+ public private(set) var selected = 0
14+ /// The first row shown.
15+ public private(set) var offset = 0
16+
17+ public init(count: Int = 0) {
18+ self.count = max(0, count)
19+ }
20+
21+ /// The list now has `count` rows (it was refreshed); the selection stays in it.
22+ public mutating func resize(to count: Int) {
23+ self.count = max(0, count)
24+ select(selected)
25+ }
26+
27+ /// Moves the selection with the arrows, Page Up/Down, Home and End. Returns whether the key
28+ /// was one of those (the caller handles the others).
29+ @discardableResult
30+ public mutating func handle(_ key: Key, pageSize: Int) -> Bool {
31+ let page = max(1, pageSize)
32+ switch key {
33+ case .arrowUp: select(selected - 1)
34+ case .arrowDown: select(selected + 1)
35+ case .pageUp: select(selected - page)
36+ case .pageDown: select(selected + page)
37+ case .home: select(0)
38+ case .end: select(count - 1)
39+ default: return false
40+ }
41+ scroll(height: page)
42+ return true
43+ }
44+
45+ /// Exactly `height` lines: the visible rows, cut or padded to `width`, the selected one in
46+ /// reverse video, then blank lines.
47+ public mutating func render(
48+ _ rows: [String], width: Int, height: Int, style: Style
49+ ) -> [String] {
50+ resize(to: rows.count)
51+ scroll(height: height)
52+ var lines: [String] = []
53+ for index in offset ..< min(rows.count, offset + height) {
54+ let line = TextLayout.fit(rows[index], width: width)
55+ lines.append(index == selected ? style.reverse(line) : line)
56+ }
57+ return lines + Array(repeating: "", count: max(0, height - lines.count))
58+ }
59+
60+ private mutating func select(_ row: Int) {
61+ selected = count == 0 ? 0 : min(max(row, 0), count - 1)
62+ }
63+
64+ /// Keeps the selected row on screen.
65+ private mutating func scroll(height: Int) {
66+ let height = max(1, height)
67+ if selected < offset { offset = selected }
68+ if selected >= offset + height { offset = selected - height + 1 }
69+ offset = min(offset, max(0, count - height))
70+ }
71+}
new file mode 100644
@@ -0,0 +1,71 @@
1+/// The selected row of a list and the first row shown, kept within bounds as the list changes.
2+///
3+/// ```swift
4+/// var list = ListView(count: 30)
5+/// list.handle(.arrowDown, pageSize: 10) // selected 1
6+/// list.handle(.end, pageSize: 10) // selected 29, offset 20
7+/// list.render(rows, width: 40, height: 10, style: style) // 10 lines, row 29 highlighted
8+/// ```
9+public struct ListView: Sendable, Equatable {
10+ /// Rows in the list.
11+ public private(set) var count: Int
12+ /// The highlighted row; 0 when the list is empty.
13+ public private(set) var selected = 0
14+ /// The first row shown.
15+ public private(set) var offset = 0
16+
17+ public init(count: Int = 0) {
18+ self.count = max(0, count)
19+ }
20+
21+ /// The list now has `count` rows (it was refreshed); the selection stays in it.
22+ public mutating func resize(to count: Int) {
23+ self.count = max(0, count)
24+ select(selected)
25+ }
26+
27+ /// Moves the selection with the arrows, Page Up/Down, Home and End. Returns whether the key
28+ /// was one of those (the caller handles the others).
29+ @discardableResult
30+ public mutating func handle(_ key: Key, pageSize: Int) -> Bool {
31+ let page = max(1, pageSize)
32+ switch key {
33+ case .arrowUp: select(selected - 1)
34+ case .arrowDown: select(selected + 1)
35+ case .pageUp: select(selected - page)
36+ case .pageDown: select(selected + page)
37+ case .home: select(0)
38+ case .end: select(count - 1)
39+ default: return false
40+ }
41+ scroll(height: page)
42+ return true
43+ }
44+
45+ /// Exactly `height` lines: the visible rows, cut or padded to `width`, the selected one in
46+ /// reverse video, then blank lines.
47+ public mutating func render(
48+ _ rows: [String], width: Int, height: Int, style: Style
49+ ) -> [String] {
50+ resize(to: rows.count)
51+ scroll(height: height)
52+ var lines: [String] = []
53+ for index in offset ..< min(rows.count, offset + height) {
54+ let line = TextLayout.fit(rows[index], width: width)
55+ lines.append(index == selected ? style.reverse(line) : line)
56+ }
57+ return lines + Array(repeating: "", count: max(0, height - lines.count))
58+ }
59+
60+ private mutating func select(_ row: Int) {
61+ selected = count == 0 ? 0 : min(max(row, 0), count - 1)
62+ }
63+
64+ /// Keeps the selected row on screen.
65+ private mutating func scroll(height: Int) {
66+ let height = max(1, height)
67+ if selected < offset { offset = selected }
68+ if selected >= offset + height { offset = selected - height + 1 }
69+ offset = min(offset, max(0, count - height))
70+ }
71+}
added Sources/RazorbillTUI/Style.swift +34 -0
new file mode 100644
@@ -0,0 +1,34 @@
1+/// ANSI text styles, or plain text when colours are off (`NO_COLOR`, tests).
2+///
3+/// ```swift
4+/// let style = Style(colors: true)
5+/// style.bold("razorbill") // "\u{1B}[1mrazorbill\u{1B}[0m"
6+/// Style(colors: false).bold("razorbill") // "razorbill"
7+/// ```
8+public struct Style: Sendable, Equatable {
9+ public var colors: Bool
10+
11+ public init(colors: Bool) {
12+ self.colors = colors
13+ }
14+
15+ public func bold(_ text: String) -> String { wrap(text, "1") }
16+ public func dim(_ text: String) -> String { wrap(text, "2") }
17+ /// Swapped foreground and background: the selected row, the current tab.
18+ public func reverse(_ text: String) -> String { wrap(text, "7") }
19+ public func green(_ text: String) -> String { wrap(text, "32") }
20+ public func red(_ text: String) -> String { wrap(text, "31") }
21+ public func yellow(_ text: String) -> String { wrap(text, "33") }
22+
23+ private func wrap(_ text: String, _ code: String) -> String {
24+ colors ? "\u{1B}[\(code)m\(text)\u{1B}[0m" : text
25+ }
26+}
27+
28+extension TextLayout {
29+ /// `text` cut or padded with spaces to exactly `width` characters.
30+ public static func fit(_ text: String, width: Int) -> String {
31+ let cut = truncate(text, width: max(width, 0))
32+ return cut + String(repeating: " ", count: max(0, width - cut.count))
33+ }
34+}
new file mode 100644
@@ -0,0 +1,34 @@
1+/// ANSI text styles, or plain text when colours are off (`NO_COLOR`, tests).
2+///
3+/// ```swift
4+/// let style = Style(colors: true)
5+/// style.bold("razorbill") // "\u{1B}[1mrazorbill\u{1B}[0m"
6+/// Style(colors: false).bold("razorbill") // "razorbill"
7+/// ```
8+public struct Style: Sendable, Equatable {
9+ public var colors: Bool
10+
11+ public init(colors: Bool) {
12+ self.colors = colors
13+ }
14+
15+ public func bold(_ text: String) -> String { wrap(text, "1") }
16+ public func dim(_ text: String) -> String { wrap(text, "2") }
17+ /// Swapped foreground and background: the selected row, the current tab.
18+ public func reverse(_ text: String) -> String { wrap(text, "7") }
19+ public func green(_ text: String) -> String { wrap(text, "32") }
20+ public func red(_ text: String) -> String { wrap(text, "31") }
21+ public func yellow(_ text: String) -> String { wrap(text, "33") }
22+
23+ private func wrap(_ text: String, _ code: String) -> String {
24+ colors ? "\u{1B}[\(code)m\(text)\u{1B}[0m" : text
25+ }
26+}
27+
28+extension TextLayout {
29+ /// `text` cut or padded with spaces to exactly `width` characters.
30+ public static func fit(_ text: String, width: Int) -> String {
31+ let cut = truncate(text, width: max(width, 0))
32+ return cut + String(repeating: " ", count: max(0, width - cut.count))
33+ }
34+}
added Tests/RazorbillTUITests/AppShellTests.swift +191 -0
new file mode 100644
@@ -0,0 +1,191 @@
1+import RazorbillTUI
2+import Testing
3+
4+@Suite struct AppStateTests {
5+ @Test func functionKeysSelectScreens() {
6+ var state = AppState(serverURL: "http://127.0.0.1:7920")
7+ #expect(state.screen == .dashboard)
8+ #expect(state.handle(.function(1)) == .redraw)
9+ #expect(state.screen == .chat)
10+ #expect(state.handle(.function(4)) == .redraw)
11+ #expect(state.screen == .settings)
12+ #expect(state.handle(.function(4)) == .none)
13+ #expect(state.handle(.function(9)) == .none)
14+ #expect(state.screen == .settings)
15+ }
16+
17+ @Test func controlTGoesToTheNextScreenAndWraps() {
18+ var state = AppState(serverURL: "u", screen: .models)
19+ _ = state.handle(.control("t"))
20+ #expect(state.screen == .settings)
21+ _ = state.handle(.control("t"))
22+ #expect(state.screen == .chat)
23+ }
24+
25+ @Test func controlCAndControlQQuit() {
26+ var state = AppState(serverURL: "u")
27+ #expect(state.handle(.control("c")) == .quit)
28+ #expect(state.handle(.control("q")) == .quit)
29+ }
30+
31+ @Test func otherKeysBelongToTheScreen() {
32+ var state = AppState(serverURL: "u")
33+ #expect(state.handle(.character("x")) == .none)
34+ #expect(state.handle(.tab) == .none)
35+ #expect(state.handle(.resize) == .redraw)
36+ }
37+}
38+
39+@Suite struct AppRendererTests {
40+ let renderer = AppRenderer(style: Style(colors: false))
41+
42+ func text(_ state: AppState, body: [String] = [], columns: Int = 100) -> [String] {
43+ renderer.render(state, body: body, rows: 6, columns: columns).lines
44+ }
45+
46+ @Test func framesTheBodyBetweenTabsAndStatusBar() {
47+ let lines = text(AppState(serverURL: "http://127.0.0.1:7920"), body: ["a", "b"])
48+ #expect(lines.count == 6)
49+ #expect(lines[0] == " F1 Chat F2 Dashboard F3 Models F4 Settings ")
50+ #expect(lines[1 ... 4] == ["a", "b", "", ""])
51+ #expect(lines[5].hasPrefix("… connecting to http://127.0.0.1:7920"))
52+ #expect(lines[5].hasSuffix("Ctrl-T next · Ctrl-Q quit"))
53+ #expect(lines[5].count == 100)
54+ }
55+
56+ @Test func currentTabIsReversed() {
57+ let colored = AppRenderer(style: Style(colors: true))
58+ let bar = colored.render(AppState(serverURL: "u"), body: [], rows: 4, columns: 80).lines[0]
59+ #expect(bar.contains("\u{1B}[7m F2 Dashboard \u{1B}[0m"))
60+ }
61+
62+ @Test func connectedStatusNamesVersionModelAndMemory() {
63+ var state = AppState(serverURL: "http://127.0.0.1:7920")
64+ state.connection = .connected(version: "0.2.0")
65+ state.model = "qwen"
66+ state.memory = MemoryUse(used: 1 << 30, limit: 32 << 30)
67+ #expect(
68+ text(state)[5].hasPrefix(
69+ "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB"))
70+ }
71+
72+ @Test(arguments: [
73+ (Connection.unreachable, "○ no server at u — start one with: rzb serve"),
74+ (Connection.unauthorized, "✕ u refused the API key — check --api-key-env"),
75+ (Connection.notLocal, "✕ u is another machine — rzb tui needs a server on this one"),
76+ ])
77+ func eachConnectionProblemSaysWhatToDo(_ connection: Connection, _ expected: String) {
78+ var state = AppState(serverURL: "u")
79+ state.connection = connection
80+ #expect(text(state)[5].hasPrefix(expected))
81+ }
82+
83+ @Test func narrowTerminalDropsTheKeysThenCutsTheText() {
84+ var state = AppState(serverURL: "http://127.0.0.1:7920")
85+ state.connection = .unreachable
86+ let status = text(state, columns: 30)[5]
87+ #expect(status.count == 30)
88+ #expect(!status.contains("Ctrl-T"))
89+ #expect(status.hasSuffix("…"))
90+ }
91+
92+ @Test func cursorIsHiddenUnlessTheBodyPlacesIt() {
93+ let state = AppState(serverURL: "u")
94+ #expect(renderer.render(state, body: [], rows: 6, columns: 80).hidesCursor)
95+ let screen = renderer.render(
96+ state, body: ["x"], cursor: (row: 0, column: 3), rows: 6, columns: 80)
97+ #expect(!screen.hidesCursor && screen.cursorRow == 1 && screen.cursorColumn == 3)
98+ }
99+
100+ @Test func placeholdersNameTheirTicket() {
101+ #expect(AppRenderer.placeholder(for: .chat).joined().contains("#55"))
102+ #expect(AppRenderer.placeholder(for: .settings).joined().contains("#58"))
103+ }
104+}
105+
106+@Suite struct ListViewTests {
107+ let style = Style(colors: false)
108+
109+ @Test func arrowsAndPagesStayInBounds() {
110+ var list = ListView(count: 30)
111+ list.handle(.arrowUp, pageSize: 10)
112+ #expect(list.selected == 0)
113+ list.handle(.pageDown, pageSize: 10)
114+ #expect(list.selected == 10 && list.offset == 1)
115+ list.handle(.end, pageSize: 10)
116+ #expect(list.selected == 29 && list.offset == 20)
117+ list.handle(.home, pageSize: 10)
118+ #expect(list.selected == 0 && list.offset == 0)
119+ let handled = list.handle(.enter, pageSize: 10)
120+ #expect(!handled)
121+ }
122+
123+ @Test func rendersExactlyTheHeightWithTheSelectionHighlighted() {
124+ var list = ListView()
125+ let rows = (0 ..< 5).map { "row \($0)" }
126+ list.resize(to: rows.count)
127+ list.handle(.arrowDown, pageSize: 3)
128+ let colored = Style(colors: true)
129+ let lines = list.render(rows, width: 8, height: 3, style: colored)
130+ #expect(lines == ["row 0 ", "\u{1B}[7mrow 1 \u{1B}[0m", "row 2 "])
131+ #expect(list.render(["a"], width: 4, height: 3, style: style) == ["a ", "", ""])
132+ }
133+
134+ @Test func shrinkingListKeepsTheSelectionInside() {
135+ var list = ListView(count: 10)
136+ list.handle(.end, pageSize: 5)
137+ list.resize(to: 3)
138+ #expect(list.selected == 2)
139+ list.resize(to: 0)
140+ #expect(list.selected == 0)
141+ }
142+}
143+
144+@Suite struct FormViewTests {
145+ @Test func textFieldEditsAtTheCursor() {
146+ var field = TextField(text: "abc")
147+ field.handle(.arrowLeft)
148+ field.handle(.character("x"))
149+ #expect(field.text == "abxc" && field.cursor == 3)
150+ field.handle(.home)
151+ field.handle(.delete)
152+ field.handle(.end)
153+ field.handle(.backspace)
154+ #expect(field.text == "bx")
155+ field.handle(.home)
156+ field.handle(.backspace)
157+ #expect(field.text == "bx" && field.cursor == 0)
158+ let handled = field.handle(.function(1))
159+ #expect(!handled)
160+ }
161+
162+ @Test func tabAndShiftTabMoveTheFocusAround() {
163+ var form = FormView(fields: [.init(label: "Host"), .init(label: "Port")])
164+ var actions = [form.handle(.tab)]
165+ #expect(form.focus == 1)
166+ actions.append(form.handle(.tab))
167+ #expect(form.focus == 0)
168+ actions.append(form.handle(.backtab))
169+ #expect(form.focus == 1)
170+ actions.append(form.handle(.character("8")))
171+ #expect(form.values == ["", "8"])
172+ actions += [form.handle(.enter), form.handle(.escape), form.handle(.function(2))]
173+ #expect(actions == [.none, .none, .none, .none, .submit, .cancel, .ignored])
174+ }
175+
176+ @Test func rendersAlignedLabelsSecretsAndTheCursor() {
177+ var form = FormView(fields: [
178+ .init(label: "Host", text: "127.0.0.1"),
179+ .init(label: "API key", text: "abc", secret: true),
180+ ])
181+ _ = form.handle(.tab)
182+ let (lines, cursor) = form.render(width: 40, style: Style(colors: false))
183+ #expect(lines == ["Host: 127.0.0.1", "API key: •••"])
184+ #expect(cursor.row == 1 && cursor.column == 12)
185+ }
186+
187+ @Test func shiftTabIsDecoded() {
188+ var decoder = KeyDecoder()
189+ #expect(decoder.decode([27, 91, 90]) == [.backtab])
190+ }
191+}
new file mode 100644
@@ -0,0 +1,191 @@
1+import RazorbillTUI
2+import Testing
3+
4+@Suite struct AppStateTests {
5+ @Test func functionKeysSelectScreens() {
6+ var state = AppState(serverURL: "http://127.0.0.1:7920")
7+ #expect(state.screen == .dashboard)
8+ #expect(state.handle(.function(1)) == .redraw)
9+ #expect(state.screen == .chat)
10+ #expect(state.handle(.function(4)) == .redraw)
11+ #expect(state.screen == .settings)
12+ #expect(state.handle(.function(4)) == .none)
13+ #expect(state.handle(.function(9)) == .none)
14+ #expect(state.screen == .settings)
15+ }
16+
17+ @Test func controlTGoesToTheNextScreenAndWraps() {
18+ var state = AppState(serverURL: "u", screen: .models)
19+ _ = state.handle(.control("t"))
20+ #expect(state.screen == .settings)
21+ _ = state.handle(.control("t"))
22+ #expect(state.screen == .chat)
23+ }
24+
25+ @Test func controlCAndControlQQuit() {
26+ var state = AppState(serverURL: "u")
27+ #expect(state.handle(.control("c")) == .quit)
28+ #expect(state.handle(.control("q")) == .quit)
29+ }
30+
31+ @Test func otherKeysBelongToTheScreen() {
32+ var state = AppState(serverURL: "u")
33+ #expect(state.handle(.character("x")) == .none)
34+ #expect(state.handle(.tab) == .none)
35+ #expect(state.handle(.resize) == .redraw)
36+ }
37+}
38+
39+@Suite struct AppRendererTests {
40+ let renderer = AppRenderer(style: Style(colors: false))
41+
42+ func text(_ state: AppState, body: [String] = [], columns: Int = 100) -> [String] {
43+ renderer.render(state, body: body, rows: 6, columns: columns).lines
44+ }
45+
46+ @Test func framesTheBodyBetweenTabsAndStatusBar() {
47+ let lines = text(AppState(serverURL: "http://127.0.0.1:7920"), body: ["a", "b"])
48+ #expect(lines.count == 6)
49+ #expect(lines[0] == " F1 Chat F2 Dashboard F3 Models F4 Settings ")
50+ #expect(lines[1 ... 4] == ["a", "b", "", ""])
51+ #expect(lines[5].hasPrefix("… connecting to http://127.0.0.1:7920"))
52+ #expect(lines[5].hasSuffix("Ctrl-T next · Ctrl-Q quit"))
53+ #expect(lines[5].count == 100)
54+ }
55+
56+ @Test func currentTabIsReversed() {
57+ let colored = AppRenderer(style: Style(colors: true))
58+ let bar = colored.render(AppState(serverURL: "u"), body: [], rows: 4, columns: 80).lines[0]
59+ #expect(bar.contains("\u{1B}[7m F2 Dashboard \u{1B}[0m"))
60+ }
61+
62+ @Test func connectedStatusNamesVersionModelAndMemory() {
63+ var state = AppState(serverURL: "http://127.0.0.1:7920")
64+ state.connection = .connected(version: "0.2.0")
65+ state.model = "qwen"
66+ state.memory = MemoryUse(used: 1 << 30, limit: 32 << 30)
67+ #expect(
68+ text(state)[5].hasPrefix(
69+ "● rzb 0.2.0 at http://127.0.0.1:7920 · qwen · memory 1.0 GB / 32.0 GB"))
70+ }
71+
72+ @Test(arguments: [
73+ (Connection.unreachable, "○ no server at u — start one with: rzb serve"),
74+ (Connection.unauthorized, "✕ u refused the API key — check --api-key-env"),
75+ (Connection.notLocal, "✕ u is another machine — rzb tui needs a server on this one"),
76+ ])
77+ func eachConnectionProblemSaysWhatToDo(_ connection: Connection, _ expected: String) {
78+ var state = AppState(serverURL: "u")
79+ state.connection = connection
80+ #expect(text(state)[5].hasPrefix(expected))
81+ }
82+
83+ @Test func narrowTerminalDropsTheKeysThenCutsTheText() {
84+ var state = AppState(serverURL: "http://127.0.0.1:7920")
85+ state.connection = .unreachable
86+ let status = text(state, columns: 30)[5]
87+ #expect(status.count == 30)
88+ #expect(!status.contains("Ctrl-T"))
89+ #expect(status.hasSuffix("…"))
90+ }
91+
92+ @Test func cursorIsHiddenUnlessTheBodyPlacesIt() {
93+ let state = AppState(serverURL: "u")
94+ #expect(renderer.render(state, body: [], rows: 6, columns: 80).hidesCursor)
95+ let screen = renderer.render(
96+ state, body: ["x"], cursor: (row: 0, column: 3), rows: 6, columns: 80)
97+ #expect(!screen.hidesCursor && screen.cursorRow == 1 && screen.cursorColumn == 3)
98+ }
99+
100+ @Test func placeholdersNameTheirTicket() {
101+ #expect(AppRenderer.placeholder(for: .chat).joined().contains("#55"))
102+ #expect(AppRenderer.placeholder(for: .settings).joined().contains("#58"))
103+ }
104+}
105+
106+@Suite struct ListViewTests {
107+ let style = Style(colors: false)
108+
109+ @Test func arrowsAndPagesStayInBounds() {
110+ var list = ListView(count: 30)
111+ list.handle(.arrowUp, pageSize: 10)
112+ #expect(list.selected == 0)
113+ list.handle(.pageDown, pageSize: 10)
114+ #expect(list.selected == 10 && list.offset == 1)
115+ list.handle(.end, pageSize: 10)
116+ #expect(list.selected == 29 && list.offset == 20)
117+ list.handle(.home, pageSize: 10)
118+ #expect(list.selected == 0 && list.offset == 0)
119+ let handled = list.handle(.enter, pageSize: 10)
120+ #expect(!handled)
121+ }
122+
123+ @Test func rendersExactlyTheHeightWithTheSelectionHighlighted() {
124+ var list = ListView()
125+ let rows = (0 ..< 5).map { "row \($0)" }
126+ list.resize(to: rows.count)
127+ list.handle(.arrowDown, pageSize: 3)
128+ let colored = Style(colors: true)
129+ let lines = list.render(rows, width: 8, height: 3, style: colored)
130+ #expect(lines == ["row 0 ", "\u{1B}[7mrow 1 \u{1B}[0m", "row 2 "])
131+ #expect(list.render(["a"], width: 4, height: 3, style: style) == ["a ", "", ""])
132+ }
133+
134+ @Test func shrinkingListKeepsTheSelectionInside() {
135+ var list = ListView(count: 10)
136+ list.handle(.end, pageSize: 5)
137+ list.resize(to: 3)
138+ #expect(list.selected == 2)
139+ list.resize(to: 0)
140+ #expect(list.selected == 0)
141+ }
142+}
143+
144+@Suite struct FormViewTests {
145+ @Test func textFieldEditsAtTheCursor() {
146+ var field = TextField(text: "abc")
147+ field.handle(.arrowLeft)
148+ field.handle(.character("x"))
149+ #expect(field.text == "abxc" && field.cursor == 3)
150+ field.handle(.home)
151+ field.handle(.delete)
152+ field.handle(.end)
153+ field.handle(.backspace)
154+ #expect(field.text == "bx")
155+ field.handle(.home)
156+ field.handle(.backspace)
157+ #expect(field.text == "bx" && field.cursor == 0)
158+ let handled = field.handle(.function(1))
159+ #expect(!handled)
160+ }
161+
162+ @Test func tabAndShiftTabMoveTheFocusAround() {
163+ var form = FormView(fields: [.init(label: "Host"), .init(label: "Port")])
164+ var actions = [form.handle(.tab)]
165+ #expect(form.focus == 1)
166+ actions.append(form.handle(.tab))
167+ #expect(form.focus == 0)
168+ actions.append(form.handle(.backtab))
169+ #expect(form.focus == 1)
170+ actions.append(form.handle(.character("8")))
171+ #expect(form.values == ["", "8"])
172+ actions += [form.handle(.enter), form.handle(.escape), form.handle(.function(2))]
173+ #expect(actions == [.none, .none, .none, .none, .submit, .cancel, .ignored])
174+ }
175+
176+ @Test func rendersAlignedLabelsSecretsAndTheCursor() {
177+ var form = FormView(fields: [
178+ .init(label: "Host", text: "127.0.0.1"),
179+ .init(label: "API key", text: "abc", secret: true),
180+ ])
181+ _ = form.handle(.tab)
182+ let (lines, cursor) = form.render(width: 40, style: Style(colors: false))
183+ #expect(lines == ["Host: 127.0.0.1", "API key: •••"])
184+ #expect(cursor.row == 1 && cursor.column == 12)
185+ }
186+
187+ @Test func shiftTabIsDecoded() {
188+ var decoder = KeyDecoder()
189+ #expect(decoder.decode([27, 91, 90]) == [.backtab])
190+ }
191+}