jekyll-vitepress-theme 1.11.0 → 1.12.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: 31b1b2c1994a774599c9b5612781ac138dc561291572b97a4a2d3a96530618a6
4
- data.tar.gz: 85fc67f3109b3e0c8a0964a98604c219c7fb418b4482580802aae6bc056f5adb
3
+ metadata.gz: 92fbcc13d3a8a09416bc7f3db061472ce56f96c9bb0957547950face3c740f32
4
+ data.tar.gz: 97a7e1547607241f197b69346c47ddfbf5a85ad9a2ee30f61ba9e67aee361b59
5
5
  SHA512:
6
- metadata.gz: '099a79e03be5ea69bf4a6d60f5ec0d9c567439f54b75e777f00d2199fc8ca055b3a15bb9d751993f6544b6d2e363ef0d0615adb5d09b8965fa04b7a1cbcf0b9b'
7
- data.tar.gz: 5b527894fd9d9a99c5e2521cc9c40aea76507136fa7125915ad10347c503b0bd9570e9d5ba4287d9b975541deac4c3e784141c59e555806fde0a15a43684a13d
6
+ metadata.gz: 2903fdd47be94142d7b697490d082a918e50da8010fdb28d52ef2b7b2626153c020f0bd28c43cf6d22f2f0240058e9e41274fe78ea5c1cfb5a211f634d209596
7
+ data.tar.gz: c0f453fb3e597ae5c42f8a63a6b0f34bab5bbdc0d7e08befe95d659322104e2582a2471bf2b5a916a2128465093bcc3d822aa368b4d729e3ceec246c2d34d922
data/_includes/seo.html CHANGED
@@ -15,7 +15,7 @@
15
15
  {% if seo.sitemap_url %}<link rel="sitemap" type="application/xml" href="{{ seo.sitemap_url | escape }}">{% endif %}
16
16
 
17
17
  <meta property="og:site_name" content="{{ site.title | default: site.jekyll_vitepress.branding.site_title | escape }}">
18
- <meta property="og:title" content="{{ seo.page_title | escape }}">
18
+ <meta property="og:title" content="{{ seo.share_title | default: seo.page_title | escape }}">
19
19
  {% if seo.description %}<meta property="og:description" content="{{ seo.description | escape }}">{% endif %}
20
20
  {% if seo.canonical_url %}<meta property="og:url" content="{{ seo.canonical_url | escape }}">{% endif %}
21
21
  <meta property="og:type" content="{{ seo.og_type }}">
@@ -41,7 +41,7 @@
41
41
  {% if seo.facebook.admins %}<meta property="fb:admins" content="{{ seo.facebook.admins | escape }}">{% endif %}
42
42
 
43
43
  <meta name="twitter:card" content="{{ seo.twitter.card | escape }}">
44
- <meta name="twitter:title" content="{{ seo.page_title | escape }}">
44
+ <meta name="twitter:title" content="{{ seo.share_title | default: seo.page_title | escape }}">
45
45
  {% if seo.description %}<meta name="twitter:description" content="{{ seo.description | escape }}">{% endif %}
46
46
  {% if seo.image.url %}<meta name="twitter:image" content="{{ seo.image.url | escape }}">{% endif %}
47
47
  {% if seo.image.alt %}<meta name="twitter:image:alt" content="{{ seo.image.alt | escape }}">{% endif %}
@@ -0,0 +1,24 @@
1
+ {%- comment -%}
2
+ Tells readers of unreleased and older docs which version they are on, and
3
+ links to the stable docs. `jekyll-vitepress build` sets site.vitepress_version
4
+ for each version it builds; the stable docs and single builds show nothing.
5
+ {%- endcomment -%}
6
+ {%- assign version = site.vitepress_version -%}
7
+ {%- if version and version.kind and version.kind != 'stable' -%}
8
+ {%- assign labels = site.jekyll_vitepress.labels -%}
9
+ {%- assign banner_site = site.title | default: site.jekyll_vitepress.branding.site_title -%}
10
+ {%- if version.kind == 'next' -%}
11
+ {%- assign banner_text = labels.version_banner_next | default: "You're reading the docs for unreleased :site from :branch." -%}
12
+ {%- else -%}
13
+ {%- assign banner_text = labels.version_banner_older | default: "You're reading the docs for :site :version." -%}
14
+ {%- endif -%}
15
+ {%- assign banner_link = labels.version_banner_link | default: 'Read the :stable docs' -%}
16
+ {%- assign stable_title = version.stable.title | remove: ' (stable)' -%}
17
+ {%- capture branch_code -%}<code>{{ version.branch | escape }}</code>{%- endcapture -%}
18
+ <div class="VPVersionBanner" id="vp-version-banner" role="note">
19
+ <p>
20
+ {{ banner_text | escape | replace: ':site', banner_site | replace: ':version', version.title | replace: ':branch', branch_code }}
21
+ <a href="{{ version.stable.url }}">{{ banner_link | replace: ':stable', stable_title | escape }}</a>
22
+ </p>
23
+ </div>
24
+ {%- endif -%}
@@ -1,11 +1,18 @@
1
1
  <!DOCTYPE html>
