kiln 0.2.1 → 0.3.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: b5769fc8686c82a97194dbf3704c7e46b32fccd599d9a0af64680e7e6599079f
4
- data.tar.gz: e08bf6dd11727a3273d54347a45e9d3493d9ef333c85301cbfe37a70025c99b0
3
+ metadata.gz: c772401bb8ff9c43bcd918a850289bd31b0dc3195a0a5b7be50973f554df70ee
4
+ data.tar.gz: 8558b70d8844348ec5156ec5ad779111c230f3d11479d4cfc18fb725afd92cc6
5
5
  SHA512:
6
- metadata.gz: 0b479bfb6d6b644b7dd1a36dbc1572cf73351b7575f41e008abf57c846c472ac48ca3f00b237e61bc8da41c8b212ff74bb52100062e7c9ce5da0dfad158e4561
7
- data.tar.gz: 681aca4de196497241120cd95288b81dfeae61faabe7b21d5314a180066bdf6772de5c89195d9bdf97a70a7976154d9fac906ebeffac3849e07708f34360af8d
6
+ metadata.gz: a014c9b3538b0eec91581eda212d4218324534c3090a8b71ed43939b33eee1aa86bd520b697839e4b910921ae39eac52740d9f54fe18bec7d8e0a09a3f2446bb
7
+ data.tar.gz: d83adf20710d4c706f59cca82a0962603d9131ffcadceda9600ad6c4764f8e789497d067be79323529e43195c0beb810d266d0499794535307272c0a9bd96f44
data/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (2026-12-05)
4
+
5
+ Added:
6
+
7
+ - `scope "/wiki"` in `Kiln.pages` builds only the routes under the given path prefixes. Routes
8
+ outside every scope are neither built nor reported as uncovered, and `Kiln::Router#rows` lists
9
+ them with the status `:outside`. `Kiln.render` and the `not_found` page are not limited by it.
10
+ From `public/`, a scoped build copies only the files under a scope and the files a written page
11
+ or stylesheet links to.
12
+ - `kiln:build` and `kiln:serve` set `ENV["KILN_BUILD"] = "1"`, so an app can route
13
+ development-only pages in a build (`if Rails.env.local? || ENV["KILN_BUILD"]`) and leave out
14
+ development gems. When the command names a kiln task it is set as Kiln loads, so
15
+ `config/application.rb` sees it after `Bundler.require`.
16
+ - `Kiln::Content` collections read `*.html` files beside `*.md`: the body is an HTML fragment used
17
+ as written, with the same frontmatter, filename rules, translations and drafts.
18
+ `Kiln::Content.file` reads `.html` too. Two files with the same slug fail when the collection
19
+ loads.
20
+ - `Entry#headings` lists the h2 and h3 headings with their level, id and text. An HTML heading
21
+ without an id gets one made from its text, as commonmarker makes them for Markdown.
22
+ - `Kiln::Content.wikilinks(:wiki) { |slug| url }` turns on wikilinks for a collection:
23
+ `[[slug]]`, `[[slug#anchor]]`, `[[slug|text]]` and `[[#anchor]]` become links in `Entry#html`,
24
+ outside `a`, `code`, `pre`, `svg` and similar elements. A link to an unknown slug gets the class
25
+ `missing`. `Entry#links`, `Entry#missing_links`, `Collection#backlinks` and `Collection#graph`
26
+ expose the links as data.
27
+ - `kiln_link_graph(collection, current:, depth:, limit:, label:, kind:, still:, nonce:)` draws a
28
+ collection's link graph with an inline script and stylesheet, written once per page and carrying
29
+ the request's CSP nonce. Each node is an HTML link over an `<svg>` of edges, so Turbo, prefetch,
30
+ focus and middle click treat it as any other link, and a Turbo morph keeps the drawing. Nodes can
31
+ be dragged, hovering highlights a node and its neighbours, and dots and labels stay inside the
32
+ box without overlapping. Apps theme it with `--kiln-graph-*` custom properties, and forced
33
+ colours mode uses system colours. It has no dependencies.
34
+ - `Kiln::Content.order(:wiki, by: [ :kind, :part, :title ])` sorts a collection by frontmatter
35
+ keys or entry methods instead of newest first. A missing value sorts last and the slug breaks
36
+ ties. `Collection#previous(entry)` and `Collection#next(entry)` return the neighbouring visible
37
+ entry in that order, and `within: { kind: "article" }` skips entries that do not match.
38
+
39
+ Fixed:
40
+
41
+ - The link check reads an href with raw non-ASCII characters or spaces as a browser does, so
42
+ `href="#for-食べる"` matches the id `for-食べる` instead of failing as a broken link. The asset
43
+ export reads such URLs too.
44
+
3
45
  ## 0.2.1 (2026-11-15)
4
46
 
5
47
  Added:
data/lib/kiln/assets.rb CHANGED
@@ -72,7 +72,7 @@ module Kiln
72
72
  ref = (url || import).strip
73
73
  next if ref.empty? || ref.match?(EXTERNAL)
74
74
 
75
- asset_path(URI.join("http://kiln#{css_path}", ref).path)
75
+ asset_path(URI.join("http://kiln#{css_path}", Links.escape(ref)).path)
76
76
  rescue URI::Error
77
77
  nil
78
78
  end
@@ -80,7 +80,7 @@ module Kiln
80
80
 
81
81
  # Normalizes a URL to an asset path ("/assets/app-abc.css"), or nil when it isn't one of ours.
82
82
  def asset_path(url)
83
- uri = URI.parse(url.to_s.strip)
83
+ uri = URI.parse(Links.escape(url.to_s.strip))
84
84
  return if uri.host && uri.host != @host
85
85
 
86
86
  uri.path if uri.path&.start_with?("#{prefix}/")
data/lib/kiln/build.rb CHANGED
@@ -109,7 +109,7 @@ module Kiln
109
109
  # Everything in the output that is not a rendered page or an asset.
110
110
  def write_extras
111
111
  write_files
112
- writer.copy_public(app.root.join("public"), generated: generated_files)
112
+ writer.copy_public(app.root.join("public"), generated: generated_files, only: (scoped_public if @pages.scopes.any?))
113
113
  Redirects.new(@redirects, host: config.host).write(writer) if @redirects.any?
114
114
  write_sitemap if config.url
115
115
  write_cname if config.cname
@@ -126,6 +126,15 @@ module Kiln
126
126
  end
127
127
  end
128
128
 
129
+ # With a scope, the public/ files under it and the ones a written page or stylesheet points at.
130
+ # Other public files, such as another part of the app's docs, are not part of the site.
131
+ def scoped_public
132
+ public = StaticResolver.new(app.root.join("public"))
133
+ linked = Links.paths(@stage, host: config.host).filter_map { public.resolve(it)&.to_s }.to_set
134
+ root = app.root.join("public").expand_path
135
+ ->(relative) { @pages.in_scope?("/#{relative}") || linked.include?(root.join(relative).to_s) }
136
+ end
137
+
129
138
  # Files Kiln writes on purpose that may also exist in public/ (Rails ships a public/404.html).
130
139
  def generated_files
131
140
  [ ("404.html" if config.not_found), ("CNAME" if config.cname), *config.files.keys.map(&:to_s) ].compact
@@ -8,14 +8,18 @@ module Kiln
8
8
  def initialize(name, dir)
9
9
  @name, @dir = name.to_s, Pathname(dir)
10
10
  @stamp = stamp
