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
@@ -1,60 +1,84 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
- require 'open3'
5
4
 
6
5
  require_relative '../node'
6
+ require_relative '../scene'
7
+ require_relative '../services'
7
8
 
8
9
  module Raindown
9
10
  # JavaScript Components, the .js and .mjs files in a project's .raindown folder, which export classes with rewrite and
10
- # optionally render, like Ruby nodes. They run in a NodeJS process of Raindown's own, started when a folder has them,
11
- # so only projects with JavaScript Components need NodeJS.
11
+ # optionally render, like Ruby nodes. They run in QuickJS, inside Raindown, so they need nothing installed, or in a
12
+ # host of an app's own, like its page. Wherever they run, they get Raindown's services as raindown in their context.
13
+ # A host answers requests, which JSON can hold, with request(**message):
14
+ # { op: 'load', folder } → { nodes: [{ name, render, rasterize, file }], errors: [{ file, error }] }
15
+ # { op: 'call', calls: [{ id, name, args, props, method, context, root }] }
16
+ # → { answers: [{ value } or { error }] }
17
+ # and raises an Error for a request that fails. A call makes its node, with its args and props, the first time its id
18
+ # is called, so a node takes one request, and calls go together, so a note's nodes take one between them.
12
19
  module JSNodes
13
20
  EXTENSIONS = %w[.js .mjs].freeze
14
- SCRIPT = File.join(__dir__, 'host.mjs')
21
+ # Raindown's services for JavaScript nodes, which every host runs before its own script, like an app's page.
22
+ SERVICES = File.join(__dir__, 'services.js')
15
23
 
16
24
  class Error < StandardError; end
17
25
 
18
- # The NodeJS process running the nodes, which answers each request with a line of JSON. NodeJS can't read the script
19
- # inside Raindown's package, so it's passed to node -e.
20
- class Host
21
- def initialize
22
- @input, @output, = Open3.popen2('node', '--input-type=module', '-e', File.read(SCRIPT))
23
- rescue Errno::ENOENT
24
- raise Error, 'JavaScript Components need NodeJS 22 or later on your PATH'
25
- end
26
-
27
- def request(**message)
28
- @input.puts(JSON.generate(message))
29
- reply = JSON.parse(@output.gets || raise(Error, 'NodeJS stopped running the JavaScript Components'))
30
- raise Error, reply['error'] if reply['error']
31
-
32
- reply
33
- end
34
- end
35
-
36
26
  class << self
37
- # A host in place of NodeJS, answering the same requests, like the Obsidian plugin's worker, which runs them itself.
27
+ # A host of an app's own, answering the same requests, like the Obsidian plugin's worker or the desktop app's page.
38
28
  attr_writer :host
39
29
  end
40
30
 
41
31
  module_function
42
32
 
43
- # Loads the JavaScript Components in a .raindown folder, starting NodeJS the first time a folder has any.
33
+ # Loads the JavaScript Components in a .raindown folder, starting their host the first time a folder has any, and
34
+ # gives why any file couldn't be loaded, like ".raindown/sky.mjs: SyntaxError: …", or why none could, when the host
35
+ # couldn't load them, so the folder's other nodes still load.
44
36
  def load(folder)
45
- return if Dir.glob(EXTENSIONS.map { "*#{it}" }, base: folder).empty?
37
+ return [] if Dir.glob(EXTENSIONS.map { "*#{it}" }, base: folder).empty?
46
38
 
47
- host.request(op: 'load', folder:).fetch('nodes').each do |node|
48
- node_classes[node['name']] ||= JSNode.for(name: node['name'], render: node['render'])
49
- end
39
+ reply = host.request(op: 'load', folder:)
40
+ reply.fetch('nodes').each { add(folder, it) }
41
+ reply.fetch('errors', []).map { "#{Nodes::FOLDER}/#{it['file']}: #{it['error']}" }
42
+ rescue Error => e
43
+ ["#{Nodes::FOLDER}: #{e.message}"]
44
+ end
45
+
46
+ # A node as the host described it, unless one of its name is already loaded.
47
+ def add(folder, node)
48
+ file = node['file'] && File.join(folder, node['file'])
49
+ node_classes[node['name']] ||= JSNode.for(name: node['name'], render: node['render'], rasterize: node['rasterize'], file:)
50
50
  end
