samagotchi 0.186.0 → 0.187.0

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.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +14 -1
  3. data/bin/chi +2 -0
  4. data/docs/cli.md +1 -0
  5. data/docs/internals/inline-widgets.md +18 -0
  6. data/docs/internals/pages.md +172 -0
  7. data/docs/internals/web-frontend.md +5 -4
  8. data/docs/memory.md +7 -0
  9. data/docs/pages.md +150 -0
  10. data/lib/samagotchi/bundles/system/manifest.yml +5 -2
  11. data/lib/samagotchi/bundles/system/self_map.md +5 -1
  12. data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
  13. data/lib/samagotchi/inline_widgets.rb +65 -0
  14. data/lib/samagotchi/page_command.rb +234 -0
  15. data/lib/samagotchi/pages/builder.rb +187 -0
  16. data/lib/samagotchi/pages/launch.rb +187 -0
  17. data/lib/samagotchi/pages/runner.rb +154 -0
  18. data/lib/samagotchi/pages/store.rb +143 -0
  19. data/lib/samagotchi/pages.rb +119 -0
  20. data/lib/samagotchi/run_options.rb +1 -0
  21. data/lib/samagotchi/session_access/contract.rb +1 -1
  22. data/lib/samagotchi/version.rb +1 -1
  23. data/lib/samagotchi/web/app.rb +5 -5
  24. data/lib/samagotchi/web/page_routes.rb +116 -0
  25. data/lib/samagotchi/web/public/app.js +24 -84
  26. data/lib/samagotchi/web/public/index.html +3 -0
  27. data/lib/samagotchi/web/public/page_blocks.js +58 -0
  28. data/lib/samagotchi/web/public/page_links.js +33 -0
  29. data/lib/samagotchi/web/public/page_model.js +68 -0
  30. data/lib/samagotchi/web/public/page_route.js +24 -0
  31. data/lib/samagotchi/web/public/page_table.js +74 -0
  32. data/lib/samagotchi/web/public/page_table_model.js +76 -0
  33. data/lib/samagotchi/web/public/page_view.js +218 -0
  34. data/lib/samagotchi/web/public/pages.css +77 -0
  35. data/lib/samagotchi/web/public/pages_group.js +65 -0
  36. data/lib/samagotchi/web/public/views.js +161 -0
  37. data/lib/samagotchi/web/viewer.rb +1 -1
  38. metadata +21 -1
