raindown 0.21.3 → 0.23.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: 714d64b4843d94b4752da53527dcc7c2f3e1fe77ce4aea56aec0ca0b76dfaa6a
4
- data.tar.gz: be27d12a02197bcac1b2ef6f404779de9a47a3d8047787db4291731e4ff3cbc9
3
+ metadata.gz: d8f771e6d03694259adcb9e610b3bb963484f2206b9e07c1d7fd6f6620f42052
4
+ data.tar.gz: 2d872e77989e94b7094ece252fb592a54e797f0caa890aff521042b70926d789
5
5
  SHA512:
6
- metadata.gz: b90a67a177422426703135277ab357e1d332968303ca4adaca91043f99b8ae70f91ab52de03097d1f307ea52519ef687edce28f4b08eafd9d69b0a6caf8b9885
7
- data.tar.gz: 6d1e00f5edcdaabeecc8bb87b2a9854f075649efe4dee83447156eaff48c5c3f4d58ae4ba88a0ab8bfd21f69902b10cc0996f8f5969ae2d3c2276999b1506d99
6
+ metadata.gz: f74bb5da60658f7d58c03b412319a7303e7d1d4a768e0794b58e43bf8489c8628ff1a20db911691cbd76d3169fa1f836956cd3cb4bd873cd5d8e736f6b87fb52
7
+ data.tar.gz: c5c8abc856f4e1191ed84b12124846026bc6bd3ecca37dabe445f5b3d420d1cc707b4d19af906611bc76febab17abb09ef9b082701cf316fb04b59e09e6e6d3c
@@ -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
@@ -5,8 +5,9 @@ require_relative 'code_blocks'
5
5
  module Raindown
6
6
  # Finds code in Markdown the way Commonmarker reads it: code spans and fenced, indented or quoted code blocks.
7
7
  module Code
8
- # A code span on one line, like `{x}`, between runs of the same number of backticks.
9
- SPAN = /(?<!`)(`+)(?!`).+?(?<!`)\1(?!`)/n
8
+ # A code span on one line, like `{x}`, between runs of the same number of backticks, from the run it opens with.
9
+ SPAN = /\G(`+)(?!`).+?(?<!`)\1(?!`)/n
10
+ NOT_BACKTICK = /[^`]/n
10
11
 
11
12
  module_function
12
13
 
@@ -47,8 +48,19 @@ module Raindown
47
48
  ranges
48
49
  end
49
50
 
51
+ # The line's spans, each matched from its next run of backticks, which byteindex finds without a regex, so the
52
+ # text between spans is never scanned, and nor is a line without a backtick, as most are. A run that opens no span
53
+ # is passed over whole.
50
54
  def span_ranges(line, start)
51
- line.b.to_enum(:scan, SPAN).map { (start + ::Regexp.last_match.begin(0))...(start + ::Regexp.last_match.end(0)) }
55
+ bytes = line.b
56
+ ranges = []
57
+ from = 0
58
+ while (open = bytes.byteindex('`', from))
59
+ from = SPAN.match(bytes, open)&.end(0)
60
+ ranges << ((start + open)...(start + from)) if from
61
+ from ||= bytes.byteindex(NOT_BACKTICK, open) || break
62
+ end
63
+ ranges
52
64
  end
53
65
 
54
66
  def range(position, line_offsets)
@@ -15,8 +15,10 @@ module Raindown
15
15
 
16
16
  # The block opening at index, closed by a fence of the same character that's at least as long.
17
17
  def at(lines, index)
18
- fence, language = lines[index]&.match(FENCE)&.captures
19
- return unless fence
18
+ # Most lines open no fence, and match? makes no match to find that out.
19
+ return unless lines[index]&.match?(FENCE)
20
+
21
+ fence, language = lines[index].match(FENCE).captures
20
22
 
21
23
  close = (index + 1...lines.length).find { |i| lines[i].match?(CLOSINGS[fence]) }
22
24
  { open: index, close:, language:, body: lines[index + 1...close].join } if close
