raindown 0.19.0 → 0.21.2

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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/lib/raindown/area.rb +88 -0
  3. data/lib/raindown/chart/drawing.rb +0 -2
  4. data/lib/raindown/chart/line.rb +1 -1
  5. data/lib/raindown/cli.rb +4 -2
  6. data/lib/raindown/config.rb +11 -0
  7. data/lib/raindown/document.rb +7 -3
  8. data/lib/raindown/editing.rb +4 -2
  9. data/lib/raindown/endpoint/curl.rb +0 -1
  10. data/lib/raindown/grid.rb +154 -0
  11. data/lib/raindown/grid_directives.rb +43 -0
  12. data/lib/raindown/grid_wrapping.rb +46 -0
  13. data/lib/raindown/http_json.rb +45 -0
  14. data/lib/raindown/image.rb +44 -0
  15. data/lib/raindown/js/js_nodes.rb +83 -36
  16. data/lib/raindown/js/quickjs_host.rb +63 -0
  17. data/lib/raindown/js/quickjs_runtime.js +61 -0
  18. data/lib/raindown/js/services.js +31 -0
  19. data/lib/raindown/markdown_nodes.rb +2 -0
  20. data/lib/raindown/node_blocks.rb +22 -9
  21. data/lib/raindown/node_injector.rb +56 -17
  22. data/lib/raindown/nodes.rb +50 -15
  23. data/lib/raindown/outdent.rb +100 -0
  24. data/lib/raindown/problem.rb +12 -3
  25. data/lib/raindown/project/card.rb +54 -0
  26. data/lib/raindown/project/endpoint.rb +14 -0
  27. data/lib/raindown/project/project.rb +168 -0
  28. data/lib/raindown/project_nodes.rb +47 -0
  29. data/lib/raindown/rasters.rb +98 -0
  30. data/lib/raindown/scene.rb +10 -0
  31. data/lib/raindown/services/connections.rb +65 -0
  32. data/lib/raindown/services/local.rb +139 -0
  33. data/lib/raindown/services.rb +72 -0
  34. data/lib/raindown/table/table.rb +2 -2
  35. data/lib/raindown/table/table_column.rb +0 -2
  36. data/lib/raindown/table/table_file.rb +0 -1
  37. data/lib/raindown/table/written_table.rb +0 -2
  38. data/lib/raindown/tui/endpoints.rb +1 -1
  39. data/lib/raindown/tui/navigator/navigator.rb +1 -1
  40. data/lib/raindown/watcher/project.rb +2 -2
  41. data/lib/raindown/weather/branch_tree.rb +129 -0
  42. data/lib/raindown/weather/forecast.rb +193 -0
  43. data/lib/raindown/weather/forecast_cache.rb +58 -0
  44. data/lib/raindown/weather/forecast_cards.rb +115 -0
  45. data/lib/raindown/weather/sky.rb +82 -0
  46. data/lib/raindown/weather/weather.rb +140 -0
  47. data/lib/raindown/yjit.rb +20 -0
  48. data/lib/raindown.rb +10 -1
  49. data/lib/version.rb +1 -1
  50. metadata +28 -6
  51. data/lib/raindown/js/host.mjs +0 -51
  52. data/lib/raindown/tui/card.rb +0 -56
  53. data/lib/raindown/tui/endpoint.rb +0 -16
  54. data/lib/raindown/tui/project.rb +0 -147
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9b5aafde0e04b0aa360b2dbafc68d924cdbf5675e3e80728219166c03c3a8ad4
4
- data.tar.gz: 04a815c2fb42f8b756aadab2a183789b53258727900fd44636b602aaa394931f
3
+ metadata.gz: 14386d5918ff2a82381d76226f8d51f2464681836ab62438e9820a5e3622bd98
4
+ data.tar.gz: 5d54b9b4656de75b45333f566f7a6ddd6903ab96611c4edbef98c44b14234b3c
5
5
  SHA512:
