Class: Tuile::Component::TextView
- Inherits:
-
Tuile::Component
- Object
- Tuile::Component
- Tuile::Component::TextView
- Defined in:
- lib/tuile/component/text_view.rb
Overview
A read-only viewer for prose: chunks of formatted text that scroll vertically. Shape-wise a hybrid between Label (string-shaped content via #text=) and List (scroll keys, optional scrollbar, auto-scroll).
Text is modeled as a StyledString: embedded ‘n` are hard line breaks, lines wider than the viewport are word-wrapped via StyledString#wrap (style spans are preserved across wrap boundaries — unlike the older ANSI-as-bytes wrapping, color does not get dropped on continuation rows). #text= accepts a String (parsed via StyledString.parse, so embedded ANSI is honored) or a StyledString directly; #text always returns the StyledString.
For incremental updates pick the right primitive: #append (aliased as ‘<<`) is verbatim and stream-friendly — chunks are concatenated straight onto the buffer, with embedded `n` becoming hard breaks. #add_line is the “log entry” convenience — it starts the content on a fresh line by inserting a leading `n` when the buffer is non-empty. #remove_last_n_lines pops hard lines back off the tail — the inverse of building up a region with #append / #add_line, so a caller streaming reformattable content (e.g. partially-rendered Markdown that may need to retract its last paragraph) can replace the tail without rewriting the whole text. Turn on #auto_scroll to keep the latest content in view.
TextView is meant to be the content of a Window — focus indication and keyboard-hint surfacing rely on the surrounding window chrome.
Defined Under Namespace
Classes: Region
Instance Attribute Summary collapse
-
#auto_scroll ⇒ Boolean
If true, mutating the text scrolls the viewport so the last line stays in view.
-
#content_size ⇒ Size
readonly
Longest hard-line’s display width × number of hard lines.
-
#scrollbar_visibility ⇒ Symbol
‘:gone` or `:visible`.
-
#top_line ⇒ Integer
Index of the first visible physical line.
Attributes inherited from Tuile::Component
Instance Method Summary collapse
-
#<<(str) ⇒ self
Verbatim append, returning ‘self` for chainability (`view << a << b`).
-
#add_line(str) ⇒ void
Appends ‘str` as a new entry: starts a fresh hard line first (when the buffer is non-empty) and then appends `str`.
-
#append(str) ⇒ void
Appends ‘str` verbatim.
-
#clear ⇒ void
Clears the text.
-
#create_region ⇒ Region
Creates a new empty Region at the spatial tail of the document and returns its handle.
-
#empty? ⇒ Boolean
True iff #text is empty (no hard lines).
- #focusable? ⇒ Boolean
- #handle_key(key) ⇒ Boolean
- #handle_mouse(event) ⇒ void
-
#initialize ⇒ TextView
constructor
A new instance of TextView.
-
#insert(at, str) ⇒ void
Inserts ‘str` at hard-line index `at`.
-
#remove_last_n_lines(n) ⇒ void
Drops the last ‘n` hard lines from the buffer.
-
#repaint ⇒ void
Paints the text into #rect.
-
#replace(range, str) ⇒ void
Replaces a contiguous range of hard lines with the parsed content of ‘str`.
- #tab_stop? ⇒ Boolean
-
#text ⇒ StyledString
The current text.
-
#text=(value) ⇒ void
Replaces the text.
Methods inherited from Tuile::Component
#active=, #active?, #attached?, #children, #cursor_position, #depth, #find_shortcut_component, #focus, #keyboard_hint, #on_child_removed, #on_focus, #on_tree, #root, #screen
Constructor Details
#initialize ⇒ TextView
Returns a new instance of TextView.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/tuile/component/text_view.rb', line 32 def initialize super # Three parallel structures, kept in lockstep by every mutator: # `@hard_lines` is the logical model (one entry per `\n`-delimited # line, width-independent); `@physical_lines` is the rendered view # (each hard line word-wrapped to `wrap_width` and padded with # trailing blanks, so painting a row is a lookup); and # `@hard_line_wrap_counts` is an Integer-per-hard-line cache of # how many physical rows each hard line occupies, so a mid-buffer # splice can find its starting physical-row offset without # re-wrapping every preceding hard line. # # Invariants: # - `@hard_line_wrap_counts.size == @hard_lines.size` # - `@hard_line_wrap_counts.sum == @physical_lines.size` # A full rebuild ({#rewrap}) happens on {#text=} and width changes; # other mutators splice incrementally. @hard_lines = [] @physical_lines = [] @hard_line_wrap_counts = [] @text = StyledString::EMPTY @content_size = Size::ZERO @blank_line = StyledString::EMPTY @top_line = 0 @auto_scroll = false @scrollbar_visibility = :gone # The view always has at least one region — an implicit default. It # owns whatever hard lines exist that no later region claims. App # code that never calls {#create_region} sees the same behavior as # before (a single region containing everything); apps that do call # {#create_region} stack additional regions at the spatial tail. @regions = [Region.send(:new, self)] end |
Instance Attribute Details
#auto_scroll ⇒ Boolean
Returns if true, mutating the text scrolls the viewport so the last line stays in view. Default ‘false`.
85 86 87 |
# File 'lib/tuile/component/text_view.rb', line 85 def auto_scroll @auto_scroll end |
#content_size ⇒ Size (readonly)
382 383 384 |
# File 'lib/tuile/component/text_view.rb', line 382 def content_size @content_size end |
#scrollbar_visibility ⇒ Symbol
Returns ‘:gone` or `:visible`.
81 82 83 |
# File 'lib/tuile/component/text_view.rb', line 81 def @scrollbar_visibility end |
#top_line ⇒ Integer
Returns index of the first visible physical line.
78 79 80 |
# File 'lib/tuile/component/text_view.rb', line 78 def top_line @top_line end |
Instance Method Details
#<<(str) ⇒ self
Verbatim append, returning ‘self` for chainability (`view << a << b`).
191 192 193 194 |
# File 'lib/tuile/component/text_view.rb', line 191 def <<(str) append(str) self end |
#add_line(str) ⇒ void
This method returns an undefined value.
Appends ‘str` as a new entry: starts a fresh hard line first (when the buffer is non-empty) and then appends `str`. Equivalent to `append(“n” + str)` on a non-empty buffer, or `append(str)` on an empty one. `nil` and `“”` produce a blank entry on a non-empty buffer and a no-op on an empty buffer (matches the old `append` semantics for “log line” callers).
204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/tuile/component/text_view.rb', line 204 def add_line(str) parsed = StyledString.parse(str) if empty? || @regions.last.empty? # No previous line in the tail region to break away from — just # append. (If the tail region is empty but earlier regions have # content, the verbatim {#append} path already starts a fresh # hard line in the tail.) append(parsed) else append(StyledString.plain("\n") + parsed) end end |
#append(str) ⇒ void
This method returns an undefined value.
Appends ‘str` verbatim. Embedded `n` characters become hard line breaks; otherwise the text is concatenated onto the current last hard line. Designed for streaming use (e.g. an LLM chat window receiving partial messages — feed each chunk straight in). Accepts the same input forms as #text=; empty/`nil` input is a no-op.
For the “add an entry on a new line” pattern use #add_line.
Cost is O(appended + width-of-current-last-hard-line) — the previously last hard line is re-wrapped (because the extension may cause it to wrap differently), any additional hard lines created by embedded ‘n` are wrapped fresh. The cached #text is invalidated and rebuilt on demand.
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/tuile/component/text_view.rb', line 154 def append(str) screen.check_locked appended = StyledString.parse(str) return if appended.empty? tail_region = @regions.last tail_was_empty = tail_region.empty? new_segments = appended.lines width = wrap_width if tail_was_empty # An empty spatial-tail region (either a fresh buffer, or an empty # region the app created at the tail) means new content starts on # a fresh hard line — we must not extend the previous region's # last line. new_segments.each { |hl| push_hard_line(hl, width) } added = new_segments.size else extension = new_segments.first unless extension.empty? old_last = pop_hard_line push_hard_line(old_last + extension, width) end new_segments[1..].each { |hl| push_hard_line(hl, width) } added = new_segments.size - 1 end tail_region.send(:line_count=, tail_region.line_count + added) @text = nil @content_size = compute_content_size update_top_line_if_auto_scroll invalidate end |
#clear ⇒ void
This method returns an undefined value.
Clears the text. Equivalent to ‘text = “”`.
338 339 340 |
# File 'lib/tuile/component/text_view.rb', line 338 def clear self.text = StyledString::EMPTY end |
#create_region ⇒ Region
Creates a new empty Region at the spatial tail of the document and returns its handle. Subsequent #append / #<< / #add_line calls route through this new region (since it is now the spatial tail). Earlier regions keep their content and their handles stay valid; their Tuile::Component::TextView::Region#range shifts as later regions grow.
Apps streaming logically-distinct sections (e.g. an LLM’s “thinking” vs. “assistant” output) create one region per section, hold the handles, and call ‘region.append` / `region.text=` directly when they need to grow or rewrite an earlier section.
130 131 132 133 134 |
# File 'lib/tuile/component/text_view.rb', line 130 def create_region region = Region.send(:new, self) @regions << region region end |
#empty? ⇒ Boolean
Returns true iff #text is empty (no hard lines).
137 |
# File 'lib/tuile/component/text_view.rb', line 137 def empty? = @hard_lines.empty? |
#focusable? ⇒ Boolean
373 |
# File 'lib/tuile/component/text_view.rb', line 373 def focusable? = true |
#handle_key(key) ⇒ Boolean
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/tuile/component/text_view.rb', line 386 def handle_key(key) return false unless active? return true if super case key when *Keys::DOWN_ARROWS then move_top_line_by(1) when *Keys::UP_ARROWS then move_top_line_by(-1) when Keys::PAGE_DOWN then move_top_line_by() when Keys::PAGE_UP then move_top_line_by(-) when Keys::CTRL_D then move_top_line_by( / 2) when Keys::CTRL_U then move_top_line_by(- / 2) when *Keys::HOMES, "g" then move_top_line_to(0) when *Keys::ENDS_, "G" then move_top_line_to(top_line_max) else return false end true end |
#handle_mouse(event) ⇒ void
This method returns an undefined value.
406 407 408 409 410 411 412 |
# File 'lib/tuile/component/text_view.rb', line 406 def handle_mouse(event) super case event. when :scroll_down then move_top_line_by(4) when :scroll_up then move_top_line_by(-4) end end |
#insert(at, str) ⇒ void
This method returns an undefined value.
Inserts ‘str` at hard-line index `at`. Equivalent to `replace(at…at, str)` — a no-removal splice that grows the buffer by the parsed line count. `at == hard-line count` is allowed and appends at the end; for that case #append / #add_line are usually more idiomatic.
332 333 334 |
# File 'lib/tuile/component/text_view.rb', line 332 def insert(at, str) replace(at...at, str) end |
#remove_last_n_lines(n) ⇒ void
This method returns an undefined value.
Drops the last ‘n` hard lines from the buffer. The inverse of building up a tail region with #append / #add_line: a caller streaming partially-rendered content whose tail must occasionally be retracted (e.g. Markdown-to-ANSI where a new token reformats the table being built) can call `remove_last_n_lines(k)` followed by `append(new_tail)` to replace the damaged region in place.
‘n == 0` and the empty-buffer case are no-ops (no invalidation). `n >= hard-line count` empties the buffer.
Operates on **hard lines** (the ‘n`-delimited entries the buffer stores), not on wrapped physical rows — same granularity as #add_line. Cost is O(rendered-rows of the popped lines).
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
# File 'lib/tuile/component/text_view.rb', line 234 def remove_last_n_lines(n) raise TypeError, "expected Integer, got #{n.inspect}" unless n.is_a?(Integer) raise ArgumentError, "n must not be negative, got #{n}" if n.negative? screen.check_locked return if n.zero? || empty? to_drop = [n, @hard_lines.size].min to_drop.times { pop_hard_line } # Cascade-shrink regions from the spatial tail. The tail region # gives up lines first; if more are still owed (because the tail # was shorter than `to_drop`), earlier regions shrink in turn. remaining = to_drop @regions.reverse_each do |region| break if remaining.zero? take = [remaining, region.line_count].min region.send(:line_count=, region.line_count - take) remaining -= take end @text = nil @content_size = compute_content_size @top_line = top_line_max if @top_line > top_line_max update_top_line_if_auto_scroll invalidate end |
#repaint ⇒ void
This method returns an undefined value.
Paints the text into Tuile::Component#rect.
Skips the Tuile::Component#repaint default’s auto-clear: every row is painted explicitly (with padded blanks past the last line), so the “fully draw over your rect” contract is met without an upfront wipe.
420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/tuile/component/text_view.rb', line 420 def repaint return if rect.empty? = if VerticalScrollBar.new(rect.height, line_count: @physical_lines.size, top_line: @top_line) end (0...rect.height).each do |row| line = paintable_line(row + @top_line, row, ) screen.print TTY::Cursor.move_to(rect.left, rect.top + row), line end end |
#replace(range, str) ⇒ void
This method returns an undefined value.
Replaces a contiguous range of hard lines with the parsed content of ‘str`. The replacement is parsed exactly like #text= and #append: a String is run through StyledString.parse (so embedded ANSI is honored), a StyledString is used as-is, `nil` behaves like an empty replacement (the range is deleted). Embedded `“n”` in the replacement produces multiple hard lines, so a single `replace` can grow or shrink the buffer.
‘range` selects which hard lines to swap out:
-
an ‘Integer` `n` is shorthand for `n..n` (replace one existing line — `n` must be in `[0, hard-line count)`);
-
a non-empty ‘Range` of hard-line indices replaces those lines;
-
an empty ‘Range` (e.g. `2…2`, or the canonical end-insertion `hard_lines.size…hard_lines.size`) is insertion at that position — no lines are removed. #insert is a thin alias for this case.
Endpoints must be non-negative integers; ‘begin` may equal `hard-line count` (insertion at the end), `end` may not exceed `hard-line count - 1`. `nil` endpoints (beginless / endless ranges) are not accepted.
Cost is roughly ‘O(from + length + new content)`: the splice updates only the affected slice of the physical-row buffer, using the per-hard-line wrap-count cache to locate the starting offset without re-wrapping preceding lines. Lines outside the splice are never re-wrapped. #top_line is clamped if the new line count puts it past the end; #auto_scroll pins it to the bottom as usual. The call is a no-op (no invalidation) when the parsed replacement equals the covered range (vacuously true for an empty range plus empty replacement, so `replace(n…n, “”)` is a cheap no-op).
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/tuile/component/text_view.rb', line 306 def replace(range, str) screen.check_locked from, to = normalize_replace_range(range) parsed = StyledString.parse(str) new_hard_lines = parsed.empty? ? [] : parsed.lines length = to - from + 1 return if new_hard_lines == @hard_lines[from, length] splice_hard_lines(from, length, new_hard_lines) update_region_counts(from, length, new_hard_lines.size) @text = nil @content_size = compute_content_size @top_line = top_line_max if @top_line > top_line_max update_top_line_if_auto_scroll invalidate end |
#tab_stop? ⇒ Boolean
375 |
# File 'lib/tuile/component/text_view.rb', line 375 def tab_stop? = true |
#text ⇒ StyledString
Returns the current text. Defaults to an empty StyledString. Internally the text is stored as an array of hard lines so #append can stay O(appended) instead of re-scanning the whole buffer; the joined StyledString returned here is reconstructed on first read after a mutation and cached, so repeated reads are O(1) but the first read after #append pays O(total spans).
73 74 75 |
# File 'lib/tuile/component/text_view.rb', line 73 def text @text ||= build_text end |
#text=(value) ⇒ void
This method returns an undefined value.
Replaces the text. Embedded ‘n` characters become hard line breaks. A `String` is parsed via StyledString.parse (so embedded ANSI is honored); a `StyledString` is used as-is; `nil` is coerced to an empty StyledString.
Detaches every existing Region (including the original default) and installs a fresh internal default region that owns all the new hard lines. Any handle the caller was holding becomes detached and raises on use — see Tuile::Component::TextView::Region#attached?. The no-op short-circuit (matching value, same StyledString) preserves existing regions.
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/tuile/component/text_view.rb', line 99 def text=(value) new_text = StyledString.parse(value) content_unchanged = text == new_text # `text=` is a structural reset: even when the new content matches # the old, existing region handles must die — the caller said "set # the text," not "merge with what's there." The unchanged-content # path still skips the expensive rewrap / invalidate work. @text = new_text @hard_lines = new_text.empty? ? [] : new_text.lines @regions.each { |r| r.send(:detach!) } @regions = [Region.send(:new, self, @hard_lines.size)] return if content_unchanged @content_size = compute_content_size rewrap update_top_line_if_auto_scroll invalidate end |