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.

Instance Attribute Summary collapse

Attributes inherited from Tuile::Component

#key_shortcut, #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_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
# File 'lib/tuile/component/text_view.rb', line 32

def initialize
  super
  # `@hard_lines` is the logical model — one entry per `\n`-delimited
  # line of the original text, 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.
  # Resizing rebuilds `@physical_lines` from `@hard_lines`; `#append`
  # extends both.
  @hard_lines = []
  @physical_lines = []
  @text = StyledString::EMPTY
  @content_size = Size::ZERO
  @blank_line = StyledString::EMPTY
  @top_line = 0
  @auto_scroll = false
  @scrollbar_visibility = :gone
end

Instance Attribute Details

#auto_scrollBoolean

Returns if true, mutating the text scrolls the viewport so the last line stays in view. Default ‘false`.

Returns:

  • (Boolean)

    if true, mutating the text scrolls the viewport so the last line stays in view. Default ‘false`.



69
70
71
# File 'lib/tuile/component/text_view.rb', line 69

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



250
251
252
# File 'lib/tuile/component/text_view.rb', line 250

def content_size
  @content_size
end

#scrollbar_visibilitySymbol

Returns ‘:gone` or `:visible`.

Returns:

  • (Symbol)

    ‘:gone` or `:visible`.



65
66
67
# File 'lib/tuile/component/text_view.rb', line 65

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.



62
63
64
# File 'lib/tuile/component/text_view.rb', line 62

def top_line
  @top_line
end

Instance Method Details

#<<(str) ⇒ self

Verbatim append, returning ‘self` for chainability (`view << a << b`).

Parameters:

Returns:

  • (self)


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

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:



157
158
159
160
161
162
163
164
# File 'lib/tuile/component/text_view.rb', line 157

def add_line(str)
  parsed = StyledString.parse(str)
  if empty?
    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:



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/tuile/component/text_view.rb', line 107

def append(str)
  screen.check_locked
  appended = StyledString.parse(str)
  return if appended.empty?

  new_segments = appended.lines
  width = wrap_width

  if empty?
    new_segments.each do |hl|
      @hard_lines << hl
      append_physical_lines(hl, width)
    end
  else
    extension = new_segments.first
    unless extension.empty?
      old_last = @hard_lines.pop
      drop_physical_rows_for(old_last, width)
      extended = old_last + extension
      @hard_lines << extended
      append_physical_lines(extended, width)
    end
    new_segments[1..].each do |hl|
      @hard_lines << hl
      append_physical_lines(hl, width)
    end
  end

  @text = nil
  @content_size = compute_content_size
  update_top_line_if_auto_scroll
  invalidate
end

#clearvoid

This method returns an undefined value.

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



206
207
208
# File 'lib/tuile/component/text_view.rb', line 206

def clear
  self.text = StyledString::EMPTY
end

#empty?Boolean

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

Returns:

  • (Boolean)

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



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

def empty? = @hard_lines.empty?

#focusable?Boolean

Returns:

  • (Boolean)


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

def focusable? = true

#handle_key(key) ⇒ Boolean

Parameters:

  • key (String)

Returns:

  • (Boolean)


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 254

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:



274
275
276
277
278
279
280
# File 'lib/tuile/component/text_view.rb', line 274

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

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



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/tuile/component/text_view.rb', line 183

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?

  width = wrap_width
  to_drop = [n, @hard_lines.size].min
  to_drop.times do
    popped = @hard_lines.pop
    drop_physical_rows_for(popped, width)
  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

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



288
289
290
291
292
293
294
295
296
297
298
# File 'lib/tuile/component/text_view.rb', line 288

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

#tab_stop?Boolean

Returns:

  • (Boolean)


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

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



57
58
59
# File 'lib/tuile/component/text_view.rb', line 57

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.

Parameters:



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/tuile/component/text_view.rb', line 77

def text=(value)
  new_text = StyledString.parse(value)
  return if text == new_text

  @text = new_text
  @hard_lines = new_text.empty? ? [] : new_text.lines
  @content_size = compute_content_size
  rewrap
  update_top_line_if_auto_scroll
  invalidate
end