6
- metadata.gz: fdb94e3edf51cd99ad3e6dd24f376f420d44c0e17eb5af90f56a2a5809a9da4962cfc72f5759dc30cc2050f76b6c70739726f0e4de598edaaab48a452c9eaac3
7
- data.tar.gz: 51225830c8c64cd5dfb8bde92e2e9244db0a8d2418deaa167c437c0ddc16a4534ca91af90cc8b919dd963fb37040f0a781543d688d8068e447f676aaea177198
6
+ metadata.gz: 953e7b73e969477ec22dba2d0364404a2885ed51e78e3a9607535c303344015b13b40786f344ba60c1aa0803f4e286d2d48cc57a308ed1ffb3aac8b26b779101
7
+ data.tar.gz: 1c3fc1c75e2b0d15cb596c2a0824f5e6ced56da43edd66b9875d6daed8796c22e13f2aeb789cd2762734798ab96ff783b2e885ae66a74a3a2267c5fbaac59a0e
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # The space a Ruby node paints behind its text in an app that draws pixels, given to its rasterize as area:, like a
5
+ # JavaScript Component's, painted in Ruby: its width and height, in pixels, the time, where the text ends on each of
6
+ # its rows, in pixels across, a character's width and height, as cell, its pixels, each set as 0xRRGGBB, one at a time,
7
+ # like area.pixels[x, y] = 0x2e3440, or all at once, with area.pixels = colors, and the buttons it's painted, which,
8
+ # clicked, change the props in set on its node's directive. Its rasterize gives how many milliseconds until it's
9
+ # painted again, like a JavaScript one's, or nothing, for when its size or text changes, which an app makes it wait
10
+ # longer for when painting it takes long, as each time is a trip to Ruby and its pixels back. A pixel it doesn't set
11
+ # shows what's behind it. Its pixels are only made once it paints one, so a node that gives a Scene instead, like
12
+ # weather:, costs nothing.
13
+ class Area
14
+ attr_reader :width, :height, :time, :text_ends, :cell, :buttons
15
+
16
+ def initialize(width:, height:, text_ends: [], cell: [8, 16], time: Time.now)
17
+ @width = width
18
+ @height = height
19
+ @text_ends = text_ends
20
+ @cell = cell
21
+ @time = time
22
+ @buttons = []
23
+ end
24
+
25
+ def pixels
26
+ @pixels ||= Pixels.new(@width, @height)
27
+ end
28
+
29
+ # All its pixels at once, as 0xRRGGBB, across then down, width by height.
30
+ def pixels=(colors)
31
+ @pixels = Pixels.new(@width, @height, colors)
32
+ end
33
+
34
+ # A rectangle it's painted a button, which, clicked, changes the props in set on its node's directive, like
35
+ # { zoom: 8 }, as typing them there would, and only props the directive already has.
36
+ def button(x:, y:, width:, height:, set:)
37
+ @buttons << { x:, y:, width:, height:, set: }
38
+ end
39
+
40
+ # Its pixels as bytes, red, green, blue and alpha for each, those it didn't set clear.
41
+ def to_bytes
42
+ return "\0".b * (@width * @height * 4) unless @pixels
43
+
44
+ @pixels.to_bytes
45
+ end
46
+
47
+ # For an app, its pixels' bytes in Base64, to copy in as they are, its buttons, and how many milliseconds until
48
+ # it's painted again, if it said.
49
+ def to_h(again = nil)
50
+ { painter: 'pixels', width:, height:, pixels: [to_bytes].pack('m0'), buttons:, again: }
51
+ end
52
+
53
+ # An area's pixels, each a colour as 0xRRGGBB, or nil where it's clear.
54
+ class Pixels
55
+ def initialize(width, height, colors = [])
56
+ @width = width
57
+ @height = height
58
+ @colors = Array.new(width * height) { colors[it] }
59
+ end
60
+
61
+ def [](x, y)
62
+ @colors[(y.round * @width) + x.round] if inside?(x.round, y.round)
63
+ end
64
+
65
+ # A pixel, at whole pixels, so a node can give any point, as a pixel between two isn't one, and none outside it.
66
+ def []=(x, y, color)
67
+ x = x.round
68
+ y = y.round
69
+ @colors[(y * @width) + x] = color if inside?(x, y)
70
+ end
71
+
72
+ def to_bytes
73
+ @colors.map { byte_of(it) }.pack('N*')
74
+ end
75
+
76
+ private
77
+
78
+ def inside?(x, y) = x >= 0 && y >= 0 && x < @width && y < @height
79
+
80
+ # A pixel's colour with its alpha, opaque, or clear when it wasn't set.
81
+ def byte_of(color)
82
+ return 0 if color.nil?
83
+
84
+ (color << 8) | 0xff
85
+ end
86
+ end
87
+ end
88
+ end
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'unicode/display_width'
4
-
5
3
  require_relative '../node'
