raindown 0.5.1 → 0.6.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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/lib/raindown/cli.rb +2 -2
  3. data/lib/raindown/document.rb +15 -4
  4. data/lib/raindown/endpoint/curl.rb +15 -0
  5. data/lib/raindown/projects.rb +8 -4
  6. data/lib/raindown/tui/card.rb +56 -0
  7. data/lib/raindown/tui/endpoint.rb +16 -0
  8. data/lib/raindown/tui/endpoints.rb +40 -0
  9. data/lib/raindown/tui/events.rb +35 -0
  10. data/lib/raindown/tui/file_tree.rb +53 -11
  11. data/lib/raindown/tui/layout.rb +60 -78
  12. data/lib/raindown/tui/menu_overlay.rb +59 -0
  13. data/lib/raindown/tui/navigator/commands.rb +84 -0
  14. data/lib/raindown/tui/navigator/focus.rb +25 -0
  15. data/lib/raindown/tui/navigator/navigator.rb +127 -0
  16. data/lib/raindown/tui/navigator/project_menu.rb +61 -0
  17. data/lib/raindown/tui/navigator/views.rb +49 -0
  18. data/lib/raindown/tui/renderers/dashboard_renderer.rb +102 -0
  19. data/lib/raindown/tui/renderers/endpoint_renderer.rb +77 -0
  20. data/lib/raindown/tui/renderers/list_renderer.rb +15 -0
  21. data/lib/raindown/tui/renderers/outline_renderer.rb +21 -0
  22. data/lib/raindown/tui/renderers/renderer.rb +15 -0
  23. data/lib/raindown/tui/row.rb +10 -3
  24. data/lib/raindown/tui/rows.rb +57 -0
  25. data/lib/raindown/tui/{input.rb → terminal/input.rb} +10 -11
  26. data/lib/raindown/tui/terminal/ncurses_shim.rb +46 -0
  27. data/lib/raindown/tui/terminal/quiet.rb +32 -0
  28. data/lib/raindown/tui/{screen.rb → terminal/screen.rb} +32 -17
  29. data/lib/raindown/tui/terminal/styles.rb +96 -0
  30. data/lib/raindown/tui/text.rb +83 -0
  31. data/lib/raindown/tui/title.rb +29 -0
  32. data/lib/raindown/tui/views/dashboard_view.rb +145 -0
  33. data/lib/raindown/tui/views/endpoint_view.rb +75 -0
  34. data/lib/raindown/tui/{pane.rb → views/list_view.rb} +9 -8
  35. data/lib/raindown/tui/{outline.rb → views/outline_view.rb} +39 -20
  36. data/lib/raindown/tui/workers/project.rb +122 -0
  37. data/lib/raindown/tui/workers/worker.rb +124 -0
  38. data/lib/raindown/tui/workers/workers.rb +53 -0
  39. data/lib/raindown/tui.rb +8 -5
  40. data/lib/version.rb +1 -1
  41. metadata +32 -9
  42. data/lib/raindown/tui/commands.rb +0 -70
  43. data/lib/raindown/tui/navigator.rb +0 -123
  44. data/lib/raindown/tui/styles.rb +0 -36
@@ -11,27 +11,26 @@ module Raindown
11
11
  Curses::KEY_UP => :up, 'k' => :up, Curses::KEY_DOWN => :down, 'j' => :down,
12
12
  Curses::KEY_LEFT => :left, 'h' => :left, Curses::KEY_RIGHT => :right, 'l' => :right,
13
13
  "\t" => :tab, Curses::KEY_BTAB => :tab, "\r" => :enter, "\n" => :enter, Curses::KEY_ENTER => :enter,
14
- ' ' => :toggle, 'x' => :execute, 'e' => :edit, 'w' => :write_back, 'r' => :reload, 'q' => :quit
14
+ ' ' => :toggle, 'x' => :execute, 'e' => :edit, 'w' => :write_back, 'r' => :reload, 'd' => :dashboard,
15
+ 'p' => :projects, "\e" => :escape, 'q' => :quit
15
16
  }.freeze