2
- <html lang="{{ page._seo.language | default: page.lang | default: page.locale | default: site.lang | default: site.locale | default: 'en-US' }}"{% if page.dir or site.dir %} dir="{{ page.dir | default: site.dir }}"{% endif %}>
2
+ {%- comment -%} Jekyll gives every page a `dir` (its URL directory), so only a real text direction counts. {%- endcomment -%}
3
+ {%- assign html_dir = nil -%}
4
+ {%- if page.dir == 'rtl' or page.dir == 'ltr' or page.dir == 'auto' -%}
5
+ {%- assign html_dir = page.dir -%}
6
+ {%- elsif site.dir == 'rtl' or site.dir == 'ltr' or site.dir == 'auto' -%}
7
+ {%- assign html_dir = site.dir -%}
8
+ {%- endif %}
9
+ <html lang="{{ page._seo.language | default: page.lang | default: page.locale | default: site.lang | default: site.locale | default: 'en-US' }}"{% if html_dir %} dir="{{ html_dir }}"{% endif %}>
3
10
  {% include head.html %}
4
11
  {% assign theme = site.jekyll_vitepress %}
5
12
  {% assign behavior = theme.behavior %}
6
13
  {% assign page_theme = page.jekyll_vitepress %}
7
14
  {% assign scroll_offset = behavior.scroll_offset | default: 134 %}
8
- <body data-vp-scroll-offset="{{ scroll_offset }}" style="--vp-scroll-offset: {{ scroll_offset }}px;">
15
+ <body{% if site.vitepress_version and site.vitepress_version.kind != 'stable' %} class="has-version-banner"{% endif %} data-vp-scroll-offset="{{ scroll_offset }}" style="--vp-scroll-offset: {{ scroll_offset }}px;">
9
16
  {% assign is_home = false %}
10
17
  {% if page.layout == 'home' or page.url == '/' %}
11
18
  {% assign is_home = true %}
@@ -21,6 +28,7 @@
21
28
  <span tabindex="-1"></span>
22
29
  <a href="#VPContent" class="VPSkipLink visually-hidden">{{ theme.labels.skip_to_content | default: 'Skip to content' }}</a>
23
30
 
31
+ {% include vp_version_banner.html %}
24
32
  <div class="VPBackdrop backdrop" id="vp-backdrop"></div>
25
33
 
26
34
  {% include nav.html has_sidebar=has_sidebar is_home=is_home %}