51
51
 
52
52
  def node_class(name)
53
53
  node_classes[name]
54
54
  end
55
55
 
56
+ # The answers to calls of JavaScript nodes' methods, from JSNode#call_for, asked of their host together: each one's
57
+ # output, or an Error for one that raised.
58
+ def call(calls)
59
+ return [] if calls.empty?
60
+
61
+ host.request(op: 'call', calls:).fetch('answers').map do |answer|
62
+ next Error.new(answer['error']) if answer['error']
63
+
64
+ answer['value'].to_s
65
+ end
66
+ end
67
+
68
+ # The names of the folder's JavaScript Components that rasterize.
69
+ def rasterizing(folder)
70
+ node_classes.select { |_, node| node.method_defined?(:rasterize) && File.dirname(node.file) == folder }.keys
71
+ end
72
+
73
+ # QuickJS, unless an app gives its own. QuickJS is native, so it's only loaded here, not where an app gives its
74
+ # own host, like WebAssembly in the Obsidian plugin, and isn't installed on Windows, where it doesn't build.
56
75
  def host
57
- @host ||= Host.new
76
+ @host ||= begin
77
+ require_relative 'quickjs_host'
78
+ QuickJSHost.new
79
+ end
80
+ rescue LoadError
81
+ raise Error, "JavaScript Components need the quickjs gem, which doesn't build on Windows"
58
82
  end
59
83
 
60
84
  def node_classes
@@ -62,35 +86,58 @@ module Raindown
62
86
  end
63
87
  end
64
88
 
65
- # A JavaScript Component, made in the NodeJS process with its props, where its rewrite and render are sent.
89
+ # A JavaScript Component, made in its host with its props, where its rewrite and render are sent.
66
90
  class JSNode < Node
67
- # A class for each JavaScript Component, which renders its own HTML when the component has render.
68
- def self.for(name:, render:)
91
+ # A class for each JavaScript Component, from its file, which renders its own HTML when the component has render,
92
+ # and rasterizes when it has rasterize.
93
+ def self.for(name:, render:, rasterize: false, file: nil)
69
94
  Class.new(self) do
70
95
  define_singleton_method(:name) { name }
96
+ define_singleton_method(:file) { file }
71
97
  define_method(:render) { |**context| js_output(:render, context) } if render
98
+ define_method(:rasterize) { |metadata: NoMetadata, **| scene(metadata) } if rasterize && file
72
99
  end
73
100
  end
74
101
 
75
102
  def initialize(*args, **props)
76
103
  super()
77
- JSNodes.host.request(op: 'new', id: object_id, name: self.class.name, args:, props:)
104
+ @args = args
105
+ @props = props
78
106
  end
79
107
 
80
108
  def rewrite(**context)
81
109
  js_output(:rewrite, context)
82
110
  end
83
111
 
112
+ # A call of its method, for JSNodes.call, with what its host makes it with the first time, and its project's root,
113
+ # for its services, which its host gives it as raindown.
114
+ def call_for(method, context)
115
+ { id: object_id, name: self.class.name, args: @args, props: @props, method:, root: Services.for(context[:metadata]).root,
116
+ context: json_context(**context) }
117
+ end
118
+
84
119
  private
85
120
 
121
+ # What it shows behind its text, which an app paints by running its rasterize itself, every frame: the node scene,
122
+ # with its file's source, read again each time, so a change shows, its value and props, to make it with, and its
123
+ # project's root, for the services the app gives it as raindown.
124
+ def scene(metadata)
125
+ data = { node: self.class.name, source: File.read(self.class.file), args: @args, props: @props, root: Services.for(metadata).root }
126
+ Scene.new(name: 'node', data:)
127
+ end
128
+
86
129
  def js_output(method, context)
