raindown 0.17.2 → 0.19.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: ce48803b10f9d818849d224607930c3f41c63d66a830e9da2fa6ef43c877a5cb
4
- data.tar.gz: 040a45c39fc4d1439d80af01c7c6d9d937d24850f69093c9e478c79964305bb6
3
+ metadata.gz: 9b5aafde0e04b0aa360b2dbafc68d924cdbf5675e3e80728219166c03c3a8ad4
4
+ data.tar.gz: 04a815c2fb42f8b756aadab2a183789b53258727900fd44636b602aaa394931f
5
5
  SHA512:
6
- metadata.gz: 1e1109ca3ea21b6ae214b5d3bff967d2936e53b23ea0c71b1ca97bbcc208ac4249f5b14d151fb9a94f575d56fbdbfde12ccba1c12bf1b4a287ab632508df1260
7
- data.tar.gz: 22ba4b827f93a2c9edaf6d21c7be2e8d6916b5a95627e2f29b1309eec01eb6de59cb126ab9874a725ca3b089813529ec7b902501541c06661e5d87922ca9ee41
6
+ metadata.gz: fdb94e3edf51cd99ad3e6dd24f376f420d44c0e17eb5af90f56a2a5809a9da4962cfc72f5759dc30cc2050f76b6c70739726f0e4de598edaaab48a452c9eaac3
7
+ data.tar.gz: 51225830c8c64cd5dfb8bde92e2e9244db0a8d2418deaa167c437c0ddc16a4534ca91af90cc8b919dd963fb37040f0a781543d688d8068e447f676aaea177198
@@ -31,9 +31,12 @@ module Raindown
31
31
  @tail = tail
32
32
  end
33
33
 
34
- # The data is read every time, so the chart follows changes to its file.
34
+ # The data is read every time, so the chart follows changes to its file. A chart with points of its own, like a
35
+ # project's chart of its commits, needs no file.
35
36
  def rewrite(metadata: NoMetadata)
36
- return Problem.alert('Needs a file path to a CSV, TSV, JSON or YAML file') if ['', nil].include?(@data)
37
+ if ['', nil].include?(@data) && method(:points).owner == Chart
38
+ return Problem.alert('Needs a file path to a CSV, TSV, JSON or YAML file')
39
+ end
37
40
 
38
41
  points = points(metadata:)
39
42
  return '' if points.empty?
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'csv'
3
+ # Loaded when first used, as it loads strscan, a native extension, which slows a packed executable's start.
4
+ autoload :CSV, 'csv'
4
5
  require 'json'
5
6
  require 'yaml'
6
7
 
data/lib/raindown/code.rb CHANGED
@@ -1,24 +1,56 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'commonmarker'
3
+ require_relative 'code_blocks'
4
4
 
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
10
+
8
11
  module_function
9
12
 
10
- # Byte ranges of code in the Markdown, from Commonmarker's line and column positions.
13
+ # Byte ranges of code in the Markdown, from Commonmarker's line and column positions, or rendering Markdown, which
14
+ # doesn't load Commonmarker, its fenced blocks and code spans.
11
15
  def ranges(markdown)
12
- line_offsets = markdown.each_line.reduce([0]) { |offsets, line| offsets << (offsets.last + line.bytesize) }
16
+ return scanned_ranges(markdown) unless Raindown.commonmark?
17
+
18
+ offsets = line_offsets(markdown.lines)
13
19
  ranges = []
14
20
 
15
- Commonmarker.parse(markdown, options: MARKDOWN_OPTIONS).walk do |node|
16
- ranges << range(node.source_position, line_offsets) if %i[code code_block].include?(node.type)
21
+ Raindown.parse_markdown(markdown).walk do |node|
22
+ ranges << range(node.source_position, offsets) if %i[code code_block].include?(node.type)
17
23
  end
18
24
 
19
25
  ranges
20
26
  end
21
27
 
