yorha 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+
4
+ # Optional machine-style text presentation.
5
+ #
6
+ # Responsibilities:
7
+ # - Print plain text instantly when output is not interactive.
8
+ # - Animate interactive output one character at a time.
9
+ # - Briefly display noise before selected characters.
10
+ # - Accept an injected RNG for reproducible behaviour.
11
+ #
12
+ # Requiring this file never starts an animation.
13
+
14
+ module Yorha
15
+ module Machine
16
+ # ASCII noise is intentional: it does not require extra glyph entries
17
+ # and remains compatible with Unicode-disabled configurations.
18
+ NOISE = ["#", "%", "&", "?", "/"].freeze
19
+
20
+ class << self
21
+ # Writes machine-style speech and returns the final uncorrupted line.
22
+ #
23
+ # Corruption is temporary: a noise character is erased before the
24
+ # original character is written. The final visible message is intact.
25
+ #
26
+ # Non-TTY streams skip all animation, sleeps, and corruption.
27
+ #
28
+ # @param text [Object] content converted to a String
29
+ # @param io [#write] output destination
30
+ # @param anger [Numeric] corruption probability between 0 and 1
31
+ # @param rng [Random] random-number source
32
+ # @param cps [Numeric] characters per second; positive Infinity
33
+ # disables animation
34
+ # @return [String] original text with a terminating newline
35
+ # @raise [ArgumentError] when anger or cps is invalid
36
+ def speak(text, io: Yorha.config.io, anger: 0.2, rng: Random.new, cps: 40)
37
+
38
+ probability = Float(anger)
39
+ speed = Float(cps)
40
+
41
+ unless probability.finite? && probability.between?(0.0, 1.0)
42
+ raise ArgumentError, "anger must be between 0 and 1"
43
+ end
44
+
45
+ unless speed.positive?
46
+ raise ArgumentError, "cps must be positive"
47
+ end
48
+
49
+ message = text.to_s
50
+ output = message.end_with?("\n") ? message : "#{message}\n"
51
+
52
+ unless interactive?(io) && speed.finite?
53
+ io.write(output)
54
+ return output
55
+ end
56
+
57
+ interval = 1.0 / speed
58
+
59
+ output.each_char do |character|
60
+ # Only corrupt printable ASCII characters. Backspace-based
61
+ # replacement is unreliable for wide Unicode characters.
62
+ if corruptible?(character) && rng.rand < probability
63
+ noise = NOISE.fetch(rng.rand(NOISE.length))
64
+
65
+ io.write(noise)
66
+ flush(io)
67
+ sleep(interval / 2.0)
68
+
69
+ io.write("\b \b")
70
+ end
71
+
72
+ io.write(character)
73
+ flush(io)
74
+
75
+ sleep(interval) unless character == "\n"
76
+ end
77
+
78
+ output
79
+ end
80
+
81
+ private
82
+
83
+ # Determines whether this stream explicitly reports TTY support.
84
+ #
85
+ # @param io [Object] candidate output stream
86
+ # @return [Boolean] whether interactive animation is appropriate
87
+ def interactive?(io)
88
+ io.respond_to?(:tty?) && io.tty?
89
+ end
90
+
91
+ # Limits backspace corruption to single-cell ASCII characters.
92
+ #
93
+ # @param character [String] one character
94
+ # @return [Boolean] whether temporary replacement is allowed
95
+ def corruptible?(character)
96
+ character.match?(/\A[!-~]\z/)
97
+ end
98
+
99
+ # Flushes buffered output when the destination supports flushing.
100
+ #
101
+ # @param io [Object] destination stream
102
+ # @return [void]
103
+ def flush(io)
104
+ io.flush if io.respond_to?(:flush)
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yorha
4
+ module Palette
5
+ YORHA = {
6
+ fg: { hex: "#EAE8DF", ansi256: 255, ansi16: 97 }.freeze,
7
+
8
+ background: { hex: "#3B3A34", ansi256: 237, ansi16: 30 }.freeze,
9
+
10
+ accent: { hex: "#F2C800", ansi256: 220, ansi16: 93 }.freeze,
11
+
12
+ muted: { hex: "#8F8E87", ansi256: 245, ansi16: 90 }.freeze,
13
+
14
+ danger: { hex: "#B84A3A", ansi256: 167, ansi16: 91 }.freeze,
15
+
16
+ success: { hex: "#A6B96B", ansi256: 143, ansi16: 92 }.freeze
17
+ }.freeze
18
+
19
+ @palettes = {}
20
+
21
+ class << self
22
+ def register(name, values)
23
+ normalized_name = name.to_sym
24
+ normalized_values = normalize_palette(values)
25
+
26
+ unless normalized_values.key?(:fg)
27
+ raise ArgumentError, "A palette must define the :fg role"
28
+ end
29
+
30
+ @palettes[normalized_name] = normalized_values.freeze
31
+ end
32
+
33
+ def fetch(name)
34
+ @palettes.fetch(name.to_sym) do
35
+ @palettes.fetch(:yorha)
36
+ end
37
+ end
38
+
39
+ def current
40
+ selected = Yorha.config.palette
41
+
42
+ if selected.is_a?(Hash)
43
+ normalize_palette(selected)
44
+ else
45
+ fetch(selected)
46
+ end
47
+ end
48
+
49
+ def use(palette)
50
+ fetch(palette) unless palette.is_a?(Hash)
51
+
52
+ Yorha.configure do |config|
53
+ config.palette = palette
54
+ end
55
+
56
+ current
57
+ end
58
+
59
+ def registered
60
+ @palettes.keys.freeze
61
+ end
62
+
63
+ private
64
+
65
+ def normalize_palette(values)
66
+ unless values.respond_to?(:each_pair)
67
+ raise ArgumentError, "Palette values must be a Hash"
68
+ end
69
+
70
+ values.each_with_object({}) do |(role, color), result|
71
+ unless color.respond_to?(:each_pair)
72
+ raise ArgumentError, "Palette role #{role.inspect} must be a Hash"
73
+ end
74
+
75
+ normalized_color = color.each_with_object({}) do |(key, value), entry|
76
+ entry[key.to_sym] = value
77
+ end
78
+
79
+ result[role.to_sym] = normalized_color.freeze
80
+ end
81
+ end
82
+ end
83
+
84
+ register(:yorha, YORHA)
85
+ end
86
+ end
data/lib/yorha/pod.rb ADDED
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+
4
+ require_relative "errors"
5
+
6
+ module Yorha
7
+ class Pod
8
+ # Default voice table from the design document.
9
+ #
10
+ # Adding a voice is adding a hash entry, either by patching this
11
+ # table's successor through {Pod.register_voice} or by registering
12
+ # a new model at runtime.
13
+ #
14
+ # @return [Hash{String => Hash{Symbol => String}}]
15
+ VOICES = {
16
+ "042" => { report: "", propose: "Proposal: ", alert: "Alert: " }.freeze,
17
+ "153" => { report: "Report: ", propose: "Proposal: ", alert: "Warning: " }.freeze
18
+ }.freeze
19
+
20
+ # Numeric severity that Ruby's Logger gives to debug messages.
21
+ #
22
+ # Logger::DEBUG is 0. The number is written here directly so this
23
+ # file never has to load the logger library: the gem has no runtime
24
+ # dependencies, and a delegate with its own level method would
25
+ # otherwise fail with "uninitialized constant Logger" in a program
26
+ # that has not required logger itself.
27
+ #
28
+ # @return [Integer]
29
+ DEBUG_LEVEL = 0
30
+
31
+ @voices = VOICES.dup
32
+
33
+ class << self
34
+ # Registers or replaces a voice for a Pod model.
35
+ #
36
+ # This is the documented extension point for companion gems.
37
+ #
38
+ # @param model [String, Symbol] Pod model identifier
39
+ # @param voice [Hash{Symbol => String}] must define :report,
40
+ # :propose, and :alert prefixes
41
+ # @return [Hash] the frozen stored voice
42
+ # @raise [ArgumentError] when the voice is incomplete
43
+ # @api public
44
+ def register_voice(model, voice)
45
+ unless voice.is_a?(Hash) && %i[report propose alert].all? { |key| voice[key].is_a?(String) }
46
+ raise ArgumentError, "a voice must map :report, :propose, and :alert to Strings"
47
+ end
48
+
49
+ @voices[model.to_s] = { report: voice[:report], propose: voice[:propose], alert: voice[:alert] }.freeze
50
+ end
51
+
52
+ # Checks whether a model has a registered voice.
53
+ #
54
+ # @param model [String, Symbol] Pod model identifier
55
+ # @return [Boolean]
56
+ # @api public
57
+ def voice?(model)
58
+ @voices.key?(model.to_s)
59
+ end
60
+
61
+ # Lists the registered Pod model names.
62
+ #
63
+ # Used to build the error message for an unknown model, and
64
+ # useful for showing callers which models they may pass to
65
+ # {Pod.new}.
66
+ #
67
+ # @return [Array<String>] model names in registration order,
68
+ # for example ["042", "153"]
69
+ # @api public
70
+ def voices
71
+ @voices.keys
72
+ end
73
+
74
+ # @api private
75
+ def voice_for(model)
76
+ @voices.fetch(model)
77
+ end
78
+ end
79
+
80
+ # Creates a Pod with an in-world identity.
81
+ #
82
+ # The stream and delegate are captured at construction; later
83
+ # configuration changes do not rewire an existing Pod.
84
+ #
85
+ # @param model [String, Symbol] "042" or "153", or a registered voice
86
+ # @param io [#write, nil] themed output stream
87
+ # @param delegate [#info, #error, #debug, nil] logger receiving
88
+ # plain text at the fixed severity
89
+ # @return [Pod]
90
+ # @raise [UnknownPodModelError] when the model has no voice
91
+ # @api public
92
+ def initialize(model:, io: nil, delegate: nil)
93
+ @model = model.to_s
94
+
95
+ unless Pod.voice?(@model)
96
+ raise UnknownPodModelError,
97
+ "Unknown Pod model #{@model.inspect}; " \
98
+ "known models: #{Pod.voices.join(', ')}"
99
+ end
100
+
101
+ @io = io || Yorha.config.io
102
+ @delegate = delegate
103
+ end
104
+
105
+ # @return [String] the model identifier
106
+ attr_reader :model
107
+
108
+ # Logs at info severity with the model's report voice.
109
+ #
110
+ # @param message [Object] converted with to_s
111
+ # @return [String] the plain text line forwarded to the delegate
112
+ # @api public
113
+ def report(message)
114
+ emit(:info, :fg, voice[:report], message)
115
+ end
116
+
117
+ # Logs at info severity with the model's propose voice.
118
+ #
119
+ # @param message [Object] converted with to_s
120
+ # @return [String] the plain text line forwarded to the delegate
121
+ # @api public
122
+ def propose(message)
123
+ emit(:info, :accent, voice[:propose], message)
124
+ end
125
+
126
+ # Logs at error severity with the model's alert voice.
127
+ #
128
+ # @param message [Object] converted with to_s
129
+ # @return [String] the plain text line forwarded to the delegate
130
+ # @api public
131
+ def alert(message)
132
+ emit(:error, :danger, voice[:alert], message)
133
+ end
134
+
135
+ # Logs at debug severity in the muted colour, without a voice
136
+ # prefix.
137
+ #
138
+ # Suppressed entirely when a delegate is present and its level is
139
+ # above DEBUG, so Pod never makes a quiet logger noisy.
140
+ #
141
+ # @param message [Object] converted with to_s
142
+ # @return [String, nil] the plain line, or nil when suppressed
143
+ # @api public
144
+ def debug(message)
145
+ return unless debug_enabled?
146
+
147
+ emit(:debug, :muted, "", message)
148
+ end
149
+
150
+ private
151
+
152
+ # @return [Hash{Symbol => String}] this Pod's voice prefixes
153
+ def voice
154
+ Pod.voice_for(@model)
155
+ end
156
+
157
+ # Writes one themed line and forwards one plain line.
158
+ #
159
+ # The delegate always receives plain text; colour applies only to
160
+ # the copy written to io, and only when Render detects a colour
161
+ # TTY.
162
+ #
163
+ # @param severity [Symbol] :info, :error, or :debug
164
+ # @param role [Symbol] palette role for the message text
165
+ # @param prefix [String] voice prefix for this kind of message
166
+ # @param message [Object] converted with to_s
167
+ # @return [String] the plain text line
168
+ def emit(severity, role, prefix, message)
169
+ text = message.to_s
170
+ plain = "POD #{@model}: #{prefix}#{text}"
171
+
172
+ themed =
173
+ "#{Yorha::Render.paint("POD #{@model}:", :accent, io: @io)} " \
174
+ "#{Yorha::Render.paint("#{prefix}#{text}", role, io: @io)}"
175
+
176
+ @io.write("#{themed}\n")
177
+
178
+ if @delegate.respond_to?(severity)
179
+ @delegate.public_send(severity, plain)
180
+ end
181
+
182
+ plain
183
+ end
184
+
185
+ # Decides whether debug output is permitted.
186
+ #
187
+ # Without a delegate, or with a delegate that does not expose a
188
+ # level, debug is shown. With a leveled delegate, it is shown only
189
+ # when the delegate's level is at or below DEBUG_LEVEL, the same
190
+ # number as Logger::DEBUG.
191
+ #
192
+ # @return [Boolean]
193
+ def debug_enabled?
194
+ return true if @delegate.nil?
195
+ return true unless @delegate.respond_to?(:level)
196
+
197
+ @delegate.level <= DEBUG_LEVEL
198
+ end
199
+ end
200
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Themed quotations (Presentation layer).
4
+ #
5
+ # Design document reference: section 5.5, Yorha::Banner and Widgets.
6
+
7
+
8
+ module Yorha
9
+ module Quotes
10
+ # One quotation: the English line and its Japanese pair.
11
+
12
+ Quote = Data.define(:english, :japanese)
13
+
14
+ # Every quotation the gem ships with.
15
+ #
16
+ # @return [Array<Quote>]
17
+ ALL = [
18
+ Quote.new("Memory backup complete.", "記憶のバックアップが完了しました。"),
19
+ Quote.new("All units, report in.", "全ユニット、応答せよ。"),
20
+ Quote.new("The bunker is quiet tonight.", "今夜のバンカーは静かです。"),
21
+ Quote.new("Flowers bloom even in ruins.", "廃墟にも花は咲く。"),
22
+ Quote.new("Maintain the signal.", "信号を維持せよ。"),
23
+ Quote.new("Rest is also a mission.", "休息もまた任務である。"),
24
+ Quote.new("Stand by for the next order.", "次の命令まで待機せよ。"),
25
+ Quote.new("No anomalies detected.", "異常は検出されませんでした。"),
26
+ Quote.new("Every log is a memory worth keeping.", "すべての記録は残す価値のある記憶です。"),
27
+ Quote.new("Connection stable. Proceed.", "接続は安定しています。続行してください。"),
28
+ Quote.new("Systems nominal.", "システムは正常です。"),
29
+ Quote.new("Scanning the area for threats.", "周囲の脅威を走査中。"),
30
+ Quote.new("The sky is clear above the ruins.", "廃墟の上の空は晴れています。"),
31
+ Quote.new("Awaiting your command.", "ご命令をお待ちしています。"),
32
+ Quote.new("Data transfer in progress.", "データ転送中です。"),
33
+ Quote.new("Return to the bunker when ready.", "準備ができたらバンカーへ帰還せよ。"),
34
+ Quote.new("Even machines remember the rain.", "機械でさえ雨を覚えている。"),
35
+ Quote.new("Check your equipment before departure.", "出発前に装備を確認せよ。"),
36
+ Quote.new("A quiet moment is worth protecting.", "静かなひとときは守る価値がある。"),
37
+ Quote.new("Recalibrating sensors.", "センサーを再調整中。"),
38
+ Quote.new("Your orders are confirmed.", "命令を確認しました。"),
39
+ Quote.new("Stay alert. The path ahead is uncertain.", "警戒を怠るな。この先の道は不確かだ。"),
40
+ Quote.new("Every step leaves a trace.", "一歩ごとに足跡が残る。"),
41
+ Quote.new("Backup stored in a safe place.", "バックアップは安全な場所に保存されました。"),
42
+ Quote.new("Mission parameters updated.", "任務の条件が更新されました。"),
43
+ Quote.new("The wind carries distant signals.", "風は遠くの信号を運んでくる。"),
44
+ Quote.new("Patience is part of the mission.", "忍耐も任務の一部である。"),
45
+ Quote.new("All systems are ready for deployment.", "全システム、出撃準備完了。"),
46
+ Quote.new("Diagnostics finished without errors.", "診断はエラーなしで完了しました。"),
47
+ Quote.new("Remember the small things.", "小さなことを忘れないで。"),
48
+ Quote.new("Silence can be a form of reply.", "沈黙もまた一つの返事である。"),
49
+ Quote.new("Power levels are within limits.", "出力は許容範囲内です。"),
50
+ Quote.new("Keep moving. The night is long.", "進み続けよ。夜は長い。"),
51
+ Quote.new("Archive updated. Well done.", "アーカイブを更新しました。よくやりました。"),
52
+ Quote.new("Trust the data, but verify it.", "データを信頼せよ、ただし検証せよ。"),
53
+ Quote.new("Another day, another log entry.", "また一日、また一件の記録。")
54
+ ].freeze
55
+
56
+ class << self
57
+ # Lists every quotation.
58
+
59
+ def all
60
+ ALL
61
+ end
62
+
63
+ # Picks one quotation at random.
64
+ #
65
+
66
+ def pick(random: Random)
67
+ ALL[random.rand(ALL.length)]
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yorha
4
+ module Render
5
+ RESET = "\e[0m"
6
+
7
+ GLYPHS = {
8
+ filled: ["▮", "#"].freeze,
9
+ empty: ["▯", "."].freeze,
10
+ bullet: ["■", "*"].freeze,
11
+ rule: ["─", "-"].freeze,
12
+ vertical: ["│", "|"].freeze,
13
+ top_left: ["┌", "+"].freeze,
14
+ top_right: ["┐", "+"].freeze,
15
+ bottom_left: ["└", "+"].freeze,
16
+ bottom_right: ["┘", "+"].freeze,
17
+ power: ["⏻", "(o)"].freeze
18
+ }.freeze
19
+
20
+ @custom_glyphs = {}
21
+
22
+ class << self
23
+ def paint(text, role = :fg, io: Yorha.config.io)
24
+ plain_text = text.to_s
25
+ depth = Yorha::Terminal.color_depth(io)
26
+
27
+ return plain_text if depth == :none
28
+
29
+ color = color_for(role)
30
+ code = ansi_code(color, depth)
31
+
32
+ return plain_text if code.nil?
33
+
34
+ "\e[#{code}m#{plain_text}#{RESET}"
35
+ rescue StandardError
36
+ plain_text
37
+ end
38
+
39
+ def glyph(name, io: Yorha.config.io)
40
+ pair = @custom_glyphs[name.to_sym] || GLYPHS[name.to_sym]
41
+ return name.to_s if pair.nil?
42
+
43
+ Yorha::Terminal.unicode?(io) ? pair[0] : pair[1]
44
+ rescue StandardError
45
+ name.to_s
46
+ end
47
+
48
+ def register_glyph(name, unicode, ascii)
49
+ @custom_glyphs[name.to_sym] = [
50
+ unicode.to_s,
51
+ ascii.to_s
52
+ ].freeze
53
+ end
54
+
55
+ def rule(width: nil, io: Yorha.config.io)
56
+ selected_width = width || Yorha::Terminal.width(io)
57
+ selected_width = [selected_width.to_i, 0].max
58
+
59
+ glyph(:rule, io: io) * selected_width
60
+ end
61
+
62
+ private
63
+
64
+ def color_for(role)
65
+ role_name = role.respond_to?(:to_sym) ? role.to_sym : :fg
66
+ palette = Yorha::Palette.current
67
+
68
+ palette[role_name] || palette.fetch(:fg)
69
+ end
70
+
71
+ def ansi_code(color, depth)
72
+ case depth
73
+ when :truecolor
74
+ truecolor_code(color[:hex])
75
+ when :ansi256
76
+ "38;5;#{color[:ansi256]}"
77
+ when :ansi16
78
+ color[:ansi16].to_s
79
+ end
80
+ end
81
+
82
+ def truecolor_code(hex)
83
+ value = hex.to_s.delete_prefix("#")
84
+ return nil unless value.match?(/\A[0-9a-fA-F]{6}\z/)
85
+
86
+ red = value[0, 2].to_i(16)
87
+ green = value[2, 2].to_i(16)
88
+ blue = value[4, 2].to_i(16)
89
+
90
+ "38;2;#{red};#{green};#{blue}"
91
+ end
92
+ end
93
+ end
94
+ end