16
17
 
17
18
  module_function
18
19
 
19
20
  # A key from getch, which is a string for a printable character and otherwise a number.
21
+ # Letters are the same with Shift, as the buttons show them as capitals.
20
22
  def key_event(key)
21
23
  key = key.chr if key.is_a?(Integer) && key < 256
22
- KEYS[key]
24
+ KEYS[key.is_a?(String) ? key.downcase : key]
23
25
  end
24
26
 
25
- # A scroll of the wheel moves the cursor, and a click sends the event of what's under it.
26
- def mouse_event(event, zones)
27
- wheel.find { |button, _| event.bstate.anybits?(button) }&.last || click(zones, column: event.x, row: event.y)
28
- end
27
+ # The mouse buttons that click, which are the left button's. Scrolling does nothing, and since older ncurses,
28
+ # like macOS's, has no button for scrolling down, it can't be mistaken for a click.
29
+ CLICKS = Curses::BUTTON1_PRESSED | Curses::BUTTON1_CLICKED
29
30
 
30
- # Older ncurses has no fifth button, which is the wheel scrolling down.
31
- def wheel
32
- { Curses::BUTTON4_PRESSED => :up }.tap do |buttons|
33
- buttons[Curses::BUTTON5_PRESSED] = :down if Curses.const_defined?(:BUTTON5_PRESSED)
34
- end
31
+ # A click sends the event of what's under it.
32
+ def mouse_event(event, zones)
33
+ click(zones, column: event.x, row: event.y) if event.bstate.anybits?(CLICKS)
35
34
  end
36
35
 
37
36
  # Where each of a Layout's segments with an event is on the screen, as [row, columns, event].
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'curses'
4
+
5
+ module Raindown
6
+ module TUI
7
+ # ncurses before 6.1, like macOS's, repeats a character with the terminal's rep capability by writing one byte of it,
8
+ # so a run of █ in a bar chart draws as ?. Terminals with their own terminfo entries, like Ghostty's and kitty's,
9
+ # have rep, while the system's entries from those ncurses versions don't. So with old ncurses, a terminal whose
10
+ # entry isn't the system's starts curses as xterm-256color, which they draw the same, and TERM is put back after,
11
+ # for the commands run from the screen, like the editor.
12
+ module NcursesShim
13
+ FALLBACK = 'xterm-256color'
14
+ SYSTEM_TERMINFO = %w[/usr/share/terminfo /usr/lib/terminfo /lib/terminfo].freeze
15
+ FIXED_VERSION = [6, 1].freeze
16
+
17
+ module_function
18
+
19
+ def starting(version: Curses::VERSION)
20
+ term = ENV.fetch('TERM', nil)
21
+ ENV['TERM'] = FALLBACK if fallback?(term, version)
22
+ yield
23
+ ensure
24
+ ENV['TERM'] = term
25
+ end
26
+
27
+ def fallback?(term, version)
28
+ return false if term.nil? || term.empty? || term == FALLBACK
29
+
30
+ old?(version) && !system_entry?(term)
31
+ end
32
+
33
+ def old?(version)
34
+ numbers = version.to_s[/ncurses (\d+)\.(\d+)/, 0]&.scan(/\d+/)&.map(&:to_i)
35
+ numbers ? (numbers <=> FIXED_VERSION).negative? : false
36
+ end
37
+
38
+ # Entries are in a folder named by their first letter, or on macOS, its hex code, like 78/xterm-256color.
39
+ def system_entry?(term)
40
+ SYSTEM_TERMINFO.any? do |folder|
41
+ [term[0], term[0].ord.to_s(16)].any? { File.exist?(File.join(folder, it, term)) }
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'stringio'
4
+
5
+ module Raindown
6
+ module TUI
7
+ # Keeps text off the screen while it's up, since it would be written over it, and scroll it from the bottom line.
8
+ module Quiet
9
+ module_function
10
+
11
+ # What's written to stderr while the block runs, like a warning, is written once it's done.
12
+ def holding_stderr
13
+ stderr = $stderr
14
+ $stderr = StringIO.new
15
+ yield
16
+ ensure
17
+ held = $stderr.string
18
+ $stderr = stderr
19
+ $stderr.write(held) unless held.empty?
20
+ end
21
+
22
+ # Ruby's warnings are off while the block runs.
23
+ def quietly
24
+ verbose = $VERBOSE
25
+ $VERBOSE = nil
26
+ yield
27
+ ensure
28
+ $VERBOSE = verbose
29
+ end
30
+ end
31
+ end
32
+ end
@@ -3,7 +3,9 @@
3
3
  require 'curses'