87
- JSNodes.host.request(op: 'call', id: object_id, method:, context: json_context(**context)).fetch('value').to_s
130
+ output = JSNodes.call([call_for(method, context)]).first
131
+ raise output if output.is_a?(JSNodes::Error)
132
+
133
+ output
88
134
  end
89
135
 
90
- # JSON can't hold Pages, so the metadata is its root and each file's front matter and path.
136
+ # JSON can't hold Pages, so the metadata is its root and each file's front matter and path, nor the services, which
137
+ # its host makes again.
91
138
  def json_context(metadata: NoMetadata, **context)
92
139
  root = metadata.root if metadata.respond_to?(:root)
93
- { **context, metadata: { root:, files: metadata.list.map(&:metadata) } }
140
+ { **context.except(:raindown), metadata: { root:, files: metadata.list.map(&:metadata) } }
94
141
  end
95
142
  end
96
143
  end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Raindown
6
+ module JSNodes
7
+ # JavaScript Components run in QuickJS, inside Raindown's own process, so they need nothing installed, answering
8
+ # JSNodes' requests. Like a page, it has no Node APIs, but a node's file can import others by their paths
9
+ # from it, like '../lib/release.mjs', and has setTimeout, URL and TextEncoder, and Raindown's services. What it
10
+ # logs goes to stderr.
11
+ class QuickJSHost
12
+ RUNTIME = %w[services.js quickjs_runtime.js].map { File.join(__dir__, it) }
13
+ # How long a request can run, in milliseconds, its services' time included.
14
+ TIMEOUT = 60_000
15
+
16
+ def initialize
17
+ require 'quickjs'
18
+ @vm = Quickjs::VM.new(features: [Quickjs::FEATURE_TIMEOUT, Quickjs::POLYFILL_URL, Quickjs::POLYFILL_ENCODING],
19
+ timeout_msec: TIMEOUT)
20
+ @vm.module_loader = ->(specifier, importer) { module_of(specifier, importer) }
21
+ @vm.define_function('__raindownService') { |root, name, args| JSON.generate(Services.at(root).call(name, JSON.parse(args))) }
22
+ @vm.on_log { warn it }
23
+ @vm.eval_code(RUNTIME.map { File.read(it) }.join("\n"))
24
+ end
25
+
26
+ def request(**message)
27
+ errors = import(message[:folder]) if message[:op] == 'load'
28
+ reply = JSON.parse(@vm.call('__raindown.request', JSON.generate(sent(message))))
29
+ raise Error, reply['error'] if reply['error']
30
+
31
+ reply.merge('errors' => errors || [])
32
+ rescue Quickjs::RuntimeError => e
33
+ raise Error, e.message
34
+ end
35
+
36
+ private
37
+
38
+ def files(folder) = Dir.glob(EXTENSIONS.map { "*#{it}" }, base: folder).sort.map { File.join(folder, it) }
39
+
40
+ def sent(message)
41
+ return message unless message[:op] == 'load'
42
+
43
+ { op: 'load', files: files(message[:folder]) }
44
+ end
45
+
46
+ # Each of the folder's files, but one that can't be, so the others still load, and why any couldn't be.
47
+ def import(folder)
48
+ files(folder).filter_map do |file|
49
+ @vm.import('* as exports', filename: file, code_to_expose: "__raindown.register(#{JSON.generate(file)}, exports)")
50
+ nil
51
+ rescue Quickjs::RuntimeError => e
52
+ { 'file' => File.basename(file), 'error' => e.message }
53
+ end
54
+ end
55
+
56
+ # A module's source by its path from the file importing it, which must be a file.
57
+ def module_of(specifier, importer)
58
+ path = File.expand_path(specifier, File.dirname(importer.to_s))
59
+ { code: File.read(path), as: path } if File.file?(path)
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,61 @@
1
+ // QuickJS's side of a project's JavaScript Components, which QuickJSHost runs after services.js, answering the same
2
+ // requests as any host, as JSON, through __raindown.request. QuickJSHost imports each file of a folder, registering its
3
+ // exports, then asks to load them. A service is asked of Ruby through __raindownService, which it defines.
4
+ globalThis.__raindown = (() => {
5
+ const classes = {}
6
+ const fileOf = {}
7
+ const exportsOf = {}
8
+ const nodes = {}
9
+ const ask = async (root, name, args) => JSON.parse(__raindownService(root, name, JSON.stringify(args)))
10
+
11
+ const requests = {
12
+ // Every exported class with rewrite in the files is a node, named by its export, or by its class for a default one.
13
+ load({ files }) {
14
+ const loaded = []
15
+ for (const file of files) {
16
+ for (const [name, value] of Object.entries(exportsOf[file] ?? {})) {
17
+ if (typeof value?.prototype?.rewrite !== 'function') continue
18
+ const nodeName = name === 'default' ? value.name : name
19
+ classes[nodeName] = value
20
+ fileOf[nodeName] = file.split('/').at(-1)
21
+ loaded.push(nodeName)
22
+ }
23
+ }
24
+ const described = loaded.map((name) => ({
25
+ name,
26
+ render: typeof classes[name].prototype.render === 'function',
27
+ rasterize: typeof classes[name].prototype.rasterize === 'function',
28
+ file: fileOf[name]
29
+ }))
30
+ return { nodes: described }
31
+ },
32
+
33
+ // Each call makes its node the first time, and answers apart, so one that throws doesn't fail the others.
34
+ async call({ calls }) {
35
+ const answers = calls.map(async ({ id, name, args, props, method, context, root }) => {
36
+ try {
37
+ nodes[id] ??= new classes[name](props, ...args)
38
+ return { value: await nodes[id][method]({ ...context, raindown: raindownServices(root, ask) }) }
39
+ } catch (error) {
40
+ return { error: String(error?.message ?? error) }
41
+ }
42
+ })
43
+ return { answers: await Promise.all(answers) }
44
+ }
45
+ }
46
+
47
+ return {
48
+ register(file, exports) {
49
+ exportsOf[file] = exports
50
+ },
51
+
52
+ async request(json) {
53
+ const message = JSON.parse(json)
54
+ try {
55
+ return JSON.stringify(await requests[message.op](message))
56
+ } catch (error) {
57
+ return JSON.stringify({ error: String(error?.message ?? error) })
58
+ }
59
+ }
60
+ }
61
+ })()
@@ -0,0 +1,31 @@
1
+ // Raindown's services for a JavaScript node, as raindown in its methods' context, the same wherever it runs: in
2
+ // QuickJS in the terminal, an app's page, the Obsidian plugin or a phone. Each asks the host with ask(root, name, args), which
3
+ // answers with a promise, from Raindown::Services on the desktop, so they're all async, and a service a platform hasn't
4
+ // got rejects. A plain script, not a module, so each host can put it before its own code.
5
+ function raindownServices(root, ask) {
6
+ const call = (name, ...args) => ask(root, name, args)
7
+
8
+ return {
9
+ root,
10
+ // { status, headers, body, json() }, its body as text, or as Base64 with encoding: 'base64', for a file that isn't text,
11
+ // like an image.
12
+ fetch: async (url, { method, headers, body, encoding } = {}) => {
13
+ const response = await call('fetch', url, { method, headers, body, encoding })
14
+ return { ...response, json: () => JSON.parse(response.body) }
15
+ },
16
+ // The project's files, by their paths from its root, which they can't leave, read as text, or as Base64 with
17
+ // encoding: 'base64', for a file that isn't text, like an image.
18
+ files: {
19
+ read: (path, { encoding } = {}) => call('read', path, { encoding }),
20
+ list: (pattern = '**/*') => call('list', pattern),
21
+ write: (path, text) => call('write', path, text)
22
+ },
23
+ // Values JSON can hold, kept for the project, for so many seconds, or until they're kept again.
24
+ cache: {
25
+ get: (key) => call('cache_get', key),
26
+ set: (key, value, { seconds } = {}) => call('cache_set', key, value, seconds ?? null)
27
+ },
28
+ // What git writes, run in the project, like git('branch', '--list'), where there's git.
29
+ git: (...args) => call('git', ...args)
30
+ }
31
+ }
@@ -19,11 +19,13 @@ module Raindown
19
19
 