11
- translations, entries = files.map { Entry.new(@name, it) }.partition(&:locale)
11
+ loaded = files.map { Entry.new(@name, it, siblings: self) }
12
+ loaded.group_by { [ it.slug, it.locale ] }.each_value do |same|
13
+ raise ArgumentError, "#{same.map(&:path).to_sentence} have the same slug #{same.first.slug.inspect}" if same.size > 1
14
+ end
15
+ translations, entries = loaded.partition(&:locale)
12
16
  @entries = entries.sort_by { [ it.published_at&.in_time_zone || Time.at(0), it.slug ] }.reverse
13
17
  translations.each { attach(it) }
14
18
  end
15
19
 
16
- # Visible entries, newest first.
20
+ # Visible entries, newest first, or in the order from Kiln::Content.order.
17
21
  def all
18
- Content.show_drafts ? @entries : @entries.select(&:published?)
22
+ Content.show_drafts ? ordered : ordered.select(&:published?)
19
23
  end
20
24
 
21
25
  def each(&) = all.each(&)
@@ -27,8 +31,63 @@ module Kiln
27
31
  # True when files were added, removed or changed since loading.
28
32
  def stale? = stamp != @stamp
29
33
 
34
+ # The visible entry before or after an entry (or a slug) in the order of all, or nil. within
35
+ # keeps only the entries whose attributes match, by ===: within: { kind: "article" }.
36
+ def previous(entry, within: nil) = neighbour(entry, -1, within)
37
+ def next(entry, within: nil) = neighbour(entry, 1, within)
38
+
39
+ # Visible entries that link to an entry (or a slug), in the order of all.
40
+ def backlinks(entry)
41
+ slug = entry.respond_to?(:slug) ? entry.slug : entry.to_s
42
+ select { it.links.include?(slug) }
43
+ end
44
+
45
+ # The link graph as plain data, for an app to render as JSON. Nodes are the visible entries,
46
+ # with slug, title, url and the named attributes (frontmatter keys or Entry methods, nil when
47
+ # absent). Edges join two entries when either links to the other, once per pair, with from
48
+ # and to in slug order.
49
+ #
50
+ # graph(:kind) # => { nodes: [ { slug:, title:, url:, kind: }, ... ], edges: [ { from:, to: }, ... ] }
51
+ def graph(*attributes)
52
+ url = Content.wikilink_url(name) or raise Kiln::Error, "the #{name} collection has no wikilinks. Turn them on with Kiln::Content.wikilinks(:#{name}) { ... }"
53
+ nodes = map do |entry|
54
+ extra = attributes.to_h { [ it.to_sym, attribute(entry, it) ] }
55
+ { slug: entry.slug, title: entry.title, url: url.call(entry.slug), **extra }
56
+ end
57
+ edges = flat_map { |entry| entry.links.map { [ entry.slug, it ].sort } }.uniq
58
+ { nodes:, edges: edges.map { |from, to| { from:, to: } } }
59
+ end
60
+
61
+ # Visible entries by slug and by URL, for Wikilinks.
62
+ def link_targets(url)
63
+ (@link_targets ||= {})[[ Content.show_drafts, url ]] ||= begin
64
+ by_slug = all.index_by(&:slug)
65
+ [ by_slug, by_slug.transform_keys { url.call(it) } ]
66
+ end
67
+ end
68
+
30
69
  private
31
- def files = Dir[@dir.join("*.md")].sort
70
+ # A frontmatter key or an Entry method, nil when the entry has neither.
71
+ def attribute(entry, key) = (entry.public_send(key) if entry.respond_to?(key))
72
+
73
+ # Sorted by the keys from Kiln::Content.order, nil last, then by slug.
74
+ def ordered
75
+ keys = Content.order_for(name) or return @entries
76
+ (@ordered ||= {})[keys] ||= @entries.sort_by do |entry|
77
+ [ *keys.map { |key| attribute(entry, key).then { [ it.nil? ? 1 : 0, it ] } }, entry.slug ]
78
+ end
79
+ rescue ArgumentError
80
+ raise ArgumentError, "#{name} entries cannot be ordered by #{keys.join(", ")}: one key has values that do not compare, such as 1 and \"2\""
81
+ end
82
+
83
+ def neighbour(entry, step, within)
84
+ slug = entry.respond_to?(:slug) ? entry.slug : entry.to_s
85
+ list = within ? select { |other| within.all? { |key, value| value === attribute(other, key) } } : all
86
+ index = list.index { it.slug == slug } or return
87
+ list[index + step] if (index + step).between?(0, list.size - 1)
88
+ end
89
+
90
+ def files = Dir[@dir.join("*.{md,html}")].sort
32
91
 
33
92
  def attach(translation)
34
93
  entry = @entries.find { it.slug == translation.slug }
@@ -1,19 +1,21 @@
1
1
  module Kiln
2
2
  module Content
3
3
  class Entry
4
- # SLUG.md, or SLUG.LOCALE.md for a translation. A locale is two lowercase letters, optionally
5
- # followed by a dash and two uppercase letters: es, ja, pt-BR.
6
- FILENAME = /\A(?<name>.+?)(?:\.(?<locale>[a-z]{2}(?:-[A-Z]{2})?))?\.md\z/
4
+ # SLUG.md or SLUG.html, or SLUG.LOCALE.md for a translation. A locale is two lowercase letters,
5
+ # optionally followed by a dash and two uppercase letters: es, ja, pt-BR.
6
+ FILENAME = /\A(?<name>.+?)(?:\.(?<locale>[a-z]{2}(?:-[A-Z]{2})?))?\.(?<format>md|html)\z/
7
7
  # A leading YYYY-MM-DD or YYYY-MM date. The slug is the rest of the name, or the whole name when
8
8
  # it is only a date. A month-only date means the 1st of that month.
9
9
  DATED = /\A(?<date>\d{4}-\d{2}(?:-\d{2})?)(?:-(?<slug>.+))?\z/
10
10
 
11
- attr_reader :collection, :path, :slug, :locale, :attributes, :body, :published_at
11
+ # format is "md" or "html". An HTML body is used as written.
12
+ attr_reader :collection, :path, :slug, :locale, :format, :attributes, :body, :published_at
12
13
 
13
- def initialize(collection, path)
14
- @collection, @path = collection&.to_s, Pathname(path)
15
- match = FILENAME.match(@path.basename.to_s) or raise ArgumentError, "#{@path} is not a Markdown file: its name must end in .md"
16
- @locale = match[:locale]
14
+ # siblings is the Collection the entry belongs to, which resolves its wikilinks.
15
+ def initialize(collection, path, siblings: nil)
16
+ @collection, @path, @siblings = collection&.to_s, Pathname(path), siblings
17
+ match = FILENAME.match(@path.basename.to_s) or raise ArgumentError, "#{@path} is not a content file: its name must end in .md or .html"
18
+ @locale, @format = match[:locale], match[:format]
17
19
  dated = DATED.match(match[:name])
18
20
  @slug = (dated && dated[:slug]) || match[:name]
19
21
  text = @path.read
@@ -36,11 +38,31 @@ module Kiln
36
38
  def scheduled? = published_at.present? && published_at.in_time_zone.future?
37
39
  def published? = !draft? && !scheduled?
38
40
 
41
+ def markdown? = format == "md"
42
+
39
43
  def html
40
- return Markdown.render(body, path:, line_offset: @frontmatter_lines).html_safe if Content.source_positions
41
- @html ||= Markdown.render(body).html_safe
44
+ if markdown? && Content.source_positions
45
+ html = Markdown.render(body, path:, line_offset: @frontmatter_lines).html_safe
46
+ return wikilink_url ? Wikilinks.resolve(self, html, @siblings, wikilink_url).html : html
47
+ end
48
+ wikilink_url ? linked.html : rendered
42
49
  end
43
50
 
