Class: Tuile::Component::Notification

Inherits:
Popup
  • Object
show all
Defined in:
lib/tuile/component/notification.rb,
sig/tuile.rbs

Overview

A transient message in the screen's top-right corner — the TTY toast:

Component::Notification.show("Saved")
Component::Notification.show("Disk full", color: Theme.ref(:error))

┌─────────┐  ← flush: row 0, right edge at the last column
│Saved    │  ← oldest on top, retires in 3 s
│Disk full│  ← then this one, 3 s after that
└─────────┘

Notification.show is the only entry point (new is private): it finds the live notification and appends to it, so a burst stacks as entries in one box instead of opening five overlapping ones.

One repeating ticker retires the oldest entry every DISPLAY_SECONDS and closes the box when the last one goes — five messages raised together appear at once and drain over fifteen seconds. A message arriving mid-cycle waits its turn and does not restart the clock, so the bottom entry of a full box is visible for about N × DISPLAY_SECONDS. Past MAX_MESSAGES a message is dropped and reported to Tuile.logger; an app notifying faster than that wants a LogWindow.

The box is flush to the corner, at most WIDTH_FRACTION of the screen wide (floor MIN_CAP_WIDTH) and HEIGHT_FRACTION tall, and grows but never shrinks while it lives; a long message wraps to MAX_ROWS_PER_MESSAGE rows and is then ellipsized, and entries past the height cap wait unpainted. DECISIONS.md D-notification has why each of those is what it is.