20
20
  module_function
21
21
 
22
+ # Its templates are read as they're written, so loading one can't fail, and there are never errors to give.
22
23
  def load(folder)
23
24
  Dir.glob(EXTENSIONS.map { "*#{it}" }, base: folder).each do |file|
24
25
  name = File.basename(file, '.*')
25
26
  node_classes[name] ||= MarkdownNode.for(name:, path: File.join(folder, file)) if name.match?(NAME)
26
27
  end
28
+ []
27
29
  end
28
30
 
29
31
  # Whether a file is a Markdown Component, by its extension and name, so .raindown/data/blueprints.md isn't one.
@@ -19,7 +19,8 @@ module Raindown
19
19
  # A bare :Changelog is write-in: it only renders, with its render, never its rewrite. In Antlers' delimiters, like
20
20
  # <{ Changelog }>, it's write-in too, and the template pass renders it, as a WriteInNode, so it's only found here
21
21
  # for a document's outline. toc: and list: are Raindown's own nodes. A name only starts a block when it's a loaded
22
- # node, so other text like "Note:" is left alone.
22
+ # node, so other text like "Note:" is left alone. Where bare directives work, a bare grid, a block starting with a
23
+ # rule like +---+, is a grid: without its directive, which it writes from its first line, its rule.
23
24
  module NodeBlocks
