raindown 0.22.0 → 0.24.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 96b04a893baf519b6fe2a26bb1d4a27c90a030e7b0be6d754696860495db7e08
4
- data.tar.gz: 5f43ba40f8569ae40697c3207fec8fc698328d28089502177c55d63471218323
3
+ metadata.gz: 0f3b834e7a8b9d814671cf9933f6098c256506d62b9732c56f0b9fa6f7c551fc
4
+ data.tar.gz: b6774b87bf5aac5d9b3441132b317471cfaf5f2d86c016161440cd067c8916ee
5
5
  SHA512:
6
- metadata.gz: 63b1e3a97e370a10ac1880aa108263b89d862244804c886f0d729c2f5e3dcaf3ae53abfeda7ce81c8fd13212207de6cce89d3f9a7eaf5621fe1deef9462f3e75
7
- data.tar.gz: 2c8f75f680a003171854195b33d37e82c532858d0f5d82547750a2af24066eadedc445a1ca31a7e3fb22e14d0da56b7d7126758f939abe4ebf4ed4b0167b5a19
6
+ metadata.gz: 5d4b2140306944e1a4e3594c0e2d08ae21c347aea5b774975019899b66108bd998814690dafd80fe29d7ecec46c378272e549d166d4c86376085de7d073bff22
7
+ data.tar.gz: d89db7996b541065249cd15f948c16e6827024bfa3cf38db49f9bbddb9a1648895077d261156e69a6e0b237784e1471d830a44ec36aca4e528811fa873187441
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'node_blocks'
4
+
5
+ module Raindown
6
+ # What an input does to a note, rather than typing, which Raindown makes rather than an app, so it reads
7
+ # directives as Raindown does: props set on the directive on a line, counted from 0, like { zoom: 9 } for a map's
8
+ # zoom: 8, each written where the directive has it, as it'd be typed. A directive in a grid's cell is by the column
9
+ # its cell starts at, after its |. The directive decides what can change, so a prop it hasn't got, or a line that
10
+ # isn't one, leaves the note as it was. An app makes it at once too, with SCRIPT, so it shows straight away, before
11
+ # Raindown makes it again as it writes the note back.
12
+ class Action
13
+ # The same action in JavaScript, raindownAfterAction(markdown, action, { bare }), for an app to take at once.
14
+ SCRIPT = File.join(__dir__, 'js', 'action.js')
15
+
16
+ attr_reader :line, :column, :set
17
+
18
+ def initialize(line:, set:, column: nil)
19
+ @line = line
20
+ @column = column
21
+ @set = set.transform_keys(&:to_sym)
22
+ end
23
+
24
+ # The Markdown after the action.
25
+ def apply(markdown, bare: false)
26
+ lines = markdown.lines
27
+ edited = lines[line] && directive_edited(lines[line], bare:)
28
+ return markdown unless edited
29
+
30
+ lines[line] = edited
31
+ lines.join
32
+ end
33
+
34
+ private
35
+
36
+ # The line with the props set on its directive, or nil.
37
+ def directive_edited(text, bare:)
38
+ props, at = props_of(text, bare:)
39
+ return unless props
40
+
41
+ values = values_in(props)
42
+ return unless set.keys.all? { values.key?(it) }
43
+
44
+ with_values(text, values.values_at(*set.keys).map { |start, stop| [at + start, at + stop] })
45
+ end
46
+
47
+ # The line with each of the set's values typed over where the prop's value was, from the last, so where the others
48
+ # are doesn't move.
49
+ def with_values(text, spans)
50
+ spans.zip(set.values).sort_by { |(start, _), _| -start }.each_with_object(text.dup) do |((start, stop), value), edited|
51
+ edited[start...stop] = typed(value)
52
+ end
53
+ end
54
+
55
+ # The directive's props on the line, and where they start in it, or nil when it isn't a directive with props.
56
+ def props_of(text, bare:)
57
+ from, to = directive_span(text)
58
+ match, = NodeBlocks.directive(text[from...to], bare: bare || !column.nil?)
59
+ return unless match && match[3]
60
+
61
+ [match[3], from + match.begin(3)]
62
+ end
63
+
64
+ # Where the directive is in the line: all of it but its line break, or its cell, up to the next |, without the
65
+ # spaces around it.
66
+ def directive_span(text)
67
+ return [0, text.chomp.length] unless column
68
+
69
+ cell = text[column..].to_s.split('|').first.to_s
70
+ from = column + cell[/\A\s*/].length
71
+ [from, from + cell.strip.length]
72
+ end
73
+
74
+ # Where each prop's value is in the props, as [start, stop], by its name, after a value that's the node's argument
75
+ # when it comes first.
76
+ def values_in(args)
77
+ start = argument_end(args)
78
+ args[start..].to_enum(:scan, NodeBlocks::PROP).to_h do
79
+ match = Regexp.last_match
80
+ [match[1].to_sym, [start + match.begin(2), start + match.end(2)]]
81
+ end
82
+ end
83
+
84
+ # Where the node's argument ends, or 0 when the props come first.
85
+ def argument_end(args)
86
+ return 0 if args.match?(NodeBlocks::PROP_FIRST)
87
+
88
+ args.match(NodeBlocks::ARG)&.end(0).to_i
89
+ end
90
+
91
+ # A value as it'd be typed: text in quotes, in double ones when it has a single one, and other values as they are.
92
+ def typed(value)
93
+ return 'nil' if value.nil?
94
+ return value.to_s unless value.is_a?(String)
95
+ return "'#{value}'" unless value.include?("'")
96
+ raise ArgumentError, "Can't write #{value} as a prop, as it has both kinds of quote" if value.include?('"')
97
+
98
+ "\"#{value}\""
99
+ end
100
+ end
101
+ end
data/lib/raindown/code.rb CHANGED
@@ -12,7 +12,8 @@ module Raindown
12
12
  module_function
13
13
 
14
14
  # Byte ranges of code in the Markdown, from Commonmarker's line and column positions, or rendering Markdown, which
15
- # doesn't load Commonmarker, its fenced blocks and code spans.
15
+ # doesn't load Commonmarker, or without it, like in WebAssembly, where the Obsidian plugin writes back a Markdown
16
+ # Component's template, its fenced blocks and code spans.
16
17
  def ranges(markdown)
17
18
  return scanned_ranges(markdown) unless Raindown.commonmark?
18
19
 
@@ -24,6 +25,8 @@ module Raindown
24
25
  end
25
26
 
26
27
  ranges
28
+ rescue LoadError
29
+ scanned_ranges(markdown)
27
30
  end
28
31
 
29
32
  # The byte offset each line starts at, and the end's.
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative '../raindown'
4
+ require_relative 'action'
4
5
  require_relative 'rewriter'
5
6
 
6
7
  module Raindown
@@ -8,6 +9,10 @@ module Raindown
8
9
  # would be written back to the file, with its failed endpoint checks. "raindown FILE --stdin" and "raindown server"
9
10
  # both answer with it.
10
11
  module Editing
12
+ # What an editor does at once in JavaScript, as Markdown's typed, as raindownEditing, like lining up tables, the
13
+ # same as TableFormatter, and what Enter and Tab do in a table's cells, which the Obsidian plugin and the app share.
14
+ SCRIPT = File.join(__dir__, 'js', 'editing.js')
15
+
11
16
  module_function
12
17
 
13
18
  # Without commonmark, it's Markdown, for the editor to render itself.
@@ -17,12 +22,20 @@ module Raindown
17
22
  **Config.render_options(path))
18
23
  end
19
24
 
20
- # Its warnings say why any of the project's nodes couldn't be loaded too.
21
- def rewrite_markdown(markdown, path:, bare: false, execute: false)
25
+ # Its warnings say why any of the project's nodes couldn't be loaded too. Each action an input took, like a button's,
26
+ # as { line:, set: }, or with column: for a directive in a grid's cell, is taken first, as Action takes it.
27
+ def rewrite_markdown(markdown, path:, bare: false, execute: false, actions: [])
22
28
  load_errors = Nodes.load(path)
29
+ markdown = acted(markdown, actions, path:, bare:)
23
30
  rewrite = Rewriter.rewrite(content: markdown, path:, bare:, execute:, metadata: Pages.for(path))
24
31
  failures = rewrite.failures.map { "Endpoint check failed: #{it}" }
25
32
  { output: rewrite.content, warnings: load_errors + failures + rewrite.problems }