4
4
 
5
5
  require_relative 'input'
6
- require_relative 'layout'
6
+ require_relative '../layout'
7
+ require_relative 'quiet'
8
+ require_relative 'ncurses_shim'
7
9
  require_relative 'styles'
8
10
 
9
11
  module Raindown
@@ -20,14 +22,20 @@ module Raindown
20
22
  end
21
23
 
22
24
  def run
25
+ Quiet.holding_stderr { loop_screen }
26
+ end
27
+
28
+ private
29
+
30
+ def loop_screen
23
31
  start
24
32
 
25
33
  loop do
26
34
  draw
27
- effect = @navigator.handle(read)
35
+ effect = @navigator.next_step(read)
28
36
  break if effect == :quit
29
37
 
30
- perform(*effect) if effect.is_a?(Array)
38
+ perform(effect)
31
39
  end
32
40
  rescue Interrupt
33
41
  nil
@@ -35,23 +43,18 @@ module Raindown
35
43
  stop
36
44
  end
37
45
 
38
- private
39
-
40
- def perform(name, *args)
41
- case name
42
- when :run
43
- suspend { system(*args.first) }
44
- @navigator.ran
45
- when :wait
46
- message, task = args
47
- show(message)
48
- task.call
46
+ # Runs a command, like the editor, then tells the Navigator, or shows a message while a slow task runs.
47
+ def perform(effect)
48
+ case effect
49
+ in Run(command:) then suspend { system(*command) }.then { @navigator.ran }
50
+ in Wait(message:, task:) then show(message).then { task.call }
51
+ else nil
49
52
  end
50
53
  end
51
54
 
52
55
  def start
53
56
  ENV['ESCDELAY'] ||= '25'
54
- Curses.init_screen
57
+ NcursesShim.starting { Curses.init_screen }
55
58
  @styles = Styles.start
56
59
  Curses.noecho
57
60
  Curses.cbreak
@@ -59,7 +62,8 @@ module Raindown
59
62
  Curses.curs_set(0)
60
63
  Curses.stdscr.keypad(true)
61
64
  Curses.stdscr.timeout = TICK
62
- Curses.mousemask(Curses::BUTTON1_PRESSED | Curses::BUTTON1_CLICKED | Input.wheel.keys.sum)
65
+ # The terminal sends the app its mouse events, so scrolling doesn't scroll the terminal either.
66
+ Curses.mousemask(Input::CLICKS)
63
67
  Curses.mouseinterval(0)
64
68
  end
65
69
 
@@ -80,9 +84,19 @@ module Raindown
80
84
  segments.each { |segment| paint(window, segment) }
81
85
  end
82
86
 
87
+ repaint_title(lines.first, window)
83
88
  window.refresh
84
89
  end
85
90
 
91
+ # The title's rain cloud is one column to ncurses, and two in terminals like iTerm and kitty, which would put
92
+ # the rest of the title a column out when ncurses changes part of it. So when it changes, the screen is
93
+ # repainted, and the title is written in one go.
94
+ def repaint_title(title, window)
95
+ text = title&.map(&:text)&.join
96
+ window.redraw if @title && text != @title
97
+ @title = text
98
+ end
99
+
86
100
  def paint(window, segment)