28
+ # The byte offset each line starts at, and the end's.
29
+ def line_offsets(lines)
30
+ lines.reduce([0]) { |offsets, line| offsets << (offsets.last + line.bytesize) }
31
+ end
32
+
33
+ def scanned_ranges(markdown)
34
+ lines = markdown.lines
35
+ offsets = line_offsets(lines)
36
+ ranges = []
37
+ index = 0
38
+ while index < lines.length
39
+ if (block = CodeBlocks.at(lines, index))
40
+ ranges << (offsets[index]...offsets[block[:close] + 1])
41
+ index = block[:close]
42
+ else
43
+ ranges.concat(span_ranges(lines[index], offsets[index]))
44
+ end
45
+ index += 1
46
+ end
47
+ ranges
48
+ end
49
+
50
+ 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)) }
52
+ end
53
+
22
54
  def range(position, line_offsets)
23
55
  start = line_offsets[position[:start_line] - 1] + position[:start_column] - 1
24
56
  # A block that ends with its last line ends at column 0 of the line after.
@@ -1,7 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'commonmarker'
4
-
5
3
  require_relative '../raindown'
6
4
  require_relative 'bare_directives'
7
5
  require_relative 'code_blocks'
@@ -72,7 +70,7 @@ module Raindown
72
70
  private
73
71
 
74
72
  def root
75
- @root ||= Commonmarker.parse(@markdown, options: MARKDOWN_OPTIONS)
73
+ @root ||= Raindown.parse_markdown(@markdown)
76
74
  end
77
75
 
78
76
  def text(heading)
@@ -10,9 +10,11 @@ module Raindown
10
10
  module Editing
11
11
  module_function
12
12
 
13
- def render_markdown(markdown, path:, bare: false)
13
+ # Without commonmark, it's Markdown, for the editor to render itself.
14
+ def render_markdown(markdown, path:, bare: false, commonmark: true)
14
15
  Nodes.load(path)
15
- Raindown.render(markdown:, metadata: Pages.for(path), bare: bare || BareDirectives.file?(path), **Config.render_options(path))
16
+ Raindown.render(markdown:, metadata: Pages.for(path), bare: bare || BareDirectives.file?(path), commonmark:,
17
+ **Config.render_options(path))
16
18
  end
17
19
 
18
20
  def rewrite_markdown(markdown, path:, bare: false, execute: false)
@@ -1,10 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'ipaddr'
4
3
  require 'open3'
5
4
  require 'shellwords'
6
- require 'socket'
7
5
  require 'uri'
6
+ require_relative 'curl_request'
8
7
  require_relative 'curl_response'
9
8
 
10
9
  module Raindown
@@ -13,9 +12,14 @@ module Raindown
13
12
  # are allowed: nothing that reads or writes local files, loads a config, or uses another protocol.
14
13
  # Link-local addresses, like the cloud metadata service at 169.254.169.254, are refused, as they can give out
15
14
  # credentials, and redirects aren't followed (no -L), so a URL can't redirect there either.
15
+ # Or, without processes, like in WebAssembly, the request's sent by Curl.fetcher, as the Obsidian plugin sends it with
16
+ # Obsidian's requestUrl, which refuses link-local hosts but can't pin an address or stop redirects as curl does here.
16
17
  module Curl
17
18
  class Error < StandardError; end
18
- Request = Data.define(:method, :url)
19
+ class << self
20
+ # Given a Request, returns its Response, in place of curl.
21
+ attr_accessor :fetcher
22
+ end
19
23
 
20
24
  TIMEOUT = '30'
21
25
  # The variables curl reads a proxy from, which then looks the names up rather than curl.
@@ -54,6 +58,8 @@ module Raindown
54
58
  # Placeholders like {base_url} are replaced from the variables, word by word, so a value can't add options.
55
59
  def run(snippet, variables = nil)
56
60
  args = arguments(snippet, variables)
61
+ return fetch(args) if fetcher
62
+
57
63
  stdout, stderr, status = Open3.capture3('curl', *SAFE_OPTIONS, '--silent', '--show-error', '--max-time', TIMEOUT,
58
64
  *resolve_options(args), *args, '--write-out', Response::WRITE_OUT)
59
65
  raise Error, stderr.strip.empty? ? "curl exited with #{status.exitstatus}" : stderr.strip unless status.success?