24
25
  class MissingEndTag < StandardError; end
25
26
  class BrokenText < StandardError; end
@@ -31,6 +32,7 @@ module Raindown
31
32
  # <{ Card }>, or <{ :Card }>, which a lowercase name like toc needs, as <{ toc }> is a variable.
32
33
  SELF_CLOSING = /\A( {0,3})<\{\s*(?::|(?=[A-Z]))(#{NAME})(?:\s+(.*?))?\s*\}>[ \t]*$/
33
34
  BARE_SELF_CLOSING = /\A( {0,3}):(#{NAME})(?:[ \t]+(.*?))?[ \t]*$/
35
+ BARE_GRID = /\A {0,3}\+-[-+]*\+[ \t]*$/
34
36
  # Unquoted text after name:, like YAML's, runs up to the next prop, so title: Hello world limit: 3 has two. A comma
35
37
  # before the next prop, like data.csv, total: true, separates them like a space, while one in text, like Hello,
36
38
  # world, is part of it.
@@ -43,8 +45,9 @@ module Raindown
43
45
 
44
46
  module_function
45
47
 
46
- # Each block outside code and front matter as { open:, close:, last:, writes:, node: }, where close is nil for a
47
- # bare block, and writes is whether its output's written into the file. A self-closing node is a block of one line.
48
+ # Each block outside code and front matter as { open:, first:, close:, last:, writes:, node: }, where first is the
49
+ # first line it wrote, close is nil for a bare block, and writes is whether its output's written into the file. A
50
+ # self-closing node is a block of one line.
48
51
  def find(lines, front_matter: {}, bare: false)
49
52
  with_nodes(spans(lines, bare:), front_matter)
50
53
  end
@@ -113,15 +116,17 @@ module Raindown
113
116
  end
114
117
 
115
118
  def rendered_lines(lines, block, context)
116
- output = node_markdown(block, context).chomp
119
+ written = Problem.without_alert(lines[block[:first]...(block[:close] || (block[:last] + 1))])
120
+ output = node_markdown(block, context, written:).chomp
117
121
  close = marker(lines[block[:close]]) if block[:close]
118
122
 
119
- [marker(lines[block[:open]]), *("#{output}\n".lines unless output.empty?), *close]
123
+ [*lines[block[:open]...block[:first]].map { marker(it) }, *("#{output}\n".lines unless output.empty?), *close]
120
124
  end
121
125
 
122
- # A node that raises shows why in its place, rather than stopping the page.
123
- def node_markdown(block, context)
124
- return Nodes.rendered(block[:node], context) if !block[:writes] || Nodes.html?(block[:node])
126
+ # A node that raises shows why in its place, rather than stopping the page. A node that renders its own HTML can take
127
+ # written:, its block's lines as they're written in the file, like a grid: drawn from them.
128
+ def node_markdown(block, context, written:)
129
+ return Nodes.rendered(block[:node], context, written:) if !block[:writes] || Nodes.html?(block[:node])
125
130
 
126
131
  Nodes.call(block[:node], :rewrite, **context.to_h).to_s
127
132
  rescue StandardError => e
@@ -133,10 +138,13 @@ module Raindown
133
138
  end
134
139
 
135
140
  def span_at(lines, index, bare:)
141
+ return bare_grid(lines, index) if bare && lines[index].match?(BARE_GRID)
142
+
136
143
  found, pattern = directive(lines[index], bare:)
137
144
  return unless found && (klass = Nodes.node_class(found[2]))
138
145
 
139
- span = { name: found[2], class: klass, args: found[3].to_s, antlers: %i[open self_closing].include?(pattern) }
146
+ span = { name: found[2], class: klass, args: found[3].to_s, antlers: %i[open self_closing].include?(pattern),
147
+ first: index + 1 }
140
148
  case pattern
141
149
  when :open, :comment_open
142
150
  end_tag(lines, index, found[2], comment: pattern == :comment_open)
@@ -159,6 +167,11 @@ module Raindown
159
167
  nil
160
168
  end
161
169
 
170
+ def bare_grid(lines, index)
171
+ grid = { name: 'grid', class: Nodes.node_class('grid'), args: '', antlers: false }
172
+ { **bare_block(lines, index), first: index, writes: true, **grid }
173
+ end
174
+
162
175
  # A bare block holds the lines straight below it, up to the next blank line, with fenced code kept whole.
163
176
  def bare_block(lines, open) = { open:, close: nil, last: CodeBlocks.last_before_blank(lines, open) }
164
177
 
@@ -4,6 +4,7 @@ require_relative '../raindown'
4
4
  require_relative 'bare_directives'
5
5
  require_relative 'front_matter'
6
6
  require_relative 'node_blocks'
7
+ require_relative 'outdent'
7
8
  require_relative 'written'
8
9
 
9
10
  module Raindown
@@ -30,49 +31,87 @@ module Raindown
30
31
  @problems = []
31
32
  @bare = BareDirectives.enabled?(path:, content:, bare:)
32
33
  @metadata = metadata
34
+ @ahead = {}
33
35
  end
34
36
 
37
+ # Outdented blocks' directives are written first, then the rest of the file's.
35
38
  def call
36
- lines = @content.lines
37
- blocks = NodeBlocks.find(lines, front_matter: FrontMatter.parse(@content).first, bare: @bare)
38
- .select { |block| block[:writes] }
39
- return @content if blocks.empty?
39
+ front_matter = FrontMatter.parse(@content).first
40
+ outdented = Outdent.rewrite(@content) { |content, range| write(content, front_matter:, within: range) }
41
+ write(outdented, front_matter:)
42
+ end
43
+
44
+ private
45
+
46
+ # Writes the blocks whose directives are within the range of lines, or all of them.
47
+ def write(content, front_matter:, within: nil)
48
+ lines = content.lines
49
+ blocks = NodeBlocks.find(lines, front_matter:, bare: @bare).select do |block|
50
+ block[:writes] && (within.nil? || within.cover?(block[:open]))
51
+ end
52
+ return content if blocks.empty?
40
53
 
54
+ @ahead = written_ahead(lines, blocks)
41
55
  # From the bottom up, so the lines above each block stay where they are, so its problems are put back in order.
56
+ problems = @problems
57
+ @problems = []
42
58
  blocks.reverse_each { |block| lines[block[:open]..block[:last]] = block_lines(lines, block) }
43
- @problems.reverse!
59
+ @problems = problems + @problems.reverse
44
60
  lines.join
45
61
  end
46
62
 
47
- private
48
-
49
63
  def block_lines(lines, block)
50
- comment, written = comment_and_written(written_lines(lines, block))
51
- # The document as it's written so far, from the bottom up, so a node sees what the nodes below it just wrote, like
52
- # the TOC the headings they write.
53
- context = { document: lines.join, metadata: @metadata, bare: @bare, comment:, written: }
54
- written = written_lines_of(node_written(block, context))
55
- return [line(lines[block[:open]]), *bare(written, block)] unless block[:close]
64
+ written = written_lines_of(node_written(block, context_of(lines, block)))
65
+ return [*directive(lines, block), *bare(written, block)] unless block[:close]
56
66
 
57
67
  delimited(lines, block, written)
58
68
  end
59
69
 
70
+ # The document as it's written so far, from the bottom up, so a node sees what the nodes below it just wrote, like
71
+ # the TOC the headings they write.
72
+ def context_of(lines, block)
73
+ comment, written = comment_and_written(Problem.without_alert(written_lines(lines, block)))
74
+ { document: lines.join, metadata: @metadata, bare: @bare, comment:, written: }
75
+ end
76
+
77
+ # What the JavaScript nodes among the blocks write, by each block's line, asked of their host together, as a request
78
+ # costs about as much as a node. So they see the document as it was before the blocks wrote, not what the nodes
79
+ # below them just wrote. A host that can't be asked leaves each to be asked alone, to say why in its place.
80
+ def written_ahead(lines, blocks)
81
+ ahead = blocks.select { it[:node].is_a?(JSNode) }
82
+ calls = ahead.map { it[:node].call_for(:rewrite, context_of(lines, it)) }
83
+ ahead.map { it[:open] }.zip(JSNodes.call(calls)).to_h
84
+ rescue JSNodes::Error
85
+ {}
86
+ end
87
+
60
88
  # A node that raises writes why in its place, like a Problem, so the rest of the file still writes back.
61
89
  def node_written(block, context)
62
90
  @problems << block[:node].warning if block[:node].is_a?(Problem)
63
- written = Nodes.call(block[:node], :rewrite, **context)
91
+ written = written_by(block, context)
64
92
  return written if written.is_a?(Written)
65
93
 
66
94
  Written.new(written.to_s)
67
95
  rescue StandardError => e
68
96
  problem = Problem.new("Couldn't write: #{e.message}", block[:open] + 1)
69
97
  @problems << problem.warning
70
- Written.new(problem.rewrite)
98
+ Written.new(problem.rewrite(written: context[:written]))
99
+ end
100
+
101
+ # What the block's node writes, as it was asked ahead, or asked now.
102
+ def written_by(block, context)
103
+ output = @ahead.fetch(block[:open]) { return Nodes.call(block[:node], :rewrite, **context) }
104
+ raise output if output.is_a?(JSNodes::Error)
105
+
106
+ output
71
107
  end
72
108
 
73
109
  # The directive, what the node wrote and the end tag, straight after each other, as a comment on its own line ends
74
110
  # at its -->, so what's written below it, like a list, is its own block.
75
- def delimited(lines, block, written) = [line(lines[block[:open]]), *written, line(lines[block[:close]])]
111
+ def delimited(lines, block, written) = [*directive(lines, block), *written, line(lines[block[:close]])]
112
+
113
+ # Its directive's line, or none for a bare grid, which has none.
114
+ def directive(lines, block) = lines[block[:open]...block[:first]].map { line(it) }
76
115
 
77
116
  # A bare block ends at the next blank line, so what it writes can't have one.
78
117
  def bare(written, block)
@@ -100,7 +139,7 @@ module Raindown
100
139
 
101
140
  # What the block's node wrote last time, between its directive and its end tag, or the next blank line.
102
141
  def written_lines(lines, block)
103
- lines[(block[:open] + 1)...(block[:close] || (block[:last] + 1))]
142
+ lines[block[:first]...(block[:close] || (block[:last] + 1))]
104
143
  end
105
144
 
106
145
  def line(line)