87
101
  window.attron(@styles.fetch(segment.style, Curses::A_NORMAL)) { window.addstr(segment.text) }
88
102
  end
@@ -102,8 +116,9 @@ module Raindown
102
116
  Input.key_event(key)
103
117
  end
104
118
 
119
+ # The curses gem warns the first time it makes a MouseEvent, that it's "undefining the allocator" of the class.
105
120
  def mouse
106
- event = Curses.getmouse
121
+ event = Quiet.quietly { Curses.getmouse }
107
122
  Input.mouse_event(event, @zones) if event
108
123
  end
109
124
 
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'curses'
4
+
5
+ module Raindown
6
+ module TUI
7
+ # The curses attributes of a Layout's styles. The title is white on blue, and the selected row white on a lighter
8
+ # blue, or on dark grey in the panes without the focus, while other colours are on the terminal's own background.
9
+ # With only 8 colours, there's no dark grey, so those rows are underlined, and without colours,
10
+ # the rest are in reverse.
11
+ module Styles
12
+ COLORS = { directive: Curses::COLOR_CYAN, button: Curses::COLOR_YELLOW, error: Curses::COLOR_RED,
13
+ folder: Curses::COLOR_BLUE }.freeze
14
+ # The colours of endpoints' HTTP methods, like GET in green, from the 256 colours most terminals have,
15
+ # which are the same in every theme, unlike the 8 they all do, where green can look yellow.
16
+ METHODS = { get: 40, post: 33, delete: 196, put: 220, patch: 171, head: 44, options: 44 }.freeze
17
+ BASIC_METHODS = { get: Curses::COLOR_GREEN, post: Curses::COLOR_BLUE, delete: Curses::COLOR_RED,
18
+ put: Curses::COLOR_YELLOW, patch: Curses::COLOR_MAGENTA, head: Curses::COLOR_CYAN,
19
+ options: Curses::COLOR_CYAN }.freeze
20
+ # The title's and the selected row's blues, from the 256 colours most terminals have, or the 8 they all do.
21
+ BLUES = { title: 25, selected: 33 }.freeze
22
+ BASIC_BLUES = { title: Curses::COLOR_BLUE, selected: Curses::COLOR_CYAN }.freeze
23
+ BRIGHT_WHITE = 15
24
+ DARK_GREY = 238
25
+
26
+ module_function
27
+
28
+ # Sets up the colours, once the screen has started, and returns the attribute of each style.
29
+ def start
30
+ return plain unless Curses.has_colors?
31
+
32
+ start_colors
33
+ colored
34
+ end
35
+
36
+ def plain
37
+ { title: Curses::A_REVERSE | Curses::A_BOLD, selected: Curses::A_REVERSE, selected_button: Curses::A_REVERSE,
38
+ cursor: Curses::A_UNDERLINE, cursor_button: Curses::A_UNDERLINE | Curses::A_BOLD, heading: Curses::A_BOLD,
39
+ body: Curses::A_DIM, error: Curses::A_BOLD, button: Curses::A_BOLD, folder: Curses::A_BOLD, project: Curses::A_BOLD, dashboard: Curses::A_BOLD,
40
+ key: Curses::A_REVERSE, border: Curses::A_DIM, run: Curses::A_REVERSE | Curses::A_BOLD, divider: Curses::A_BOLD,
41
+ selected_divider: Curses::A_REVERSE, cursor_divider: Curses::A_BOLD }
42
+ end
43
+
44
+ def colored
45
+ plain.merge(
46
+ title: pair(:title) | Curses::A_BOLD, selected: pair(:selected) | white_bold,
47
+ selected_button: pair(:selected_button) | Curses::A_BOLD, directive: pair(:directive),
48
+ error: pair(:error) | Curses::A_BOLD, button: pair(:button) | Curses::A_BOLD, divider: pair(:divider),
49
+ selected_divider: pair(:selected_divider), run: pair(:run) | Curses::A_BOLD, **files, **unfocused
50
+ )
51
+ end
52
+
53
+ def files
54
+ { folder: pair(:folder) | Curses::A_BOLD, project: pair(:directive) | Curses::A_BOLD,
55
+ dashboard: pair(:directive) | Curses::A_BOLD, **METHODS.keys.to_h { [:"method_#{it}", pair(:"method_#{it}") | Curses::A_BOLD] } }
56
+ end
57
+
58
+ # The selected rows of the panes without the focus, on dark grey where there's one.
59
+ def unfocused
60
+ return { cursor_button: pair(:button) | Curses::A_BOLD, cursor_divider: pair(:divider) } unless Curses.colors >= 256
61
+
62
+ { cursor: pair(:cursor), cursor_button: pair(:cursor_button) | Curses::A_BOLD, cursor_divider: pair(:cursor_divider) }
63
+ end
64
+
65
+ # Each colour pair as [name, foreground, background], where -1 is the terminal's own background.
66
+ def pairs
67
+ many = Curses.colors >= 256
68
+ blues = many ? BLUES : BASIC_BLUES
69
+ white = many ? BRIGHT_WHITE : Curses::COLOR_WHITE
70
+
71
+ [*COLORS.map { |name, color| [name, color, -1] },
72
+ *(many ? METHODS : BASIC_METHODS).map { |name, color| [:"method_#{name}", color, -1] },
73
+ [:title, white, blues[:title]],
74
+ [:selected, white, blues[:selected]], [:selected_button, Curses::COLOR_YELLOW, blues[:selected]],
75
+ [:cursor, white, DARK_GREY], [:cursor_button, Curses::COLOR_YELLOW, DARK_GREY], [:divider, blues[:title], -1],
76
+ [:selected_divider, blues[:title], blues[:selected]], [:cursor_divider, blues[:title], DARK_GREY],
77
+ [:run, white, Curses::COLOR_GREEN]]
78
+ end
79
+
80
+ def pair(name)
81
+ Curses.color_pair(pairs.index { it.first == name } + 1)
82
+ end
83
+
84
+ # The 8 colour white is grey, which bold brightens.
85
+ def white_bold
86
+ Curses.colors >= 256 ? Curses::A_NORMAL : Curses::A_BOLD
87
+ end
88
+
89
+ def start_colors
90
+ Curses.start_color
91
+ Curses.use_default_colors
92
+ pairs.each.with_index(1) { |(_name, foreground, background), index| Curses.init_pair(index, foreground, background) }
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'unicode/display_width'
4
+
5
+ module Raindown
6
+ module TUI
7
+ # Text measured in a terminal's columns, where a wide character like 界 takes two, cut to fit them in styled Segments.
8
+ module Text
9
+ Segment = Data.define(:text, :style, :event)
10
+ INDENT = ' '
11
+
12
+ private
13
+
14
+ # A path from the home folder when it's in it, like ~/dev/raindown.
15
+ def from_home(path)
16
+ home = Dir.home
17
+ path == home || path.start_with?(File.join(home, '')) ? path.sub(home, '~') : path
18
+ rescue ArgumentError
19
+ path
20
+ end
21
+
22
+ # The text fit to the width, as a Segment in the style.
23
+ def segment(text, style, width: self.width, event: nil)
24
+ Segment.new(text: fit(printable(text), width), style:, event:)
25
+ end
26
+
27
+ # Text cut or padded to the width, with a cut shown by an ellipsis.
28
+ def fit(text, width)
29
+ return '' if width <= 0
30
+ return text + (' ' * (width - display_width(text))) if display_width(text) <= width
31
+
32
+ cut = +''
33
+ cut_width = 0
34
+ text.each_char do |char|
35
+ break if cut_width + display_width(char) > width - 1
36
+
37
+ cut << char
38
+ cut_width += display_width(char)
39
+ end
40
+ "#{cut}…#{' ' * (width - 1 - cut_width)}"
41
+ end
42
+
43
+ # The widths of texts side by side in a width: each as wide as it is, and the last as wide as what's left,
44
+ # with none past the width.
45
+ def spread(texts, width)
46
+ texts.each_with_index.map do |text, index|
47
+ part = index == texts.length - 1 ? width : [display_width(text), width].min
48
+ width -= part
49
+ part
50
+ end
51
+ end
52
+
53
+ # The line's segments, with others drawn over its columns from the column on, like a box over the screen.
54
+ def overlay_segments(line, segments, column:)
55
+ width = segments.sum { display_width(it.text) }
56
+ [*segments_between(line, 0, column), *segments, *segments_between(line, column + width, Float::INFINITY)]
57
+ end
58
+
59
+ # The parts of the line's segments between two columns, where a wide character cut in two leaves spaces.
60
+ def segments_between(line, from, to)
61
+ column = 0
62
+ line.filter_map do |segment|
63
+ text = segment.text.each_char.map do |char|
64
+ start = column
65
+ column += display_width(char)
66
+ overlap = [column, to].min - [start, from].max
67
+ overlap == display_width(char) ? char : ' ' * [overlap, 0].max
68
+ end.join
69
+ segment.with(text:) unless text.empty?
70
+ end
71
+ end
72
+
73
+ # Tabs and control characters, like in a directive's output, would move the terminal's cursor.
74
+ def printable(text)
75
+ text.gsub("\t", INDENT).gsub(/[[:cntrl:]]/, '')
76
+ end
77
+
78
+ def display_width(text)
79
+ Unicode::DisplayWidth.of(text)
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ module TUI
5
+ # A Layout's title line: Raindown's name, the folder the files are shown from, and the page.
6
+ module Title
7
+ # The rain cloud without the emoji variation selector, like the nav's projects, which terminals draw one column wide,
8
+ # as it's measured, so the title line reaches the edge.
9
+ NAME = '🌧 Raindown'
10
+
11
+ private
12
+
13
+ # The name, the folder, which opens the project menu when there's more than one project, and the page.
14
+ def title
15
+ parts = [[name, nil], ["#{location}#{' ▾' if navigator.projects?}", (:projects if navigator.projects?)],
16
+ [" › #{view_renderer.page}", nil]]
17
+
18
+ parts.zip(spread(parts.map(&:first), width)).map do |(text, event), part_width|
19
+ segment(text, :title, width: part_width, event:)
20
+ end
21
+ end
22
+
23
+ def name = " #{NAME} "
24
+
25
+ # The folder the files are shown from.
26
+ def location = from_home(navigator.base)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,145 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../events'
4
+
5
+ module Raindown
6
+ module TUI
7
+ # Every chart in the projects' Markdown files, drawn from its data by its project's Worker, as cards in a grid
8
+ # with a cursor. A chart is a chart: directive, or a project's own node that's a Raindown::Chart,
9
+ # like "Sales < Raindown::Chart". Charts are drawn again every few seconds, so they follow changes to their data,
10
+ # like a CSV file, without a save.
11
+ # A key's next step, for the Navigator, is nil, or an Open or Edit of a chart's directive.
12
+ class DashboardView
13
+ # Seconds between drawing the charts again.
14
+ REDRAW = 2
15
+ MOVES = %i[up down left right].freeze
16
+ # Columns between the cards, and the narrowest a card is, with its border.
17
+ GAP = 2
18
+ MIN_CARD_WIDTH = 28
19
+
20
+ attr_reader :root, :errors, :cursor, :project
21
+
22
+ def initialize(root:, workers:)
23
+ @root = root
24
+ @workers = workers
25
+ @cursor = 0
26
+ @offset = 0
27
+ @rows = []
28
+ end
29
+
30
+ def renderer = DashboardRenderer
31
+ def target = self
32
+ def path = nil
33
+ def changed? = false
34
+
35
+ def status(_navigator)
36
+ found = "#{charts.length} #{charts.length == 1 ? 'chart' : 'charts'} in #{File.basename(project || root)}"
37
+ errors.empty? ? [:info, found] : [:error, "#{found}, but couldn't read #{errors.join(', ')}"]
38
+ end
39
+
40
+ # Finds the charts again, like when it's opened, or a file is saved or added.
41
+ def load
42
+ draw(find: true)
43
+ @cursor = @cursor.clamp(0, [charts.length - 1, 0].max)
44
+ end
45
+
46
+ # The charts, as each project's Worker drew them, of the project they're narrowed to, if any.
47
+ def charts
48
+ project ? @cards.select { it.project == project } : @cards
49
+ end
50
+
51
+ # Narrows the charts to a project's, or with nil, shows every project's.
52
+ def project=(project)
53
+ @project = project
54
+ @cursor = 0
55
+ @offset = 0
56
+ end
57
+
58
+ def cards
59
+ draw if Process.clock_gettime(Process::CLOCK_MONOTONIC) - @drawn_at >= REDRAW
60
+ charts
61
+ end
62
+
63
+ # The charts' indexes in rows, as many of a project's as fit across the width after a column of margin, with each
64
+ # project's charts starting a row. They're kept, so up and down move a row.
65
+ def rows(width)
66
+ @rows = charts.each_index.chunk_while { |a, b| charts[a].project == charts[b].project }.flat_map { group_rows(it, width) }
67
+ end
68
+
69
+ # The widths a card can be: no narrower than MIN_CARD_WIDTH, when there's room, and no wider than the width.
70
+ def card_widths(width) = [MIN_CARD_WIDTH, width - 1].min..(width - 1)
71
+
72
+ def selected = charts[@cursor]
73
+
74
+ def first_in_row?
75
+ @rows.empty? || @rows.any? { it.first == @cursor }
76
+ end
77
+
78
+ # Every key but Tab to the files, or left from the first card in a row.
79
+ def next_step?(key) = !%i[tab tick].include?(key) && !(key == :left && first_in_row?)
80
+
81
+ def next_step(key)
82
+ chart = selected
83
+ case key
84
+ when *MOVES then move(key).then { nil }
85
+ when :enter then chart && Open.new(path: chart.path, line: chart.line)
86
+ when :edit then chart && Edit.new(path: chart.path, line: chart.line)
87
+ when :reload then load.then { nil }
88
+ end
89
+ end
90
+
91
+ def cursor=(index)
92
+ @cursor = index.clamp(0, [charts.length - 1, 0].max)
93
+ end
94
+
95
+ # The first row of cards to show, given each row's height, scrolled so the cursor's row is shown.
96
+ def scroll(row_heights, height)
97
+ row = row_of(@cursor)
98
+ @offset = row if row < @offset
99
+ @offset += 1 while @offset < row && row_heights[@offset..row].sum > height
100
+ @offset = @offset.clamp(0, [row_heights.length - 1, 0].max)
101
+ end
102
+
103
+ private
104
+
105
+ def draw(find: false)
106
+ @cards = []
107
+ @errors = []
108
+ @workers.each do |worker|
109
+ answer = worker.call(:charts, find:)
110
+ @cards.concat(answer[:cards])
111
+ @errors.concat(answer[:errors])
112
+ rescue Worker::Error => e
113
+ @errors << "#{File.basename(worker.root)}: #{e.message}"
114
+ end
115
+ @cards.sort_by! { [it.project, it.path, it.line] }
116
+ @drawn_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
117
+ end
118
+
119
+ def group_rows(indexes, width)
120
+ indexes.each_with_object([[]]) do |index, rows|
121
+ rows << [] if rows.last.any? && row_width(rows.last + [index], width) > width
122
+ rows.last << index
123
+ end
124
+ end
125
+
126
+ # A row of cards' width, after a column of margin, with a gap between each.
127
+ def row_width(row, width)
128
+ 1 + row.sum { charts[it].box_width(within: card_widths(width)) } + (GAP * (row.length - 1))
129
+ end
130
+
131
+ # Left and right move along the cards, and up and down to the card in the same place in the row above or below.
132
+ def move(name)
133
+ return self.cursor = @cursor + (name == :left ? -1 : 1) if %i[left right].include?(name)
134
+
135
+ row = row_of(@cursor)
136
+ target = @rows[(row + (name == :up ? -1 : 1)).clamp(0, [@rows.length - 1, 0].max)]
137
+ self.cursor = target ? target[[@rows[row].index(@cursor), target.length - 1].min] : @cursor
138
+ end
139
+
140
+ def row_of(index)
141
+ @rows.index { it.include?(index) } || 0
142
+ end
143
+ end
144
+ end
145
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../events'
4
+ require_relative '../workers/worker'
5
+
6
+ module Raindown
7
+ module TUI
8
+ # An endpoint opened from the files, beside them: its request, and the response its file has, read by its project's
9
+ # Worker when it's opened, which scrolls.
10
+ # A key's next step, for the Navigator, is nil, an Open or Edit of its directive, or an Execute of it.
11
+ class EndpointView
12
+ # The date a response was fetched, on the line after it.
13
+ FETCHED = /raindown:fetched (\S+)/
14
+ FENCE = /\A\s*`{3,}(\S*)/
15
+
16
+ attr_reader :endpoint, :response, :language, :fetched, :error
17
+
18
+ def initialize(endpoint, workers:)
19
+ @endpoint = endpoint
20
+ @workers = workers
21
+ @offset = 0
22
+ end
23
+
24
+ def renderer = EndpointRenderer
25
+ def target = endpoint
26
+ def path = endpoint.path
27
+ def status(_navigator) = [:info, endpoint.text]
28
+ def changed? = false
29
+ def next_step?(key) = %i[up down enter edit execute].include?(key)
30
+
31
+ # Clicks on the response only move the focus to it.
32
+ def cursor=(_index); end
33
+
34
+ # Reads the response again, like after the request's run.
35
+ def load
36
+ lines = output_lines
37
+ @fetched = lines.pop[FETCHED, 1] if lines.last&.match?(FETCHED)
38
+ @language = lines.first.to_s[FENCE, 1]
39
+ @response = @language ? lines[1...-1] : lines
40
+ @error = nil
41
+ rescue Worker::Error => e
42
+ @response = []
43
+ @error = e.message
44
+ end
45
+
46
+ def next_step(key)
47
+ case key
48
+ when :up, :down then scroll(key == :up ? -1 : 1)
49
+ when :enter then Open.new(path: endpoint.path, line: endpoint.line)
50
+ when :edit then Edit.new(path: endpoint.path, line: endpoint.line)
51
+ when :execute then Execute.new(path: endpoint.path, line: endpoint.line, name: endpoint.text)
52
+ end
53
+ end
54
+
55
+ # The response's lines that fit in the height, from where it's scrolled to.
56
+ def visible(height)
57
+ @offset = @offset.clamp(0, [response.length - height, 0].max)
58
+ response[@offset, height] || []
59
+ end
60
+
61
+ private
62
+
63
+ def output_lines
64
+ outline = @workers.for(path).call(:outline, path)
65
+ directive = outline.directives.find { it.endpoint? && it.line == endpoint.line }
66
+ directive&.output ? outline.lines[(directive.output.begin - 1)...directive.output.end] : []
67
+ end
68
+
69
+ def scroll(by)
70
+ @offset += by
71
+ nil
72
+ end
73
+ end
74
+ end
75
+ end