@@ -63,22 +69,19 @@ module Raindown
63
69
  raise Error, 'curl is not installed'
64
70
  end
65
71
 
66
- # The snippet's method and URL, like GET https://httpbin.org/uuid, or nil when it can't be read.
72
+ # The snippet's request, like GET https://httpbin.org/uuid, or nil when it can't be read.
67
73
  def request(snippet, variables = nil)
68
- args = arguments(snippet, variables)
69
- Request.new(method: request_method(args), url: args.find { it.match?(URL) })
74
+ Request.from(arguments(snippet, variables))
70
75
  rescue Error
71
76
  nil
72
77
  end
73
78
 
74
- # A snippet that sends data is a POST, unless it says otherwise, as with curl.
75
- def request_method(args)
76
- index = args.index('--request')
77
- return args[index + 1].upcase if index
78
- return 'HEAD' if args.include?('--head')
79
- return 'POST' if args.intersect?(VALUE_CHECKS.keys.grep(/data|json/))
79
+ # With --fail, an error status fails, as curl does.
80
+ def fetch(args)
81
+ response = fetcher.call(Request.from(args))
82
+ raise Error, "The requested URL returned error: #{response.status}" if args.include?('--fail') && response.status >= 400
80
83
 
81
- 'GET'
84
+ response
82
85
  end
83
86
 
84
87
  def arguments(snippet, variables = nil)
@@ -162,7 +165,10 @@ module Raindown
162
165
  # Resolves each URL's host and pins curl to the address it was checked at, like --resolve api.io:443:203.0.113.5,
163
166
  # so the name can't point somewhere else by the time curl looks it up. A host that's already an IP isn't pinned,
164
167
  # and behind a proxy, which looks names up itself, only a host that's an IP is checked.
168
+ # Sockets are loaded only when an endpoint runs, so writing a file back loads none, as WebAssembly has none.
165
169
  def resolve_options(args)
170
+ require 'ipaddr'
171
+ require 'socket'
166
172
  args.grep(URL).flat_map { pin_option(URI.parse(it)) }
167
173
  rescue URI::InvalidURIError => e
168
174
  raise Error, "Can't read the URL: #{e.message}"
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ module Curl
5
+ # The request a snippet makes, with its headers and body, as curl would send it, for Curl.fetcher to send in its place.
6
+ # Data, joined by &, is the body, as a form unless it's --json, or with --get, the URL's query.
7
+ class Request < Data.define(:method, :url, :headers, :body)
8
+ FORM = { 'Content-Type' => 'application/x-www-form-urlencoded' }.freeze
9
+ JSON_HEADERS = { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }.freeze
10
+ HEADER_OPTIONS = { '--user-agent' => 'User-Agent', '--referer' => 'Referer' }.freeze
11
+
12
+ def initialize(method:, url:, headers: {}, body: nil) = super
13
+
14
+ # From curl's checked arguments, with their options spelled long.
15
+ def self.from(args)
16
+ options = options(args)
17
+ url = options.assoc('--url').last
18
+ data = options.filter_map { |option, value| data_value(option, value) }.join('&')
19
+ headers = headers(options)
20
+ return new(method: request_method(args), url:, headers:) if data.empty?
21
+ return new(method: request_method(args), url: with_query(url, data), headers:) if args.include?('--get')
22
+
23
+ new(method: request_method(args), url:, headers: FORM.merge(headers), body: data)
24
+ end
25
+
26
+ # A snippet that sends data is a POST, unless it says otherwise, as with curl.
27
+ def self.request_method(args)
28
+ index = args.index('--request')
29
+ return args[index + 1].upcase if index
30
+ return 'HEAD' if args.include?('--head')
31
+ return 'GET' if args.include?('--get')
32
+ return 'POST' if args.intersect?(VALUE_CHECKS.keys.grep(/data|json/))
33
+
34
+ 'GET'
35
+ end
36
+
37
+ # The options, each with its value or nil, and each URL as a --url, like ['--url', 'https://a.io'].
38
+ def self.options(args)
39
+ words = args.dup
40
+ pairs = []
41
+ until words.empty?
42
+ word = words.shift
43
+ pairs << if VALUE_CHECKS.key?(word) then [word, words.shift]
44
+ elsif word.start_with?('--') then [word, nil]
45
+ else ['--url', word]
46
+ end
47
+ end
48
+ pairs
49
+ end
50
+
51
+ def self.headers(options)
52
+ options.each_with_object({}) do |(option, value), headers|
53
+ case option
54
+ when '--header'
55
+ name, header = value.split(':', 2)
56
+ headers[name.strip] = header.to_s.strip
57
+ when '--user' then headers['Authorization'] = "Basic #{[value].pack('m0')}"
58
+ when '--json' then headers.merge!(JSON_HEADERS)
59
+ else headers[HEADER_OPTIONS[option]] = value if HEADER_OPTIONS.key?(option)
60
+ end
61
+ end
62
+ end
63
+
64
+ # As curl sends it: --data without line breaks, and --data-urlencode encoded.
65
+ def self.data_value(option, value)
66
+ case option
67
+ when '--data', '--data-ascii' then value.delete("\r\n")
68
+ when '--data-raw', '--data-binary', '--json' then value
69
+ when '--data-urlencode' then urlencoded(value)
70
+ end
71
+ end
72
+
73
+ # Like curl's --data-urlencode, with name=content or =content, only the content's encoded.
74
+ def self.urlencoded(value)
75
+ name, equals, content = value.partition('=')
76
+ return URI.encode_uri_component(value) if equals.empty?
77
+
78
+ [name, URI.encode_uri_component(content)].reject(&:empty?).join('=')
79
+ end
80
+
81
+ def self.with_query(url, query)
82
+ return "#{url}&#{query}" if url.include?('?')
83
+
84
+ "#{url}?#{query}"
85
+ end
86
+
87
+ private_class_method :options, :headers, :data_value, :urlencoded, :with_query
88
+ end
89
+ end
90
+ end
@@ -19,10 +19,13 @@ module Raindown
19
19
  def self.parse(stdout)
