Class: Tuile::Component::TextView

Inherits:
Tuile::Component show all
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

Attributes inherited from Tuile::Component

#key_shortcut, #on_theme_changed, #parent, #rect

Instance Method Summary collapse

Methods inherited from Tuile::Component

#active=, #active?, #attached?, #children, #cursor_position, #depth, #find_shortcut_component, #focus, #keyboard_hint, #on_child_content_size_changed, #on_child_removed, #on_focus, #on_tree, #root, #screen

Constructor Details

#initializeTextView

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
  @blank_line = StyledString::EMPTY
  @top_line = 0
  @auto_scroll = false
  @follow = true
  @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_scrollBoolean

Returns if true, mutating the text scrolls the viewport so the last line stays in view — but only while the viewport is already pinned to the last line (see #following?). Scroll up to read older content and appends stop yanking you back down; scroll back to the bottom and tailing resumes. Default ‘false`.

Returns:

  • (Boolean)

    if true, mutating the text scrolls the viewport so the last line stays in view — but only while the viewport is already pinned to the last line (see #following?). Scroll up to read older content and appends stop yanking you back down; scroll back to the bottom and tailing resumes. Default ‘false`.



88
89
90
# File 'lib/tuile/component/text_view.rb', line 88

def auto_scroll
  @auto_scroll
end

#content_sizeSize (readonly)

Returns longest hard-line’s display width × number of hard lines. Reported on the unwrapped text — wrap-aware sizing would be circular (width depends on width). Empty text returns ‘Size.new(0, 0)`. Maintained incrementally by #text= and #append, so reads are O(1).

Returns:

  • (Size)

    longest hard-line’s display width × number of hard lines. Reported on the unwrapped text — wrap-aware sizing would be circular (width depends on width). Empty text returns ‘Size.new(0, 0)`. Maintained incrementally by #text= and #append, so reads are O(1).



394
395
396
# File 'lib/tuile/component/text_view.rb', line 394

def content_size
  @content_size
end

#scrollbar_visibilitySymbol

Returns ‘:gone` or `:visible`.

Returns:

  • (Symbol)

    ‘:gone` or `:visible`.



81
82
83
# File 'lib/tuile/component/text_view.rb', line 81

def scrollbar_visibility
  @scrollbar_visibility
end

#top_lineInteger

Returns index of the first visible physical line.

Returns:

  • (Integer)

    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`).

Parameters:

Returns:

  • (self)


200
201
202
203
# File 'lib/tuile/component/text_view.rb', line 200

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).

Parameters:



213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/tuile/component/text_view.rb', line 213

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.

Parameters:



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/tuile/component/text_view.rb', line 163

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
  update_top_line_if_auto_scroll
  invalidate
  self.content_size = compute_content_size
end

#clearvoid

This method returns an undefined value.

Clears the text. Equivalent to ‘text = “”`.



347
348
349
# File 'lib/tuile/component/text_view.rb', line 347

def clear
  self.text = StyledString::EMPTY
end

#create_regionRegion

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.

Returns:



139
140
141
142
143
# File 'lib/tuile/component/text_view.rb', line 139

def create_region
  region = Region.send(:new, self)
  @regions << region
  region
end

#empty?Boolean

Returns true iff #text is empty (no hard lines).

Returns:

  • (Boolean)

    true iff #text is empty (no hard lines).



146
# File 'lib/tuile/component/text_view.rb', line 146

def empty? = @hard_lines.empty?

#focusable?Boolean

Returns:

  • (Boolean)


385
# File 'lib/tuile/component/text_view.rb', line 385

def focusable? = true

#following?Boolean

Returns whether #auto_scroll is currently tailing. True while the viewport sits at the last line; flips to false the moment the user scrolls up, and back to true once they scroll to the bottom again. Only consulted when #auto_scroll is enabled.

Returns:

  • (Boolean)

    whether #auto_scroll is currently tailing. True while the viewport sits at the last line; flips to false the moment the user scrolls up, and back to true once they scroll to the bottom again. Only consulted when #auto_scroll is enabled.



94
# File 'lib/tuile/component/text_view.rb', line 94

def following? = @follow

#handle_key(key) ⇒ Boolean

Parameters:

  • key (String)

Returns:

  • (Boolean)


398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/tuile/component/text_view.rb', line 398

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(viewport_lines)
  when Keys::PAGE_UP      then move_top_line_by(-viewport_lines)
  when Keys::CTRL_D       then move_top_line_by(viewport_lines / 2)
  when Keys::CTRL_U       then move_top_line_by(-viewport_lines / 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.

Parameters:



418
419
420
421
422
423
424
# File 'lib/tuile/component/text_view.rb', line 418

def handle_mouse(event)
  super
  case event.button
  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.

Parameters:

  • at (Integer)

    0-based hard-line index in ‘[0, hard-line count]`.

  • str (String, StyledString, nil)

    content to insert.



341
342
343
# File 'lib/tuile/component/text_view.rb', line 341

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).

Parameters:

  • n (Integer)

    number of hard lines to drop; must be >= 0.

Raises:

  • (TypeError)

    if ‘n` isn’t an ‘Integer`.

  • (ArgumentError)

    if ‘n` is negative.



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/tuile/component/text_view.rb', line 243

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
  @top_line = top_line_max if @top_line > top_line_max
  update_top_line_if_auto_scroll
  invalidate
  self.content_size = compute_content_size
end

#repaintvoid

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.



432
433
434
435
436
437
438
439
440
441
442
# File 'lib/tuile/component/text_view.rb', line 432

def repaint
  return if rect.empty?

  scrollbar = if scrollbar_visible?
                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, scrollbar)
    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).

Parameters:

  • range (Range, Integer)

    hard-line indices to replace.

  • str (String, StyledString, nil)

    replacement content.

Raises:

  • (TypeError)

    if ‘range` is neither an `Integer` nor a `Range`, or if a `Range` endpoint is not an `Integer`, or if `str` is not a `String`, `StyledString`, or `nil`.

  • (ArgumentError)

    if ‘range` has a negative endpoint, extends past the last hard line, or is malformed (`end` more than one below `begin`).



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/tuile/component/text_view.rb', line 315

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
  @top_line = top_line_max if @top_line > top_line_max
  update_top_line_if_auto_scroll
  invalidate
  self.content_size = compute_content_size
end

#tab_stop?Boolean

Returns:

  • (Boolean)


387
# File 'lib/tuile/component/text_view.rb', line 387

def tab_stop? = true

#textStyledString

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).

Returns:

  • (StyledString)

    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.

Parameters:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/tuile/component/text_view.rb', line 108

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

  rewrap
  update_top_line_if_auto_scroll
  invalidate
  self.content_size = compute_content_size
end