6
4
 
7
5
  module Raindown
@@ -63,7 +63,7 @@ module Raindown
63
63
  from + ((to - from) * step.to_f / steps).round
64
64
  end
65
65
 
66
- def plot(x, y) # rubocop:disable Naming/MethodParameterName -- a dot's coordinates
66
+ def plot(x, y)
67
67
  @cells[y / 4][x / 2] |= DOTS[y % 4][x % 2]
68
68
  end
69
69
 
data/lib/raindown/cli.rb CHANGED
@@ -13,6 +13,7 @@ require_relative 'server'
13
13
  require_relative 'skeleton'
14
14
  require_relative 'watcher/file_watcher'
15
15
  require_relative 'watcher/supervisor'
16
+ require_relative 'yjit'
16
17
 
17
18
  module Raindown
18
19
  module CLI
@@ -81,6 +82,7 @@ module Raindown
81
82
  def self.run(argv)
82
83
  # Markdown is UTF-8 whatever the locale, as an app opened from the Dock, like Obsidian, starts Raindown without one.
83
84
  Encoding.default_external = Encoding::UTF_8
85
+ Yjit.enable
84
86
  return if command(argv) || Skeleton.run_command(argv)
85
87
 
86
88
  argv = with_path(argv)
@@ -166,7 +168,7 @@ module Raindown
166
168
  def render(path, output = nil, bare: false, execute: false)
167
169
  ensure_exists(path)
168
170
  abort('--html renders a file, not a directory') if File.directory?(path)
169
- Nodes.load(path)
171
+ warn(*Nodes.load(path).map { "raindown: #{it}" })
170
172
 
171
173
  metadata = Pages.for(path)
172
174
  rewrite = Rewriter.update(path:, bare:, execute:, metadata:)
@@ -200,7 +202,7 @@ module Raindown
200
202
  ensure_exists(path)
201
203
  return Watcher::Supervisor.new(directory: path, bare:, execute:).start if File.directory?(path)
202
204
 
203
- Nodes.load(path)
205
+ warn(*Nodes.load(path).map { "raindown: #{it}" })
204
206
  Watcher::FileWatcher.new(path:, bare:, execute:).start
205
207
  end
206
208
 
@@ -5,9 +5,11 @@ require 'yaml'
5
5
  module Raindown
6
6
  # A project's settings, from config.yml in its .raindown folder:
7
7
  # highlight_code: false # Code blocks aren't highlighted, so the browser can highlight them instead.
8
+ # kind: notes # What the project's for, code or notes, so an app shows what fits it.
8
9
  module Config
9
10
  FILE = 'config.yml'
10
11
  DEFAULTS = { highlight_code: true }.freeze
12
+ KINDS = %w[code notes].freeze
11
13
 
12
14
  module_function
13
15
 
@@ -20,6 +22,15 @@ module Raindown
20
22
  DEFAULTS.merge(YAML.safe_load_file(file, symbolize_names: true) || {})
21
23
  end
22
24
 
25
+ # The project's kind, code or notes, from kind: in its config, or else code when it's a git repository.
26
+ def kind(root)
27
+ kind = self.for(File.join(root, FILE))[:kind].to_s
28
+ return kind if KINDS.include?(kind)
29
+ return 'code' if File.exist?(File.join(root, '.git'))
30
+
31
+ 'notes'
32
+ end
33
+
23
34
  # The settings for rendering a file, like Raindown.render(**Config.render_options(path)).
24
35
  def render_options(path)
25
36
  self.for(path).slice(:highlight_code)
@@ -6,6 +6,7 @@ require_relative 'code_blocks'
6
6
  require_relative 'endpoint/endpoint_runner'
7
7
  require_relative 'front_matter'
8
8
  require_relative 'node_blocks'
9
+ require_relative 'outdent'
9
10
 
10
11
  module Raindown
11
12
  # A Markdown file's structure, read from its source so each part has the line it's on, for tools like an editor.
@@ -45,7 +46,9 @@ module Raindown
45
46
 
46
47
  def initialize(markdown:, bare: false)
47
48
  @markdown = markdown
48
- @lines = markdown.lines
49
+ # An outdent block's lines are read without their <, so its directives are found as anywhere else.
50
+ @lines = Outdent.without_markers(markdown).lines
51
+ @outdents = Outdent.blocks(markdown.lines)
49
52
  @bare = bare || BareDirectives.front_matter?(markdown)