20
20
  body, _, info = stdout.rpartition(INFO_MARKER)
21
21
  status, seconds, content_type = info.split(' ', 3)
22
- language = LANGUAGES.find { |pattern, _| content_type.to_s.match?(pattern) }&.last || ''
22
+ received(body:, content_type:, status: status.to_i, milliseconds: (seconds.to_f * 1000).round)
23
+ end
23
24
 
24
- new(body: language == 'json' ? pretty_json(body) : body, language:, status: status.to_i,
25
- milliseconds: (seconds.to_f * 1000).round)
25
+ # A response however it was sent, like by Curl.fetcher.
26
+ def self.received(body:, content_type:, status:, milliseconds:)
27
+ language = LANGUAGES.find { |pattern, _| content_type.to_s.match?(pattern) }&.last || ''
28
+ new(body: language == 'json' ? pretty_json(body) : body, language:, status:, milliseconds:)
26
29
  end
27
30
 
28
31
  def self.pretty_json(body)
@@ -33,6 +33,11 @@ module Raindown
33
33
  end
34
34
  end
35
35
 
36
+ class << self
37
+ # A host in place of NodeJS, answering the same requests, like the Obsidian plugin's worker, which runs them itself.
38
+ attr_writer :host
39
+ end
40
+
36
41
  module_function
37
42
 
38
43
  # Loads the JavaScript Components in a .raindown folder, starting NodeJS the first time a folder has any.
@@ -4,6 +4,7 @@ require_relative '../raindown'
4
4
  require_relative 'bare_directives'
5
5
  require_relative 'front_matter'
6
6
  require_relative 'node_blocks'
7
+ require_relative 'written'
7
8
 
8
9
  module Raindown
9
10
  # Writes each node block's Markdown below its directive, replacing what it wrote before, when it's in comments or
@@ -11,6 +12,10 @@ module Raindown
11
12
  class NodeInjector
12
13
  class BlankLine < StandardError; end
13
14
 