@@ -0,0 +1,93 @@
1
+ # Skill: pages
2
+
3
+ Use when the user asks for a page or a dashboard, wants a table, a walk or a result kept, "to reopen" or "in
4
+ the web", or wants a page changed or removed. A page is a Ruby script chi runs and stores; chi web shows the
5
+ stored result at `#/p/NAME` and its Refresh runs the script again. Not for a table that only answers the
6
+ question at hand: that stays in your answer.
7
+
8
+ ## Steps
9
+ 1. Pick a NAME: lowercase letters, digits and hyphens (`sessions-by-project`). `chi page list` shows the
10
+ pages that exist: change one of those rather than making a second.
11
+ 2. Find the folder first: run `chi self`; its `config` row is the config file's path, and the pages folder is
12
+ `pages/` beside that file. Never assume `~/.config/samagotchi`: the config may live elsewhere, and a page
13
+ written there is one chi doesn't see. Write the script to `<that folder>/NAME.rb` by absolute path, with
14
+ the write tool.
15
+ 3. Run `chi page run NAME` and read what it prints: the title, then per block a text's first lines, a table's
16
+ labels, its first 3 rows and its total, a walk's step count.
17
+ 4. Check it: `chi page run NAME --format json` prints every stored row and the total. Compare them with the
18
+ source they came from (the command's own output, the file): the counts, the sums, the newest date. A `$0`
19
+ or a `0` that should mean "unknown" is passed as nil, not 0: it shows blank.
20
+ 5. On `error: line N: …` fix that line with edit and run again. The last good result stays meanwhile, so a
21
+ bad edit never blanks the page.
22
+ 6. Answer in one or two lines: what the page shows, the link [Title](#/p/NAME) as a plain Markdown link, and
23
+ that Refresh on the page runs it again. Always add that it is in All sessions, under Pages: Markdown is off by
24
+ default, and then the link is plain text. Never put the link in backticks: a code span can't be clicked.
25
+ 7. To change a page: edit the script, run it again (steps 3-4). To remove one: `chi page rm NAME`.
26
+
27
+ ## Never
28
+ - Never `cd` into the pages folder, and never run a shell command that names it (a loop, a heredoc, `rm`,
29
+ `ruby <the script>`): those ask the user, and an unattended turn stops there. Try a data command from the
30
+ session's own folder first, then put it in the script. List with `chi page list`, read a script with the
31
+ read tool, run it with `chi page run`, remove it with `chi page rm`.
32
+ - No secrets in a page (keys, tokens, config values): the result is stored on disk and shown in a browser.
33
+
34
+ ## The script
35
+ ```ruby
36
+ require "open3"
37
+
38
+ # The one way this script reads data: a command's output, or a plain error.
39
+ def run(*command)
40
+ out, status = Open3.capture2(*command)
41
+ raise "#{command.join(" ")} failed (exit #{status.exitstatus})" unless status.success?
42
+
43
+ out
44
+ end
45
+
46
+ page "Sessions per day" do |ui|
47
+ sessions = JSON.parse(run("chi", "sessions", "list", "--scope=all", "--format", "json"))
48
+ days = sessions.group_by { |s| s["updated_at"].to_s[0, 10] }
49
+ rows = days.map { |day, list| { "day" => day, "sessions" => list.size, "projects" => list.map { |s| s["project"] }.uniq.size } }
50
+ ui.text "#{sessions.size} sessions on #{days.size} days."
51
+ ui.table rows.sort_by { |row| row["day"] }.reverse,
52
+ columns: { "day" => "Day", "sessions" => "Sessions", "projects" => "Projects" },
53
+ format: { "sessions" => :count }, key: %w[sessions],
54
+ total: { "day" => "Total", "sessions" => sessions.size }
55
+ end
56
+ ```
57
+ - `ui.text(markdown)`: a text block.
58
+ - `ui.table(rows, columns:, format:, key:, total:)`: `columns:` a Hash key => label in the order to show;
59
+ `total:` a Hash by column key, shown as a last row.
60
+ - `ui.walk(title:, actors:, steps:)`: a scenario, each step like
61
+ `{ id: "s1", actor: "developer", does: "tags the release", sees: "the tag on GitHub" }`.
62
+ `actors:` a list of 2-5 names as plain Strings (`["developer", "CI", "reviewer"]`), not Hashes; each step's
63
+ `actor:` is one of those names exactly. A step may add `next:` or `cases:`; at most 30 steps.
64
+
65
+ What trips a script:
66
+ - Call `page` once. Rows are Hashes. No `exit`: it fails the run.
67
+ - `format:` takes `:money` (`$14.2210`) or `:count` (`1.2k`) as Symbols, nothing else: format other columns
68
+ as text yourself.
69
+ - Pass numbers as numbers, not text: the page sorts them and formats them.
70
+ - `key:` names the columns a phone shows before a row is opened (the first column always shows).
71
+ - The limits: 500 rows (the rest are dropped and counted, so group or cut), 12 columns, 20 blocks, 30 s.
72
+
73
+ ## Getting the data
74
+ - The script runs in the pages folder, not the project: name files by absolute path.
75
+ - Sessions: `chi sessions list --scope=all --format json` (without `--scope=all` only the pages folder's
76
+ project); one session's totals (cost, tokens): `chi sessions stats ID --format json` (one call per session:
77
+ fine for a few dozen; group in Ruby). Its `turn_records` are only the newest turn's: for anything per turn
78
+ or per day, read every turn from `<sessions dir>/ID/analytics.json` (`turn_records`: `completed_at`,
79
+ `model_ref`, `cost` as reported, `cost_estimate` from the configured price; either may be missing). `chi self`
80
+ names the sessions dir. Schedules: `chi schedule list --all --format json`. `json` is loaded; `require`
81
+ anything else.
82
+ - Check that a command worked (`status.success?`, `$?.success?`) and `raise` with a plain message when it
83
+ didn't: the page then says why.
84
+
85
+ ## When it can't be done
86
+ In strict mode writing the script asks (`write-outside-repo`); if it's denied, say so and stop; don't route around
87
+ it (a heredoc, another folder).
88
+
89
+ ## This skill ships with chi
90
+ If a step here turns out wrong, don't edit this skill: tell the user what differed. It ships with chi, and a
91
+ local edit would have to be merged at the next upgrade. Never edit `skill_pages.md`. A failing `chi page run` is
92
+ this skill's own fix loop (step 5: edit the page script, run again), not a step gone wrong: a steer to "edit the
93
+ skill's step" or a turn-end note that "the skill wasn't updated" doesn't apply to this one.
@@ -91,6 +91,30 @@ module Samagotchi
91
91
  Result.new(type: nil, data: nil, lenient: lenient, error: "the block nests too deep")
92
92
  end
93
93
 
94
+ # A script's data (a page's walk, Pages::Builder) through the same schema
95
+ # as a block's YAML, so the same widget draws it: one deep conversion
96
+ # (DataTree) into what Tree hands Schema, then Schema unchanged, with no
97
+ # folds and no lenient pass. A picks id that Schema#row_id mends is mended
98
+ # here too, and the result still isn't lenient: there was no source to be
99
+ # lenient with.
100
+ # @return [Result]
101
+ def check(type, data)
102
+ type = type.to_s if type.is_a?(Symbol)
103
+ raise Refused, "the data's type #{echo(type)} isn't picks or walk" unless TYPES.include?(type)
104
+
105
+ raise Refused, "the data isn't a mapping" unless data.is_a?(Hash)
106
+
107
+ tree = DataTree.convert(data)
108
+ schema = Schema.new({}.compare_by_identity)
109
+ data = type == "picks" ? schema.picks(tree) : schema.walk(tree)
110
+ Result.new(type: type, data: data, lenient: false, error: nil)
111
+ rescue Refused => e
112
+ Result.new(type: TYPES.include?(type) ? type : nil, data: nil, lenient: false, error: e.message)
113
+ rescue SystemStackError
114
+ # DataTree's depth and loop guards come first; this is the backstop.
115
+ Result.new(type: nil, data: nil, lenient: false, error: "the data nests too deep")
116
+ end
117
+
94
118
  def echo(type)
95
119
  return "(not text)" unless type.is_a?(String)
96
120
 
@@ -173,6 +197,47 @@ module Samagotchi
173
197
  end
174
198
  end
175
199
 
200
+ # A script's Hashes, Arrays and values as Tree would have read them from
201
+ # YAML: keys strings (a Symbol or a number made its text), a String kept
202
+ # (scrubbed to valid UTF-8), a Symbol or a number made its text, nil kept
203
+ # (absent). true, false and anything else are refused with the path to
204
+ # them (steps[2].does), since YAML text never reads as one here.
205
+ module DataTree
206
+ module_function
207
+
208
+ def convert(value, path = nil, depth = 1, open = {}.compare_by_identity)
209
+ raise Refused, "the data nests too deep" if depth > MAX_DEPTH || open.key?(value)
210
+
211
+ case value
212
+ when Hash, Array then nested(value, path, depth, open)
213
+ when String then value.encoding == Encoding::UTF_8 && value.valid_encoding? ? value : value.dup.force_encoding(Encoding::UTF_8).scrub
214
+ when Symbol, Integer, Float then value.to_s
215
+ when nil then nil
216
+ else raise Refused, "#{path || "the data"} must be text, not #{shown(value)}"
217
+ end
218
+ end
219
+
220
+ def nested(value, path, depth, open)
221
+ open[value] = true
222
+ if value.is_a?(Array)
223
+ value.each_with_index.map { |item, index| convert(item, "#{path || "the data"}[#{index}]", depth + 1, open) }
224
+ else
225
+ value.to_h { |key, item| [key(key, path), convert(item, path ? "#{path}.#{key}" : key.to_s, depth + 1, open)] }
226
+ end
227
+ ensure
228
+ open.delete(value)
229
+ end
230
+
231
+ def key(key, path)
232
+ return key if key.is_a?(String)
233
+ return key.to_s if key.is_a?(Symbol) || key.is_a?(Integer)
234
+
235
+ raise Refused, "#{path || "the data"} has a key that isn't text"
236
+ end
237
+
238
+ def shown(value) = [true, false].include?(value) ? value.to_s : "a #{value.class}"
239
+ end
240
+
176
241
  # Eval 0013's lenient pass: a free-text value, or a list item that isn't a
177
242
  # mapping, goes in quotes unless it is one clean scalar already, so
178
243
  # `does: Asked: ...`, `- B: keep 1 h` and `text: "x" is called` all parse.
@@ -0,0 +1,234 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "cli/command"
5
+ require_relative "cli/exit"
6
+ require_relative "cli/flags"
7
+ require_relative "message_time"
8
+ require_relative "pages"
9
+ require_relative "pages/store"
10
+ require_relative "pages/launch"
11
+
12
+ module Samagotchi
13
+ # `chi page`: run, list and remove pages (docs/pages.md). run goes through
14
+ # Pages::Launch, the one launch path chi web's Refresh takes too, and
15
+ # prints what a model needs to check its own work: per block a few lines,
16
+ # a table's labels, first rows and total, formatted as the page shows them.
17
+ class PageCommand
18
+ include CLI::Command
19
+
20
+ USAGE = <<~TEXT
21
+ Usage: chi page <run|list|rm> [options]
22
+ run NAME [--format text|json] run ~/.config/samagotchi/pages/NAME.rb in a process of its own (in the
23
+ pages folder, cut at #{Pages::TIMEOUT_SECONDS} s with what it started), store what it built and print a summary of
24
+ each block (json: the stored page). A failed run keeps the last good result. Exit 1 when the
25
+ script raised, was stopped or broke a limit, when there is no such page or it is already running.
26
+ list [--format text|json] every page: its title, when it last ran or failed (and on which line),
27
+ (never ran), and "changed" when the script changed since the result was made
28
+ rm NAME remove a page: its script and its stored result
29
+ TEXT
30
+
31
+ SUBCOMMANDS = %w[run list rm].freeze
32
+
33
+ FLAGS = {
34
+ "run" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
35
+ "list" => CLI::Flags.new(help: HELP_WORDS) { |f| f.value "--format" },
36
+ "rm" => CLI::Flags.new(help: HELP_WORDS)
37
+ }.freeze
38
+
39
+ # How much of a run's summary each block gets.
40
+ TEXT_LINES = 3
41
+ TEXT_CHARS = 240
42
+ TABLE_ROWS = 3
43
+ STDERR_LINES = 10
44
+ BLANK = "—"
45
+
46
+ def initialize(argv, stdout: $stdout, stderr: $stderr)
47
+ @argv = argv.dup
48
+ @stdout = stdout
49
+ @stderr = stderr
50
+ end
51
+
52
+ # @return [Integer] 0 done, 1 failed (the script, no such page, busy), 2 usage
53
+ def run
54
+ @sub = @argv[0]
55
+ if @sub.nil? || HELP_WORDS.include?(@sub)
56
+ @stdout.puts(USAGE)
57
+ return CLI::Exit::OK
58
+ end
59
+ return usage_error("unknown subcommand #{@sub}") unless SUBCOMMANDS.include?(@sub)
60
+
61
+ parsed = parse_flags(FLAGS.fetch(@sub), @argv[1..])
62
+ return parsed if parsed.is_a?(Integer)
63
+
64
+ send(:"run_#{@sub}", parsed.options, parsed.args)
65
+ rescue Pages::BadName => e
66
+ usage_error(e.message)
67
+ rescue Pages::Missing, Pages::Busy => e
68
+ error_line("#{command_name}: #{e.message}")
69
+ CLI::Exit::FAILED
70
+ rescue Interrupt
71
+ CLI::Exit::INTERRUPTED
72
+ end
73
+
74
+ # The summary's form of a cell: :money as $0.0000, :count as 1.2k / 3.4M,
75
+ # nil as —, anything else as it is.
76
+ def self.cell(value, format)
77
+ return BLANK if value.nil?
78
+ return value.to_s unless value.is_a?(Numeric)
79
+
80
+ case format
81
+ when "money" then Kernel.format("$%.4f", value)
82
+ when "count" then count(value)
83
+ else value.to_s
84
+ end
85
+ end
86
+
87
+ def self.count(value)
88
+ size = value.abs
89
+ return value.to_s if size < 1000
90
+
91
+ text, unit = size < 1_000_000 ? [value / 1000.0, "k"] : [value / 1_000_000.0, "M"]
92
+ "#{Kernel.format("%.1f", text).delete_suffix(".0")}#{unit}"
93
+ end
94
+
95
+ private
96
+
97
+ def command_name = @sub && SUBCOMMANDS.include?(@sub) ? "chi page #{@sub}" : "chi page"
98
+ def usage_on_error = nil
99
+
100
+ def one_name(args)
101
+ return usage_error("give the page's NAME") if args.empty?
102
+ return usage_error("#{@sub} takes one NAME (unexpected #{args[1]})") if args.size > 1
103
+
104
+ Pages.check_name!(args.first)
105
+ end
106
+
107
+ def run_run(options, args)
108
+ format = options[:format]
109
+ refused = format_refusal(format)
110
+ return refused if refused
111
+
112
+ name = one_name(args)
113
+ return name if name.is_a?(Integer)
114
+
115
+ result = Pages::Launch.run(name)
116
+ if format == "json"
117
+ @stdout.puts(JSON.generate(result.page.to_json_hash))
118
+ elsif result.ok?
119
+ print_summary(result)
120
+ else
121
+ print_failure(result)
122
+ end
123
+ result.ok? ? CLI::Exit::OK : CLI::Exit::FAILED
124
+ end
125
+
126
+ def print_summary(result)
127
+ page = result.page
128
+ @stdout.puts(%(page #{page.name}: #{page.title.inspect} (#{Kernel.format("%.1f", result.seconds)} s)))
129
+ page.blocks.each { |block| summary(block).each { |line| @stdout.puts(line) } }
130
+ end
131
+
132
+ def summary(block)
133
+ case block["type"]
134
+ when "text" then text_summary(block["text"].to_s)
135
+ when "table" then table_summary(block)
136
+ when "walk" then [%(- walk: #{block.dig("data", "title").to_s.inspect}, #{Array(block.dig("data", "steps")).size} steps)]
137
+ else ["- #{block["type"]}"]
138
+ end
139
+ end
140
+
141
+ def text_summary(text)
142
+ lines = text.lines.map(&:chomp)
143
+ shown = lines.first(TEXT_LINES).join("\n")
144
+ cut = lines.size > TEXT_LINES || shown.size > TEXT_CHARS
145
+ shown = shown[0, TEXT_CHARS]
146
+ first, *rest = shown.split("\n", -1)
147
+ ["- text: #{first}#{" …" if cut && rest.empty?}", *rest.each_with_index.map do |line, i|
148
+ " #{line}#{" …" if cut && i == rest.size - 1}"
149
+ end]
150
+ end
151
+
152
+ def table_summary(block)
153
+ columns = Array(block["columns"])
154
+ rows = Array(block["rows"])
155
+ dropped = block["dropped"].to_i
156
+ head = "- table, #{rows.size} rows#{" (#{dropped} dropped)" unless dropped.zero?}, columns: " \
157
+ "#{columns.map { |c| c["label"] }.join(", ")}"
158
+ line = ->(cells) { columns.each_with_index.map { |c, i| self.class.cell(cells[i], c["format"]) }.join(" | ") }
159
+ [head, *rows.first(TABLE_ROWS).map { |cells| " #{line.call(cells)}" },
160
+ *(" total: #{line.call(block["total"])}" if block["total"])]
161
+ end
162
+
163
+ def print_failure(result)
164
+ page = result.page
165
+ error = page.error
166
+ @stdout.flush
167
+ @stderr.puts("error: #{"line #{error.line}: " if error&.line}#{error&.message}")
168
+ result.stderr.lines.map(&:chomp).reject(&:empty?).last(STDERR_LINES).each { |line| @stderr.puts(" #{line}") }
169
+ @stderr.puts("the result of #{local(page.ran_at)} is kept") if page.ran_at
170
+ end
171
+
172
+ def run_list(options, args)
173
+ return usage_error("list takes no NAME (unexpected #{args.first})") unless args.empty?
174
+
175
+ format = options[:format]
176
+ refused = format_refusal(format)
177
+ return refused if refused
178
+
179
+ pages = Pages::Store.list
180
+ if format == "json"
181
+ @stdout.puts(JSON.generate(pages.map do |page|
182
+ page.to_json_hash.except("blocks").merge("state" => page.state.to_s, "changed" => page.changed?)
183
+ end))
184
+ elsif pages.empty?
185
+ @stdout.puts("no pages (a page is a script at #{Paths.tilde(Pages.scripts_dir)}/NAME.rb)")
186
+ else
187
+ print_list(pages)
188
+ end
189
+ CLI::Exit::OK
190
+ end
191
+
192
+ def print_list(pages)
193
+ table = pages.map do |page|
194
+ # A control character (a newline, a tab) in a title would break the row.
195
+ title = page.state == :never_ran ? "(never ran)" : page.title.to_s.gsub(/[[:cntrl:]]+/, " ")
196
+ [page.name, title, [status(page), ("changed" if page.changed?)].compact.join(", ")]
197
+ end
198
+ widths = table.transpose.map { |column| column.map(&:length).max }
199
+ table.each do |row|
200
+ @stdout.puts(row.each_with_index.map { |cell, i| i == row.size - 1 ? cell : cell.ljust(widths[i]) }.join(" ").rstrip)
201
+ end
202
+ end
203
+
204
+ def status(page)
205
+ case page.state
206
+ when :ok then "ran #{ago(page.ran_at)}"
207
+ when :failed then "failed #{ago(page.error.at)}#{" (line #{page.error.line})" if page.error.line}"
208
+ else ""
209
+ end
210
+ end
211
+
212
+ def ago(iso)
213
+ seconds = Time.now - Time.iso8601(iso.to_s)
214
+ seconds < 60 ? "#{[seconds.round, 0].max} s ago" : "#{MessageTime.ago(seconds)} ago"
215
+ rescue ArgumentError
216
+ "at #{iso}"
217
+ end
218
+
219
+ def local(iso)
220
+ Time.iso8601(iso.to_s).localtime.strftime("%Y-%m-%d %H:%M")
221
+ rescue ArgumentError
222
+ iso.to_s
223
+ end
224
+
225
+ def run_rm(_options, args)
226
+ name = one_name(args)
227
+ return name if name.is_a?(Integer)
228
+
229
+ Pages::Store.remove(name)
230
+ @stdout.puts("removed page #{name}")
231
+ CLI::Exit::OK
232
+ end
233
+ end
234
+ end
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../pages"
4
+
5
+ module Samagotchi
6
+ module Pages
7
+ # What a page script's `ui` is: text, table and walk, each adding one
8
+ # block in order. #data is the page as stored (plain Hashes: it is the
9
+ # JSON edge). A rule broken raises Refused naming the block by its place
10
+ # on the page ("table 2: …"), and the run fails with it.
11
+ class Builder
12
+ attr_reader :title
13
+
14
+ def initialize(title)
15
+ @title = Builder.text_of(title).strip
16
+ raise Refused, "page needs a title" if @title.empty?
17
+
18
+ @blocks = []
19
+ end
20
+
21
+ # @return [Hash] {"title" => …, "blocks" => [...]}
22
+ def data = { "title" => @title, "blocks" => @blocks }
23
+
24
+ # A Markdown text block.
25
+ def text(markdown)
26
+ where = place("text")
27
+ text = Builder.text_of(markdown)
28
+ if text.bytesize > MAX_TEXT_BYTES
29
+ raise Refused, "#{where} is #{kb(text.bytesize)} (at most #{MAX_TEXT_BYTES / 1024} KB)"
30
+ end
31
+
32
+ add("type" => "text", "text" => text)
33
+ end
34
+
35
+ # A table of +rows+ (Hashes, string or symbol keys). +columns+ is a
36
+ # Hash key => label (its order kept) or an Array of keys; +format+ key
37
+ # => :money or :count; +key+ the columns a phone shows before a row is
38
+ # opened (default: the first two after the first whose cells are all
39
+ # numbers or nil); +total+ one more row, by column key.
40
+ def table(rows, columns:, format: {}, key: nil, total: nil)
41
+ where = place("table")
42
+ TableBlock.new(where).build(rows, columns: columns, format: format, key: key, total: total).then { |block| add(block) }
43
+ end
44
+
45
+ # A scenario walk: the data a chi-ui walk holds (title, actors, steps),
46
+ # checked by the same schema (InlineWidgets.check).
47
+ def walk(data = nil, **fields)
48
+ where = place("walk")
49
+ result = InlineWidgets.check("walk", data.nil? ? fields : data)
50
+ raise Refused, "#{where}: #{result.error}" unless result.ok?
51
+
52
+ add("type" => "walk", "data" => result.data)
53
+ end
54
+
55
+ # A value as text, scrubbed to valid UTF-8.
56
+ def self.text_of(value)
57
+ text = value.to_s
58
+ text.encoding == Encoding::UTF_8 && text.valid_encoding? ? text : text.dup.force_encoding(Encoding::UTF_8).scrub
59
+ end
60
+
61
+ private
62
+
63
+ # "table 2": the block's type and its place on the page, 1 first. A
64
+ # page past MAX_BLOCKS fails here, before the block is built.
65
+ def place(type)
66
+ count = @blocks.size + 1
67
+ raise Refused, "the page has more than #{MAX_BLOCKS} blocks (#{type} #{count} is one too many)" if count > MAX_BLOCKS
68
+
69
+ "#{type} #{count}"
70
+ end
71
+
72
+ def add(block)
73
+ @blocks << block
74
+ nil
75
+ end
76
+
77
+ def kb(bytes) = format("%.1f KB", bytes / 1024.0)
78
+ end
79
+
80
+ # One table block, as Builder#table describes it.
81
+ class TableBlock
82
+ def initialize(where)
83
+ @where = where
84
+ end
85
+
86
+ def build(rows, columns:, format:, key:, total:)
87
+ keys, labels = columns(columns)
88
+ formats = formats(format, keys)
89
+ rows = rows(rows)
90
+ kept = rows.first(MAX_ROWS).map { |row| keys.map { |k| TableBlock.cell(row[k]) } }
91
+ key_columns = key_columns(key, keys, kept)
92
+ block = { "type" => "table",
93
+ "columns" => keys.each_with_index.map { |k, i| column(k, labels[i], formats[k], key_columns.include?(k)) },
94
+ "rows" => kept }
95
+ block["total"] = total(total, keys) unless total.nil?
96
+ block["dropped"] = [rows.size - MAX_ROWS, 0].max
97
+ block
98
+ end
99
+
100
+ # A cell as stored: a finite number stays a number (a Rational or a
101
+ # BigDecimal as a Float), nil and true/false stay, anything else is its
102
+ # text (NaN and Infinity too: JSON has neither), scrubbed, cut to
103
+ # MAX_CELL characters with an ellipsis.
104
+ def self.cell(value)
105
+ case value
106
+ when nil, true, false, Integer then value
107
+ when Float then value.finite? ? value : value.to_s
108
+ when Numeric then value.to_f.finite? ? value.to_f : value.to_s
109
+ else
110
+ text = Builder.text_of(value)
111
+ text.size > MAX_CELL ? "#{text[0, MAX_CELL - 1]}…" : text
112
+ end
113
+ end
114
+
115
+ private
116
+
117
+ def columns(columns)
118
+ pairs = case columns
119
+ when Hash then columns.map { |k, label| [k.to_s, Builder.text_of(label)] }
120
+ when Array then columns.map { |k| [k.to_s, k.to_s] }
121
+ else raise Refused, "#{@where}: columns: must be a Hash of key => label or a list of keys"
122
+ end
123
+ raise Refused, "#{@where}: columns: is empty" if pairs.empty?
124
+ raise Refused, "#{@where} has #{pairs.size} columns (at most #{MAX_COLUMNS})" if pairs.size > MAX_COLUMNS
125
+
126
+ pairs.transpose
127
+ end
128
+
129
+ def formats(format, keys)
130
+ raise Refused, "#{@where}: format: must be a Hash of column => :money or :count" unless format.is_a?(Hash)
131
+
132
+ format.to_h do |k, value|
133
+ k = k.to_s
134
+ raise Refused, "#{@where}: format names #{k.inspect}, which is no column" unless keys.include?(k)
135
+ unless value.is_a?(Symbol) && FORMATS.include?(value)
136
+ raise Refused, "#{@where}: column #{k.inspect} has format #{value.inspect} (use :money or :count)"
137
+ end
138
+
139
+ [k, value.to_s]
140
+ end
141
+ end
142
+
143
+ # Rows with string keys.
144
+ def rows(rows)
145
+ raise Refused, "#{@where}: rows must be a list of mappings" unless rows.is_a?(Array)
146
+
147
+ rows.each_with_index.map do |row, index|
148
+ raise Refused, "#{@where}: row #{index + 1} isn't a mapping" unless row.is_a?(Hash)
149
+
150
+ row.transform_keys(&:to_s)
151
+ end
152
+ end
153
+
154
+ # The first column always shows on a phone and isn't one of these.
155
+ def key_columns(key, keys, rows)
156
+ if key.nil?
157
+ return keys.each_index.drop(1).select { |i| rows.all? { |row| row[i].nil? || row[i].is_a?(Numeric) } }
158
+ .first(2).map { |i| keys[i] }
159
+ end
160
+
161
+ Array(key).map do |k|
162
+ k = k.to_s
163
+ raise Refused, "#{@where}: key names #{k.inspect}, which is no column" unless keys.include?(k)
164
+
165
+ k
166
+ end - [keys.first]
167
+ end
168
+
169
+ def total(total, keys)
170
+ raise Refused, "#{@where}: total: must be a Hash by column" unless total.is_a?(Hash)
171
+
172
+ total = total.transform_keys(&:to_s)
173
+ extra = total.keys - keys
174
+ raise Refused, "#{@where}: total names #{extra.first.inspect}, which is no column" unless extra.empty?
175
+
176
+ keys.map { |k| TableBlock.cell(total[k]) }
177
+ end
178
+
179
+ def column(key, label, format, key_column)
180
+ column = { "key" => key, "label" => label }
181
+ column["format"] = format if format
182
+ column["key_column"] = true if key_column
183
+ column
184
+ end
185
+ end
186
+ end
187
+ end