26
33
  end
34
+
35
+ def acted(markdown, actions, path:, bare:)
36
+ actions.reduce(markdown) do |text, action|
37
+ Action.new(**action.transform_keys(&:to_sym)).apply(text, bare: BareDirectives.enabled?(path:, content: text, bare:))
38
+ end
39
+ end
27
40
  end
28
41
  end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # What a product built on Raindown does with it, set before any note's written: Raindown itself, with its own nodes,
5
+ # like toc: and table:, endpoints, tables lined up, and a project's Ruby, JavaScript and Markdown Components in its
6
+ # .raindown folder, or Components, the Obsidian plugin for beginners, with only Markdown Components, in a vault's
7
+ # Components folder, which Obsidian shows, and nothing else, so the rest of a note, like a table, stays as it's
8
+ # written.
9
+ class Edition
10
+ attr_reader :folder
11
+
12
+ def initialize(folder:, full:)
13
+ @folder = folder
14
+ @full = full
15
+ end
16
+
17
+ # Whether it has Raindown's own nodes, endpoints, tables lined up, and Ruby and JavaScript Components.
18
+ def full?
19
+ @full
20
+ end
21
+
22
+ FULL = new(folder: '.raindown', full: true)
23
+ COMPONENTS = new(folder: 'Components', full: false)
24
+ end
25
+
26
+ class << self
27
+ attr_writer :edition
28
+
29
+ def edition
30
+ @edition ||= Edition::FULL
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,65 @@
1
+ // An action an input took, like a rasterize button's, taken in a host at once, so it shows straight away, as
2
+ // Raindown::Action takes it, which takes it again as it writes the note back, and has the last word: props set on the
3
+ // directive on a line, counted from 0, like { zoom: 9 } for a map's zoom: 8, each written where the directive has it,
4
+ // as it'd be typed, or in a grid's cell, by the column it starts at, after its |. A prop the directive hasn't got, or a
5
+ // line that isn't one, leaves the Markdown as it was. Its patterns are NodeBlocks', which spec/raindown/action_spec.rb
6
+ // checks it reads as Raindown::Action does. A plain script, not a module, like services.js, so each host can put it
7
+ // before its own code.
8
+ function raindownAfterAction(markdown, { line, column = null, set }, { bare = false } = {}) {
9
+ // Nodes::BUILT_INS, then a project's own nodes' names, which are capitalized.
10
+ const NAME = String.raw`(?:toc|list|chart|table|image|grid|weather|[A-Z]\w*(?:::[A-Z]\w*)*)`
11
+ const UNQUOTED = String.raw`.+?(?=(?:,[ \t]*|[ \t]+)\w+(?:=|:[ \t])|,?[ \t]*$)`
12
+ const PROP = String.raw`(\w+)(?:=|:[ \t]+)("[^"]*"|'[^']*'|(?<==)\S+?(?=,?(?:\s|$))|${UNQUOTED})`
13
+ const ARG = new RegExp(String.raw`^("[^"]*"|'[^']*'|[^\s"']${UNQUOTED}|[^\s"'])(?:,\s*|\s+|$)`)
14
+ // Each directive's start, up to its props, and its props, in the order NodeBlocks tries them.
15
+ const DIRECTIVES = [
16
+ String.raw`^( {0,3}<\{\s*${NAME}:\s+)(.*?)\s*\}>[ \t]*$`,
17
+ String.raw`^( {0,3}<!--\s*${NAME}:\s+)(.*?)\s*-->[ \t]*$`,
18
+ String.raw`^( {0,3}<\{\s*(?::|(?=[A-Z]))${NAME}\s+)(.*?)\s*\}>[ \t]*$`
19
+ ]
20
+ const BARE_DIRECTIVES = [String.raw`^( {0,3}${NAME}:[ \t]+)(.*?)[ \t]*$`, String.raw`^( {0,3}:${NAME}[ \t]+)(.*?)[ \t]*$`]
21
+ // A component's bare directive, by its capitalized name, which works anywhere, as NodeBlocks::COMPONENT_DIRECTIVES.
22
+ const COMPONENT = String.raw`[A-Z]\w*(?:::[A-Z]\w*)*`
23
+ const COMPONENT_DIRECTIVES = [String.raw`^( {0,3}${COMPONENT}:[ \t]+)(.*?)[ \t]*$`, String.raw`^( {0,3}:${COMPONENT}[ \t]+)(.*?)[ \t]*$`]
24
+
25
+ const lines = markdown.split('\n')
26
+ const text = lines[line]
27
+ if (text === undefined) return markdown
28
+
29
+ // Where the directive is in the line: all of it but a line break's \r, or its cell, up to the next |, without the
30
+ // spaces around it.
31
+ let [from, to] = [0, text.replace(/\r$/, '').length]
32
+ if (column !== null) {
33
+ const cell = text.slice(column).split('|')[0]
34
+ from = column + cell.length - cell.trimStart().length
35
+ to = from + cell.trim().length
36
+ }
37
+ let patterns = [...DIRECTIVES, ...COMPONENT_DIRECTIVES]
38
+ if (bare || column !== null) patterns = [...DIRECTIVES, ...BARE_DIRECTIVES]
39
+ const match = patterns.map((pattern) => text.slice(from, to).match(new RegExp(pattern))).find(Boolean)
40
+ if (!match) return markdown
41
+
42
+ // Where each prop's value is in the line, by its name, after a value that's the node's argument when it comes first.
43
+ const props = match[2]
44
+ const at = from + match[1].length
45
+ let start = props.match(ARG)?.[0].length ?? 0
46
+ if (new RegExp(`^${PROP}`).test(props)) start = 0
47
+ const values = {}
48
+ for (const found of props.slice(start).matchAll(new RegExp(PROP, 'g'))) {
49
+ const end = at + start + found.index + found[0].length
50
+ values[found[1]] = [end - found[2].length, end]
51
+ }
52
+ if (!Object.keys(set).every((name) => name in values)) return markdown
53
+
54
+ // Each value typed over where the prop's was, from the last, so where the others are doesn't move.
55
+ const typed = (value) => {
56
+ if (value === null) return 'nil'
57
+ if (typeof value !== 'string') return String(value)
58
+ if (!value.includes("'")) return `'${value}'`
59
+ if (value.includes('"')) throw new Error(`Can't write ${value} as a prop, as it has both kinds of quote`)
60
+ return `"${value}"`
61
+ }
62
+ const spans = Object.entries(set).map(([name, value]) => [...values[name], typed(value)]).sort(([a], [b]) => b - a)
63
+ lines[line] = spans.reduce((edited, [begin, end, value]) => edited.slice(0, begin) + value + edited.slice(end), text)
64
+ return lines.join('\n')
65
+ }
@@ -0,0 +1,516 @@
1
+ // Editing Markdown as it's typed, as Raindown would write it back, which an editor does at once, so it never waits for
2
+ // Raindown: lining up tables, the same as Raindown's TableFormatter, and what Enter, Tab and Option or Alt and Enter
3
+ // do in a table's cell, like in a spreadsheet, and finding Raindown's directives, like a table: block's, in Markdown.
4
+ // The Obsidian plugin and the app both edit with it, as raindownEditing, each in its own editor. A plain script, like
5
+ // services.js, so each host can put it before its own code, which is a CommonJS module too, where it's required.
6
+ const raindownEditing = (() => {
7
+ // A comment on its own line that isn't a directive, which straight below a directive is its node's comment, like
8
+ // table:'s <!-- 2 rows · 3f2a9c -->, as Raindown reads it.
9
+ const BLOCK_COMMENT = /^\s*<!--(?!\s*(?::[A-Za-z]|[A-Za-z][\w-]*(?:::[A-Z]\w*)*:)).*-->\s*$/;
10
+
11
+ // Highlighting, like the VS Code extension's: directives in comments, like <!-- toc: --> and the end tag <!-- :toc -->,
12
+ // in <{ }>, and bare ones where they'd write back, like toc:, with the self-closing :toc. Not in code or front matter.
13
+ const NAME = String.raw`[A-Za-z][\w-]*(?:::[A-Z]\w*)*`;
14
+
15
+ const COMMENT_DIRECTIVE = new RegExp(String.raw`<!--\s*(?:(:${NAME})|(${NAME}:))(.*?)-->`, 'g');
16
+
17
+ const ANTLERS = /<\{(.*?)\}>/g;
18
+
19
+ const BARE_SELF_CLOSING = /^( {0,3})(:toc)[ \t]*$/;
20
+
21
+ const BARE_OPEN = new RegExp(String.raw`^( {0,3})(${NAME}:)(?=[ \t]*$|[ \t]+\S)`);
22
+ // A component's bare directive, BookCard: or :BookCard, which works in every note, as only a component the project
23
+ // has starts one, so it's only a directive when it's named in components.
24
+ const COMPONENT_LINE = /^( {0,3})(:?)([A-Z]\w*(?:::[A-Z]\w*)*)(:?)(?=[ \t]*$|[ \t]+\S)/;
25
+
26
+ // Strings, {variables}, numbers, :flags, props like folder: or limit=, and words.
27
+ const ARGUMENT = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\{[A-Za-z_][\w.]*\}|(?<![\w:])-?\d+(?:\.\d+)?\b|(?<![\w:]):[A-Za-z_][\w-]*|[A-Za-z_][\w-]*(?::(?![\w:])|=)|[A-Za-z_][\w.-]*/g;
28
+
29
+ // The highlighted parts of a note, in order, as { from, to, type }, where type is a class like cm-raindown-name.
30
+ function directiveTokens(text, { bare = false, components = [] } = {}) {
31
+ const front = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(text);
32
+ const bareHere = bare || /^raindown:\s*true\s*$/m.test(front?.[1] ?? '');
33
+ const tokens = [];
34
+ let offset = front ? front[0].length : 0;
35
+ let fence = null;
36
+
37
+ for (const line of text.slice(offset).split('\n')) {
38
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
39
+ if (fence) {
40
+ if (marker?.[0] === fence[0] && marker.length >= fence.length) fence = null;
41
+ } else if (marker) {
42
+ fence = marker;
43
+ } else {
44
+ tokens.push(...lineTokens(line, { bare: bareHere, components }).map((token) => ({ ...token, from: token.from + offset, to: token.to + offset })));
45
+ }
46
+ offset += line.length + 1;
47
+ }
48
+
49
+ return tokens.sort((a, b) => a.from - b.from);
50
+ }
51
+
52
+ function lineTokens(line, { bare, components }) {
53
+ const code = [...line.matchAll(/(`+)[^`]*?\1/g)].map((match) => [match.index, match.index + match[0].length]);
54
+ const tokens = [];
55
+ const add = (from, to, type) => {
56
+ if (!code.some(([start, end]) => from < end && to > start)) tokens.push({ from, to, type });
57
+ };
58
+
59
+ for (const match of line.matchAll(COMMENT_DIRECTIVE)) {
60
+ const name = match[1] ?? match[2];
61
+ const start = match.index + match[0].indexOf(name);
62
+ add(start, start + name.length, match[1] ? 'end' : 'name');
63
+ argumentTokens(match[3], start + name.length, { antlers: false }, add);
64
+ }
65
+ for (const match of line.matchAll(ANTLERS)) {
66
+ const end = match.index + match[0].length;
67
+ add(match.index, match.index + 2, 'delimiter');
68
+ argumentTokens(match[1], match.index + 2, { antlers: true }, add);
69
+ add(end - 2, end, 'delimiter');
70
+ }
71
+ if (!bare) {
72
+ addComponentTokens(line, components, add);
73
+ return tokens;
74
+ }
75
+
76
+ const selfClosing = BARE_SELF_CLOSING.exec(line);
77
+ const open = BARE_OPEN.exec(line);
78
+ if (selfClosing) add(selfClosing[1].length, selfClosing[1].length + selfClosing[2].length, 'self-closing');
79
+ if (open) {
80
+ const end = open[1].length + open[2].length;
81
+ add(open[1].length, end, 'name');
82
+ argumentTokens(line.slice(end), end, { antlers: false }, add);
83
+ }
84
+
85
+ return tokens;
86
+ }
87
+
88
+ // Adds the tokens of a component's bare directive on the line, BookCard: with its arguments, or :BookCard, when it's
89
+ // one of components.
90
+ function addComponentTokens(line, components, add) {
91
+ const found = COMPONENT_LINE.exec(line);
92
+ if (!found || !components.includes(found[3]) || Boolean(found[2]) === Boolean(found[4])) return;
93
+
94
+ const [indent, name] = [found[1].length, found[2] + found[3] + found[4]];
95
+ if (found[2]) {
96
+ add(indent, indent + name.length, 'self-closing');
97
+ return;
98
+ }
99
+ add(indent, indent + name.length, 'name');
100
+ argumentTokens(line.slice(indent + name.length), indent + name.length, { antlers: false }, add);
101
+ }
102
+
103
+ // The row of a table the cursor's in, with the |+ rows carrying it on: the lines it spans, the column the cursor's in,
104
+ // the line its table starts on, whether it's the header or the delimiter row below it, and the line of the row below
105
+ // it, or null outside a table's rows.
106
+ function tableRowAt(lines, { line, ch }) {
107
+ const row = (number) => /^\s*[|+]/.test(lines[number] ?? '') && lines[number].trim();
108
+ let start = line;
109
+ while (start > 0 && row(start - 1)) start--;
110
+ if (!row(line) || !isTableStart(lines, start)) return null;
111
+
112
+ const lead = lines[line].search(/[|+]/);
113
+ if (ch <= lead) return null;
114
+
115
+ let [first, last] = [line, line];
116
+ while (first > start + 2 && CONTINUATION.test(lines[first])) first--;
117
+ while (CONTINUATION.test(lines[last + 1] ?? '')) last++;
118
+ const header = line === start;
119
+ const below = header ? start + 2 : last + 1;
120
+ const column = [...lines[line].slice(lead + 1, ch).matchAll(/(?<!\\)\|/g)].length;
121
+ return { start, first, last, column, header, delimiter: line === start + 1, next: row(below) ? below : null };
122
+ }
123
+
124
+ // Whether the table starting on the line is a table: block's, below its directive and its comment.
125
+ function underTableDirective(text, lines, start, options) {
126
+ const above = BLOCK_COMMENT.test(lines[start - 1] ?? '') ? start - 1 : start;
127
+ const directiveEnd = lines.slice(0, above).join('\n').length;
128
+ return tableFiles(text, options).some(({ at }) => at === directiveEnd);
129
+ }
130
+
131
+ // What Enter does to the cell the cursor's in, in a table: block's table, each cell of a row on its own: 'collapse' one
132
+ // shown in full on |+ rows, or 'expand' one cut to fit, ending in an ellipsis, deleting it so Raindown shows its full
133
+ // text. Elsewhere it's null, and Enter only moves to the row below.
134
+ function cellToggle(text, lines, row, options) {
135
+ if (!underTableDirective(text, lines, row.start, options)) return null;
136
+
137
+ const below = lines.slice(row.first + 1, row.last + 1).map(tableCells);
138
+ if (below.some((cells) => cells[row.column])) return 'collapse';
139
+ if (tableCells(lines[row.first])[row.column]?.endsWith('…')) return 'expand';
140
+ return null;
141
+ }
142
+
143
+ // Whether the cursor's in a table: block's fixed column, like |=====|, or on the |+ rows of a cell in one.
144
+ function inFixedCell(text, cursor, options) {
145
+ const lines = text.split('\n');
146
+ const row = tableRowAt(lines, cursor);
147
+ if (!row || row.delimiter || !fixedColumn(tableCells(lines[row.start + 1])[row.column] ?? '')) return false;
148
+
149
+ return underTableDirective(text, lines, row.start, options);
150
+ }
151
+
152
+ // What Enter does to the cell at the offset, for its hint.
153
+ function cellToggleAt(text, offset, options) {
154
+ const lines = text.split('\n');
155
+ const row = tableRowAt(lines, positionOf(text, offset));
156
+ return row && cellToggle(text, lines, row, options);
157
+ }
158
+
159
+ // Where a cell is in a row's line, from after the pipe before it to the pipe after it, or null past its last.
160
+ function cellBounds(line, column) {
161
+ const lead = line.match(/^[ \t]*\|\+?/)?.[0].length ?? 0;
162
+ const pipes = [...line.matchAll(/(?<!\\)\|/g)].map(({ index }) => index).filter((index) => index >= lead);
163
+ const from = column === 0 ? lead : pipes[column - 1] + 1;
164
+ if (Number.isNaN(from)) return null;
165
+
166
+ return { from, to: pipes[column] ?? line.length };
167
+ }
168
+
169
+ // Where the cursor goes to be at the end of a cell's text in a row's line: after its last letter, or inside it when
170
+ // it's empty.
171
+ function cellEndIn(line, column) {
172
+ const cell = cellBounds(line, column);
173
+ if (!cell) return line.length;
174
+
175
+ return cell.from + Math.max(1, line.slice(cell.from, cell.to).trimEnd().length);
176
+ }
177
+
178
+ // An empty row for the row's table, indented like it, which the table lines up.
179
+ function emptyRow(lines, row) {
180
+ const cells = tableCells(lines[row.start + 1]).map(() => '');
181
+ return `${lines[row.first].match(/^[ \t]*/)[0]}| ${cells.join(' | ')} |`;
182
+ }
183
+
184
+ // A row and its |+ rows with one column's cell joined back onto the row's line, its parts joined with spaces, leaving
185
+ // the other columns' cells as they are, and the |+ rows nothing's left on out.
186
+ function collapsedColumn(rows, column) {
187
+ const cells = rows.map(tableCells);
188
+ const indent = rows[0].match(/^[ \t]*/)[0];
189
+ const joined = cells.map((row) => row[column] ?? '').filter(Boolean).join(' ');
190
+ const first = cells[0].map((cell, index) => (index === column ? joined : cell));
191
+ const below = cells.slice(1).map((row) => row.map((cell, index) => (index === column ? '' : cell))).filter((row) => row.some(Boolean));
192
+ return [`${indent}| ${first.join(' | ')} |`, ...below.map((row) => `${indent}|+${row.join(' | ')} |`)];
193
+ }
194
+
195
+ // The change Enter makes in a table's row, like in a spreadsheet: done with the cell, moving the cursor to the end of the
196
+ // same cell in the row below, which is added in the last row. In a table: block's table, it expands a cell cut to fit,
197
+ // staying in it, and collapses one shown in full, joining its text on the |+ rows back onto its row first, so Raindown
198
+ // clips it again. As offsets, with what it toggled, or null outside a table's rows.
199
+ function enteredCell(text, offset, options) {
200
+ const lines = text.split('\n');
201
+ const row = tableRowAt(lines, positionOf(text, offset));
202
+ if (!row) return null;
203
+
204
+ const toggle = cellToggle(text, lines, row, options);
205
+ if (toggle === 'expand') return expandedCell(text, lines, row);
206
+
207
+ const rows = lines.slice(row.first, row.last + 1);
208
+ const kept = toggle === 'collapse' ? collapsedColumn(rows, row.column) : rows;
209
+ // In the last row, a row's added below it to move to, like a spreadsheet's next row.
210
+ const added = row.next === null && !row.header ? [emptyRow(lines, row)] : [];
211
+ const insert = [...kept, ...added].join('\n');
212
+ const from = offsetOf(text, { line: row.first, ch: 0 });
213
+ const to = offsetOf(text, { line: row.last, ch: lines[row.last].length });
214
+ const after = text.slice(0, from) + insert + text.slice(to);
215
+ const target = row.next === null ? row.first + kept.length - 1 + added.length : row.next - (rows.length - kept.length);
216
+ const cursor = offsetOf(after, { line: target, ch: cellEndIn(after.split('\n')[target], row.column) });
217
+
218
+ return { from, to, insert, cursor, toggle };
219
+ }
220
+
221
+ // The change expanding a cell cut to fit: its ellipsis deleted, with the cursor where it was.
222
+ function expandedCell(text, lines, row) {
223
+ const line = lines[row.first];
224
+ const cell = cellBounds(line, row.column);
225
+ const at = offsetOf(text, { line: row.first, ch: line.lastIndexOf('…', cell.to) });
226
+ return { from: at, to: at + 1, insert: '', cursor: at, toggle: 'expand' };
227
+ }
228
+
229
+ // Where Tab moves the cursor in a table's row, like in a spreadsheet: to the end of the next cell's text on its line, or
230
+ // the first of the row below, or with back, like Shift and Tab, the previous cell, or the last of the row above. It
231
+ // stays put in the table's last cell, or first, so Tab never splits a row. Null outside a table's rows.
232
+ function tabbedCell(text, offset, { back = false } = {}) {
233
+ const lines = text.split('\n');
234
+ const position = positionOf(text, offset);
235
+ const row = tableRowAt(lines, position);
236
+ if (!row) return null;
237
+
238
+ const { line } = position;
239
+ const columns = tableCells(lines[row.start + 1]).length;
240
+ const at = (number, column) => offsetOf(text, { line: number, ch: cellEndIn(lines[number], column) });
241
+ const column = row.column + (back ? -1 : 1);
242
+ if (column >= 0 && column < columns) return at(line, column);
243
+ if (!back) return row.next === null ? at(line, row.column) : at(row.next, 0);
244
+
245
+ let above = row.first - 1;
246
+ if (above === row.start + 1) above = row.start;
247
+ while (above > row.start + 2 && CONTINUATION.test(lines[above])) above--;
248
+ return above < row.start ? at(line, row.column) : at(above, columns - 1);
249
+ }
250
+
251
+ // The change Option or Alt and Enter makes in a table's cell, like a line break in a spreadsheet: a |+ row below the
252
+ // cursor's row carrying the cell on, with what's after the cursor in it, rather than splitting the row, which would
253
+ // end the table. As offsets, with where the cursor goes, or null outside a table's rows, or in its header or
254
+ // delimiter row.
255
+ function carriedOnCell(text, offset) {
256
+ const lines = text.split('\n');
257
+ const { line, ch } = positionOf(text, offset);
258
+ const row = tableRowAt(lines, { line, ch });
259
+ if (!row || row.header || row.delimiter) return null;
260
+
261
+ const { column } = row;
262
+ const current = lines[line];
263
+ const cellEnd = current.slice(ch).search(/(?<!\\)\|/);
264
+ const end = cellEnd === -1 ? current.length : ch + cellEnd;
265
+ const carried = `|+${' | '.repeat(column)}`;
266
+ const cells = tableCells(lines[row.start + 1]).map((_, index) => (index === column ? current.slice(ch, end).trim() : ''));
267
+ const from = offsetOf(text, { line, ch: 0 });
268
+ const insert = `${current.slice(0, ch).trimEnd()} ${current.slice(end)}\n|+${cells.join(' | ')} |`;
269
+
270
+ return { from, to: from + current.length, insert, cursor: from + insert.indexOf('\n') + 1 + carried.length };
271
+ }
272
+
273
+ // Each table: directive's file, like 'data/books.csv', with where its line ends, for a button to open it there.
274
+ function tableFiles(text, options) {
275
+ const tokens = directiveTokens(text, options);
276
+
277
+ return tokens.flatMap((token, index) => {
278
+ if (!/^:?table:?$/.test(text.slice(token.from, token.to))) return [];
279
+
280
+ let lineEnd = text.indexOf('\n', token.to);
281
+ if (lineEnd === -1) lineEnd = text.length;
282
+ const data = directiveArgument(text.slice(token.to, lineEnd));
283
+ if (!data) return [];
284
+
285
+ return [{ at: lineEnd, data }];
286
+ });
287
+ }
288
+
289
+ // The value after a directive's name, like its file, quoted or not, as Raindown reads it, up to any props, like
290
+ // data/books.csv in table: data/books.csv total: true, or table: data/books.csv, total: true, or null without one.
291
+ function directiveArgument(rest) {
292
+ const text = rest.replace(/\s*(?:-->|\}>)\s*$/, '').trim();
293
+ const quoted = /^(["'])(.*?)\1/.exec(text);
294
+ if (quoted) return quoted[2];
295
+
296
+ return /^(.*?)(?=(?:,[ \t]*|\s+)\w+(?:=|:\s)|,?\s*$)/.exec(text)[1] || null;
297
+ }
298
+
299
+ // In <{ }>, its first word is the directive, like toc: or :toc, and words are variables. Outside, words are text.
300
+ function argumentTokens(text, offset, { antlers }, add) {
301
+ let first = antlers;
302
+ for (const match of text.matchAll(ARGUMENT)) {
303
+ const type = argumentType(match[0], { antlers, first });
304
+ first = false;
305
+ if (type) add(offset + match.index, offset + match.index + match[0].length, type);
306
+ }
307
+ }
308
+
309
+ function argumentType(token, { antlers, first }) {
310
+ if (/^["']/.test(token)) return 'string';
311
+ if (token.startsWith('{')) return 'variable';
312
+ if (/^-?\d/.test(token)) return 'number';
313
+ if (token.startsWith(':')) return first ? 'end' : 'flag';
314
+ if (/[:=]$/.test(token)) return first ? 'name' : 'prop';
315
+
316
+ return antlers ? 'variable' : null;
317
+ }
318
+
319
+ // Whether the cursor's in a table cell starting with =, so a formula that's still being typed.
320
+ function inFormulaCell(line, ch) {
321
+ const start = line.lastIndexOf('|', ch - 1);
322
+ if (!line.trimStart().startsWith('|') || start === -1) return false;
323
+
324
+ return line.slice(start + 1, ch).trimStart().startsWith('=');
325
+ }
326
+
327
+ // The start of each line of a Markdown table, and its |+ rows, as Raindown's columns only line up in a monospace font,
328
+ // with its header, to show in bold, its delimiter row, to show muted, and its pipes, to show faint, but for those of a
329
+ // row carrying one on, its |+ and pipes, in the accent colour.
330
+ function tableLines(markdown) {
331
+ const lines = markdown.split('\n');
332
+ let offset = 0;
333
+ return lines.flatMap((line, number) => {
334
+ const from = offset;
335
+ offset += line.length + 1;
336
+ if (!/^[ \t]*\|.*\|[ \t]*$/.test(line)) return [];
337
+
338
+ const header = isTableStart(lines, number) ? [{ from, to: from + line.length, type: 'table-header' }] : [];
339
+ const delimiter = number > 0 && isTableStart(lines, number - 1) ? [{ from, to: from + line.length, type: 'table-delimiter' }] : [];
340
+ // A row carrying on the one above has its |+ and pipes in the accent colour, so it's plain it's part of that row.
341
+ const type = CONTINUATION.test(line) ? 'table-expansion' : 'table-pipe';
342
+ const pipes = [...line.matchAll(/(?<!\\)\||(?<=^[ \t]*\|)\+/g)].map(({ index }) => ({ from: from + index, to: from + index + 1, type }));
343
+ return [{ from, type: 'table' }, ...header, ...delimiter, ...pipes];
344
+ });
345
+ }
346
+
347
+ // Lining up tables as they're typed, the same as Raindown's TableFormatter, so its write-back finds them lined up.
348
+ const DELIMITER_CELL = /^:?[-=]+:?$/;
349
+
350
+ // A row carrying on the one above it, starting with |+ in place of a row's "| ", which Raindown joins into its cells.
351
+ const CONTINUATION = /^[ \t\n\v\f\r]*\|\+/;
352
+
353
+ const FENCE = /^\s*(```|~~~)/;
354
+
355
+ // Ruby's strip, which leaves other spaces, like a no-break space, in the cell.
356
+ const STRIP = /^[ \t\n\v\f\r\0]+|[ \t\n\v\f\r\0]+$/g;
357
+
358
+ // East Asian wide and fullwidth letters, and emoji, take two columns, like unicode-display-width's with emoji: :all.
359
+ const WIDE = new RegExp(String.raw`[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF` +
360
+ String.raw`\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}\uFE0F\u20E3]` +
361
+ String.raw`|\p{Emoji_Presentation}`, 'u');
362
+
363
+ const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}]+$/u;
364
+
365
+ // Graphemes, where the engine can tell them, or else characters, as in QuickJS, which hasn't got Intl.
366
+ const graphemes = typeof Intl === 'object' && Intl.Segmenter && new Intl.Segmenter();
367
+
368
+ function displayWidth(text) {
369
+ let width = 0;
370
+ for (const segment of segmentsOf(text)) {
371
+ if (WIDE.test(segment)) width += 2;
372
+ else if (!ZERO_WIDTH.test(segment)) width += 1;
373
+ }
374
+ return width;
375
+ }
376
+
377
+ function segmentsOf(text) {
378
+ if (!graphemes) return Array.from(text);
379
+
380
+ return Array.from(graphemes.segment(text), ({ segment }) => segment);
381
+ }
382
+
383
+ // How a row's line starts, before its first cell: |+ when it carries on the row above, as wide as a row's "| ".
384
+ function rowLead(line) {
385
+ return CONTINUATION.test(line) ? '|+' : '| ';
386
+ }
387
+
388
+ // A row's cells, split on pipes that aren't escaped, without its outer pipes, or the |+ starting a continuation row.
389
+ function tableCells(line) {
390
+ let content = line.replace(STRIP, '');
391
+ const lead = rowLead(line).trimEnd();
392
+ if (content.startsWith(lead)) content = content.slice(lead.length);
393
+ if (content.endsWith('|') && !content.endsWith('\\|')) content = content.slice(0, -1);
394
+ if (!content) return [];
395
+
396
+ return content.split(/(?<!\\)\|/).map((cell) => cell.replace(STRIP, ''));
397
+ }
398
+
399
+ function isTableStart(lines, index) {
400
+ const [header, delimiter] = [lines[index], lines[index + 1]];
401
+ if (!header.includes('|') || delimiter === undefined || CONTINUATION.test(header)) return false;
402
+
403
+ const cells = tableCells(delimiter);
404
+ if (!cells.length || cells.length !== tableCells(header).length) return false;
405
+
406
+ return cells.every((cell) => DELIMITER_CELL.test(cell));
407
+ }
408
+
409
+ // Whether a column's delimiter cell makes it fixed, like Raindown's TableColumn: equals signs, or one typed into dashes,
410
+ // as fewer of them than dashes, while a dash typed into equals signs makes it widen again.
411
+ function fixedColumn(delimiter) {
412
+ const [equals, dashes] = ['=', '-'].map((sign) => delimiter.split(sign).length - 1);
413
+ return equals > 0 && (dashes === 0 || equals < dashes);
414
+ }
415
+
416
+ // A column, like Raindown's TableColumn: its alignment, from its delimiter cell's colons, and its width, that of its
417
+ // widest cell, or as wide as its delimiter when that's equals signs, which is fixed, letting a longer cell run past.
418
+ function tableColumn(delimiter, cells) {
419
+ const fixed = fixedColumn(delimiter);
420
+ // An equals sign typed into dashes isn't part of its width, so it's fixed as wide as it was.
421
+ const typed = delimiter.includes('-') ? delimiter.split('=').length - 1 : 0;
422
+ const width = fixed ? delimiter.length - typed : Math.max(3, ...cells.map(displayWidth));
423
+ const dash = fixed ? '=' : '-';
424
+ let alignment = null;
425
+ if (delimiter.startsWith(':') && delimiter.endsWith(':')) alignment = 'center';
426
+ else if (delimiter.endsWith(':')) alignment = 'right';
427
+ else if (delimiter.startsWith(':')) alignment = 'left';
428
+
429
+ return {
430
+ pad(cell) {
431
+ const padding = Math.max(0, width - displayWidth(cell));
432
+ if (alignment === 'center') return ' '.repeat(Math.floor(padding / 2)) + cell + ' '.repeat(Math.ceil(padding / 2));
433
+ if (alignment === 'right') return ' '.repeat(padding) + cell;
434
+ return cell + ' '.repeat(padding);
435
+ },
436
+ delimiterCell() {
437
+ if (alignment === 'center') return `:${dash.repeat(width - 2)}:`;
438
+ if (alignment === 'right') return `${dash.repeat(width - 1)}:`;
439
+ if (alignment === 'left') return `:${dash.repeat(width - 1)}`;
440
+ return dash.repeat(width);
441
+ }
442
+ };
443
+ }
444
+
445
+ // A table's lines with each column padded to fit, keeping each row's + when it carries on the row above, or as they
446
+ // were when a row has more cells than its header.
447
+ function alignedTable(table) {
448
+ const indent = table[0].match(/^[ \t\n\v\f\r]*/)[0];
449
+ const [header, delimiter, ...body] = table.map(tableCells);
450
+ if (body.some((row) => row.length > header.length)) return table;
451
+
452
+ const rows = [header, ...body.map((row) => [...row, ...Array(header.length - row.length).fill('')])];
453
+ const columns = delimiter.map((cell, column) => tableColumn(cell, rows.map((row) => row[column])));
454
+ const line = (lead, cells) => `${indent}${lead}${cells.join(' | ')} |`;
455
+ const lines = [table[0], ...table.slice(2)].map((original, row) => line(rowLead(original), rows[row].map((cell, column) => columns[column].pad(cell))));
456
+
457
+ return [lines[0], line('| ', columns.map((column) => column.delimiterCell())), ...lines.slice(1)];
458
+ }
459
+
460
+ // The note with every table lined up, outside code. Like Raindown, one lined up at the very end gets a line break
461
+ // after it.
462
+ function alignTables(markdown) {
463
+ const lines = markdown.split('\n');
464
+ const output = [];
465
+ let inFence = false;
466
+ for (let index = 0; index < lines.length;) {
467
+ if (FENCE.test(lines[index])) inFence = !inFence;
468
+ if (inFence || !isTableStart(lines, index)) {
469
+ output.push(lines[index++]);
470
+ continue;
471
+ }
472
+
473
+ let end = index + 2;
474
+ while (end < lines.length && lines[end].includes('|') && lines[end].trim()) end++;
475
+ const table = lines.slice(index, end);
476
+ const aligned = alignedTable(table);
477
+ output.push(...aligned, ...(end === lines.length && aligned !== table ? [''] : []));
478
+ index = end;
479
+ }
480
+ return output.join('\n');
481
+ }
482
+
483
+ function offsetOf(text, { line, ch }) {
484
+ return text.split('\n').slice(0, line).reduce((offset, before) => offset + before.length + 1, ch);
485
+ }
486
+
487
+ function positionOf(text, offset) {
488
+ const lines = text.slice(0, offset).split('\n');
489
+ return { line: lines.length - 1, ch: lines.at(-1).length };
490
+ }
491
+
492
+ // The |+ lines carrying on the table rows a deletion removes the whole of, each with its line break, so they go with
493
+ // their row rather than being left below the row above, which Raindown would read them as carrying on. As ranges in the
494
+ // text before the deletion, which is ranges too.
495
+ function orphanedRows(text, deletions) {
496
+ const lines = text.split('\n');
497
+ const starts = [0];
498
+ lines.forEach((line) => starts.push(starts.at(-1) + line.length + 1));
499
+ const removed = (number) => deletions.some(({ from, to }) => from <= starts[number] && starts[number] + lines[number].length <= to);
500
+
501
+ return lines.flatMap((line, number) => {
502
+ if (!line.trim() || !removed(number) || !/^[ \t]*\|/.test(line) || CONTINUATION.test(line)) return [];
503
+
504
+ let last = number;
505
+ while (CONTINUATION.test(lines[last + 1] ?? '')) last++;
506
+ const rows = Array.from({ length: last - number }, (_, index) => number + 1 + index).filter((row) => !removed(row));
507
+ return rows.map((row) => ({ from: starts[row], to: Math.min(starts[row + 1], text.length) }));
508
+ });
509
+ }
510
+
511
+ return {
512
+ BLOCK_COMMENT, alignTables, carriedOnCell, cellToggleAt, directiveTokens, enteredCell, inFixedCell, inFormulaCell, offsetOf, orphanedRows, positionOf, tabbedCell, tableCells, tableFiles, tableLines
513
+ };
514
+ })();
515
+
516
+ if (typeof module === 'object') module.exports = raindownEditing;
@@ -12,10 +12,12 @@ module Raindown
12
12
  # host of an app's own, like its page. Wherever they run, they get Raindown's services as raindown in their context.
13
13
  # A host answers requests, which JSON can hold, with request(**message):
14
14
  # { op: 'load', folder } → { nodes: [{ name, render, rasterize, file }], errors: [{ file, error }] }
15
- # { op: 'call', calls: [{ id, name, args, props, method, context, root }] }
15
+ # { op: 'call', calls: [{ id, name, args, props, method, context, root }], metadata }
16
16
  # → { answers: [{ value } or { error }] }
17
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.
18
+ # is called, so a node takes one request, and calls go together, so a note's nodes take one between them. The
19
+ # metadata, its project's root and each file's front matter and path, is sent once for them, as it's every file's, and
20
+ # each call's context gets it.
19
21
  module JSNodes
20
22
  EXTENSIONS = %w[.js .mjs].freeze
21
23
  # Raindown's services for JavaScript nodes, which every host runs before its own script, like an app's page.
@@ -53,18 +55,24 @@ module Raindown
53
55
  node_classes[name]
54
56
  end
55
57
 
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)
58
+ # The answers to calls of JavaScript nodes' methods, from JSNode#call_for, asked of their host together, with the
59
+ # metadata they share: each one's output, or an Error for one that raised.
60
+ def call(calls, metadata: NoMetadata)
59
61
  return [] if calls.empty?
60
62
 
61
- host.request(op: 'call', calls:).fetch('answers').map do |answer|
63
+ host.request(op: 'call', calls:, metadata: json_metadata(metadata)).fetch('answers').map do |answer|
62
64
  next Error.new(answer['error']) if answer['error']
63
65
 
64
66
  answer['value'].to_s
65
67
  end
66
68
  end
67
69
 
70
+ # JSON can't hold Pages, so the metadata is its root and each file's front matter and path.
71
+ def json_metadata(metadata)
72
+ root = metadata.root if metadata.respond_to?(:root)
73
+ { root:, files: metadata.list.map(&:metadata) }
74
+ end
75
+
68
76
  # The names of the folder's JavaScript Components that rasterize.
69
77
  def rasterizing(folder)
70
78
  node_classes.select { |_, node| node.method_defined?(:rasterize) && File.dirname(node.file) == folder }.keys
@@ -127,17 +135,15 @@ module Raindown
127
135
  end
128
136
 
129
137
  def js_output(method, context)
130
- output = JSNodes.call([call_for(method, context)]).first
138
+ output = JSNodes.call([call_for(method, context)], metadata: context.fetch(:metadata, NoMetadata)).first
131
139
  raise output if output.is_a?(JSNodes::Error)
132
140
 
133
141
  output
134
142
  end
135
143
 
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.
138
- def json_context(metadata: NoMetadata, **context)
139
- root = metadata.root if metadata.respond_to?(:root)
140
- { **context.except(:raindown), metadata: { root:, files: metadata.list.map(&:metadata) } }
144
+ # Without the metadata, which JSNodes.call sends once for a note's calls, or the services, which its host makes again.
145
+ def json_context(**context)
146
+ context.except(:raindown, :metadata)
141
147
  end
142
148
  end
143
149
  end
@@ -30,12 +30,13 @@ globalThis.__raindown = (() => {
30
30
  return { nodes: described }
31
31
  },
32
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 }) {
33
+ // Each call makes its node the first time, and answers apart, so one that throws doesn't fail the others. The
34
+ // metadata the calls share goes in each one's context.
35
+ async call({ calls, metadata }) {
35
36
  const answers = calls.map(async ({ id, name, args, props, method, context, root }) => {
36
37
  try {
37
38
  nodes[id] ??= new classes[name](props, ...args)
38
- return { value: await nodes[id][method]({ ...context, raindown: raindownServices(root, ask) }) }
39
+ return { value: await nodes[id][method]({ ...context, metadata, raindown: raindownServices(root, ask) }) }
39
40
  } catch (error) {
40
41
  return { error: String(error?.message ?? error) }
41
42
  }
@@ -19,11 +19,12 @@ 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
+ # Its templates are read as they're written, so loading one can't fail, and there are never errors to give. The
23
+ # folder loaded last has the name, so each reads its own folder's template, not one loaded before from another.
23
24
  def load(folder)
24
25
  Dir.glob(EXTENSIONS.map { "*#{it}" }, base: folder).each do |file|
25
26
  name = File.basename(file, '.*')
26
- node_classes[name] ||= MarkdownNode.for(name:, path: File.join(folder, file)) if name.match?(NAME)
27
+ node_classes[name] = MarkdownNode.for(name:, path: File.join(folder, file)) if name.match?(NAME)
27
28
  end
28
29
  []
29
30
  end
@@ -19,8 +19,11 @@ 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. 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.
22
+ # node, so other text like "Note:" is left alone. A component's directive, by its capitalized name, can be bare
23
+ # anywhere, as only a component the project has, like .raindown/BookCard.md, starts one, which it has on purpose, while
24
+ # Raindown's own, like toc:, list: and table:, which are common words, are bare only where bare directives work. There,
25
+ # a bare grid, a block starting with a rule like +---+, is a grid: without its directive, which it writes from its
26
+ # first line, its rule.
24
27
  module NodeBlocks
25
28
  class MissingEndTag < StandardError; end
26
29
  class BrokenText < StandardError; end
@@ -33,6 +36,14 @@ module Raindown
33
36
  SELF_CLOSING = /\A( {0,3})<\{\s*(?::|(?=[A-Z]))(#{NAME})(?:\s+(.*?))?\s*\}>[ \t]*$/
34
37
  BARE_SELF_CLOSING = /\A( {0,3}):(#{NAME})(?:[ \t]+(.*?))?[ \t]*$/
35
38
  BARE_GRID = /\A {0,3}\+-[-+]*\+[ \t]*$/
39
+ DIRECTIVES = { open: OPEN, comment_open: COMMENT_OPEN, self_closing: SELF_CLOSING }.freeze
40
+ # A component's directive, by its capitalized name, bare, which works anywhere, as only one a project has starts one.
41
+ COMPONENT = '[A-Z]\\w*(?:::[A-Z]\\w*)*'
42
+ COMPONENT_DIRECTIVES = {
43
+ **DIRECTIVES, bare_open: /\A( {0,3})(#{COMPONENT}):(?:[ \t]+(.*?))?[ \t]*$/,
44
+ bare_self_closing: /\A( {0,3}):(#{COMPONENT})(?:[ \t]+(.*?))?[ \t]*$/
45
+ }.freeze
46
+ BARE_DIRECTIVES = { **DIRECTIVES, bare_open: BARE_OPEN, bare_self_closing: BARE_SELF_CLOSING }.freeze
36
47
  # Unquoted text after name:, like YAML's, runs up to the next prop, so title: Hello world limit: 3 has two. A comma
37
48
  # before the next prop, like data.csv, total: true, separates them like a space, while one in text, like Hello,
38
49
  # world, is part of it.
@@ -42,6 +53,15 @@ module Raindown
42
53
  PROP = /(\w+)(?:=|:[ \t]+)("[^"]*"|'[^']*'|(?<==)\S+?(?=,?(?:\s|\z))|#{UNQUOTED})/
43
54
  # A value before the props is the node's argument.
44
55
  ARG = /\A("[^"]*"|'[^']*'|[^\s"']#{UNQUOTED}|[^\s"'])(?:,\s*|\s+|\z)/
56
+ PROP_FIRST = /\A#{PROP}/
57
+ # A whole number, or text in quotes without escapes, read without parsing it as Ruby, as most values are.
58
+ INTEGER = /\A-?(?:0|[1-9]\d*)\z/
59
+ PLAIN_QUOTED = /\A(?:'[^'\\]*'|"[^"\\#]*")\z/
60
+ # The line ending a block, by its node's name and whether it's in a comment, compiled once for each.
61
+ END_TAGS = Hash.new do |tags, (name, comment)|
62
+ first, last = comment ? Directives::COMMENT : Directives::DELIMITERS
63
+ tags[[name, comment]] = /\A {0,3}#{Regexp.escape(first)}\s*:#{Regexp.escape(name)}\s*#{Regexp.escape(last)}[ \t]*$/
64
+ end
45
65
 
46
66
  module_function
47
67
 
@@ -154,11 +174,10 @@ module Raindown
154
174
  end
155
175
  end
156
176
 
157
- # The directive on the line and which kind it is, or nil.
177
+ # The directive on the line and which kind it is, or nil: bare only for a component, unless bare directives work.
158
178
  def directive(line, bare:)
159
- patterns = { open: OPEN, comment_open: COMMENT_OPEN, self_closing: SELF_CLOSING }
160
- patterns.merge!(bare_open: BARE_OPEN, bare_self_closing: BARE_SELF_CLOSING) if bare
161
-
179
+ patterns = COMPONENT_DIRECTIVES
180
+ patterns = BARE_DIRECTIVES if bare
162
181
  patterns.each do |pattern, regexp|
163
182
  match = line.match(regexp)
164
183
  return [match, pattern] if match
@@ -178,7 +197,7 @@ module Raindown
178
197
  # The end tag written the same way as the directive: in a comment, or in Antlers' delimiters.
179
198
  def end_tag(lines, open, name, comment:)
180
199
  first, last = comment ? Directives::COMMENT : Directives::DELIMITERS
181
- tag = /\A {0,3}#{Regexp.escape(first)}\s*:#{Regexp.escape(name)}\s*#{Regexp.escape(last)}[ \t]*$/
200
+ tag = END_TAGS[[name, comment]]
182
201
  close = (open + 1...lines.length).find { |index| lines[index].match?(tag) }
183
202
  raise MissingEndTag, "#{first} #{name}: #{last} on line #{open + 1} needs #{first} :#{name} #{last}" unless close
184
203
 
@@ -187,7 +206,7 @@ module Raindown
187
206
 
188
207
  # The props, after a value that's the node's argument when it comes first, like 'data.csv' in chart: 'data.csv'.
189
208
  def args(text, variables, antlers: true)
190
- arg = text.match(ARG) unless text.match?(/\A#{PROP}/)
209
+ arg = text.match(ARG) unless text.match?(PROP_FIRST)
191
210
  return [props(text, variables, antlers:)] unless arg
192
211
 
193
212
  [props(arg.post_match, variables, antlers:), [value(arg[1], variables, antlers:)]]
@@ -205,6 +224,9 @@ module Raindown
205
224
  # author.name, while bare or in a comment, which read like Markdown, it's text, like notes in list: folder: notes,
206
225
  # and only one in braces is a variable, like {author.name}.
207
226
  def value(value, variables, antlers: true)
227
+ return value.to_i if value.match?(INTEGER)
228
+ return value[1..-2] if value.match?(PLAIN_QUOTED)
229
+
208
230
  Lowkey::ValueParser.parse(value) do
209
231
  next value[1..-2] if value.match?(/\A(["']).*\1\z/)
210
232
  next Variables.value(variables, value[1..-2]) if !antlers && value.match?(/\A\{.+\}\z/)
@@ -80,7 +80,7 @@ module Raindown
80
80
  def written_ahead(lines, blocks)
81
81
  ahead = blocks.select { it[:node].is_a?(JSNode) }
82
82
  calls = ahead.map { it[:node].call_for(:rewrite, context_of(lines, it)) }
83
- ahead.map { it[:open] }.zip(JSNodes.call(calls)).to_h
83
+ ahead.map { it[:open] }.zip(JSNodes.call(calls, metadata: @metadata)).to_h
84
84
  rescue JSNodes::Error
85
85
  {}
86
86
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'edition'
3
4
  require_relative 'fragments'
4
5
  require_relative 'js/js_nodes'
5
6
  require_relative 'markdown_nodes'
@@ -35,16 +36,25 @@ module Raindown
35
36
 
36
37
  module_function
37
38
 
38
- # Loads the .raindown folder beside the file or in the nearest directory above it, once per process, and gives why
39
- # any of its files couldn't be loaded, like ".raindown/stars.rb:3: syntax errors found". Each file loads on its own,
40
- # so one that can't be leaves the others loaded.
39
+ # Loads the .raindown folder beside the file or in the nearest directory above it, or the edition's own, like
40
+ # Components', once per process, and gives why any of its files couldn't be loaded, like ".raindown/stars.rb:3:
41
+ # syntax errors found". Each file loads on its own, so one that can't be leaves the others loaded. An edition that
42
+ # isn't full only has Markdown Components.
41
43
  def load(path)
42
44
  folder = find_folder(File.dirname(File.expand_path(path)))
43
45
  return [] if folder.nil?
44
46
  return load_errors[folder] if loaded.include?(folder)
45
47
 
46
48
  loaded << folder
47
- load_errors[folder] = load_ruby(folder) + JSNodes.load(folder) + MarkdownNodes.load(folder)
49
+ load_errors[folder] = load_folder(folder)
50
+ end
51
+
52
+ # The folder's components loaded, with why any couldn't be: only its Markdown Components in an edition that isn't
53
+ # full.
54
+ def load_folder(folder)
55
+ return MarkdownNodes.load(folder) unless Raindown.edition.full?
56
+
57
+ load_ruby(folder) + JSNodes.load(folder) + MarkdownNodes.load(folder)
48
58
  end
49
59
 
50
60
  # Dirload's steps, for the folder's Ruby files, as dirload(folder) takes them, a file that fails one being left out
@@ -80,7 +90,7 @@ module Raindown
80
90
 
81
91
  def find_folder(directory)
82
92
  loop do
83
- folder = File.join(directory, FOLDER)
93
+ folder = File.join(directory, Raindown.edition.folder)
84
94
  return folder if File.directory?(folder)
85
95
 
86
96
  parent = File.dirname(directory)
@@ -94,9 +104,9 @@ module Raindown
94
104
  @loaded ||= []
95
105
  end
96
106
 
97
- # The node class a block names, when it's loaded.
107
+ # The node class a block names, when it's loaded, and Raindown's own, in a full edition.
98
108
  def node_class(name)
99
- return loaded_class(name) unless BUILT_INS.key?(name)
109
+ return loaded_class(name) unless BUILT_INS.key?(name) && Raindown.edition.full?
100
110
 
101
111
  loaded_class(BUILT_INS[name]) || Raindown.const_get(BUILT_INS[name])
102
112
  end
@@ -78,9 +78,10 @@ module Raindown
78
78
  end
79
79
  end
80
80
 
81
- # Markdown in one of the project's files, as Raindown would write it back, with its nodes, as { output, warnings }.
82
- def rewrite_markdown(markdown, path)
83
- Editing.rewrite_markdown(markdown, path:, bare: @bare)
81
+ # Markdown in one of the project's files, as Raindown would write it back, with its nodes, as { output, warnings },
82
+ # after the actions inputs took, like a button's.
83
+ def rewrite_markdown(markdown, path, actions = [])
84
+ Editing.rewrite_markdown(markdown, path:, bare: @bare, actions:)
84
85
  end
85
86
 
86
87
  # The names of the nodes that rasterize, Raindown's own and the project's, for a file in it.
@@ -48,12 +48,20 @@ module Raindown
48
48
  # grid's cell is by the column its cell starts at, after its |.
49
49
  def repaint(path:, line:, column: nil, **space)
50
50
  Nodes.load(path)
51
- node = node_on(path, line, column)
51
+ node, props = node_on(path, line, column)
52
52
  raise ArgumentError, "Nothing on line #{line + 1} of #{path} rasterizes" unless node
53
53
 
54
54
  metadata = Pages.for(path)
55
- area = Area.new(**space)
56
- { painting: painting_of(node, area, metadata), formatting: formatting(node, metadata) }
55
+ painting = painting_of(node, Area.new(**space), metadata)
56
+ { painting: with_buttons_for(painting, props), formatting: formatting(node, metadata) }
57
+ end
58
+
59
+ # The painting with only the buttons for props its directive has, so the directive decides which it has, as a
60
+ # button changes them with an Action, which only changes those.
61
+ def with_buttons_for(painting, props)
62
+ return painting unless painting[:buttons]
63
+
64
+ painting.merge(buttons: painting[:buttons].select { |button| button[:set].keys.all? { props.include?(it.to_sym) } })
57
65
  end
58
66
 
59
67
  # What the node shows: a Scene, for one of an app's own painters to paint, like weather:'s valley, or else the area
@@ -75,7 +83,7 @@ module Raindown
75
83
  end
76
84
 
77
85
  # The node on the line, read with outdent blocks' lines without their <, as anywhere else, or in the grid cell at
78
- # the column.
86
+ # the column, with the names of the props its directive has.
79
87
  def node_on(path, line, column)
80
88
  content = Utils.read_markdown(path)
81
89
  lines = Outdent.without_markers(content).lines
@@ -83,7 +91,8 @@ module Raindown
83
91
 
84
92
  bare = BareDirectives.enabled?(path:, content:)
85
93
  blocks = NodeBlocks.find(lines, front_matter: FrontMatter.parse(content).first, bare:)
86
- blocks.find { it[:open] == line && it[:node].respond_to?(:rasterize) }&.dig(:node)
94
+ node = blocks.find { it[:open] == line && it[:node].respond_to?(:rasterize) }&.dig(:node)
95
+ [node, prop_names(lines[line], bare:)]
87
96
  end
88
97
 
89
98
  # The node whose directive starts the grid cell at the column of the line, up to the cell's next |.
@@ -92,7 +101,15 @@ module Raindown
92
101
  return unless GridDirectives.directive?(text)
93
102
 
94
103
  blocks = NodeBlocks.find(["#{text}\n"], bare: true)
95
- blocks.find { it[:node].respond_to?(:rasterize) }&.dig(:node)
104
+ [blocks.find { it[:node].respond_to?(:rasterize) }&.dig(:node), prop_names(text, bare: true)]
105
+ end
106
+
107
+ # The names of the props the directive on the line has.
108
+ def prop_names(text, bare:)
109
+ match, = NodeBlocks.directive(text.to_s.chomp, bare:)
110
+ return [] unless match&.[](3)
111
+
112
+ NodeBlocks.args(match[3], {}).first.keys
96
113
  end
97
114
  end
98
115
  end
@@ -22,9 +22,14 @@ module Raindown
22
22
  def rewrite(content:, path:, bare: false, execute: false, metadata: NoMetadata)
23
23
  injector = NodeInjector.new(content:, path:, bare:, metadata:)
24
24
  injected = injector.call
25
- endpoints = EndpointRunner.new(content: injected, path:, bare: BareDirectives.enabled?(path:, content: injected, bare:), execute:)
26
- Rewrite.new(original: content, content: TableFormatter.rewrite(content: endpoints.rewrite), failures: endpoints.failures,
27
- problems: injector.problems)
25
+ return Rewrite.new(original: content, content: injected, failures: [], problems: injector.problems) unless Raindown.edition.full?
26
+
27
+ # Only a file naming an endpoint has one to run, so the rest aren't read again for one.
28
+ if injected.include?('endpoint:')
29
+ endpoints = EndpointRunner.new(content: injected, path:, bare: BareDirectives.enabled?(path:, content: injected, bare:), execute:)
30
+ end
31
+ Rewrite.new(original: content, content: TableFormatter.rewrite(content: endpoints&.rewrite || injected),
32
+ failures: Array(endpoints&.failures), problems: injector.problems)
28
33
  end
29
34
 
30
35
  # Writes the file only when it changed.
@@ -27,7 +27,7 @@ module Raindown
27
27
  # The services for a project, by its root, made once.
28
28
  def at(root)
29
29
  @at ||= {}
30
- @at[File.expand_path(root)] ||= new(root:)
30
+ @at[root] ||= @at[File.expand_path(root)] ||= new(root:)
31
31
  end
32
32
 
33
33
  # The services for the page being written, from its metadata's root, or else the current folder.
@@ -13,6 +13,8 @@ module Raindown
13
13
  CONTINUATION = /\A\s*\|\+/
14
14
 
15
15
  def self.rewrite(content:, **)
16
+ return content unless content.include?('|')
17
+
16
18
  new(content:).format
17
19
  end
18
20
 
data/lib/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Raindown
4
- VERSION = '0.22.0'
4
+ VERSION = '0.24.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: raindown
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.22.0
4
+ version: 0.24.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - maedi
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: 1.5.0
18
+ version: 1.5.1
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
- version: 1.5.0
25
+ version: 1.5.1
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: commonmarker
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -209,6 +209,7 @@ files:
209
209
  - lib/nodes/list_node.rb
210
210
  - lib/nodes/write_in_node.rb
211
211
  - lib/raindown.rb
212
+ - lib/raindown/action.rb
212
213
  - lib/raindown/actions.rb
213
214
  - lib/raindown/area.rb
214
215
  - lib/raindown/bare_directives.rb
@@ -228,6 +229,7 @@ files:
228
229
  - lib/raindown/directives.rb
229
230
  - lib/raindown/document.rb
230
231
  - lib/raindown/editing.rb
232
+ - lib/raindown/edition.rb
231
233
  - lib/raindown/endpoint/curl.rb
232
234
  - lib/raindown/endpoint/curl_request.rb
233
235
  - lib/raindown/endpoint/curl_response.rb
@@ -244,6 +246,8 @@ files:
244
246
  - lib/raindown/heading_ids.rb
245
247
  - lib/raindown/http_json.rb
246
248
  - lib/raindown/image.rb
249
+ - lib/raindown/js/action.js
250
+ - lib/raindown/js/editing.js
247
251
  - lib/raindown/js/js_nodes.rb
248
252
  - lib/raindown/js/quickjs_host.rb
249
253
  - lib/raindown/js/quickjs_runtime.js