15
+ # A comment on its own line that isn't a directive, like <!-- 2 rows · 3f2a9c -->, which straight below a directive
16
+ # is its node's comment, passed to its rewrite as comment:.
17
+ COMMENT = /\A\s*<!--(?!\s*(?::[A-Za-z]|[A-Za-z][\w-]*(?:::[A-Z]\w*)*:))\s*(.*?)\s*-->\s*\z/
18
+
14
19
  # Rewriter interface. Content without a node block is returned unchanged.
15
20
  def self.rewrite(content:, path: nil, bare: false, metadata: NoMetadata, **)
16
21
  new(content:, path:, bare:, metadata:).call
@@ -42,22 +47,27 @@ module Raindown
42
47
  private
43
48
 
44
49
  def block_lines(lines, block)
45
- context = { document: @content, metadata: @metadata, bare: @bare, written: written_lines(lines, block) }
46
- markdown = node_markdown(block, context)
47
- written = markdown.empty? ? [] : "#{markdown}\n".lines
50
+ comment, written = comment_and_written(written_lines(lines, block))
51
+ # The document as it's written so far, from the bottom up, so a node sees what the nodes below it just wrote, like
52
+ # the TOC the headings they write.
53
+ context = { document: lines.join, metadata: @metadata, bare: @bare, comment:, written: }
54
+ written = written_lines_of(node_written(block, context))
48
55
  return [line(lines[block[:open]]), *bare(written, block)] unless block[:close]
49
56
 
50
57
  delimited(lines, block, written)
51
58
  end
52
59
 
53
60
  # A node that raises writes why in its place, like a Problem, so the rest of the file still writes back.
54
- def node_markdown(block, context)
61
+ def node_written(block, context)
55
62
  @problems << block[:node].warning if block[:node].is_a?(Problem)
56
- Nodes.call(block[:node], :rewrite, **context).to_s.chomp
63
+ written = Nodes.call(block[:node], :rewrite, **context)
64
+ return written if written.is_a?(Written)
65
+
66
+ Written.new(written.to_s)
57
67
  rescue StandardError => e
58
68
  problem = Problem.new("Couldn't write: #{e.message}", block[:open] + 1)
59
69
  @problems << problem.warning
60
- problem.rewrite
70
+ Written.new(problem.rewrite)
61
71
  end
62
72
 
63
73
  # The directive, what the node wrote and the end tag, straight after each other, as a comment on its own line ends
@@ -72,6 +82,22 @@ module Raindown
72
82
  raise BlankLine, "#{name} writes blank lines, so it needs <!-- #{name}: --> and <!-- :#{name} --> around it"
73
83
  end
74
84
 
85
+ # Its lines: its comment, straight below its directive, then its Markdown.
86
+ def written_lines_of(written)
87
+ markdown = written.to_s.chomp
88
+ lines = markdown.empty? ? [] : "#{markdown}\n".lines
89
+ return lines unless written.comment
90
+
91
+ ["<!-- #{written.comment} -->\n", *lines]
92
+ end
93
+
94
+ # The comment the block's node wrote straight below its directive, if it wrote one, and the lines it wrote below that.
95
+ def comment_and_written(lines)
96
+ return [nil, lines] unless lines.first&.match?(COMMENT)
97
+
98
+ [lines.first[COMMENT, 1], lines.drop(1)]
99
+ end
100
+
75
101
  # What the block's node wrote last time, between its directive and its end tag, or the next blank line.
76
102
  def written_lines(lines, block)
77
103
  lines[(block[:open] + 1)...(block[:close] || (block[:last] + 1))]
@@ -9,7 +9,7 @@ require_relative 'node'
9
9
  require_relative 'problem'
10
10
  require_relative 'stat'
11
11
  require_relative 'table/table'
12
- require_relative 'toc'
12
+ require_relative 'toc/toc'
13
13
 
14
14
  module Raindown
15
15
  # Nodes are LowNodes that a node block writes into the Markdown and renders into the HTML.
@@ -140,8 +140,10 @@ module Raindown
140
140
  end
141
141
  end
142
142
 
143
+ # Rendering Markdown, a node's written as it would be written back.
143
144
  def html(node, context, **keywords)
144
145
  return node.render_template(props: {}).to_s if template?(node.class)