@@ -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,62 @@
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
+
22
+ const lines = markdown.split('\n')
23
+ const text = lines[line]
24
+ if (text === undefined) return markdown
25
+
26
+ // 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
27
+ // spaces around it.
28
+ let [from, to] = [0, text.replace(/\r$/, '').length]
29
+ if (column !== null) {
30
+ const cell = text.slice(column).split('|')[0]
31
+ from = column + cell.length - cell.trimStart().length
32
+ to = from + cell.trim().length
33
+ }
34
+ let patterns = DIRECTIVES
35
+ if (bare || column !== null) patterns = [...DIRECTIVES, ...BARE_DIRECTIVES]
36
+ const match = patterns.map((pattern) => text.slice(from, to).match(new RegExp(pattern))).find(Boolean)
37
+ if (!match) return markdown
38
+
39
+ // 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.
40
+ const props = match[2]
41
+ const at = from + match[1].length
42
+ let start = props.match(ARG)?.[0].length ?? 0
43
+ if (new RegExp(`^${PROP}`).test(props)) start = 0
44
+ const values = {}
45
+ for (const found of props.slice(start).matchAll(new RegExp(PROP, 'g'))) {
46
+ const end = at + start + found.index + found[0].length
47
+ values[found[1]] = [end - found[2].length, end]
48
+ }
49
+ if (!Object.keys(set).every((name) => name in values)) return markdown
50
+
51
+ // Each value typed over where the prop's was, from the last, so where the others are doesn't move.
52
+ const typed = (value) => {
53
+ if (value === null) return 'nil'
54
+ if (typeof value !== 'string') return String(value)
55
+ if (!value.includes("'")) return `'${value}'`
56
+ if (value.includes('"')) throw new Error(`Can't write ${value} as a prop, as it has both kinds of quote`)
57
+ return `"${value}"`
58
+ }
59
+ const spans = Object.entries(set).map(([name, value]) => [...values[name], typed(value)]).sort(([a], [b]) => b - a)
60
+ lines[line] = spans.reduce((edited, [begin, end, value]) => edited.slice(0, begin) + value + edited.slice(end), text)
61
+ return lines.join('\n')
62
+ }
@@ -0,0 +1,495 @@
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
+
23
+ // Strings, {variables}, numbers, :flags, props like folder: or limit=, and words.
24
+ 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;
25
+
26
+ // The highlighted parts of a note, in order, as { from, to, type }, where type is a class like cm-raindown-name.
27
+ function directiveTokens(text, { bare = false } = {}) {
28
+ const front = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(text);
29
+ const bareHere = bare || /^raindown:\s*true\s*$/m.test(front?.[1] ?? '');
30
+ const tokens = [];
31
+ let offset = front ? front[0].length : 0;
32
+ let fence = null;
33
+
34
+ for (const line of text.slice(offset).split('\n')) {
35
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
36
+ if (fence) {
37
+ if (marker?.[0] === fence[0] && marker.length >= fence.length) fence = null;
38
+ } else if (marker) {
39
+ fence = marker;
40
+ } else {
41
+ tokens.push(...lineTokens(line, { bare: bareHere }).map((token) => ({ ...token, from: token.from + offset, to: token.to + offset })));
42
+ }
43
+ offset += line.length + 1;
44
+ }
45
+
46
+ return tokens.sort((a, b) => a.from - b.from);
47
+ }
48
+
49
+ function lineTokens(line, { bare }) {
50
+ const code = [...line.matchAll(/(`+)[^`]*?\1/g)].map((match) => [match.index, match.index + match[0].length]);
51
+ const tokens = [];
52
+ const add = (from, to, type) => {
53
+ if (!code.some(([start, end]) => from < end && to > start)) tokens.push({ from, to, type });
54
+ };
55
+
56
+ for (const match of line.matchAll(COMMENT_DIRECTIVE)) {
57
+ const name = match[1] ?? match[2];
58
+ const start = match.index + match[0].indexOf(name);
59
+ add(start, start + name.length, match[1] ? 'end' : 'name');
60
+ argumentTokens(match[3], start + name.length, { antlers: false }, add);
61
+ }
62
+ for (const match of line.matchAll(ANTLERS)) {
63
+ const end = match.index + match[0].length;
64
+ add(match.index, match.index + 2, 'delimiter');
65
+ argumentTokens(match[1], match.index + 2, { antlers: true }, add);
66
+ add(end - 2, end, 'delimiter');
67
+ }
68
+ if (!bare) return tokens;
69
+
70
+ const selfClosing = BARE_SELF_CLOSING.exec(line);
71
+ const open = BARE_OPEN.exec(line);
72
+ if (selfClosing) add(selfClosing[1].length, selfClosing[1].length + selfClosing[2].length, 'self-closing');
73
+ if (open) {
74
+ const end = open[1].length + open[2].length;
75
+ add(open[1].length, end, 'name');
76
+ argumentTokens(line.slice(end), end, { antlers: false }, add);
77
+ }
78
+
79
+ return tokens;
80
+ }
81
+
82
+ // 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,
83
+ // the line its table starts on, whether it's the header or the delimiter row below it, and the line of the row below
84
+ // it, or null outside a table's rows.
85
+ function tableRowAt(lines, { line, ch }) {
86
+ const row = (number) => /^\s*[|+]/.test(lines[number] ?? '') && lines[number].trim();
87
+ let start = line;
88
+ while (start > 0 && row(start - 1)) start--;
89
+ if (!row(line) || !isTableStart(lines, start)) return null;
90
+
91
+ const lead = lines[line].search(/[|+]/);
92
+ if (ch <= lead) return null;
93
+
94
+ let [first, last] = [line, line];
95
+ while (first > start + 2 && CONTINUATION.test(lines[first])) first--;
96
+ while (CONTINUATION.test(lines[last + 1] ?? '')) last++;
97
+ const header = line === start;
98
+ const below = header ? start + 2 : last + 1;
99
+ const column = [...lines[line].slice(lead + 1, ch).matchAll(/(?<!\\)\|/g)].length;
100
+ return { start, first, last, column, header, delimiter: line === start + 1, next: row(below) ? below : null };
101
+ }
102
+
103
+ // Whether the table starting on the line is a table: block's, below its directive and its comment.
104
+ function underTableDirective(text, lines, start, options) {
105
+ const above = BLOCK_COMMENT.test(lines[start - 1] ?? '') ? start - 1 : start;
106
+ const directiveEnd = lines.slice(0, above).join('\n').length;
107
+ return tableFiles(text, options).some(({ at }) => at === directiveEnd);
108
+ }
109
+
110
+ // 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
111
+ // shown in full on |+ rows, or 'expand' one cut to fit, ending in an ellipsis, deleting it so Raindown shows its full
112
+ // text. Elsewhere it's null, and Enter only moves to the row below.
113
+ function cellToggle(text, lines, row, options) {
114
+ if (!underTableDirective(text, lines, row.start, options)) return null;
115
+
116
+ const below = lines.slice(row.first + 1, row.last + 1).map(tableCells);
117
+ if (below.some((cells) => cells[row.column])) return 'collapse';
118
+ if (tableCells(lines[row.first])[row.column]?.endsWith('…')) return 'expand';
119
+ return null;
120
+ }
121
+
122
+ // Whether the cursor's in a table: block's fixed column, like |=====|, or on the |+ rows of a cell in one.
123
+ function inFixedCell(text, cursor, options) {
124
+ const lines = text.split('\n');
125
+ const row = tableRowAt(lines, cursor);
126
+ if (!row || row.delimiter || !fixedColumn(tableCells(lines[row.start + 1])[row.column] ?? '')) return false;
127
+
128
+ return underTableDirective(text, lines, row.start, options);
129
+ }
130
+
131
+ // What Enter does to the cell at the offset, for its hint.
132
+ function cellToggleAt(text, offset, options) {
133
+ const lines = text.split('\n');
134
+ const row = tableRowAt(lines, positionOf(text, offset));
135
+ return row && cellToggle(text, lines, row, options);
136
+ }
137
+
138
+ // 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.
139
+ function cellBounds(line, column) {
140
+ const lead = line.match(/^[ \t]*\|\+?/)?.[0].length ?? 0;
141
+ const pipes = [...line.matchAll(/(?<!\\)\|/g)].map(({ index }) => index).filter((index) => index >= lead);
142
+ const from = column === 0 ? lead : pipes[column - 1] + 1;
143
+ if (Number.isNaN(from)) return null;
144
+
145
+ return { from, to: pipes[column] ?? line.length };
146
+ }
147
+
148
+ // 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
149
+ // it's empty.
150
+ function cellEndIn(line, column) {
151
+ const cell = cellBounds(line, column);
152
+ if (!cell) return line.length;
153
+
154
+ return cell.from + Math.max(1, line.slice(cell.from, cell.to).trimEnd().length);
155
+ }
156
+
157
+ // An empty row for the row's table, indented like it, which the table lines up.
158
+ function emptyRow(lines, row) {
159
+ const cells = tableCells(lines[row.start + 1]).map(() => '');
160
+ return `${lines[row.first].match(/^[ \t]*/)[0]}| ${cells.join(' | ')} |`;
161
+ }
162
+
163
+ // A row and its |+ rows with one column's cell joined back onto the row's line, its parts joined with spaces, leaving
164
+ // the other columns' cells as they are, and the |+ rows nothing's left on out.
165
+ function collapsedColumn(rows, column) {
166
+ const cells = rows.map(tableCells);
167
+ const indent = rows[0].match(/^[ \t]*/)[0];
168
+ const joined = cells.map((row) => row[column] ?? '').filter(Boolean).join(' ');
169
+ const first = cells[0].map((cell, index) => (index === column ? joined : cell));
170
+ const below = cells.slice(1).map((row) => row.map((cell, index) => (index === column ? '' : cell))).filter((row) => row.some(Boolean));
171
+ return [`${indent}| ${first.join(' | ')} |`, ...below.map((row) => `${indent}|+${row.join(' | ')} |`)];
172
+ }
173
+
174
+ // 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
175
+ // 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,
176
+ // staying in it, and collapses one shown in full, joining its text on the |+ rows back onto its row first, so Raindown
177
+ // clips it again. As offsets, with what it toggled, or null outside a table's rows.
178
+ function enteredCell(text, offset, options) {
179
+ const lines = text.split('\n');
180
+ const row = tableRowAt(lines, positionOf(text, offset));
181
+ if (!row) return null;
182
+
183
+ const toggle = cellToggle(text, lines, row, options);
184
+ if (toggle === 'expand') return expandedCell(text, lines, row);
185
+
186
+ const rows = lines.slice(row.first, row.last + 1);
187
+ const kept = toggle === 'collapse' ? collapsedColumn(rows, row.column) : rows;
188
+ // In the last row, a row's added below it to move to, like a spreadsheet's next row.
189
+ const added = row.next === null && !row.header ? [emptyRow(lines, row)] : [];
190
+ const insert = [...kept, ...added].join('\n');
191
+ const from = offsetOf(text, { line: row.first, ch: 0 });
192
+ const to = offsetOf(text, { line: row.last, ch: lines[row.last].length });
193
+ const after = text.slice(0, from) + insert + text.slice(to);
194
+ const target = row.next === null ? row.first + kept.length - 1 + added.length : row.next - (rows.length - kept.length);
195
+ const cursor = offsetOf(after, { line: target, ch: cellEndIn(after.split('\n')[target], row.column) });
196
+
197
+ return { from, to, insert, cursor, toggle };
198
+ }
199
+
200
+ // The change expanding a cell cut to fit: its ellipsis deleted, with the cursor where it was.
201
+ function expandedCell(text, lines, row) {
202
+ const line = lines[row.first];
203
+ const cell = cellBounds(line, row.column);
204
+ const at = offsetOf(text, { line: row.first, ch: line.lastIndexOf('…', cell.to) });
205
+ return { from: at, to: at + 1, insert: '', cursor: at, toggle: 'expand' };
206
+ }
207
+
208
+ // 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
209
+ // the first of the row below, or with back, like Shift and Tab, the previous cell, or the last of the row above. It
210
+ // stays put in the table's last cell, or first, so Tab never splits a row. Null outside a table's rows.
211
+ function tabbedCell(text, offset, { back = false } = {}) {
212
+ const lines = text.split('\n');
213
+ const position = positionOf(text, offset);
214
+ const row = tableRowAt(lines, position);
215
+ if (!row) return null;
216
+
217
+ const { line } = position;
218
+ const columns = tableCells(lines[row.start + 1]).length;
219
+ const at = (number, column) => offsetOf(text, { line: number, ch: cellEndIn(lines[number], column) });
220
+ const column = row.column + (back ? -1 : 1);
221
+ if (column >= 0 && column < columns) return at(line, column);
222
+ if (!back) return row.next === null ? at(line, row.column) : at(row.next, 0);
223
+
224
+ let above = row.first - 1;
225
+ if (above === row.start + 1) above = row.start;
226
+ while (above > row.start + 2 && CONTINUATION.test(lines[above])) above--;
227
+ return above < row.start ? at(line, row.column) : at(above, columns - 1);
228
+ }
229
+
230
+ // The change Option or Alt and Enter makes in a table's cell, like a line break in a spreadsheet: a |+ row below the
231
+ // cursor's row carrying the cell on, with what's after the cursor in it, rather than splitting the row, which would
232
+ // end the table. As offsets, with where the cursor goes, or null outside a table's rows, or in its header or
233
+ // delimiter row.
234
+ function carriedOnCell(text, offset) {
235
+ const lines = text.split('\n');
236
+ const { line, ch } = positionOf(text, offset);
237
+ const row = tableRowAt(lines, { line, ch });
238
+ if (!row || row.header || row.delimiter) return null;
239
+
240
+ const { column } = row;
241
+ const current = lines[line];
242
+ const cellEnd = current.slice(ch).search(/(?<!\\)\|/);
243
+ const end = cellEnd === -1 ? current.length : ch + cellEnd;
244
+ const carried = `|+${' | '.repeat(column)}`;
245
+ const cells = tableCells(lines[row.start + 1]).map((_, index) => (index === column ? current.slice(ch, end).trim() : ''));
246
+ const from = offsetOf(text, { line, ch: 0 });
247
+ const insert = `${current.slice(0, ch).trimEnd()} ${current.slice(end)}\n|+${cells.join(' | ')} |`;
248
+
249
+ return { from, to: from + current.length, insert, cursor: from + insert.indexOf('\n') + 1 + carried.length };
250
+ }
251
+
252
+ // Each table: directive's file, like 'data/books.csv', with where its line ends, for a button to open it there.
253
+ function tableFiles(text, options) {
254
+ const tokens = directiveTokens(text, options);
255
+
256
+ return tokens.flatMap((token, index) => {
257
+ if (!/^:?table:?$/.test(text.slice(token.from, token.to))) return [];
258
+
259
+ let lineEnd = text.indexOf('\n', token.to);
260
+ if (lineEnd === -1) lineEnd = text.length;
261
+ const data = directiveArgument(text.slice(token.to, lineEnd));
262
+ if (!data) return [];
263
+
264
+ return [{ at: lineEnd, data }];
265
+ });
266
+ }
267
+
268
+ // The value after a directive's name, like its file, quoted or not, as Raindown reads it, up to any props, like
269
+ // data/books.csv in table: data/books.csv total: true, or table: data/books.csv, total: true, or null without one.
270
+ function directiveArgument(rest) {
271
+ const text = rest.replace(/\s*(?:-->|\}>)\s*$/, '').trim();
272
+ const quoted = /^(["'])(.*?)\1/.exec(text);
273
+ if (quoted) return quoted[2];
274
+
275
+ return /^(.*?)(?=(?:,[ \t]*|\s+)\w+(?:=|:\s)|,?\s*$)/.exec(text)[1] || null;
276
+ }
277
+
278
+ // In <{ }>, its first word is the directive, like toc: or :toc, and words are variables. Outside, words are text.
279
+ function argumentTokens(text, offset, { antlers }, add) {
280
+ let first = antlers;
281
+ for (const match of text.matchAll(ARGUMENT)) {
282
+ const type = argumentType(match[0], { antlers, first });
283
+ first = false;
284
+ if (type) add(offset + match.index, offset + match.index + match[0].length, type);
285
+ }
286
+ }
287
+
288
+ function argumentType(token, { antlers, first }) {
289
+ if (/^["']/.test(token)) return 'string';
290
+ if (token.startsWith('{')) return 'variable';
291
+ if (/^-?\d/.test(token)) return 'number';
292
+ if (token.startsWith(':')) return first ? 'end' : 'flag';
293
+ if (/[:=]$/.test(token)) return first ? 'name' : 'prop';
294
+
295
+ return antlers ? 'variable' : null;
296
+ }
297
+
298
+ // Whether the cursor's in a table cell starting with =, so a formula that's still being typed.
299
+ function inFormulaCell(line, ch) {
300
+ const start = line.lastIndexOf('|', ch - 1);
301
+ if (!line.trimStart().startsWith('|') || start === -1) return false;
302
+
303
+ return line.slice(start + 1, ch).trimStart().startsWith('=');
304
+ }
305
+
306
+ // The start of each line of a Markdown table, and its |+ rows, as Raindown's columns only line up in a monospace font,
307
+ // with its header, to show in bold, its delimiter row, to show muted, and its pipes, to show faint, but for those of a
308
+ // row carrying one on, its |+ and pipes, in the accent colour.
309
+ function tableLines(markdown) {
310
+ const lines = markdown.split('\n');
311
+ let offset = 0;
312
+ return lines.flatMap((line, number) => {
313
+ const from = offset;
314
+ offset += line.length + 1;
315
+ if (!/^[ \t]*\|.*\|[ \t]*$/.test(line)) return [];
316
+
317
+ const header = isTableStart(lines, number) ? [{ from, to: from + line.length, type: 'table-header' }] : [];
318
+ const delimiter = number > 0 && isTableStart(lines, number - 1) ? [{ from, to: from + line.length, type: 'table-delimiter' }] : [];
319
+ // 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.
320
+ const type = CONTINUATION.test(line) ? 'table-expansion' : 'table-pipe';
321
+ const pipes = [...line.matchAll(/(?<!\\)\||(?<=^[ \t]*\|)\+/g)].map(({ index }) => ({ from: from + index, to: from + index + 1, type }));
322
+ return [{ from, type: 'table' }, ...header, ...delimiter, ...pipes];
323
+ });
324
+ }
325
+
326
+ // Lining up tables as they're typed, the same as Raindown's TableFormatter, so its write-back finds them lined up.
327
+ const DELIMITER_CELL = /^:?[-=]+:?$/;
328
+
329
+ // A row carrying on the one above it, starting with |+ in place of a row's "| ", which Raindown joins into its cells.
330
+ const CONTINUATION = /^[ \t\n\v\f\r]*\|\+/;
331
+
332
+ const FENCE = /^\s*(```|~~~)/;
333
+
334
+ // Ruby's strip, which leaves other spaces, like a no-break space, in the cell.
335
+ const STRIP = /^[ \t\n\v\f\r\0]+|[ \t\n\v\f\r\0]+$/g;
336
+
337
+ // East Asian wide and fullwidth letters, and emoji, take two columns, like unicode-display-width's with emoji: :all.
338
+ const WIDE = new RegExp(String.raw`[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF` +
339
+ String.raw`\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}\uFE0F\u20E3]` +
340
+ String.raw`|\p{Emoji_Presentation}`, 'u');
341
+
342
+ const ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}]+$/u;
343
+
344
+ // Graphemes, where the engine can tell them, or else characters, as in QuickJS, which hasn't got Intl.
345
+ const graphemes = typeof Intl === 'object' && Intl.Segmenter && new Intl.Segmenter();
346
+
347
+ function displayWidth(text) {
348
+ let width = 0;
349
+ for (const segment of segmentsOf(text)) {
350
+ if (WIDE.test(segment)) width += 2;
351
+ else if (!ZERO_WIDTH.test(segment)) width += 1;
352
+ }
353
+ return width;
354
+ }
355
+
356
+ function segmentsOf(text) {
357
+ if (!graphemes) return Array.from(text);
358
+
359
+ return Array.from(graphemes.segment(text), ({ segment }) => segment);
360
+ }
361
+
362
+ // How a row's line starts, before its first cell: |+ when it carries on the row above, as wide as a row's "| ".
363
+ function rowLead(line) {
364
+ return CONTINUATION.test(line) ? '|+' : '| ';
365
+ }
366
+
367
+ // A row's cells, split on pipes that aren't escaped, without its outer pipes, or the |+ starting a continuation row.
368
+ function tableCells(line) {
369
+ let content = line.replace(STRIP, '');
370
+ const lead = rowLead(line).trimEnd();
371
+ if (content.startsWith(lead)) content = content.slice(lead.length);
372
+ if (content.endsWith('|') && !content.endsWith('\\|')) content = content.slice(0, -1);
373
+ if (!content) return [];
374
+
375
+ return content.split(/(?<!\\)\|/).map((cell) => cell.replace(STRIP, ''));
376
+ }
377
+
378
+ function isTableStart(lines, index) {
379
+ const [header, delimiter] = [lines[index], lines[index + 1]];
380
+ if (!header.includes('|') || delimiter === undefined || CONTINUATION.test(header)) return false;
381
+
382
+ const cells = tableCells(delimiter);
383
+ if (!cells.length || cells.length !== tableCells(header).length) return false;
384
+
385
+ return cells.every((cell) => DELIMITER_CELL.test(cell));
386
+ }
387
+
388
+ // Whether a column's delimiter cell makes it fixed, like Raindown's TableColumn: equals signs, or one typed into dashes,
389
+ // as fewer of them than dashes, while a dash typed into equals signs makes it widen again.
390
+ function fixedColumn(delimiter) {
391
+ const [equals, dashes] = ['=', '-'].map((sign) => delimiter.split(sign).length - 1);
392
+ return equals > 0 && (dashes === 0 || equals < dashes);
393
+ }
394
+
395
+ // A column, like Raindown's TableColumn: its alignment, from its delimiter cell's colons, and its width, that of its
396
+ // widest cell, or as wide as its delimiter when that's equals signs, which is fixed, letting a longer cell run past.
397
+ function tableColumn(delimiter, cells) {
398
+ const fixed = fixedColumn(delimiter);
399
+ // An equals sign typed into dashes isn't part of its width, so it's fixed as wide as it was.
400
+ const typed = delimiter.includes('-') ? delimiter.split('=').length - 1 : 0;
401
+ const width = fixed ? delimiter.length - typed : Math.max(3, ...cells.map(displayWidth));
402
+ const dash = fixed ? '=' : '-';
403
+ let alignment = null;
404
+ if (delimiter.startsWith(':') && delimiter.endsWith(':')) alignment = 'center';
405
+ else if (delimiter.endsWith(':')) alignment = 'right';
406
+ else if (delimiter.startsWith(':')) alignment = 'left';
407
+
408
+ return {
409
+ pad(cell) {
410
+ const padding = Math.max(0, width - displayWidth(cell));
411
+ if (alignment === 'center') return ' '.repeat(Math.floor(padding / 2)) + cell + ' '.repeat(Math.ceil(padding / 2));
412
+ if (alignment === 'right') return ' '.repeat(padding) + cell;
413
+ return cell + ' '.repeat(padding);
414
+ },
415
+ delimiterCell() {
416
+ if (alignment === 'center') return `:${dash.repeat(width - 2)}:`;
417
+ if (alignment === 'right') return `${dash.repeat(width - 1)}:`;
418
+ if (alignment === 'left') return `:${dash.repeat(width - 1)}`;
419
+ return dash.repeat(width);
420
+ }
421
+ };
422
+ }
423
+
424
+ // A table's lines with each column padded to fit, keeping each row's + when it carries on the row above, or as they
425
+ // were when a row has more cells than its header.
426
+ function alignedTable(table) {
427
+ const indent = table[0].match(/^[ \t\n\v\f\r]*/)[0];
428
+ const [header, delimiter, ...body] = table.map(tableCells);
429
+ if (body.some((row) => row.length > header.length)) return table;
430
+
431
+ const rows = [header, ...body.map((row) => [...row, ...Array(header.length - row.length).fill('')])];
432
+ const columns = delimiter.map((cell, column) => tableColumn(cell, rows.map((row) => row[column])));
433
+ const line = (lead, cells) => `${indent}${lead}${cells.join(' | ')} |`;
434
+ const lines = [table[0], ...table.slice(2)].map((original, row) => line(rowLead(original), rows[row].map((cell, column) => columns[column].pad(cell))));
435
+
436
+ return [lines[0], line('| ', columns.map((column) => column.delimiterCell())), ...lines.slice(1)];
437
+ }
438
+
439
+ // The note with every table lined up, outside code. Like Raindown, one lined up at the very end gets a line break
440
+ // after it.
441
+ function alignTables(markdown) {
442
+ const lines = markdown.split('\n');
443
+ const output = [];
444
+ let inFence = false;
445
+ for (let index = 0; index < lines.length;) {
446
+ if (FENCE.test(lines[index])) inFence = !inFence;
447
+ if (inFence || !isTableStart(lines, index)) {
448
+ output.push(lines[index++]);
449
+ continue;
450
+ }
451
+
452
+ let end = index + 2;
453
+ while (end < lines.length && lines[end].includes('|') && lines[end].trim()) end++;
454
+ const table = lines.slice(index, end);
455
+ const aligned = alignedTable(table);
456
+ output.push(...aligned, ...(end === lines.length && aligned !== table ? [''] : []));
457
+ index = end;
458
+ }
459
+ return output.join('\n');
460
+ }
461
+
462
+ function offsetOf(text, { line, ch }) {
463
+ return text.split('\n').slice(0, line).reduce((offset, before) => offset + before.length + 1, ch);
464
+ }
465
+
466
+ function positionOf(text, offset) {
467
+ const lines = text.slice(0, offset).split('\n');
468
+ return { line: lines.length - 1, ch: lines.at(-1).length };
469
+ }
470
+
471
+ // The |+ lines carrying on the table rows a deletion removes the whole of, each with its line break, so they go with
472
+ // their row rather than being left below the row above, which Raindown would read them as carrying on. As ranges in the
473
+ // text before the deletion, which is ranges too.
474
+ function orphanedRows(text, deletions) {
475
+ const lines = text.split('\n');
476
+ const starts = [0];
477
+ lines.forEach((line) => starts.push(starts.at(-1) + line.length + 1));
478
+ const removed = (number) => deletions.some(({ from, to }) => from <= starts[number] && starts[number] + lines[number].length <= to);
479
+
480
+ return lines.flatMap((line, number) => {
481
+ if (!line.trim() || !removed(number) || !/^[ \t]*\|/.test(line) || CONTINUATION.test(line)) return [];
482
+
483
+ let last = number;
484
+ while (CONTINUATION.test(lines[last + 1] ?? '')) last++;
485
+ const rows = Array.from({ length: last - number }, (_, index) => number + 1 + index).filter((row) => !removed(row));
486
+ return rows.map((row) => ({ from: starts[row], to: Math.min(starts[row + 1], text.length) }));
487
+ });
488
+ }
489
+
490
+ return {
491
+ BLOCK_COMMENT, alignTables, carriedOnCell, cellToggleAt, directiveTokens, enteredCell, inFixedCell, inFormulaCell, offsetOf, orphanedRows, positionOf, tabbedCell, tableCells, tableFiles, tableLines
492
+ };
493
+ })();
494
+
495
+ 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
  }
@@ -33,6 +33,8 @@ module Raindown
33
33
  SELF_CLOSING = /\A( {0,3})<\{\s*(?::|(?=[A-Z]))(#{NAME})(?:\s+(.*?))?\s*\}>[ \t]*$/
34
34
  BARE_SELF_CLOSING = /\A( {0,3}):(#{NAME})(?:[ \t]+(.*?))?[ \t]*$/
35
35
  BARE_GRID = /\A {0,3}\+-[-+]*\+[ \t]*$/
36
+ DIRECTIVES = { open: OPEN, comment_open: COMMENT_OPEN, self_closing: SELF_CLOSING }.freeze
37
+ BARE_DIRECTIVES = { **DIRECTIVES, bare_open: BARE_OPEN, bare_self_closing: BARE_SELF_CLOSING }.freeze
36
38
  # Unquoted text after name:, like YAML's, runs up to the next prop, so title: Hello world limit: 3 has two. A comma
37
39
  # before the next prop, like data.csv, total: true, separates them like a space, while one in text, like Hello,
38
40
  # world, is part of it.
@@ -42,6 +44,15 @@ module Raindown
42
44
  PROP = /(\w+)(?:=|:[ \t]+)("[^"]*"|'[^']*'|(?<==)\S+?(?=,?(?:\s|\z))|#{UNQUOTED})/
43
45
  # A value before the props is the node's argument.
44
46
  ARG = /\A("[^"]*"|'[^']*'|[^\s"']#{UNQUOTED}|[^\s"'])(?:,\s*|\s+|\z)/
47
+ PROP_FIRST = /\A#{PROP}/
48
+ # A whole number, or text in quotes without escapes, read without parsing it as Ruby, as most values are.
49
+ INTEGER = /\A-?(?:0|[1-9]\d*)\z/
50
+ PLAIN_QUOTED = /\A(?:'[^'\\]*'|"[^"\\#]*")\z/
51
+ # The line ending a block, by its node's name and whether it's in a comment, compiled once for each.
52
+ END_TAGS = Hash.new do |tags, (name, comment)|
53
+ first, last = comment ? Directives::COMMENT : Directives::DELIMITERS
54
+ tags[[name, comment]] = /\A {0,3}#{Regexp.escape(first)}\s*:#{Regexp.escape(name)}\s*#{Regexp.escape(last)}[ \t]*$/
55
+ end
45
56
 
46
57
  module_function
47
58
 
@@ -156,9 +167,8 @@ module Raindown
156
167
 
157
168
  # The directive on the line and which kind it is, or nil.
158
169
  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
-
170
+ patterns = DIRECTIVES
171
+ patterns = BARE_DIRECTIVES if bare
162
172
  patterns.each do |pattern, regexp|
163
173
  match = line.match(regexp)
164
174
  return [match, pattern] if match
@@ -178,7 +188,7 @@ module Raindown
178
188
  # The end tag written the same way as the directive: in a comment, or in Antlers' delimiters.
179
189
  def end_tag(lines, open, name, comment:)
180
190
  first, last = comment ? Directives::COMMENT : Directives::DELIMITERS
181
- tag = /\A {0,3}#{Regexp.escape(first)}\s*:#{Regexp.escape(name)}\s*#{Regexp.escape(last)}[ \t]*$/
191
+ tag = END_TAGS[[name, comment]]
182
192
  close = (open + 1...lines.length).find { |index| lines[index].match?(tag) }
183
193
  raise MissingEndTag, "#{first} #{name}: #{last} on line #{open + 1} needs #{first} :#{name} #{last}" unless close
184
194
 
@@ -187,7 +197,7 @@ module Raindown
187
197
 
188
198
  # The props, after a value that's the node's argument when it comes first, like 'data.csv' in chart: 'data.csv'.
189
199
  def args(text, variables, antlers: true)
190
- arg = text.match(ARG) unless text.match?(/\A#{PROP}/)
200
+ arg = text.match(ARG) unless text.match?(PROP_FIRST)
191
201
  return [props(text, variables, antlers:)] unless arg
192
202
 
193
203
  [props(arg.post_match, variables, antlers:), [value(arg[1], variables, antlers:)]]
@@ -205,6 +215,9 @@ module Raindown
205
215
  # author.name, while bare or in a comment, which read like Markdown, it's text, like notes in list: folder: notes,
206
216
  # and only one in braces is a variable, like {author.name}.
207
217
  def value(value, variables, antlers: true)
218
+ return value.to_i if value.match?(INTEGER)
219
+ return value[1..-2] if value.match?(PLAIN_QUOTED)
220
+
208
221
  Lowkey::ValueParser.parse(value) do
209
222
  next value[1..-2] if value.match?(/\A(["']).*\1\z/)
210
223
  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
@@ -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,12 @@ 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
+ # Only a file naming an endpoint has one to run, so the rest aren't read again for one.
26
+ if injected.include?('endpoint:')
27
+ endpoints = EndpointRunner.new(content: injected, path:, bare: BareDirectives.enabled?(path:, content: injected, bare:), execute:)
28
+ end
29
+ Rewrite.new(original: content, content: TableFormatter.rewrite(content: endpoints&.rewrite || injected),
30
+ failures: Array(endpoints&.failures), problems: injector.problems)
28
31
  end
29
32
 
30
33
  # 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/raindown.rb CHANGED
@@ -70,7 +70,8 @@ module Raindown
70
70
  output = Directives.render("#{html.chomp}\n")
71
71
  next output if commonmark
72
72
 
73
- output.gsub(/[\u{E000}\u{E001}]/, CODE_BRACES.invert)
73
+ # With tr, as a regex of the placeholders reads the output a character at a time, taking three times as long.
74
+ output.tr(CODE_BRACES.values.join, CODE_BRACES.keys.join)
74
75
  end
75
76
  end
76
77
  end
@@ -119,8 +120,9 @@ module Raindown
119
120
  preserve_code(doc:)
120
121
 
121
122
  html = highlight_code? ? doc.to_html(options: HTML_OPTIONS) : unhighlighted_html(doc:)
122
- html.gsub('<!-- ANTLERS', '<{').gsub('ANTLERS -->', '}>')
123
- .gsub(/[\u{E000}\u{E001}]/, CODE_BRACE_ENTITIES)
123
+ html = html.gsub('<!-- ANTLERS', '<{').gsub('ANTLERS -->', '}>')
124
+ # Each placeholder's found as text, which is several times faster than a regex of both.
125
+ CODE_BRACE_ENTITIES.reduce(html) { |text, (brace, entity)| text.gsub(brace, entity) }
124
126
  end
125
127
 
126
128
  # Code blocks without highlighting, with a language class for highlighting in the browser.
data/lib/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Raindown
4
- VERSION = '0.21.3'
4
+ VERSION = '0.23.0'
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: raindown
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.21.3
4
+ version: 0.23.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - maedi
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-11-14 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: antlers
@@ -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
@@ -244,6 +245,8 @@ files:
244
245
  - lib/raindown/heading_ids.rb
245
246
  - lib/raindown/http_json.rb
246
247
  - lib/raindown/image.rb
248
+ - lib/raindown/js/action.js
249
+ - lib/raindown/js/editing.js
247
250
  - lib/raindown/js/js_nodes.rb
248
251
  - lib/raindown/js/quickjs_host.rb
249
252
  - lib/raindown/js/quickjs_runtime.js
@@ -381,14 +384,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
381
384
  requirements:
382
385
  - - ">="
383
386
  - !ruby/object:Gem::Version
384
- version: 3.4.2
387
+ version: 4.0.0
385
388
  required_rubygems_version: !ruby/object:Gem::Requirement
386
389
  requirements:
387
390
  - - ">="
388
391
  - !ruby/object:Gem::Version
389
392
  version: '0'
390
393
  requirements: []
391
- rubygems_version: 3.6.2
394
+ rubygems_version: 4.0.20
392
395
  specification_version: 4
393
396
  summary: Markup your markdown with a template and annotation layer
394
397
  test_files: []