50
53
  end
51
54
 
@@ -84,8 +87,9 @@ module Raindown
84
87
 
85
88
  def node_directives
86
89
  NodeBlocks.spans(@lines, bare: @bare).map do |span|
87
- output = trimmed(span[:open] + 1, span[:close] ? span[:close] - 1 : span[:last])
88
- directive(span[:name], span[:args], span[:open]..span[:last], output:, writes: span[:writes])
90
+ last = span[:close] ? span[:last] : Outdent.bare_block_last(@outdents, span[:open], span[:last])
91
+ output = trimmed(span[:first], span[:close] ? span[:close] - 1 : last)
92
+ directive(span[:name], span[:args], span[:open]..last, output:, writes: span[:writes])
89
93
  end
90
94
  end
91
95
 
@@ -17,10 +17,12 @@ module Raindown
17
17
  **Config.render_options(path))
18
18
  end
19
19
 
20
+ # Its warnings say why any of the project's nodes couldn't be loaded too.
20
21
  def rewrite_markdown(markdown, path:, bare: false, execute: false)
21
- Nodes.load(path)
22
+ load_errors = Nodes.load(path)
22
23
  rewrite = Rewriter.rewrite(content: markdown, path:, bare:, execute:, metadata: Pages.for(path))
23
- { output: rewrite.content, warnings: rewrite.failures.map { "Endpoint check failed: #{it}" } + rewrite.problems }
24
+ failures = rewrite.failures.map { "Endpoint check failed: #{it}" }
25
+ { output: rewrite.content, warnings: load_errors + failures + rewrite.problems }
24
26
  end
25
27
  end
26
28
  end
@@ -2,7 +2,6 @@
2
2
 
3
3
  require 'open3'
4
4
  require 'shellwords'
5
- require 'uri'
6
5
  require_relative 'curl_request'
7
6
  require_relative 'curl_response'