146
+ return call(node, :rewrite, **context.to_h, **keywords).to_s if !Raindown.commonmark? && node.respond_to?(:rewrite)
145
147
 
146
148
  call(node, :render, **context.to_h, **keywords).to_s
147
149
  end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raindown
4
+ # What Pages keeps for as long as the process runs, like "raindown server", until it changes: each root's files, and
5
+ # each file's front matter. An editor that's told of every change to the files, like the Obsidian plugin, which knows
6
+ # its vault's, watches them, so their modified times aren't checked each time they're listed, which in WebAssembly takes
7
+ # as long as listing thousands of them.
8
+ module Listings
9
+ # Each file's front matter, by its path, with the time it was modified when it was read.
10
+ def front_matters
11
+ @front_matters ||= {}
12
+ end
13
+
14
+ # Each file's metadata from its path, by its root and path, like order: 1 for docs/_1-setup.md, which only changes
15
+ # with its path.
16
+ def implicit_metadatas
17
+ @implicit_metadatas ||= {}
18
+ end
19
+
20
+ # The front matter the editor's already read, by path, is kept rather than read again.
21
+ def watch(front_matters = {})
22
+ @watched = true
23
+ front_matters.each { |path, front_matter| self.front_matters[path] = [:given, front_matter] }
24
+ end
25
+
26
+ def watched?
27
+ @watched == true
28
+ end
29
+
30
+ # Files or folders added, changed or removed, by path, so their front matter's read again, and each root's listing
31
+ # has the files added and not those removed, rather than listing every file again.
32
+ def changed(paths)
33
+ return if paths.empty?
34
+
35
+ pages.clear
36
+ paths.each do |path|
37
+ front_matters.delete(path)
38
+ listings.each do |root, listing|
39
+ next unless path.start_with?("#{root}/")
40
+
41
+ listing[:file_paths].reject! { it == path || it.start_with?("#{path}/") }
42
+ listing[:file_paths] << path if File.file?(path) && !path.delete_prefix(root).include?('/.')
43
+ end
44
+ end
45
+ end
46
+
47
+ # Each root's Pages, while an editor watching the files says none have changed, so their metadata's worked out once.
48
+ def pages
49
+ @pages ||= {}
50
+ end
51
+
52
+ # The files under the root, outside hidden folders, like Dirload lists them. They're listed again once a folder among
53
+ # them has changed, which adding, removing or renaming a file or folder in it does, or the editor watching says so.
54
+ def file_paths(root)
55
+ listing = listings[root]
56
+ return listing[:file_paths] if listing && (watched? || listing[:folders].all? { |folder, at| modified_at(folder) == at })
57
+
58
+ folders, file_paths = Dir["#{root}/**/*"].partition { File.directory?(it) }
59
+ listings[root] = { file_paths:, folders: [root, *folders].to_h { [it, modified_at(it)] } }
60
+ file_paths
61
+ end
62
+
63
+ def listings
64
+ @listings ||= {}
65
+ end
66
+
67
+ def modified_at(path)
68
+ File.mtime(path) if File.exist?(path)
69
+ end
70
+ end
71
+ end
@@ -1,8 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'front_matter'
3
+ require_relative '../front_matter'
4
+ require_relative 'listings'
4
5
  require_relative 'page'
5
- require_relative 'utils'
6
+ require_relative '../utils'
6
7
 
7
8
  module Raindown
8
9
  # The metadata of a project's Markdown files, which list: lists by tag.
@@ -13,49 +14,31 @@ module Raindown
13
14
  # folder: basics, order: 1, path: docs/_basics/_1-getting-started.md
14
15
  # Folder tags can share a folder name with "&", like docs/_1&_basics/getting-started.md.
15
16
  # An app can add its own metadata by subclassing and overriding implicit_metadata, like Raindeer's URL paths.
16
- # Each file's front matter is only read once something lists the files. The listing and the front matter are kept for
17
- # as long as the process runs, like "raindown server", until they change.
17
+ # Each file's front matter is only read once something lists the files, and kept, with the listing, by Listings.
18
18
  class Pages
19
19
  EXTENSIONS = %w[md rd markdown raindown].freeze