51
+ # The h2 and h3 headings, each with level, id and text. Every one has an id: Markdown headings
52
+ # get one from commonmarker, and an HTML heading without one gets it from its text.
53
+ def headings = @headings ||= Headings.list(wikilink_url ? linked.html : rendered)
54
+
55
+ # The id of every element in html, for checking links to its anchors.
56
+ def ids = @ids ||= rendered.scan(Headings::ID).map { CGI.unescapeHTML(it.compact.first) }.to_set
57
+
58
+ # Slugs of the visible entries this entry links to, by wikilink or by an href equal to an
59
+ # entry's URL, without its own slug. Needs Kiln::Content.wikilinks for the collection.
60
+ def links = linked.links
61
+
62
+ # Wikilinks to slugs with no visible entry ("slug"), and links to an entry's anchor that it
63
+ # has no element for ("slug#anchor").
64
+ def missing_links = linked.missing
65
+
44
66
  def to_param = slug
45
67
  def [](key) = attributes[key.to_s]
46
68
  def to_h = attributes
@@ -52,6 +74,19 @@ module Kiln
52
74
  end
53
75
 
54
76
  private
77
+ def rendered
78
+ @rendered ||= (markdown? ? Markdown.render(body) : Headings.anchor(body)).html_safe
79
+ end
80
+
81
+ def wikilink_url = @siblings && Content.wikilink_url(collection)
82
+
83
+ def linked
84
+ @linked ||= begin
85
+ url = wikilink_url or raise Kiln::Error, "#{path} has no wikilinks. Turn them on with Kiln::Content.wikilinks(:#{collection || "name"}) { ... }"
86
+ Wikilinks.resolve(self, rendered, @siblings, url)
87
+ end
88
+ end
89
+
55
90
  def filename_date(date)
56
91
  Date.iso8601(date.length == 7 ? "#{date}-01" : date)
57
92
  rescue Date::Error