8
7
 
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'node'
4
+ require_relative 'grid_directives'
5
+ require_relative 'grid_wrapping'
6
+
7
+ module Raindown
8
+ # The node behind grid:, a frame of cells in text, like a page of photos, which editors that draw images in text fill
9
+ # with the image in each cell:
10
+ # grid:
11
+ # +-------------------+------------------+
12
+ # | ![cat](cat.png) | ![dog](dog.png) |
13
+ # | | |
14
+ # +-------------------+------------------+
15
+ # It's written from itself, as it's edited: each | added to a row's line adds a cell to that row, each line added
16
+ # between its rules makes the row taller, each - added to or taken from a rule widens or narrows the grid, and each
17
+ # row's cells share its width, in characters, equally, a cell's text wrapping onto the row's next lines. With
18
+ # cell: :fit, a cell whose text needs more grows into the room the others don't need instead, and widens the grid when
19
+ # there's none. A new grid, with no rules yet, is 80 wide. With width:, it's always width: wide, and a row whose cells
20
+ # need more than that, with cell: :fit, shares it equally, its text wrapping. A cell that starts with a node's
21
+ # directive, like chart: or a project's component, runs it, as GridDirectives does.
22
+ class Grid < Node
23
+ RULE = /\A\s*\+[-+]*\+?\s*\z/
24
+ # A reference definition, like [cat]: pictures/cat.png, which an image like ![cat] in a cell takes its path from.
25
+ DEFINITION = /\A {0,3}\[[^\]]+\]:\s*\S/
26
+ NEW_GRID = [Array.new(3) { ['', ''] }].freeze
27
+ NEW_WIDTH = 80
28
+
29
+ def initialize(width: nil, cell: nil)
30
+ @width = width&.to_i
31
+ @fit = cell.to_s.delete_prefix(':') == 'fit'
32
+ super()
33
+ end
34
+
35
+ def rewrite(written: [], metadata: NoMetadata)
36
+ rows = rows_run(written, metadata)
37
+ widths = widths_of(rows, written)
38
+ lines = [rule(widths.first)]
39
+ rows.each_with_index do |row, index|
40
+ wrapped(row, widths[index]).each { |cells| lines << row_line(cells, widths[index]) }
41
+ lines << rule(widths[index], widths[index + 1])
42
+ end
43
+ lines.join("\n")
44
+ end
45
+
46
+ # Each row as a grid of its cells, sharing its width as the text does, its cells' Markdown rendered, with the note's
47
+ # reference definitions, so a cell's image can be by reference, like ![cat], its path on a line of its own below the
48
+ # grid, like [cat]: cat.png.
49
+ def render(written: [], document: '')
50
+ definitions = document.lines.grep(DEFINITION).join
51
+ rows = rows_of(written)
52
+ rows.zip(widths_of(rows, written)).map { |row, widths| row_html(row, widths, definitions) }.join
53
+ end
54
+
55
+ private
56
+
57
+ # Its rows, with their cells' directives run.
58
+ def rows_run(written, metadata) = rows_of(written).map { GridDirectives.run(it, metadata:) }
59
+
60
+ # The rows between its rules, each line of each as its cells' text, or a new grid when it has none.
61
+ def rows_of(written)
62
+ lines = written.map(&:chomp).reject { it.strip.empty? }
63
+ rows = lines.chunk_while { |line, following| !RULE.match?(line) && !RULE.match?(following) }
64
+ .reject { RULE.match?(it.first) }
65
+ .map { |row| row.map { cells_of(it) } }
66
+ rows.empty? ? NEW_GRID : rows
67
+ end
68
+
69
+ def cells_of(line)
70
+ inner = line.strip.delete_prefix('|').delete_suffix('|')
71
+ inner.split('|', -1).map(&:strip)
72
+ end
73
+
74
+ # Its width, from its rules: the one edited to be longer or shorter than the lines left as they were, or as wide as
75
+ # those lines are, or a new grid's when it has no rules yet. Typing in a cell changes its row's line but never a rule.
76
+ def width_of(written)
77
+ lines = written.map(&:strip).reject(&:empty?)
78
+ rules = lines.grep(RULE).map(&:size)
79
+ return NEW_WIDTH if rules.empty?
80
+
81
+ kept = lines.map { Unicode::DisplayWidth.of(it, emoji: :all) }.tally.max_by(&:last).first
82
+ rules.find { it != kept } || kept
83
+ end
84
+
85
+ # Each row's cells' widths, inside their borders, as wide as width:, or as the grid, or as the widest row's cells need.
86
+ def widths_of(rows, written)
87
+ needs = rows.map { needs_of(it) }
88
+ inner = @width || [width_of(written), *needs.map { it.sum + it.size + 1 }].max
89
+ needs.map { |row| cell_widths(row, inner - row.size - 1) }
90
+ end
91
+
92
+ # The width each of a row's cells needs, inside its borders, for its text and a space either side of it, as it
93
+ # shows, so a wide character, like an emoji, takes the two it does, or none, unless cells fit their text.
94
+ def needs_of(row)
95
+ Array.new(row.map(&:size).max) do |column|
96
+ next 0 unless @fit
97
+
98
+ row.map { Unicode::DisplayWidth.of(" #{it[column]} ", emoji: :all) }.max
99
+ end
100
+ end
101
+
102
+ # The widths of a row's cells, inside their borders, sharing its room equally, but for those whose text needs more,
103
+ # which take what it needs, unless all their text needs more than the room.
104
+ def cell_widths(needs, room, grown = [])
105
+ shared = needs.each_index.to_a - grown
106
+ shares = shares_of(shared, room - needs.values_at(*grown).sum)
107
+ more = shared.select { needs[it] > shares[it] }
108
+ return cell_widths(needs, room, grown + more) if more.any? && needs.sum <= room
109
+
110
+ needs.each_index.map { shares[it] || needs[it] }
111
+ end
112
+
113
+ # The row with its cells' text wrapped to their widths, unless they fit it.
114
+ def wrapped(row, widths)
115
+ return row if @fit && needs_of(row).zip(widths).all? { |need, width| need <= width }
116
+
117
+ GridWrapping.wrapped(row, widths, kept: GridDirectives.columns(row))
118
+ end
119
+
120
+ # Room shared equally among cells, by their indexes, the first a character wider when it doesn't share evenly.
121
+ def shares_of(indexes, room)
122
+ base, extra = [room, indexes.size].max.divmod([indexes.size, 1].max)
123
+ indexes.each_with_index.to_h { |index, at| [index, base + (at < extra ? 1 : 0)] }
124
+ end
125
+
126
+ def row_html(row, widths, definitions)
127
+ cells = widths.each_index.map { |column| row.map { it[column].to_s }.join("\n").strip }
128
+ html_cells = cells.map { "<div>#{Raindown.commonmark("#{it}\n\n#{definitions}")}</div>" }.join
129
+ columns = widths.map { "minmax(0, #{it}fr)" }.join(' ')
130
+ %(<div class="raindown-grid" style="display: grid; grid-template-columns: #{columns}">#{html_cells}</div>)
131
+ end
132
+
133
+ # Each cell padded to its width as it shows, so a wide character, like an emoji, takes the two it does.
134
+ def row_line(cells, widths)
135
+ padded = widths.each_with_index.map do |width, index|
136
+ text = " #{cells[index]}"
137
+ text + (' ' * [width - Unicode::DisplayWidth.of(text, emoji: :all), 0].max)
138
+ end
139
+ "|#{padded.join('|')}|"
140
+ end
141
+
142
+ # A rule, with a + at each edge of the cells of the rows above and below it.
143
+ def rule(above, below = nil)
144
+ edges = [above, below].compact.flat_map { edges_of(it) }.uniq
145
+ line = '-' * (edges.max + 1)
146
+ edges.each { line[it] = '+' }
147
+ line
148
+ end
149
+
150
+ def edges_of(widths)
151
+ widths.reduce([0]) { |edges, width| edges << (edges.last + width + 1) }
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # A grid: row's cells that start with a node's directive, other than a grid, one of Raindown's own, like chart:, or
5
+ # the project's, like a JavaScript Component, which run as anywhere else, writing their output into the cell's lines
6
+ # below them, taking the cell's blank lines at its end, so the row stays as tall as it was if they're enough.
7
+ module GridDirectives
8
+ DIRECTIVE = /\A([A-Za-z][\w-]*):(?=\s|\z)/
9
+
10
+ module_function
11
+
12
+ # The row with each of its cells' directives run, as tall as it was unless one's output needs more lines than its
13
+ # cell has, for the file's metadata, so a project's node has its services.
14
+ def run(row, metadata: NoMetadata)
15
+ cells = Array.new(row.map(&:size).max) { |column| row.map { it[column].to_s } }
16
+ cells = cells.map { written(it, metadata) }
17
+ Array.new(cells.map(&:size).max) { |line| cells.map { it[line].to_s } }
18
+ end
19
+
20
+ # The columns of the row's cells that start with a directive, whose lines are kept as they're wrapped.
21
+ def columns(row)
22
+ row.first.to_a.each_index.select { |column| directive?(row.first[column].to_s) }
23
+ end
24
+
25
+ def written(lines, metadata)
26
+ return lines unless directive?(lines.first.to_s)
27
+
28
+ require_relative 'node_injector'
29
+ written = NodeInjector.rewrite(content: "#{lines.join("\n")}\n", bare: true, metadata:).lines.map(&:chomp)
30
+ written.pop while written.size > lines.size && written.last == ''
31
+ written + Array.new([lines.size - written.size, 0].max, '')
32
+ end
33
+
34
+ # Whether a cell's first line is a node's directive, but a grid's, and not one that only looks like one, like a
35
+ # note's "Note: hi".
36
+ def directive?(line)
37
+ name = line[DIRECTIVE, 1]
38
+ return false if name.nil? || name == 'grid'
39
+
40
+ !Nodes.node_class(name).nil?
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # A grid: row's cells' text wrapped to their widths, unless they fit it.
5
+ module GridWrapping
6
+ module_function
7
+
8
+ # The row with each cell's text wrapped at its spaces to its width: each paragraph, its lines up to a blank one,
9
+ # written again from its words, the row taller when they need more lines, never shorter. A word longer than its cell,
10
+ # like an image's path, runs on past it. The cells in kept, by their columns, keep their lines, like a directive's
11
+ # and its output's, each wrapped on its own, taking blank lines at the cell's end for the lines that adds.
12
+ def wrapped(row, widths, kept: [])
13
+ columns = widths.each_with_index.map do |width, column|
14
+ texts = row.map { it[column].to_s }
15
+ kept.include?(column) ? kept_lines(texts, width - 2) : wrapped_lines(texts, width - 2)
16
+ end
17
+ Array.new([row.size, *columns.map(&:size)].max) { |line| columns.map { it[line] } }
18
+ end
19
+
20
+ def kept_lines(texts, width)
21
+ lines = texts.flat_map { it.empty? ? [it] : lines_of(it, width) }
22
+ lines.pop while lines.size > texts.size && lines.last.empty?
23
+ lines
24
+ end
25
+
26
+ def wrapped_lines(texts, width)
27
+ texts.chunk_while { |line, following| !line.empty? && !following.empty? }.flat_map do |lines|
28
+ next lines if lines.first.empty?
29
+
30
+ lines_of(lines.join(' '), width)
31
+ end
32
+ end
33
+
34
+ # The text's lines, broken at the spaces after its words, each word keeping the spaces after it unless it ends a
35
+ # line, so spaces typed between words, like one before another as a word's typed between two, are kept.
36
+ def lines_of(text, width)
37
+ text.scan(/\S+\s*/).each_with_object([+'']) do |word, lines|
38
+ if lines.last.empty? || Unicode::DisplayWidth.of(lines.last + word.rstrip, emoji: :all) <= width
39
+ lines.last << word
40
+ else
41
+ lines << +word
42
+ end
43
+ end.map(&:rstrip)
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Raindown
6
+ # JSON from the web, for nodes that ask an API, like painting:'s museum and weather:'s forecast, following a redirect
7
+ # or two, and raising an Error when it can't be reached or doesn't answer with JSON. Net::HTTP is loaded when it's
8
+ # first asked, as where there are no sockets, like WebAssembly in the Obsidian plugin, it can't be.
9
+ module HTTPJSON
10
+ TIMEOUT = 10
11
+
12
+ class Error < StandardError; end
13
+
14
+ module_function
15
+
16
+ def get(url, headers: {}, redirects: 3)
17
+ load_web
18
+ json_from(url, headers, redirects)
19
+ end
20
+
21
+ def load_web
22
+ require 'net/http'
23
+ require 'openssl'
24
+ rescue LoadError
25
+ raise Error, "Raindown can't reach the web here"
26
+ end
27
+
28
+ def json_from(url, headers, redirects)
29
+ response = request(URI(url), headers)
30
+ redirect = response.is_a?(Net::HTTPRedirection) && redirects.positive?
31
+ return get(URI.join(url, response['location']).to_s, headers:, redirects: redirects - 1) if redirect
32
+ raise Error, "#{url} answered #{response.code}" unless response.is_a?(Net::HTTPSuccess)
33
+
34
+ JSON.parse(response.body)
35
+ rescue SocketError, SystemCallError, Timeout::Error, JSON::ParserError, OpenSSL::SSL::SSLError => e
36
+ raise Error, "Couldn't reach #{url}: #{e.message}"
37
+ end
38
+
39
+ def request(uri, headers)
40
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: TIMEOUT, read_timeout: TIMEOUT) do |http|
41
+ http.request(Net::HTTP::Get.new(uri, headers))
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cgi/escape'
4
+ require_relative 'node'
5
+ require_relative 'problem'
6
+
7
+ module Raindown
8
+ # The node behind image:, which writes a Markdown image into the file, so it shows wherever Markdown does:
9
+ # image: 'pictures/cat.png' image: 'pictures/cat.png' alt: 'A cat' width: 40
10
+ # The source is a path relative to the note, as Markdown's are, or a URL. Alt describes the image, and is its file's
11
+ # name by default. Width is how many characters wide to show it, in the HTML and in editors that draw images in text,
12
+ # which read it from the directive.
13
+ class Image < Node
14
+ def initialize(source = nil, alt: nil, width: nil)
15
+ @source = source
16
+ @alt = alt
17
+ @width = width
18
+ super()
19
+ end
20
+
21
+ def rewrite
22
+ return Problem.alert('Needs a path to an image or a URL') if ['', nil].include?(@source)
23
+
24
+ "![#{alt}](#{destination})"
25
+ end
26
+
27
+ def render
28
+ return super unless @width
29
+
30
+ %(<p><img src="#{CGI.escapeHTML(@source.to_s)}" alt="#{CGI.escapeHTML(alt)}" style="width: #{@width.to_i}ch"></p>)
31
+ end
32
+
33
+ private
34
+
35
+ def alt
36
+ (@alt || File.basename(@source.to_s, '.*')).delete('[]')
37
+ end
38
+
39
+ # A path with spaces goes in angle brackets, which Markdown allows.
40
+ def destination
41
+ @source.match?(/\s/) ? "<#{@source}>" : @source
42
+ end
43
+ end
44
+ end