@@ -1312,7 +1312,7 @@ html:not(.dark) .shiki span {
1312
1312
  .vp-doc h4[id],
1313
1313
  .vp-doc h5[id],
1314
1314
  .vp-doc h6[id] {
1315
- scroll-margin-top: calc(var(--vp-scroll-offset, 134px) - var(--vp-heading-anchor-offset, 0px));
1315
+ scroll-margin-top: calc(var(--vp-scroll-offset, 134px) + var(--vp-layout-top-height, 0px) - var(--vp-heading-anchor-offset, 0px));
1316
1316
  }
1317
1317
 
1318
1318
  .vp-doc h1 {
@@ -2138,3 +2138,57 @@ html.dark .only-light {
2138
2138
  color: var(--vp-c-text-3);
2139
2139
  line-height: 1.3;
2140
2140
  }
2141
+
2142
+ /* ==== Version banner (unreleased and older versions) ==== */
2143
+ .has-version-banner {
2144
+ --vp-layout-top-height: 40px;
2145
+ }
2146
+
2147
+ .VPVersionBanner {
2148
+ position: fixed;
2149
+ top: 0;
2150
+ right: 0;
2151
+ left: 0;
2152
+ z-index: var(--vp-z-index-layout-top);
2153
+ display: flex;
2154
+ align-items: center;
2155
+ justify-content: center;
2156
+ height: var(--vp-layout-top-height);
2157
+ padding: 0 16px;
2158
+ border-bottom: 1px solid var(--vp-c-divider);
2159
+ background: linear-gradient(var(--vp-c-warning-soft), var(--vp-c-warning-soft)), var(--vp-c-bg);
2160
+ color: var(--vp-c-text-1);
2161
+ font-size: 13px;
2162
+ line-height: 18px;
2163
+ text-align: center;
2164
+ }
2165
+
2166
+ .VPVersionBanner p {
2167
+ display: -webkit-box;
2168
+ margin: 0;
2169
+ overflow: hidden;
2170
+ -webkit-box-orient: vertical;
2171
+ -webkit-line-clamp: 2;
2172
+ }
2173
+
2174
+ .VPVersionBanner a {
2175
+ margin-left: 4px;
2176
+ color: var(--vp-c-brand-1);
2177
+ font-weight: 600;
2178
+ text-decoration: underline;
2179
+ text-underline-offset: 2px;
2180
+ white-space: nowrap;
2181
+ }
2182
+
2183
+ .VPVersionBanner code {
2184
+ padding: 1px 4px;
2185
+ border-radius: 4px;
2186
+ background: var(--vp-c-default-soft);
2187
+ font-size: 12px;
2188
+ }
2189
+
2190
+ @media (max-width: 639px) {
2191
+ .has-version-banner {
2192
+ --vp-layout-top-height: 56px;
2193
+ }
2194
+ }
@@ -1816,10 +1816,12 @@
1816
1816
  function getConfiguredScrollOffset() {
1817
1817
  var bodyScrollOffset = document.body ? document.body.getAttribute('data-vp-scroll-offset') : null;
1818
1818
  var offset = bodyScrollOffset ? parseFloat(bodyScrollOffset) : NaN;
1819
- if (!Number.isNaN(offset)) {
1820
- return offset;
1819
+ if (Number.isNaN(offset)) {
1820
+ offset = 134;
1821
1821
  }
1822
- return 134;
1822
+ // The version banner on unreleased and older docs sits above the nav.
1823
+ var versionBanner = document.getElementById('vp-version-banner');
1824
+ return versionBanner ? offset + versionBanner.offsetHeight : offset;
1823
1825
  }
1824
1826
 
1825
1827
  function getHashTarget(hash) {
@@ -2088,7 +2090,8 @@
2088
2090
  var pendingDocFrameHash = null;
2089
2091
 
2090
2092
  function shouldTargetDocFrameLink(link) {
2091
- if (!link) {
2093
+ // Pages without a sidebar (the home page) have no content frame to target.
2094
+ if (!link || !document.getElementById('vp-content-frame')) {
2092
2095
  return false;
2093
2096
  }
2094
2097
 
@@ -2321,11 +2324,8 @@
2321
2324
 
2322
2325
  event.preventDefault();
2323
2326
 
2324
- if (event.detail && typeof event.detail.visit === 'function' && event.detail.response) {
2325
- event.detail.visit(event.detail.response);
2326
- return;
2327
- }
2328
-
2327
+ // Load the page in full. A Turbo Drive visit would swap the body while
2328
+ // this script's listeners stay bound to the old nav and sidebar.
2329
2329
  if (event.detail && event.detail.response && event.detail.response.url) {
2330
2330
  window.location.href = event.detail.response.url;
2331
2331
  }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'optparse'
5
+ require_relative '../lib/jekyll/vitepress_theme/versions'
6
+ require_relative '../lib/jekyll/vitepress_theme/versioned_build'
7
+
8
+ USAGE = <<~TEXT
9
+ Usage: jekyll-vitepress build [options] [-- extra jekyll options]
10
+ jekyll-vitepress serve [options] [-- extra jekyll options]
11
+
12
+ build Builds the docs site, and every version of it configured under
13
+ jekyll_vitepress.versions in _config.yml.
14
+ serve Builds it, serves it, and rebuilds the checkout's version as files
15
+ change.
16
+
17
+ TEXT
18
+
19
+ options = { source: '.', destination: nil, baseurl: ENV.fetch('BASE', '') }
20
+ server = { host: '127.0.0.1', port: 4000 }
21
+ parser = OptionParser.new do |opts|
22
+ opts.banner = USAGE
23
+ opts.on('-s', '--source DIR', 'Docs directory holding _config.yml (default: .)') { |value| options[:source] = value }
24
+ opts.on('-d', '--destination DIR', 'Where the site goes (default: SOURCE/_site)') { |value| options[:destination] = value }
25
+ opts.on('-b', '--baseurl URL', 'Base URL the site is served under, such as /repo') { |value| options[:baseurl] = value }
26
+ opts.on('-H', '--host HOST', 'Host to serve on (default: 127.0.0.1)') { |value| server[:host] = value }
27
+ opts.on('-P', '--port PORT', Integer, 'Port to serve on (default: 4000)') { |value| server[:port] = value }
28
+ opts.on('-h', '--help', 'Show this help') do
29
+ puts opts
30
+ exit
31
+ end
32
+ end
33
+
34
+ arguments = ARGV.dup
35
+ separator = arguments.index('--')
36
+ jekyll_args = separator ? arguments.slice!(separator..)[1..] : []
37
+ command = parser.parse(arguments).first
38
+
39
+ unless %w[build serve].include?(command)
40
+ warn parser.help
41
+ exit 1
42
+ end
43
+
44
+ begin
45
+ builder = Jekyll::VitePressTheme::VersionedBuild.new(**options, jekyll_args: jekyll_args)
46
+ command == 'serve' ? builder.serve(**server) : builder.run
47
+ rescue Jekyll::VitePressTheme::VersionedBuild::Error => e
48
+ warn "jekyll-vitepress: #{e.message}"
49
+ exit 1
50
+ end
@@ -545,6 +545,7 @@ module Jekyll
545
545
  end
546
546
 
547
547
  Jekyll::Hooks.register :site, :post_read do |site|
548
+ Jekyll::VitePressTheme::Versions.apply(site)
548
549
  Jekyll::VitePressTheme::VersionLabel.apply(site)
549
550
  Jekyll::VitePressTheme::RougeStyles.apply(site)
550
551
  Jekyll::VitePressTheme::Sidebar.apply(site)
@@ -85,9 +85,16 @@ module Jekyll
85
85
  site = item.site
86
86
  config = config_for(site)
87
87
  page_title = clean_text(page_config['title'] || item.data['title'] || site_title(site))
88
- full_title = full_title_for(page_title, site_title(site), config)
88
+ plain_site_title = site_title(site)
89
+ versioned_site_title = Versions.site_title(site, plain_site_title)
90
+ full_title = if page_title == plain_site_title
91
+ versioned_site_title
92
+ else
93
+ full_title_for(page_title, versioned_site_title, config)
94
+ end
89
95
  description = clean_text(page_config['description'] || item.data['description'] || site.config['description'])
90
- canonical = canonical_url(site, page_config['canonical_url'] || item.data['canonical_url'] || item.url)
96
+ canonical_source = page_config['canonical_url'] || item.data['canonical_url'] || item.url
97
+ canonical = canonical_url(site, Versions.localize_url(site, canonical_source))
91
98
  locale = locale_for(item)
92
99
  image = image_for(item, page_config, config)
93
100
  author = author_for(item, page_config)
@@ -100,6 +107,9 @@ module Jekyll
100
107
  metadata = {
101
108
  'title' => full_title,
102
109
  'page_title' => page_title,
110
+ # Link previews show og:title rather than <title>, so outside the
111
+ # stable docs they get the title that names the version.
112
+ 'share_title' => Versions.stable?(site) ? page_title : full_title,
103
113
  'description' => description,
104
114
  'canonical_url' => canonical,
105
115
  'locale' => locale.tr('-', '_'),
@@ -1,5 +1,5 @@
1
1
  module Jekyll
2
2
  module VitePressTheme
3
- VERSION = "1.11.0".freeze
3
+ VERSION = "1.12.0".freeze
4
4
  end
5
5
  end
@@ -0,0 +1,484 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cgi'
4
+ require 'date'
5
+ require 'fileutils'
6
+ require 'json'
7
+ require 'open3'
8
+ require 'rubygems/version'
9
+ require 'tmpdir'
10
+ require 'yaml'
11
+
12
+ module Jekyll
13
+ module VitePressTheme
14
+ # Builds a docs site, and when `jekyll_vitepress.versions` is configured,
15
+ # every version of it that stays online:
16
+ #
17
+ # * stable: the newest release tag, at the site root
18
+ # * next: the checkout being built (the default branch in CI), at /next/
19
+ # * older major lines listed under `keep`, such as the newest 1.x at /v1/
20
+ #
21
+ # Each release is checked out in a Git worktree and built with the current
22
+ # docs Gemfile, so theme fixes reach older versions too. Each build runs in
23
+ # its own Jekyll process, so one version's plugins never load into another.
24
+ # The builds are then assembled into one site.
25
+ #
26
+ # Without a `versions` block it runs one ordinary build, so every project
27
+ # can publish with the same command.
28
+ # rubocop:disable-next Metrics/AbcSize, Metrics/ClassLength
29
+ class VersionedBuild
30
+ class Error < StandardError; end
31
+
32
+ Version = Struct.new(
33
+ :id, :kind, :tag, :title, :label, :path, :redirect_missing, :overlay,
34
+ :source, :root, :output,
35
+ keyword_init: true
36
+ )
37
+
38
+ CONFIG_FILES = %w[_config.yml _config.yaml _config.toml].freeze
39
+
40
+ def initialize(source: '.', destination: nil, baseurl: '', jekyll_args: [], out: $stdout)
41
+ @docs = File.expand_path(source)
42
+ @destination = File.expand_path(destination || File.join(@docs, '_site'))
43
+ @baseurl = normalize_baseurl(baseurl)
44
+ @jekyll_args = jekyll_args
45
+ @out = out
46
+ end
47
+
48
+ def run
49
+ versions = planned_versions
50
+ versions ? build_versions(versions) : build_single
51
+ end
52
+
53
+ # Builds every version, serves the site, and rebuilds the checkout's
54
+ # version whenever a file changes, the way `jekyll serve` does for a
55
+ # single site. Build hooks run once, in the first build.
56
+ def serve(host: '127.0.0.1', port: 4000)
57
+ versions = planned_versions
58
+ return serve_single(host, port) unless versions
59
+
60
+ Dir.mktmpdir('jekyll-vitepress-') do |work|
61
+ build_versions(versions, work)
62
+ checkout = versions.find { |version| version.tag.nil? }
63
+ watcher = checkout && watch(checkout, work)
64
+ begin
65
+ serve_directory(host, port)
66
+ ensure
67
+ stop(watcher)
68
+ end
69
+ end
70
+ end
71
+
72
+ private
73
+
74
+ attr_reader :docs, :destination, :baseurl, :hooks
75
+
76
+ # -- Planning -------------------------------------------------------
77
+
78
+ def plan(settings)
79
+ @root = git(docs, 'rev-parse', '--show-toplevel', allow_failure: true)&.strip
80
+ return warn_single('the docs are not in a Git checkout') unless @root && !@root.empty?
81
+
82
+ @docs_path = relative_docs_path
83
+ releases = release_tags(settings['tag_prefix'])
84
+ stable = releases.last
85
+ return warn_single('there is no release tag yet') unless stable
86
+ return warn_single("#{stable[:tag]} has no docs at #{display_docs_path}") unless docs_at?(stable[:tag])
87
+
88
+ versions = [stable_version(stable, hash_setting(settings['stable']))]
89
+ versions << next_version(hash_setting(settings['next'])) unless settings['next'] == false
90
+ versions.concat(kept_versions(settings, releases, stable))
91
+ versions.each { |version| version.overlay = Array(settings['overlay']) + Array(version.overlay) }
92
+ versions
93
+ end
94
+
95
+ def stable_version(release, options)
96
+ Version.new(
97
+ id: options['id'] || 'stable', kind: 'stable', tag: release[:tag],
98
+ title: title_for(options['title'], release[:version], "#{release[:version]} (stable)"),
99
+ label: nil, path: '/'
100
+ )
101
+ end
102
+
103
+ def next_version(options)
104
+ Version.new(
105
+ id: options['id'] || 'next', kind: 'next', tag: nil,
106
+ title: options['title'] || 'Next (unreleased)', label: options.fetch('label', 'Next'),
107
+ path: normalize_path(options['path'] || '/next/')
108
+ )
109
+ end
110
+
111
+ def kept_versions(settings, releases, stable)
112
+ Array(settings['keep']).filter_map do |entry|
113
+ entry = hash_setting(entry)
114
+ major = Integer(entry.fetch('major') { raise Error, 'Each entry under versions.keep needs a `major`' })
115
+ release = releases.reverse.find { |candidate| candidate[:segments].first == major }
116
+ next say("No #{major}.x release tag, so there is no #{major}.x version to keep") unless release
117
+ next if release[:tag] == stable[:tag]
118
+ next say("#{release[:tag]} has no docs at #{display_docs_path}, so it is skipped") unless docs_at?(release[:tag])
119
+
120
+ id = entry['id'] || "v#{major}"
121
+ Version.new(
122
+ id: id, kind: 'older', tag: release[:tag],
123
+ title: title_for(entry['title'], release[:version], release[:version]),
124
+ label: entry.fetch('label', id), path: normalize_path(entry['path'] || "/#{id}/"),
125
+ redirect_missing: entry['redirect_missing'] == true, overlay: entry['overlay']
126
+ )
127
+ end
128
+ end
129
+
130
+ def release_tags(prefix)
131
+ prefix = prefix.nil? ? 'v?' : Regexp.escape(prefix.to_s)
132
+ pattern = /\A#{prefix}(\d+\.\d+\.\d+)\z/
133
+ releases = git(@root, 'tag', '--list').lines.map(&:strip).filter_map do |tag|
134
+ match = pattern.match(tag)
135
+ next unless match
136
+
137
+ version = Gem::Version.new(match[1])
138
+ { tag: tag, version: match[1], gem_version: version, segments: version.segments }
139
+ end
140
+ releases.sort_by { |release| release[:gem_version] }
141
+ end
142
+
143
+ def docs_at?(tag)
144
+ CONFIG_FILES.any? do |name|
145
+ path = @docs_path.empty? ? name : File.join(@docs_path, name)
146
+ git(@root, 'cat-file', '-e', "#{tag}:#{path}", allow_failure: true)
147
+ end
148
+ end
149
+
150
+ # -- Building -------------------------------------------------------
151
+
152
+ def build_single
153
+ version = Version.new(id: 'current', kind: 'current', source: docs, root: docs, output: destination)
154
+ run_hook('before_build', version)
155
+ jekyll_build(docs, destination, baseurl, config_files(docs))
156
+ run_hook('after_build', version)
157
+ run_hook('after_assemble', version)
158
+ end
159
+
160
+ def planned_versions
161
+ config = site_config
162
+ settings = config.dig('jekyll_vitepress', 'versions')
163
+ @hooks = build_hooks(config)
164
+ @site_url = config['url'].to_s.strip.sub(%r{/+\z}, '')
165
+ settings.is_a?(Hash) ? plan(settings) : nil
166
+ end
167
+
168
+ def build_versions(versions, work = nil)
169
+ return Dir.mktmpdir('jekyll-vitepress-') { |dir| build_versions(versions, dir) } unless work
170
+
171
+ begin
172
+ versions.each do |version|
173
+ prepare_source(version, work)
174
+ build_version(version, versions, work)
175
+ end
176
+ assemble(versions)
177
+ ensure
178
+ versions.each { |version| remove_worktree(version) }
179
+ end
180
+ summary = versions.map { |version| "#{version.path} = #{version.tag || 'this checkout'}" }.join(', ')
181
+ say("Built #{summary} into #{destination}")
182
+ end
183
+
184
+ def prepare_source(version, work)
185
+ version.output = File.join(work, 'out', version.id)
186
+ unless version.tag
187
+ version.root = @root
188
+ version.source = docs
189
+ return
190
+ end
191
+
192
+ version.root = File.join(work, 'src', version.id)
193
+ FileUtils.mkdir_p(File.dirname(version.root))
194
+ git(@root, '-c', 'core.hooksPath=/dev/null', 'worktree', 'add', '--quiet', '--detach', version.root, version.tag)
195
+ version.source = @docs_path.empty? ? version.root : File.join(version.root, @docs_path)
196
+ copy_overlay(version)
197
+ end
198
+
199
+ def copy_overlay(version)
200
+ version.overlay.each do |path|
201
+ from = File.join(docs, path)
202
+ raise Error, "versions.overlay lists #{path}, which is not in #{docs}" unless File.exist?(from)
203
+
204
+ to = File.join(version.source, path)
205
+ FileUtils.rm_rf(to)
206
+ FileUtils.mkdir_p(File.dirname(to))
207
+ FileUtils.cp_r(from, to)
208
+ end
209
+ end
210
+
211
+ def build_version(version, versions, work)
212
+ say("Building #{version.title} (#{version.tag || 'this checkout'}) at #{version.path}")
213
+ extra = File.join(work, "#{version.id}.yml")
214
+ File.write(extra, YAML.dump(Versions::CONFIG_KEY => version_data(version, versions)))
215
+ run_hook('before_build', version)
216
+ jekyll_build(version.source, version.output, version_baseurl(version), config_files(version.source) + [extra])
217
+ run_hook('after_build', version)
218
+ end
219
+
220
+ def version_data(version, versions)
221
+ stable = versions.first
222
+ {
223
+ 'id' => version.id, 'kind' => version.kind, 'title' => version.title, 'label' => version.label,
224
+ 'ref' => version.tag || 'HEAD', 'branch' => branch_name, 'path' => version.path,
225
+ 'root_baseurl' => baseurl,
226
+ 'stable' => { 'title' => stable.title, 'url' => version_url(stable) },
227
+ 'items' => versions.map { |item| { 'id' => item.id, 'title' => item.title, 'url' => version_url(item) } } +
228
+ external_items
229
+ }
230
+ end
231
+
232
+ # Links such as a changelog, kept from the project's _data/versions.yml.
233
+ def external_items
234
+ path = File.join(docs, '_data', 'versions.yml')
235
+ return [] unless File.file?(path)
236
+
237
+ data = YAML.safe_load_file(path, permitted_classes: [Date, Time]) || {}
238
+ Array(data['items']).select { |item| item.is_a?(Hash) && (item['external'] || item['url'].to_s.include?('://')) }
239
+ end
240
+
241
+ def jekyll_build(source, output, build_baseurl, configs)
242
+ command = ['bundle', 'exec', 'jekyll', 'build', '--source', source, '--destination', output,
243
+ '--baseurl', build_baseurl, '--config', configs.join(','), *@jekyll_args]
244
+ run!(command, chdir: source, env: { 'BUNDLE_GEMFILE' => gemfile })
245
+ end
246
+
247
+ # -- Assembling -----------------------------------------------------
248
+
249
+ def assemble(versions)
250
+ guard_destination!
251
+ FileUtils.rm_rf(destination)
252
+ FileUtils.mkdir_p(destination)
253
+ stable, *others = versions
254
+ FileUtils.cp_r(File.join(stable.output, '.'), destination)
255
+ others.each do |version|
256
+ target = File.join(destination, version.path)
257
+ FileUtils.rm_rf(target)
258
+ FileUtils.mkdir_p(target)
259
+ FileUtils.cp_r(File.join(version.output, '.'), target)
260
+ end
261
+ others.select(&:redirect_missing).each { |version| write_redirects(version) }
262
+ list_sitemaps(others)
263
+ run_hook('after_assemble', stable)
264
+ end
265
+
266
+ # Old URLs that only exist in a kept version, such as pages removed
267
+ # since 1.x, redirect into that version instead of returning 404.
268
+ def write_redirects(version)
269
+ Dir.glob('**/*.html', base: version.output).each do |relative|
270
+ next if relative == '404.html' || File.exist?(File.join(destination, relative))
271
+
272
+ route = relative.delete_suffix('index.html')
273
+ target = "#{baseurl}#{version.path}#{route}"
274
+ path = File.join(destination, relative)
275
+ FileUtils.mkdir_p(File.dirname(path))
276
+ File.write(path, redirect_html(target))
277
+ end
278
+ end
279
+
280
+ def redirect_html(target)
281
+ escaped = CGI.escapeHTML(target)
282
+ canonical = @site_url.empty? ? '' : %(\n <link rel="canonical" href="#{CGI.escapeHTML(@site_url)}#{escaped}">)
283
+ <<~HTML
284
+ <!doctype html>
285
+ <html lang="en">
286
+ <head>
287
+ <meta charset="utf-8">
288
+ <title>Redirecting…</title>#{canonical}
289
+ <meta name="robots" content="noindex,follow">
290
+ <script>window.location.replace(#{JSON.generate(target)} + window.location.search + window.location.hash);</script>
291
+ <meta http-equiv="refresh" content="0;url=#{escaped}">
292
+ </head>
293
+ <body><p>This page has moved to <a href="#{escaped}">#{escaped}</a>.</p></body>
294
+ </html>
295
+ HTML
296
+ end
297
+
298
+ # Search engines find the stable sitemap through robots.txt; the other
299
+ # versions' sitemaps are listed beside it.
300
+ def list_sitemaps(versions)
301
+ robots = File.join(destination, 'robots.txt')
302
+ return unless File.file?(robots) && File.read(robots).match?(/^Sitemap:/)
303
+
304
+ lines = versions.filter_map do |version|
305
+ next unless File.file?(File.join(version.output, 'sitemap.xml'))
306
+
307
+ "Sitemap: #{@site_url}#{baseurl}#{version.path}sitemap.xml"
308
+ end
309
+ File.open(robots, 'a') { |file| lines.each { |line| file.puts(line) } } unless lines.empty?
310
+ end
311
+
312
+ def guard_destination!
313
+ protected = [docs, @root, Dir.home, '/'].compact.map { |path| File.expand_path(path) }
314
+ return unless protected.include?(destination)
315
+
316
+ raise Error, "Refusing to replace #{destination} with the built site; pass a separate --destination"
317
+ end
318
+
319
+ # -- Serving --------------------------------------------------------
320
+
321
+ def serve_single(host, port)
322
+ command = ['bundle', 'exec', 'jekyll', 'serve', '--source', docs, '--destination', destination,
323
+ '--baseurl', baseurl, '--host', host, '--port', port.to_s, *@jekyll_args]
324
+ run!(command, chdir: docs, env: { 'BUNDLE_GEMFILE' => gemfile })
325
+ end
326
+
327
+ def watch(version, work)
328
+ output = File.join(destination, version.path)
329
+ configs = config_files(docs) + [File.join(work, "#{version.id}.yml")]
330
+ command = ['bundle', 'exec', 'jekyll', 'build', '--watch', '--source', docs, '--destination', output,
331
+ '--baseurl', version_baseurl(version), '--config', configs.join(','), *@jekyll_args]
332
+ say("Rebuilding #{version.path} when #{docs} changes")
333
+ Process.spawn({ 'BUNDLE_GEMFILE' => gemfile }, *command, chdir: docs)
334
+ end
335
+
336
+ def serve_directory(host, port)
337
+ require 'webrick'
338
+ server = WEBrick::HTTPServer.new(BindAddress: host, Port: port, AccessLog: [],
339
+ Logger: WEBrick::Log.new(File::NULL))
340
+ server.mount(baseurl.empty? ? '/' : baseurl, WEBrick::HTTPServlet::FileHandler, destination)
341
+ %w[INT TERM].each { |signal| trap(signal) { server.shutdown } }
342
+ say("Serving http://#{host}:#{port}#{baseurl}/")
343
+ server.start
344
+ end
345
+
346
+ def stop(pid)
347
+ return unless pid
348
+
349
+ Process.kill('TERM', pid)
350
+ Process.wait(pid)
351
+ rescue Errno::ESRCH, Errno::ECHILD
352
+ nil
353
+ end
354
+
355
+ # -- Hooks ----------------------------------------------------------
356
+
357
+ def build_hooks(config)
358
+ value = config.dig('jekyll_vitepress', 'build')
359
+ value.is_a?(Hash) ? value : {}
360
+ end
361
+
362
+ def run_hook(name, version)
363
+ Array(hooks[name]).each do |command|
364
+ say("Running #{name} for #{version.id}: #{command}")
365
+ # Hooks get the environment from before `bundle exec`, so a hook
366
+ # can run the repository's own bundle without inheriting the docs one.
367
+ with_original_env { run!(['sh', '-c', command.to_s], chdir: docs, env: hook_env(version)) }
368
+ end
369
+ end
370
+
371
+ def hook_env(version)
372
+ {
373
+ 'VITEPRESS_DOCS' => docs,
374
+ 'VITEPRESS_SITE' => destination,
375
+ 'VITEPRESS_VERSION_ID' => version.id,
376
+ 'VITEPRESS_VERSION_KIND' => version.kind,
377
+ 'VITEPRESS_VERSION_REF' => version.tag || 'HEAD',
378
+ 'VITEPRESS_VERSION_SOURCE' => version.source,
379
+ 'VITEPRESS_VERSION_ROOT' => version.root,
380
+ 'VITEPRESS_VERSION_OUTPUT' => version.output,
381
+ 'VITEPRESS_VERSION_BASEURL' => version.path ? version_baseurl(version) : baseurl,
382
+ 'VITEPRESS_VERSION_URL' => version.path ? "#{@site_url}#{version_url(version)}" : "#{@site_url}#{baseurl}/"
383
+ }.transform_values(&:to_s)
384
+ end
385
+
386
+ # -- Helpers --------------------------------------------------------
387
+
388
+ def site_config
389
+ path = CONFIG_FILES.map { |name| File.join(docs, name) }.find { |candidate| File.file?(candidate) }
390
+ raise Error, "No _config.yml in #{docs}" unless path
391
+ return {} if path.end_with?('.toml')
392
+
393
+ YAML.safe_load_file(path, permitted_classes: [Date, Time], aliases: true) || {}
394
+ end
395
+
396
+ def config_files(source)
397
+ CONFIG_FILES.map { |name| File.join(source, name) }.select { |path| File.file?(path) }
398
+ end
399
+
400
+ def gemfile
401
+ ENV['BUNDLE_GEMFILE'] || File.join(docs, 'Gemfile')
402
+ end
403
+
404
+ def with_original_env(&)
405
+ defined?(Bundler) ? Bundler.with_original_env(&) : yield
406
+ end
407
+
408
+ def remove_worktree(version)
409
+ return unless version.tag && version.root && File.directory?(version.root)
410
+
411
+ git(@root, 'worktree', 'remove', '--force', version.root, allow_failure: true)
412
+ end
413
+
414
+ def relative_docs_path
415
+ real_root = File.realpath(@root)
416
+ real_docs = File.realpath(docs)
417
+ real_docs == real_root ? '' : real_docs.delete_prefix("#{real_root}/")
418
+ end
419
+
420
+ def display_docs_path
421
+ @docs_path.empty? ? 'the repository root' : @docs_path
422
+ end
423
+
424
+ def branch_name
425
+ @branch_name ||= begin
426
+ name = git(@root, 'rev-parse', '--abbrev-ref', 'HEAD', allow_failure: true).to_s.strip
427
+ name = ENV['GITHUB_REF_NAME'].to_s if (name.empty? || name == 'HEAD') && ENV['GITHUB_REF_TYPE'] == 'branch'
428
+ name.empty? || name == 'HEAD' ? 'main' : name
429
+ end
430
+ end
431
+
432
+ def version_baseurl(version)
433
+ "#{baseurl}#{version.path.chomp('/')}"
434
+ end
435
+
436
+ def version_url(version)
437
+ "#{baseurl}#{version.path}"
438
+ end
439
+
440
+ def title_for(template, version, default)
441
+ template ? template.to_s.gsub(':version', version) : default
442
+ end
443
+
444
+ def hash_setting(value)
445
+ value.is_a?(Hash) ? value : {}
446
+ end
447
+
448
+ def normalize_path(value)
449
+ path = "/#{value.to_s.strip.delete_prefix('/')}"
450
+ path.end_with?('/') ? path : "#{path}/"
451
+ end
452
+
453
+ def normalize_baseurl(value)
454
+ value = value.to_s.strip
455
+ return '' if value.empty? || value == '/'
456
+
457
+ "/#{value.delete_prefix('/')}".sub(%r{/+\z}, '')
458
+ end
459
+
460
+ def warn_single(reason)
461
+ say("Building one version of the docs: #{reason}.")
462
+ nil
463
+ end
464
+
465
+ def say(message)
466
+ @out.puts("jekyll-vitepress: #{message}")
467
+ nil
468
+ end
469
+
470
+ def git(dir, *args, allow_failure: false)
471
+ output, status = Open3.capture2e('git', '-C', dir, *args)
472
+ return output if status.success?
473
+ return nil if allow_failure
474
+
475
+ raise Error, "git #{args.join(' ')} failed:\n#{output}"
476
+ end
477
+
478
+ def run!(command, chdir:, env: {})
479
+ success = system(env, *command, chdir: chdir)
480
+ raise Error, "#{command.first(4).join(' ')} … failed" unless success
481
+ end
482
+ end
483
+ end
484
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module VitePressTheme
5
+ # The part of versioned docs that runs inside each version's build.
6
+ #
7
+ # `jekyll-vitepress build` builds every published version separately and
8
+ # hands each build a `vitepress_version` entry in its configuration. This
9
+ # module turns that entry into the version selector, and gives the SEO
10
+ # module the labelled site title and version-local canonical URLs. The
11
+ # banner on unreleased and older versions reads the same entry from
12
+ # `site.vitepress_version`.
13
+ module Versions
14
+ module_function
15
+
16
+ CONFIG_KEY = 'vitepress_version'
17
+
18
+ def current(site)
19
+ value = site.config[CONFIG_KEY]
20
+ value.is_a?(Hash) ? value : nil
21
+ end
22
+
23
+ def stable?(site)
24
+ version = current(site)
25
+ version.nil? || version['kind'] == 'stable'
26
+ end
27
+
28
+ def apply(site)
29
+ version = current(site)
30
+ return unless version
31
+
32
+ site.data['versions'] = {
33
+ 'current' => version['id'],
34
+ 'items' => Array(version['items']).map { |item| item.is_a?(Hash) ? item.dup : item }
35
+ }
36
+ end
37
+
38
+ # The site title that page titles end with: "RubyLLM Next" or
39
+ # "RubyLLM v1" outside the stable docs, so search results and link
40
+ # previews say which version a page belongs to.
41
+ def site_title(site, title)
42
+ return title if stable?(site)
43
+
44
+ label = current(site)['label'].to_s.strip
45
+ return title if label.empty?
46
+ return label if title.to_s.empty?
47
+
48
+ "#{title} #{label}"
49
+ end
50
+
51
+ # An absolute URL into the published site, such as a `canonical_url` in
52
+ # front matter, names the stable docs. Inside another version it should
53
+ # name that version's page, so it becomes a site path that the version's
54
+ # base URL is then added to.
55
+ def localize_url(site, value)
56
+ version = current(site)
57
+ return value unless version && value.is_a?(String)
58
+
59
+ origin = site.config['url'].to_s.strip.sub(%r{/+\z}, '')
60
+ return value if origin.empty?
61
+
62
+ prefix = "#{origin}#{version['root_baseurl'].to_s.sub(%r{/+\z}, '')}"
63
+ return value unless value == prefix || value.start_with?("#{prefix}/")
64
+
65
+ path = value.delete_prefix(prefix)
66
+ path.empty? ? '/' : path
67
+ end
68
+ end
69
+ end
70
+ end
@@ -1,5 +1,6 @@
1
1
  require 'jekyll'
2
2
  require_relative 'jekyll/vitepress_theme/version'
3
+ require_relative 'jekyll/vitepress_theme/versions'
3
4
  require_relative 'jekyll/vitepress_theme/markdown_export'
4
5
  require_relative 'jekyll/vitepress_theme/seo'
5
6
  require_relative 'jekyll/vitepress_theme/llms'
metadata CHANGED
@@ -1,11 +1,11 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-vitepress-theme
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.11.0
4
+ version: 1.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Carmine Paolino
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
@@ -73,7 +73,8 @@ description: Jekyll VitePress Theme brings VitePress-style documentation UX, sea
73
73
  structured metadata, and Jekyll-native extensions to Ruby static sites.
74
74
  email:
75
75
  - carmine@paolino.me
76
- executables: []
76
+ executables:
77
+ - jekyll-vitepress
77
78
  extensions: []
78
79
  extra_rdoc_files: []
79
80
  files:
@@ -102,6 +103,7 @@ files:
102
103
  - _includes/sidebar_items.html
103
104
  - _includes/version_link.html
104
105
  - _includes/vp_image.html
106
+ - _includes/vp_version_banner.html
105
107
  - _layouts/default.html
106
108
  - _layouts/home.html
107
109
  - assets/css/vitepress-components.css
@@ -174,6 +176,7 @@ files:
174
176
  - assets/images/theme/vitepress-logo-official.svg
175
177
  - assets/js/vitepress-theme.js
176
178
  - assets/vendor/turbo.js
179
+ - exe/jekyll-vitepress
177
180
  - lib/jekyll-vitepress-theme.rb
178
181
  - lib/jekyll/vitepress_theme/hooks.rb
179
182
  - lib/jekyll/vitepress_theme/last_updated.rb
@@ -181,6 +184,8 @@ files:
181
184
  - lib/jekyll/vitepress_theme/markdown_export.rb
182
185
  - lib/jekyll/vitepress_theme/seo.rb
183
186
  - lib/jekyll/vitepress_theme/version.rb
187
+ - lib/jekyll/vitepress_theme/versioned_build.rb
188
+ - lib/jekyll/vitepress_theme/versions.rb
184
189
  homepage: https://jekyll-vitepress.dev
185
190
  licenses:
186
191
  - MIT
@@ -206,7 +211,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
206
211
  - !ruby/object:Gem::Version
207
212
  version: '0'
208
213
  requirements: []
209
- rubygems_version: 3.6.9
214
+ rubygems_version: 4.0.20
210
215
  specification_version: 4
211
216
  summary: A polished, SEO-ready VitePress-style documentation theme for Jekyll.
212
217
  test_files: []