20
20
  SEGMENTS = Regexp.union(['/', '&', '-'])
21
21
 
22
- class << self
23
- # Each file's front matter, by its path, with the time it was modified when it was read.
24
- def front_matters
25
- @front_matters ||= {}
26
- end
22
+ extend Listings
27
23
 
24
+ class << self
28
25
  # The Markdown files under a project's root, the folder with its .raindown folder, or a vault, or else the file's
29
26
  # folder.
30
27
  def for(path)
31
- require_relative 'projects'
28
+ require_relative '../projects'
32
29
  load(root: Projects.content_root(path) || File.dirname(File.expand_path(path)))
33
30
  end
34
31
 
35
- # Lists the files under the root, without loading them, for Dirload.
32
+ # Lists the files under the root, without loading them, for Dirload, once while an editor watching them says none
33
+ # have changed.
36
34
  def load(root:)
35
+ return pages[root] if watched? && pages[root]
36
+
37
37
  require 'dirload'
38
38
  file_types = file_paths(root).group_by { Dirload.extension(file_path: it) }
39
- new(metadata: Dirload::Metadata.new(loaded_paths: {}, missed_paths: [], file_types:), root:)
40
- end
41
-
42
- # The files under the root, outside hidden folders, like Dirload lists them. They're listed again once a folder
43
- # among them has changed, which adding, removing or renaming a file or folder in it does.
44
- def file_paths(root)
45
- listing = listings[root]
46
- return listing[:file_paths] if listing&.dig(:folders)&.all? { |folder, modified| modified_at(folder) == modified }
47
-
48
- folders, file_paths = Dir["#{root}/**/*"].partition { File.directory?(it) }
49
- listings[root] = { file_paths:, folders: [root, *folders].to_h { [it, modified_at(it)] } }
50
- file_paths
51
- end
52
-
53
- def listings
54
- @listings ||= {}
55
- end
56
-
57
- def modified_at(path)
58
- File.mtime(path) if File.exist?(path)
39
+ loaded = new(metadata: Dirload::Metadata.new(loaded_paths: {}, missed_paths: [], file_types:), root:)
40
+ pages[root] = loaded if watched?
41
+ loaded
59
42
  end
60
43
  end
61
44
 
@@ -109,14 +92,18 @@ module Raindown
109
92
  end
110
93
 
111
94
  def process(file_path:)
112
- metadata = @metadata[file_path] = implicit_metadata(file_path:).merge(front_matter(file_path))
95
+ implicit = self.class.implicit_metadatas[[@root, file_path]] ||= implicit_metadata(file_path:)
96
+ metadata = @metadata[file_path] = implicit.merge(front_matter(file_path))
113
97
  metadata.each { |type, tag| Array(tag).each { |item| tag(type:, tag: item, file_path:) } }
114
98
  end
115
99
 
116
- # The file's front matter, read again only when the file's changed since it was last read.
100
+ # The file's front matter, read again only when the file's changed since it was last read, or an editor watching the
101
+ # files says so.
117
102
  def front_matter(file_path)
118
- modified = File.mtime(file_path)
119
103
  modified_then, front_matter = self.class.front_matters[file_path]
104
+ return front_matter if modified_then && self.class.watched?
105
+
106
+ modified = File.mtime(file_path)
120
107
  return front_matter if modified_then == modified
121
108
 
122
109
  FrontMatter.read(file_path).tap { self.class.front_matters[file_path] = [modified, it] }
@@ -3,7 +3,7 @@
3
3
  require 'find'
4
4
  require_relative 'gitignore'
5
5
  require_relative 'nodes'
6
- require_relative 'pages'
6
+ require_relative 'pages/pages'
7
7
 
8
8
  module Raindown
9
9
  # Raindown projects are folders with a .raindown folder, and their Markdown files are watched for changes.
@@ -6,7 +6,7 @@ require_relative 'bare_directives'
6
6
  require_relative 'document'
7
7
  require_relative 'front_matter'
8
8
  require_relative 'nodes'
9
- require_relative 'pages'
9
+ require_relative 'pages/pages'
10
10
  require_relative 'utils'
11
11
 
12
12
  module Raindown