Class: RubyRich::Status::StatusBoard

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_rich/status.rb

Overview

状态板

Instance Method Summary collapse

Constructor Details

#initialize(width: 60) ⇒ StatusBoard

Returns a new instance of StatusBoard.



111
112
113
114
# File 'lib/ruby_rich/status.rb', line 111

def initialize(width: 60)
  @width = width
  @items = []
end

Instance Method Details

#add_item(label, status, description: nil) ⇒ Object



116
117
118
119
120
121
122
123
# File 'lib/ruby_rich/status.rb', line 116

def add_item(label, status, description: nil)
  @items << {
    label: label,
    status: status,
    description: description
  }
  self
end

#render(show_descriptions: true, align_status: :right) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/ruby_rich/status.rb', line 125

def render(show_descriptions: true, align_status: :right)
  lines = []
  lines << "#{'' * (@width - 2)}"
  
  @items.each do |item|
    label = item[:label]
    status_text = RubyRich::Status.indicator(item[:status])
    description = item[:description]
    
    # 计算实际显示宽度(排除 ANSI 代码)
    status_display_width = status_text.gsub(/\e\[[0-9;]*m/, '').length
    
    case align_status
    when :right
      padding = @width - 4 - label.length - status_display_width
      padding = [padding, 1].max
      main_line = "#{label}#{' ' * padding}#{status_text}"
    when :left
      padding = @width - 4 - label.length - status_display_width
      padding = [padding, 1].max
      main_line = "#{status_text} #{label}#{' ' * padding}"
    else # center
      total_content = label.length + status_display_width + 1
      left_padding = [(@width - 2 - total_content) / 2, 1].max
      right_padding = @width - 2 - total_content - left_padding
      main_line = "#{' ' * left_padding}#{label} #{status_text}#{' ' * right_padding}"
    end
    
    lines << main_line
    
    if show_descriptions && description
      desc_lines = wrap_text(description, @width - 4)
      desc_lines.each do |desc_line|
        padding = @width - 4 - desc_line.length
        lines << "│  \e[90m#{desc_line}#{' ' * padding}\e[0m  │"
      end
    end
  end
  
  lines << "#{'' * (@width - 2)}"
  lines.join("\n")
end