@@ -0,0 +1,44 @@
1
+ module Kiln
2
+ module Content
3
+ # The h2 and h3 elements of an entry's HTML. Ids are added with string edits, so every other
4
+ # byte of the HTML stays as written.
5
+ module Headings
6
+ Heading = Data.define(:level, :id, :text)
7
+
8
+ PATTERN = %r{<h([23])(\s[^>]*)?>(.*?)</h\1\s*>}mi
9
+ ID = /\sid\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+))/i
10
+
11
+ # Gives every h2 and h3 without an id one made from its text, as commonmarker's header_ids
12
+ # do for Markdown: lowercased, without punctuation, spaces as dashes, and -1, -2 appended
13
+ # when the id is already used anywhere in the HTML.
14
+ def self.anchor(html)
15
+ used = html.scan(ID).map { it.compact.first }.to_set
16
+ html.gsub(PATTERN) do
17
+ heading, attributes, inner = $&, $2.to_s, $3
18
+ next heading if attributes.match?(ID)
19
+
20
+ id = unique(slug(text(inner)).presence || "section", used)
21
+ heading.sub(/\A<h[23]/i) { %(#{it} id="#{ERB::Util.html_escape(id)}") }
22
+ end
23
+ end
24
+
25
+ def self.list(html)
26
+ html.scan(PATTERN).map do |level, attributes, inner|
27
+ id = ID.match(attributes.to_s)&.captures&.compact&.first
28
+ Heading.new(level: level.to_i, id: id && CGI.unescapeHTML(id), text: text(inner))
29
+ end
30
+ end
31
+
32
+ def self.text(inner) = CGI.unescapeHTML(inner.gsub(/<[^>]*>/, "")).squish
33
+
34
+ def self.slug(text) = text.downcase.gsub(/[^\p{L}\p{M}\p{N}\p{Pc} -]/, "").tr(" ", "-")
35
+
36
+ def self.unique(id, used)
37
+ candidate, n = id, 0
38
+ candidate = "#{id}-#{n += 1}" while used.include?(candidate)
39
+ used << candidate
40
+ candidate
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,17 @@
1
+ :where(.kiln-graph) { position: relative; display: block; width: 100%; height: 18rem; overflow: hidden; direction: ltr; user-select: none; -webkit-user-select: none; }
2
+ :where(.kiln-graph-edges) { position: absolute; inset: 0; width: 100%; height: 100%; }
3
+ :where(.kiln-graph-edge) { stroke: var(--kiln-graph-edge, color-mix(in srgb, currentColor 22%, transparent)); stroke-width: 1.2; transition: stroke 0.15s, opacity 0.15s; }
4
+ :where(.kiln-graph-edge[data-hot]) { stroke: var(--kiln-graph-edge-hot, currentColor); stroke-width: 1.8; }
5
+ :where(.kiln-graph-node) { position: absolute; top: 50%; left: 50%; display: flex; flex-direction: column; align-items: center; gap: 1px; color: var(--kiln-graph-label, currentColor); font-size: var(--kiln-graph-label-size, 11px); line-height: 1.2; text-decoration: none; white-space: nowrap; cursor: pointer; touch-action: none; transform: translate(-50%, calc(var(--_kiln-graph-size) / -2)); transition: opacity 0.15s; }
6
+ :where(.kiln-graph-node)::before { content: ""; width: var(--_kiln-graph-size); height: var(--_kiln-graph-size); border-radius: 50%; background: var(--kiln-graph-node, color-mix(in srgb, currentColor 55%, transparent)); box-shadow: 0 0 0 2px var(--kiln-graph-halo, Canvas); }
7
+ :where(.kiln-graph-node[data-current]) { font-weight: 600; }
8
+ :where(.kiln-graph-node[data-current])::before { background: var(--kiln-graph-node-current, currentColor); }
9
+ :where(.kiln-graph-node:focus-visible) { outline: 2px solid var(--kiln-graph-node-current, currentColor); outline-offset: 2px; border-radius: 4px; }
10
+ :where(.kiln-graph-label) { padding: 0 3px; border-radius: 3px; background: color-mix(in srgb, var(--kiln-graph-halo, Canvas) 85%, transparent); }
11
+ :where(.kiln-graph-label[data-hidden]) { visibility: hidden; }
12
+ :where(.kiln-graph[data-dim]) :is(.kiln-graph-node, .kiln-graph-edge):not([data-hot]) { opacity: var(--kiln-graph-dim, 0.25); }
13
+ @media (prefers-reduced-motion: reduce) { :where(.kiln-graph) * { transition: none; } }
14
+ @media (forced-colors: active) {
15
+ :where(.kiln-graph) { forced-color-adjust: none; --kiln-graph-node-current: Highlight !important; --kiln-graph-edge: GrayText !important; --kiln-graph-edge-hot: Highlight !important; --kiln-graph-label: CanvasText !important; --kiln-graph-halo: Canvas !important; }
16
+ :where(.kiln-graph-node) { --kiln-graph-node: CanvasText !important; }
17
+ }
@@ -0,0 +1,295 @@
1
+ // Draws every [data-kiln-graph] box that kiln_link_graph renders. Each node is an HTML link placed
2
+ // over an aria-hidden <svg> of the edges, so Turbo, prefetch, focus, a middle click and screen
3
+ // readers treat it as any other link. A force simulation lays the nodes out: they push each other
4
+ // apart, edges pull their ends together, a weak pull holds the whole towards the middle, and the
5
+ // motion cools until it stops. Dragging a node moves it, hovering or focusing one lights up its
6
+ // neighbours. Inlined once per page; running it again (Turbo runs body scripts on each visit)
7
+ // draws new graphs.
8
+ (() => {
9
+ if (window.KilnLinkGraph) return window.KilnLinkGraph.init()
10
+
11
+ const SVG = "http://www.w3.org/2000/svg"
12
+ // The simulation runs in a square this wide, stretched to the box when it is painted, so the
13
+ // graph fills a box of any shape and a resize only repaints it.
14
+ const SIDE = 1000
15
+ // Pixels kept clear between a node's box (its dot and label) and the edges or another box.
16
+ const GAP = 4
17
+ const stops = new WeakMap()
18
+
19
+ function init() {
20
+ document.querySelectorAll("[data-kiln-graph]").forEach(box => {
21
+ if (stops.has(box) && box.querySelector(".kiln-graph-node")) return
22
+ stops.get(box)?.()
23
+ box.replaceChildren()
24
+ stops.set(box, draw(box))
25
+ })
26
+ }
27
+
28
+ // Returns a function that stops the drawing.
29
+ function draw(box) {
30
+ const data = JSON.parse(box.dataset.kilnGraph)
31
+ const current = box.dataset.current
32
+ const still = box.dataset.still === "true" || matchMedia("(prefers-reduced-motion: reduce)").matches
33
+ const listeners = new AbortController()
34
+ const signal = listeners.signal
35
+
36
+ const svg = box.appendChild(document.createElementNS(SVG, "svg"))
37
+ svg.setAttribute("class", "kiln-graph-edges")
38
+ svg.setAttribute("aria-hidden", "true")
39
+
40
+ const nodes = data.nodes.map(node => ({ ...node, x: 0, y: 0, vx: 0, vy: 0, neighbours: new Set() }))
41
+ const byId = new Map(nodes.map(node => [ node.id, node ]))
42
+ const links = data.edges.map(({ from, to }) => ({ a: byId.get(from), b: byId.get(to) })).filter(link => link.a && link.b)
43
+ links.forEach(link => {
44
+ link.a.neighbours.add(link.b)
45
+ link.b.neighbours.add(link.a)
46
+ link.el = svg.appendChild(document.createElementNS(SVG, "line"))
47
+ link.el.setAttribute("class", "kiln-graph-edge")
48
+ })
49
+ nodes.forEach(node => {
50
+ const isCurrent = node.id === current
51
+ node.r = 4 + Math.sqrt(node.degree) * 1.4 + (isCurrent ? 2 : 0)
52
+ const link = node.el = box.appendChild(document.createElement("a"))
53
+ link.className = "kiln-graph-node"
54
+ link.href = node.url
55
+ link.draggable = false
56
+ // The label may be short or hidden for lack of room; the link is still named in full.
57
+ link.title = node.title
58
+ link.setAttribute("aria-label", node.title)
59
+ link.style.setProperty("--_kiln-graph-size", `${node.r * 2}px`)
60
+ if (node.kind) link.dataset.kind = node.kind
61
+ if (isCurrent) {
62
+ link.setAttribute("data-current", "")
63
+ link.setAttribute("aria-current", "page")
64
+ }
65
+ node.text = link.appendChild(document.createElement("span"))
66
+ node.text.className = "kiln-graph-label"
67
+ node.text.textContent = node.label || node.title
68
+ })
69
+
70
+ let width = 0, height = 0, scaleX = 1, scaleY = 1
71
+ let alpha = 0, frame = null, frames = 0, placed = false
72
+ let hovered = null, drag = null, dragged = false
73
+
74
+ // Each node's box, from its dot's centre: half its width, and how far its label reaches below.
75
+ function measure() {
76
+ nodes.forEach(node => {
77
+ node.half = node.el.offsetWidth / 2
78
+ node.below = node.el.offsetHeight - node.r
79
+ node.labelHalf = node.text.offsetWidth / 2
80
+ })
81
+ }
82
+
83
+ // Starts on a sunflower spiral, the current node in the middle.
84
+ function place() {
85
+ const others = nodes.filter(node => node.id !== current)
86
+ others.forEach((node, index) => {
87
+ const angle = index * 2.39996
88
+ const distance = (SIDE / 2.5) * Math.sqrt((index + 1) / others.length)
89
+ Object.assign(node, { x: Math.cos(angle) * distance, y: Math.sin(angle) * distance })
90
+ })
91
+ }
92
+
93
+ // One step. The rest length of an edge and the push between nodes follow the room each node
94
+ // has, so a graph spreads the same with five nodes or fifty. An edge pulls less on a node with
95
+ // many, so a dense graph does not knot in the middle, and boxes that overlap move apart.
96
+ function tick() {
97
+ const room = SIDE / Math.sqrt(Math.max(nodes.length, 1))
98
+ const push = room * room * 0.012 * alpha
99
+ const length = Math.min(room * 0.8, SIDE / 3)
100
+ for (let i = 0; i < nodes.length; i++) {
101
+ for (let j = i + 1; j < nodes.length; j++) {
102
+ const a = nodes[i], b = nodes[j]
103
+ const dx = b.x - a.x || 0.1, dy = b.y - a.y
104
+ const force = push / Math.max(dx * dx + dy * dy, 25)
105
+ a.vx -= dx * force; a.vy -= dy * force
106
+ b.vx += dx * force; b.vy += dy * force
107
+ separate(a, b, dx, dy)
108
+ }
109
+ }
110
+ links.forEach(({ a, b }) => {
111
+ const dx = b.x - a.x, dy = b.y - a.y
112
+ const distance = Math.hypot(dx, dy) || 1
113
+ const pull = ((distance - length) / distance) * (0.3 / Math.min(a.neighbours.size, b.neighbours.size)) * alpha
114
+ a.vx += dx * pull; a.vy += dy * pull
115
+ b.vx -= dx * pull; b.vy -= dy * pull
116
+ })
117
+ nodes.forEach(node => {
118
+ if (node === drag?.node) return
119
+ node.vx = (node.vx - node.x * 0.006 * alpha) * 0.6
120
+ node.vy = (node.vy - node.y * 0.006 * alpha) * 0.6
121
+ node.x += node.vx
122
+ node.y += node.vy
123
+ })
124
+ stretch()
125
+ nodes.forEach(clamp)
126
+ alpha *= 0.985
127
+ }
128
+
129
+ // A layout smaller than the box moves to the middle and spreads out to fill it, each axis on
130
+ // its own, a tenth of the way on each step.
131
+ function stretch() {
132
+ let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity
133
+ nodes.forEach(node => {
134
+ left = Math.min(left, node.x - node.half / scaleX); right = Math.max(right, node.x + node.half / scaleX)
135
+ top = Math.min(top, node.y - node.r / scaleY); bottom = Math.max(bottom, node.y + node.below / scaleY)
136
+ })
137
+ const centreX = (left + right) / 2, centreY = (top + bottom) / 2
138
+ const factorX = 1 + Math.max(0, (SIDE - (2 * GAP) / scaleX) / Math.max(right - left, 1) - 1) * 0.1
139
+ const factorY = 1 + Math.max(0, (SIDE - (2 * GAP) / scaleY) / Math.max(bottom - top, 1) - 1) * 0.1
140
+ nodes.forEach(node => {
141
+ if (node === drag?.node) return
142
+ node.x = (node.x - centreX) * factorX + centreX * 0.9
143
+ node.y = (node.y - centreY) * factorY + centreY * 0.9
144
+ })
145
+ }
146
+
147
+ // Two boxes that overlap move apart along the axis where they overlap least.
148
+ function separate(a, b, dx, dy) {
149
+ const overlapX = (a.half + b.half + GAP) / scaleX - Math.abs(dx)
150
+ const overlapY = (Math.max(a.r + b.below, b.r + a.below) + GAP) / scaleY - Math.abs(dy)
151
+ if (overlapX <= 0 || overlapY <= 0) return
152
+
153
+ const [ axis, overlap, delta ] = overlapX < overlapY ? [ "x", overlapX, dx ] : [ "y", overlapY, dy ]
154
+ const shift = (Math.sign(delta) || 1) * overlap * 0.4 * Math.min(1, alpha * 4)
155
+ if (a !== drag?.node) a[axis] -= shift
156
+ if (b !== drag?.node) b[axis] += shift
157
+ }
158
+
159
+ // Keeps a node's box inside the box, or centred when it is wider.
160
+ function clamp(node) {
161
+ const x = Math.max(SIDE / 2 - (node.half + GAP) / scaleX, 0)
162
+ node.x = Math.min(Math.max(node.x, -x), x)
163
+ node.y = Math.min(Math.max(node.y, -SIDE / 2 + (node.r + GAP) / scaleY), SIDE / 2 - (node.below + GAP) / scaleY)
164
+ }
165
+
166
+ function paint() {
167
+ links.forEach(({ a, b, el }) => {
168
+ el.setAttribute("x1", (a.x * scaleX).toFixed(1)); el.setAttribute("y1", (a.y * scaleY).toFixed(1))
169
+ el.setAttribute("x2", (b.x * scaleX).toFixed(1)); el.setAttribute("y2", (b.y * scaleY).toFixed(1))
170
+ })
171
+ nodes.forEach(node => { node.el.style.translate = `${(node.x * scaleX).toFixed(1)}px ${(node.y * scaleY).toFixed(1)}px` })
172
+ }
173
+
174
+ // Labels never overlap each other or a node that ranks higher: the hovered node, the current
175
+ // one, the hovered node's neighbours and then the best-linked nodes claim their space first,
176
+ // and paint above the nodes after them. A label without room is hidden.
177
+ function placeLabels() {
178
+ const rank = node => (node === hovered ? 4 : 0) + (node.id === current ? 3 : 0) +
179
+ (hovered?.neighbours.has(node) ? 2 : 0) + node.degree / (nodes.length + 1)
180
+ const taken = []
181
+ const overlaps = (a, b) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
182
+ ;[ ...nodes ].sort((a, b) => rank(b) - rank(a)).forEach((node, index) => {
183
+ const x = node.x * scaleX, y = node.y * scaleY
184
+ const label = { left: x - node.labelHalf, right: x + node.labelHalf, top: y + node.r, bottom: y + node.below }
185
+ const hidden = node !== hovered && node.id !== current && taken.some(other => overlaps(label, other))
186
+ node.text.toggleAttribute("data-hidden", hidden)
187
+ node.el.style.zIndex = nodes.length - index
188
+ taken.push({ left: x - node.r, right: x + node.r, top: y - node.r, bottom: y + node.r })
189
+ if (!hidden) taken.push(label)
190
+ })
191
+ }
192
+
193
+ function run(heat) {
194
+ alpha = Math.max(alpha, heat)
195
+ frame ||= requestAnimationFrame(step)
196
+ }
197
+
198
+ function step() {
199
+ frame = null
200
+ tick(); paint()
201
+ if (++frames % 4 === 0) placeLabels()
202
+ if (alpha > 0.005 || drag?.moved) frame = requestAnimationFrame(step)
203
+ else placeLabels()
204
+ }
205
+
206
+ // Lights up a node, its edges and its neighbours; the rest fade.
207
+ function highlight(node) {
208
+ hovered = node
209
+ box.toggleAttribute("data-dim", Boolean(node))
210
+ nodes.forEach(other => other.el.toggleAttribute("data-hot", other === node || Boolean(node?.neighbours.has(other))))
211
+ links.forEach(link => link.el.toggleAttribute("data-hot", link.a === node || link.b === node))
212
+ placeLabels()
213
+ }
214
+
215
+ // Lays the graph out once the box has a size, and repaints it to fit when the size changes.
216
+ function resize() {
217
+ const rect = box.getBoundingClientRect()
218
+ if (!rect.width || !rect.height) return
219
+ width = rect.width; height = rect.height
220
+ scaleX = width / SIDE; scaleY = height / SIDE
221
+ svg.setAttribute("viewBox", `${-width / 2} ${-height / 2} ${width} ${height}`)
222
+ if (placed) {
223
+ nodes.forEach(clamp)
224
+ paint(); placeLabels()
225
+ return
226
+ }
227
+ placed = true
228
+ measure(); place()
229
+ if (!still) return run(1)
230
+
231
+ alpha = 1
232
+ while (alpha > 0.005) tick()
233
+ paint(); placeLabels()
234
+ }
235
+
236
+ // Where the pointer is, in the simulation's square.
237
+ function point(event) {
238
+ const rect = box.getBoundingClientRect()
239
+ return { x: (event.clientX - rect.left - rect.width / 2) / scaleX, y: (event.clientY - rect.top - rect.height / 2) / scaleY }
240
+ }
241
+
242
+ nodes.forEach(node => {
243
+ const link = node.el
244
+ link.addEventListener("pointerenter", () => drag || highlight(node), { signal })
245
+ link.addEventListener("pointerleave", () => drag || highlight(null), { signal })
246
+ link.addEventListener("pointerdown", event => {
247
+ if (event.button !== 0) return
248
+ link.setPointerCapture(event.pointerId)
249
+ drag = { node, x: event.clientX, y: event.clientY, moved: false }
250
+ }, { signal })
251
+ link.addEventListener("pointermove", event => {
252
+ if (drag?.node !== node) return
253
+ drag.moved ||= Math.hypot(event.clientX - drag.x, event.clientY - drag.y) > 4
254
+ if (!drag.moved) return
255
+ Object.assign(node, point(event), { vx: 0, vy: 0 })
256
+ clamp(node)
257
+ if (still) { paint(); placeLabels() } else run(0.3)
258
+ }, { signal })
259
+ link.addEventListener("pointerup", () => { dragged = Boolean(drag?.moved) }, { signal })
260
+ link.addEventListener("lostpointercapture", () => {
261
+ drag = null
262
+ highlight(link.matches(":hover, :focus-visible") ? node : null)
263
+ }, { signal })
264
+ // A drag past 4px ends in a click on the node it moved, which must not follow the link.
265
+ link.addEventListener("click", event => {
266
+ if (dragged) event.preventDefault()
267
+ dragged = false
268
+ }, { signal })
269
+ })
270
+ box.addEventListener("focusin", event => highlight(nodes.find(node => node.el === event.target) || null), { signal })
271
+ box.addEventListener("focusout", () => highlight(null), { signal })
272
+
273
+ const observer = new ResizeObserver(resize)
274
+ observer.observe(box)
275
+ return () => {
276
+ observer.disconnect()
277
+ listeners.abort()
278
+ cancelAnimationFrame(frame)
279
+ }
280
+ }
281
+
282
+ // The server renders the box empty, so a Turbo morph would take the drawing away. While the
283
+ // box's data stays the same the morph leaves it alone, and a box it did change is drawn again.
284
+ const same = (a, b) => [ "kilnGraph", "current", "still" ].every(key => a.dataset[key] === b?.dataset?.[key])
285
+ addEventListener("turbo:before-morph-element", event => {
286
+ if (stops.has(event.target) && same(event.target, event.detail.newElement)) event.preventDefault()
287
+ })
288
+
289
+ window.KilnLinkGraph = { init }
290
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init)
291
+ else init()
292
+ addEventListener("turbo:load", init)
293
+ addEventListener("turbo:render", init)
294
+ addEventListener("turbo:morph", init)
295
+ })()
@@ -0,0 +1,72 @@
1
+ module Kiln
2
+ module Content
3
+ # An interactive view of Collection#graph: a box of HTML links over an <svg> of edges, drawn by
4
+ # a small inline script and styled by an inline stylesheet that apps theme with CSS custom
5
+ # properties. No dependencies.
6
+ module LinkGraph
7
+ SCRIPT = File.read(File.join(__dir__, "link_graph.js")).freeze
8
+ STYLE = File.read(File.join(__dir__, "link_graph.css")).freeze
9
+
10
+ # The nodes and edges a graph draws: Collection#graph (or a Hash with its shape), cut to the
11
+ # entries within depth links of current and to the limit closest, best-linked nodes. degree
12
+ # counts links in the whole graph. Nodes keep the graph's order.
13
+ def self.data(graph, current: nil, depth: nil, limit: nil, label: nil, kind: nil)
14
+ graph = graph.deep_symbolize_keys
15
+ nodes, edges = graph.fetch(:nodes), graph.fetch(:edges).map { [ it[:from].to_s, it[:to].to_s ] }
16
+ neighbours = Hash.new { |hash, key| hash[key] = Set.new }
17
+ edges.each { |from, to| neighbours[from] << to; neighbours[to] << from }
18
+
19
+ distance = { current => 0 }
20
+ if current && depth
21
+ frontier = [ current ]
22
+ 1.upto(depth) do |step|
23
+ frontier = frontier.flat_map { neighbours[it].to_a }.reject { distance.key?(it) }.uniq
24
+ frontier.each { distance[it] = step }
25
+ end
26
+ nodes = nodes.select { distance.key?(it[:slug].to_s) }
27
+ end
28
+ if limit && nodes.size > limit
29
+ ranked = nodes.each_with_index.sort_by { |node, i| [ node[:slug].to_s == current ? 0 : 1, distance.fetch(node[:slug].to_s, depth.to_i + 1), -neighbours[node[:slug].to_s].size, i ] }
30
+ kept = ranked.first(limit).map(&:last).to_set
31
+ nodes = nodes.select.with_index { |_, i| kept.include?(i) }
32
+ end
33
+
34
+ ids = nodes.to_set { it[:slug].to_s }
35
+ {
36
+ nodes: nodes.map do |node|
37
+ slug = node[:slug].to_s
38
+ { id: slug, title: node[:title], label: (node[label] if label), kind: (node[kind] if kind), url: node[:url], degree: neighbours[slug].size }.compact
39
+ end,
40
+ edges: edges.select { |pair| pair.all? { ids.include?(it) } }.map { |from, to| { from:, to: } }
41
+ }
42
+ end
43
+
44
+ module Helper
45
+ # kiln_link_graph(Kiln::Content.collection(:wiki), current: @page, depth: 1, label: :short)
46
+ #
47
+ # source is a collection with wikilinks or the Hash from Collection#graph. label and kind
48
+ # name the node attributes for the label and for data-kind. depth: nil draws the whole
49
+ # graph. still: true settles the layout before painting, as prefers-reduced-motion does.
50
+ # The script and stylesheet are written once per page, with the request's CSP nonce
51
+ # unless nonce: is false or a nonce of the app's own. Other options are attributes of the box.
52
+ def kiln_link_graph(source, current: nil, depth: nil, limit: nil, label: nil, kind: :kind, still: false, nonce: true, **options)
53
+ current = current.respond_to?(:slug) ? current.slug : current&.to_s
54
+ graph = source.respond_to?(:graph) ? source.graph(*[ label, kind ].compact) : source
55
+ data = LinkGraph.data(graph, current:, depth:, limit:, label:, kind:)
56
+ box = tag.div(
57
+ **options.except(:class, :aria, :data),
58
+ class: [ "kiln-graph", options[:class] ],
59
+ role: "group",
60
+ aria: { label: "Link graph" }.merge(options[:aria] || {}),
61
+ data: { kiln_graph: data, current:, still: (true if still) }.merge(options[:data] || {})
62
+ )
63
+ return box if @kiln_link_graph_assets
64
+
65
+ @kiln_link_graph_assets = true
66
+ nonce = content_security_policy_nonce if nonce == true
67
+ safe_join([ tag.style(LinkGraph::STYLE.html_safe, nonce: nonce || nil), box, javascript_tag(LinkGraph::SCRIPT, nonce: nonce || nil) ], "\n")
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,66 @@
1
+ module Kiln
2
+ module Content
3
+ # [[slug]], [[slug#anchor]], [[slug|text]] and [[#anchor]] in an entry's HTML, for a collection
4
+ # turned on with Kiln::Content.wikilinks. The HTML is edited as a string: only the text of each
5
+ # wikilink changes.
6
+ module Wikilinks
7
+ Result = Data.define(:html, :links, :missing)
8
+
9
+ WIKILINK = /\[\[(?<slug>[^\[\]|#]*)(?:#(?<anchor>[^\[\]|]+))?(?:\|(?<text>[^\[\]]+))?\]\]/
10
+ # Text inside these elements is never a wikilink.
11
+ SKIP = %w[a code pre svg math kbd samp].to_set.freeze
12
+ ATTRIBUTES = %q{(?:"[^"]*"|'[^']*'|[^'">])*}
13
+ # A comment, a raw text element with its content, a tag, or text.
14
+ TOKEN = %r{<!--.*?-->|<(?:script|style|textarea|template)\b#{ATTRIBUTES}>.*?</(?:script|style|textarea|template)\s*>|<(?<close>/?)(?<tag>[a-zA-Z][\w:-]*)(?<attributes>#{ATTRIBUTES})>|[^<]+|<}mi
15
+ HREF = /<a\s(?:#{ATTRIBUTES}\s)?href\s*=\s*(?:"(?<href>[^"]*)"|'(?<href>[^']*)')/i
16
+
17
+ # Resolves the wikilinks in an entry's html against the visible entries of its collection.
18
+ # links are the slugs of the entries it links to, by wikilink or by an href equal to an
19
+ # entry's URL. missing are wikilinks to unknown slugs ("slug") and links to an anchor the
20
+ # target has no element for ("slug#anchor").
21
+ def self.resolve(entry, html, collection, url)
22
+ entries, by_url = collection.link_targets(url)
23
+ links, missing = [], []
24
+ depth = 0
25
+ html = String.new(html).gsub(TOKEN) do
26
+ token = Regexp.last_match
27
+ if token[:tag]
28
+ depth = [ depth + (token[:close].empty? ? 1 : -1), 0 ].max if SKIP.include?(token[:tag].downcase) && !token[:attributes].end_with?("/")
29
+ token[0]
30
+ elsif depth.zero? && !token[0].start_with?("<") && token[0].include?("[[")
31
+ token[0].gsub(WIKILINK) { link(Regexp.last_match, entry, entries, url, missing) }
32
+ else
33
+ token[0]
34
+ end
35
+ end
36
+
37
+ html.scan(HREF) do
38
+ path, anchor = CGI.unescapeHTML(Regexp.last_match[:href]).split("#", 2)
39
+ target = by_url[path] or next
40
+ target = entry if target.slug == entry.slug
41
+ links << target.slug
42
+ missing << "#{target.slug}##{anchor}" if anchor && !target.ids.include?(anchor)
43
+ end
44
+
45
+ Result.new(html: html.html_safe, links: (links.uniq - [ entry.slug ]), missing: missing.uniq)
46
+ end
47
+
48
+ def self.link(match, entry, entries, url, missing)
49
+ slug = CGI.unescapeHTML(match[:slug]).strip
50
+ anchor = match[:anchor] && CGI.unescapeHTML(match[:anchor]).strip
51
+ return match[0] if slug.empty? && anchor.nil?
52
+
53
+ target = slug.empty? ? entry : entries[slug]
54
+ slug = target.slug if target
55
+ text = match[:text]&.strip || ERB::Util.html_escape(target&.title || slug)
56
+ href = ERB::Util.html_escape([ url.call(slug), anchor ].compact.join("#"))
57
+ if target
58
+ %(<a href="#{href}" class="wikilink">#{text}</a>)
59
+ else
60
+ missing << slug
61
+ %(<a href="#{href}" class="wikilink missing">#{text}</a>)
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
data/lib/kiln/content.rb CHANGED
@@ -1,5 +1,5 @@
1
- # Kiln content layer: Markdown views (.html.md, .html.md.erb), collections of Markdown files with
2
- # YAML frontmatter, and single Markdown files. Optional and independent of the exporter, so
1
+ # Kiln content layer: Markdown views (.html.md, .html.md.erb), collections of Markdown and HTML
2
+ # files with YAML frontmatter, and single files. Optional and independent of the exporter, so
3
3
  # server-rendered Rails apps can use it too. Load it with `require "kiln/content"` after adding the
4
4
  # commonmarker and rouge gems. The content page of the docs (docs/app/views/pages/content.html.md)
5
5
  # describes every feature; comments here cover only what the code does not show.
@@ -16,8 +16,11 @@ require "action_dispatch"
16
16
  require_relative "content/markdown"
17
17
  require_relative "content/frontmatter"
18
18
  require_relative "content/handlers"
19
+ require_relative "content/headings"
20
+ require_relative "content/wikilinks"
19
21
  require_relative "content/entry"
20
22
  require_relative "content/collection"
23
+ require_relative "content/link_graph"
21
24
 
22
25
  module Kiln
23
26
  module Content
@@ -50,6 +53,31 @@ module Kiln
50
53
  end
51
54
  end
52
55
 
56
+ # Turns on wikilinks for the collection with this name. The block returns an entry's URL from
57
+ # its slug:
58
+ #
59
+ # Kiln::Content.wikilinks(:wiki) { "/wiki/#{it}" }
60
+ def wikilinks(name, &url)
61
+ raise ArgumentError, "wikilinks :#{name} needs a block that returns an entry's URL from its slug" unless url
62
+
63
+ wikilink_urls[name.to_s] = url
64
+ end
65
+
66
+ def wikilink_url(name) = wikilink_urls[name.to_s]
67
+
68
+ # Orders the collection with this name by attributes (frontmatter keys or Entry methods),
69
+ # instead of newest first. A nil value sorts after every other, and the slug breaks ties:
70
+ #
71
+ # Kiln::Content.order(:wiki, by: [ :part, :title ])
72
+ def order(name, by:)
73
+ keys = Array(by).map(&:to_sym)
74
+ raise ArgumentError, "order :#{name} needs at least one attribute in by:" if keys.empty?
75
+
76
+ orders[name.to_s] = keys
77
+ end
78
+
79
+ def order_for(name) = orders[name.to_s]
80
+
53
81
  # One Markdown file anywhere, such as a README or CONTRIBUTING.md, as an entry with
54
82
  # frontmatter, html and source positions. Read again when the file changes, once per build.
55
83
  def file(path)
@@ -67,6 +95,8 @@ module Kiln
67
95
  @root = @show_drafts = @source_positions = nil
68
96
  @collections = {}
69
97
  @files = {}
98
+ @wikilink_urls = {}
99
+ @orders = {}
70
100
  end
71
101
 
72
102
  private
@@ -77,6 +107,14 @@ module Kiln
77
107
  def files
78
108
  @files ||= {}
79
109
  end
110
+
111
+ def wikilink_urls
112
+ @wikilink_urls ||= {}
113
+ end
114
+
115
+ def orders
116
+ @orders ||= {}
117
+ end
80
118
  end
81
119
  end
82
120
  end
@@ -86,4 +124,5 @@ ActionDispatch::ExceptionWrapper.rescue_responses["Kiln::Content::NotFound"] = :
86
124
  ActiveSupport.on_load(:action_view) do
87
125
  ActionView::Template.register_template_handler :md, Kiln::Content::Handlers::Markdown
88
126
  ActionView::Template.register_template_handler :"md.erb", Kiln::Content::Handlers::MarkdownERB
127
+ include Kiln::Content::LinkGraph::Helper
89
128
  end
data/lib/kiln/links.rb CHANGED
@@ -1,4 +1,5 @@
1
1
  require "json"
2
+ require "nokogiri"
2
3
 
3
4
  module Kiln
4
5
  # The URLs a page points at, as written in its HTML. The asset export and the verifier both read
@@ -17,6 +18,46 @@ module Kiln
17
18
  end
18
19
  end
19
20
 
21
+ # Characters a browser percent-encodes when it reads a URL, which URI() rejects: anything
22
+ # outside ASCII, controls, spaces and " < > ` { } | \ ^.
23
+ UNSAFE = /[^\x21-\x7E]|["<>`{}|\\^]/
24
+
25
+ # The URL with those characters percent-encoded as UTF-8, ready for URI(). "#for-食べる" becomes
26
+ # "#for-%E9%A3%9F%E3%81%B9%E3%82%8B".
27
+ def self.escape(url)
28
+ url.gsub(UNSAFE) { it.unpack("C*").map { format("%%%02X", it) }.join }
29
+ end
30
+
31
+ # The paths on host that the HTML and CSS files in dir point at, resolved against the URL each
32
+ # file is served at.
33
+ def self.paths(dir, host:)
34
+ dir = Pathname(dir)
35
+ Dir.glob("**/*.{html,css}", base: dir).sort.each_with_object(Set.new) do |file, paths|
36
+ text = dir.join(file).read
37
+ urls =
38
+ if file.end_with?(".css")
39
+ text.scan(Assets::CSS_REFERENCE).map { |url, import| (url || import).strip }
40
+ else
41
+ Nokogiri::HTML5(text).xpath(ELEMENTS).flat_map { self.in(it) }
42
+ end
43
+ base = URI(escape("https://#{host}#{page_path(file)}"))
44
+ urls.each do |url|
45
+ uri = URI.join(base, escape(url.strip))
46
+ paths << uri.path if uri.is_a?(URI::HTTP) && uri.host.to_s.casecmp?(host)
47
+ rescue URI::Error
48
+ next
49
+ end
50
+ end
51
+ end
52
+
53
+ # The URL a file is served at: index.html -> /, docs/index.html -> /docs/, now.html -> /now.
54
+ def self.page_path(file)
55
+ path = "/#{file}"
56
+ return path.delete_suffix("index.html") if File.basename(file) == "index.html"
57
+
58
+ path.delete_suffix(".html")
59
+ end
60
+
20
61
  # Module URLs in an importmap's imports and scopes, or nil when the JSON is not an importmap.
21
62
  def self.importmap(json)
22
63
  map = JSON.parse(json)
data/lib/kiln/pages.rb CHANGED
@@ -1,11 +1,34 @@
1
1
  module Kiln
2
- # Declarations from config/kiln.rb: param sources and skips, keyed by route name.
2
+ # Declarations from config/kiln.rb: param sources and skips, keyed by route name, and the path
3
+ # prefixes that limit the build.
3
4
  class Pages
4
- attr_reader :sources, :skips
5
+ attr_reader :sources, :skips, :scopes
5
6
 
6
7
  def initialize
7
8
  @sources = {}
8
9
  @skips = {}
10
+ @scopes = []
11
+ end
12
+
13
+ # scope "/wiki"
14
+ #
15
+ # Builds only the routes under these prefixes. A route is under "/wiki" when the start of its
16
+ # path, before the first param or optional segment, is "/wiki" or starts with "/wiki/".
17
+ def scope(*prefixes)
18
+ prefixes.each do |prefix|
19
+ raise ArgumentError, "scope #{prefix.inspect} must be a path that starts with /" unless prefix.is_a?(String) && prefix.start_with?("/")
20
+
21
+ @scopes << (prefix == "/" ? prefix : prefix.chomp("/"))
22
+ end
23
+ end
24
+
25
+ # True for a route path such as "/wiki/:slug(.:format)" under one of the scopes, or for any
26
+ # path when there are none.
27
+ def in_scope?(route_path)
28
+ return true if scopes.empty?
29
+
30
+ literal = route_path[/\A[^:*(]*/]
31
+ scopes.any? { it == "/" || literal == it || literal.start_with?("#{it}/") }
9
32
  end
10
33
 
11
34
  # params :post, -> { Post.all.map { { slug: it.slug } } }
data/lib/kiln/railtie.rb CHANGED
@@ -1,5 +1,10 @@
1
1
  require "rails/railtie"
2
2
 
3
+ # Apps gate development-only routes and gems on KILN_BUILD. When the command runs a kiln task it is
4
+ # set as Kiln loads, so config/application.rb sees it after Bundler.require. The tasks also set it
5
+ # for a task that invokes them.
6
+ ENV["KILN_BUILD"] = "1" if defined?(Rake.application) && Rake.application.top_level_tasks.any? { it.start_with?("kiln:") }
7
+
3
8
  module Kiln
4
9
  class Railtie < ::Rails::Railtie
5
10
  # config/kiln.rb holds Kiln.configure and Kiln.pages. Param sources are lambdas, so loading it
data/lib/kiln/router.rb CHANGED
@@ -1,8 +1,9 @@
1
1
  module Kiln
2
2
  # Walks the app's GET routes and turns them into concrete pages, using the param sources and skips
3
- # from Kiln.pages. Routes that need params but have no source are reported as uncovered.
3
+ # from Kiln.pages. Routes that need params but have no source are reported as uncovered. Routes
4
+ # outside the scopes in Kiln.pages are listed as :outside and neither built nor reported.
4
5
  class Router
5
- # status is :built (count pages), :skipped (reason) or :uncovered.
6
+ # status is :built (count pages), :skipped (reason), :uncovered or :outside.
6
7
  Row = Data.define(:name, :path, :status, :count, :reason)
7
8
 
8
9
  # Framework routes skipped by default, keyed by "controller#action" or a whole "controller".
@@ -58,7 +59,9 @@ module Kiln
58
59
  # Explicit declarations win over the defaults. For :built, detail is the param list source.
59
60
  def classify(route)
60
61
  name = route.name&.to_sym
61
- if name && dsl.skips.key?(name)
62
+ if !dsl.in_scope?(route.path.spec.to_s)
63
+ [ :outside, nil ]
64
+ elsif name && dsl.skips.key?(name)
62
65
  [ :skipped, dsl.skips[name] || "skipped in config/kiln.rb" ]
63
66
  elsif name && dsl.sources.key?(name)
64
67
  [ :built, dsl.sources[name] ]
data/lib/kiln/verifier.rb CHANGED
@@ -20,7 +20,7 @@ module Kiln
20
20
 
21
21
  private
22
22
  def check_page(file)
23
- page = page_path(file)
23
+ page = Links.page_path(file)
24
24
  doc = parse(@output.join(file))
25
25
  skipped = @skip ? doc.css(@skip).flat_map { [ it, *it.css("*") ] }.to_set : Set.new
26
26
 
@@ -64,7 +64,7 @@ module Kiln
64
64
  url = url.strip
65
65
  return if url.empty?
66
66
 
67
- uri = URI.join("https://#{@host}#{page}", url)
67
+ uri = URI.join(Links.escape("https://#{@host}#{page}"), Links.escape(url))
68
68
  uri if uri.is_a?(URI::HTTP) && uri.host.to_s.downcase == @host
69
69
  end
70
70
 
@@ -76,14 +76,6 @@ module Kiln
76
76
  Nokogiri::HTML5(file.read)
77
77
  end
78
78
 
79
- # The URL a file is served at: index.html -> /, docs/index.html -> /docs/, now.html -> /now.
80
- def page_path(file)
81
- path = "/#{file}"
82
- return path.delete_suffix("index.html") if File.basename(file) == "index.html"
83
-
84
- path.delete_suffix(".html")
85
- end
86
-
87
79
  def error(kind, message, page)
88
80
  @errors << [ kind, message, page ]
89
81
  end
data/lib/kiln/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kiln
2
- VERSION = "0.2.1"
2
+ VERSION = "0.3.0"
3
3
  end
data/lib/kiln/writer.rb CHANGED
@@ -47,13 +47,15 @@ module Kiln
47
47
 
48
48
  # Copies public/ into the output, minus public/assets. Files already in the output win, with a
49
49
  # warning unless they are listed in `generated` (files Kiln writes on purpose, like 404.html).
50
- def copy_public(from, generated: [])
50
+ # only, when given, is called with each relative path and copies the file when it returns true.
51
+ def copy_public(from, generated: [], only: nil)
51
52
  from = Pathname(from)
52
53
  return unless from.directory?
53
54
 
54
55
  Dir.glob("**/*", File::FNM_DOTMATCH, base: from).sort.each do |relative|
55
56
  source = from.join(relative)
56
57
  next if source.directory? || relative.start_with?("assets/")
58
+ next if only && !only.call(relative)
57
59
 
58
60
  if @output.join(relative).exist?
59
61
  @report.warn(:write, "public/#{relative} not copied, a rendered file already exists", path: "/#{relative}") unless generated.include?(relative)
@@ -8,8 +8,13 @@ namespace :kiln do
8
8
  ENV["SECRET_KEY_BASE_DUMMY"] ||= "1"
9
9
  end
10
10
 
11
+ # See lib/kiln/railtie.rb. Set before :environment, so a task that runs kiln:build gets it too.
12
+ task :build_flag do
13
+ ENV["KILN_BUILD"] = "1"
14
+ end
15
+
11
16
  desc "Render every page into the output directory"
12
- task build: [ :secret_key_base, :environment ] do
17
+ task build: [ :build_flag, :secret_key_base, :environment ] do
13
18
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
14
19
  build = Kiln::Build.new
15
20
  # One log line per request buries the report. Warnings and errors still show; VERBOSE=1 shows all.
@@ -1,6 +1,6 @@
1
1
  namespace :kiln do
2
2
  desc "Serve the built output like a static host (PORT, default 4000; BIND, default localhost)"
3
- task serve: [ :secret_key_base, :environment ] do
3
+ task serve: [ :build_flag, :secret_key_base, :environment ] do
4
4
  output = Kiln.config.output_path
5
5
  abort "Kiln: #{output} does not exist. Run kiln:build first." unless output.directory?
6
6
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kiln
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.1
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso
@@ -88,7 +88,12 @@ files:
88
88
  - lib/kiln/content/entry.rb
89
89
  - lib/kiln/content/frontmatter.rb
90
90
  - lib/kiln/content/handlers.rb
91
+ - lib/kiln/content/headings.rb
92
+ - lib/kiln/content/link_graph.css
93
+ - lib/kiln/content/link_graph.js
94
+ - lib/kiln/content/link_graph.rb
91
95
  - lib/kiln/content/markdown.rb
96
+ - lib/kiln/content/wikilinks.rb
92
97
  - lib/kiln/links.rb
93
98
  - lib/kiln/manifest.rb
94
99
  - lib/kiln/page.rb