Three things it deliberately doesn't do:

  • Take focus, or receive keys. A non-modal popup sits off the key-dispatch scope (ScreenPane#handle_key), so not even Popup's q/ESC arrives here. A left click dismisses (#handle_mouse); an app wanting a key registers a global shortcut and calls Popup#close.
  • Follow a theme flip. A Theme::Ref color: is resolved once, when the message is added — a toast lives seconds, so there is no #on_theme_changed rebuild.
  • Take a size. #size= raises; the messages decide.

Constant Summary collapse

MAX_MESSAGES =

Most messages held at once, counting both the painted ones and any waiting for room. Chosen from reading time rather than geometry: the drain rate is one message per DISPLAY_SECONDS, so the queue length is a duration, and 5 × 3 s is about the longest a corner box should own the screen — and about as many short lines as anyone reads.

Returns:

  • (Integer)
5
MAX_ROWS_PER_MESSAGE =

Rows a single message may occupy before it is ellipsized.

Returns:

  • (Integer)
3
DISPLAY_SECONDS =

Seconds between retirements — how long the oldest message is held.

Returns:

  • (Float)
3.0
WIDTH_FRACTION =

Fraction of the screen width the box may not exceed (see MIN_CAP_WIDTH).

Returns:

  • (Float)
0.4
HEIGHT_FRACTION =

Fraction of the screen height the box may not exceed.

Returns:

  • (Float)
0.4
MIN_CAP_WIDTH =

Floor under the width cap, so 40 % of an 80-column terminal doesn't ellipsize every message down to five words.

Returns:

  • (Integer)
34
SPACE =

Separator for re-joining wrapped rows before ellipsizing.

Returns:

StyledString.parse(" ")
ROW_BREAK =

Hard-line separator handed to TextView#text=.

Returns:

StyledString.parse("\n")

Instance Attribute Summary

Attributes inherited from Popup

#size

Attributes included from HasContent

#content

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Popup

#center, #close, #handle_key, #layout, #modal?, #on_focus, #open, #open?, #rect=

Methods included from HasContent

#on_focus, #rect=

Constructor Details

#initializeNotification

Returns a new instance of Notification.



115
116
117
118
119
120
121
122
123
124
125
# File 'lib/tuile/component/notification.rb', line 115

def initialize
  # Built before `super`, because Popup#initialize assigns the content and
  # calls #reposition, and our override reads every one of these.
  @messages = []
  @high_water = 0
  @ticker = nil
  @view = TextView.new
  @window = Window.new
  @window.content = @view
  super(content: @window, modal: false)
end

Class Method Details

.show(text, color: nil) ⇒ Notification?

Shows text in the corner, creating the box if none is open and appending to it if one is.

@param text — the message. A String is parsed via StyledString.parse, so embedded ANSI is honored. nil and the empty string are no-ops (nothing is shown, nothing is created).

@param color — applied to every span of the message via StyledString#with_fg. A Theme::Ref is resolved against the current theme now — see the class docs on theme following. nil leaves the message's own colors alone.

@return — the live notification, or nil when text was empty.

Parameters:

Returns:



98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/tuile/component/notification.rb', line 98

def self.show(text, color: nil)
  Screen.instance.check_locked
  return nil if StyledString.parse(text).empty?

  live = Screen.instance.pane.popups.find { _1.is_a?(Notification) }
  return live.tap { _1.add_message(text, color: color) } unless live.nil?

  # Message first, so the box is sized before it is mounted: opening an
  # empty 0×0 popup and then growing it would paint a frame of nothing.
  new.tap do |notification|
    notification.add_message(text, color: color)
    notification.open
  end
end

Instance Method Details

#add_message(text, color: nil) ⇒ void

This method returns an undefined value.

Appends a message, dropping it (with a Tuile.logger warning) once MAX_MESSAGES are held. Public so a caller holding the instance can append without repeating show's lookup.

@param text — see show. Empty is a no-op.

@param color — see show.

Parameters:



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/tuile/component/notification.rb', line 150

def add_message(text, color: nil)
  # Explicit rather than inherited-through-invalidate: this appends to
  # @messages before anything repaints, so a wrong-thread call has to fail
  # before the message is recorded, not after.
  screen.check_locked
  message = build_message(text, color)
  return if message.empty?

  if @messages.size >= MAX_MESSAGES
    Tuile.logger.warn("Notification: dropping #{message.to_s.inspect}, " \
                      "#{MAX_MESSAGES} messages already queued")
    return
  end

  @messages << message
  @high_water = [@high_water, natural_width(message)].max
  reposition
  sync_ticker
end

#box_widthInteger

Grow-only: the high-water mark is kept in desired columns and the cap is applied here, last. Storing the clamped value instead would let a SIGWINCH that narrows the terminal ratchet the box permanently down to the narrow cap, with nothing to restore it when the terminal widens.

Returns:

  • (Integer)


274
# File 'lib/tuile/component/notification.rb', line 274

def box_width = [@high_water + 2, cap_width].min

#build_message(text, color) ⇒ StyledString

@param text

@param color

Parameters:

Returns:



255
256
257
258
259
260
# File 'lib/tuile/component/notification.rb', line 255

def build_message(text, color)
  message = StyledString.parse(text)
  return message if color.nil? || message.empty?

  message.with_fg(color.is_a?(Theme::Ref) ? color.resolve(screen.theme) : color)
end

#cap_heightInteger

@return — at least 3: two border rows plus one row of message.

Returns:

  • (Integer)


282
283
284
# File 'lib/tuile/component/notification.rb', line 282

def cap_height
  [[(screen.size.height * HEIGHT_FRACTION).to_i, 3].max, screen.size.height].min
end

#cap_widthInteger

Returns:

  • (Integer)


277
278
279
# File 'lib/tuile/component/notification.rb', line 277

def cap_width
  [[(screen.size.width * WIDTH_FRACTION).to_i, MIN_CAP_WIDTH].max, screen.size.width].min
end

#focusable?Boolean

Load-bearing, not cosmetic: focus landing inside a non-modal popup sits outside the key-dispatch scope, where ScreenPane#handle_key delivers to nobody — every keystroke would go dead until the user pressed Tab.

@return — false.

Returns:

  • (Boolean)


131
# File 'lib/tuile/component/notification.rb', line 131

def focusable? = false

#handle_mouse(event) ⇒ void

This method returns an undefined value.

A left click dismisses the whole box, every message with it. Other buttons are consumed and inert — including the scroll wheel, which would otherwise nuke the box on a stray spin.

Deliberately replaces rather than augments: neither super nor HasContent#handle_mouse may run, since both end at a screen.focused = … inside this subtree (see #focusable?).

@param event

Parameters:



212
213
214
# File 'lib/tuile/component/notification.rb', line 212

def handle_mouse(event)
  close if event.button == :left
end

#join_rows(rows) ⇒ StyledString

Joins pre-wrapped rows into one StyledString with \n separators, so TextView takes them as hard lines and its own wrap is a no-op over them (each row already fits the width it will be painted at).

@param rows

Parameters:

Returns:



310
311
312
313
314
# File 'lib/tuile/component/notification.rb', line 310

def join_rows(rows)
  return StyledString::EMPTY if rows.empty?

  rows.inject { |joined, row| joined + ROW_BREAK + row }
end

#keyboard_hintString

Empty: a non-modal popup never owns the status bar, and Popup's inherited q Close hint would be a lie here — no key ever reaches a notification.

Returns:

  • (String)


140
# File 'lib/tuile/component/notification.rb', line 140

def keyboard_hint = ""

#natural_width(message) ⇒ Integer

Columns the message would like, ignoring wrapping — the widest of its hard lines, not the sum of its spans (which would add every line together for a message carrying \n).

@param message

Parameters:

Returns:

  • (Integer)


267
# File 'lib/tuile/component/notification.rb', line 267

def natural_width(message) = message.lines.map(&:display_width).max || 0

#on_attachedvoid

This method returns an undefined value.



217
# File 'lib/tuile/component/notification.rb', line 217

def on_attached = sync_ticker

#on_detachedvoid

This method returns an undefined value.



220
# File 'lib/tuile/component/notification.rb', line 220

def on_detached = sync_ticker

#repositionvoid

This method returns an undefined value.

Recomputes the box from its messages and re-anchors it to the screen's top-right corner — so a SIGWINCH re-wraps and re-anchors, where Popup#reposition would have kept the stale left column of a derived position (off-screen entirely if the terminal narrowed).

Rebuilds the TextView's text too, and every mutation routes through here, because the four are one computation: the wrap width is the box width, the height is the wrapped row count, the left edge is derived from the width.



180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/tuile/component/notification.rb', line 180

def reposition
  if @messages.empty?
    self.rect = Rect.new(0, 0, 0, 0)
    return
  end

  width = box_width
  rows = @messages.flat_map { |message| wrap_message(message, width - 2) }
  height = [rows.size + 2, cap_height].min
  @size = Size.new(width, height)
  @view.text = join_rows(rows)
  self.rect = Rect.new([screen.size.width - width, 0].max, 0, width, height)
end

#retire_oldestvoid

This method returns an undefined value.

Retires the oldest message, closing the box when it was the last. Runs on the event-loop thread, from the ticker.



227
228
229
230
231
# File 'lib/tuile/component/notification.rb', line 227

def retire_oldest
  @messages.shift
  @messages.empty? ? close : reposition
  sync_ticker
end

#size=(_new_size) ⇒ void

This method returns an undefined value.

A notification is sized by its messages, so this always raises. Failing loudly beats accepting a size the next #reposition would discard.

@param _new_size

Parameters:



199
200
201
# File 'lib/tuile/component/notification.rb', line 199

def size=(_new_size)
  raise Tuile::Error, "Notification sizes itself from its messages; #{self.class}#size= is not settable"
end

#sync_tickervoid

This method returns an undefined value.

Syncs the retirement clock from the invariant "something to retire, and on screen" — the sole writer of @ticker. Four sites change whether it is wanted (append, a retirement that empties the queue, Popup#close, detach), which is the 2×2 a start-in-#on_attached / cancel-in-#on_detached pair gets half wrong. The early return is also what keeps an append from restarting the clock and extending the oldest message's life.



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/tuile/component/notification.rb', line 240

def sync_ticker
  want = attached? && !@messages.empty?
  return if want == !@ticker.nil?

  if want
    @ticker = screen.event_queue.tick(DISPLAY_SECONDS) { retire_oldest }
  else
    @ticker.cancel
    @ticker = nil
  end
end

#tab_stop?Boolean

@return — false — see #focusable?.

Returns:

  • (Boolean)


134
# File 'lib/tuile/component/notification.rb', line 134

def tab_stop? = false

#wrap_message(message, width) ⇒ ::Array[StyledString]

Wraps one message to width columns, capped at MAX_ROWS_PER_MESSAGE rows.

The overflow is ellipsized from the joined remainder, not by ellipsizing the last kept row: that row usually already fits width, so StyledString#ellipsize would be a no-op and the message would be truncated with no to say so.

@param message

@param width

Parameters:

Returns:



296
297
298
299
300
301
302
303
# File 'lib/tuile/component/notification.rb', line 296

def wrap_message(message, width)
  rows = message.wrap(width)
  return rows if rows.size <= MAX_ROWS_PER_MESSAGE

  kept = rows.take(MAX_ROWS_PER_MESSAGE - 1)
  rest = rows[(MAX_ROWS_PER_MESSAGE - 1)..].inject { |joined, row| joined + SPACE + row }
  kept + [rest.ellipsize(width)]
end