jekyll-vitepress-theme 1.11.1 → 1.12.1

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: 941eba24aff121520a234e7672392da0212ef8571ffe1c0c5d7c7d2446f2cd8c
4
- data.tar.gz: ed5ea5861a5c1af7bf26fad4e79d8bdb3ca8fb1427cf67771760e34a5a9f0c97
3
+ metadata.gz: 44d2fd26511e4e91bc4e9e51c781e5839aaba113b98a41e14d5a41679d4579ab
4
+ data.tar.gz: 795966c63dc7e849ed693c405869780512f9d24142f63bf2826049d175e4b1c4
5
5
  SHA512:
6
- metadata.gz: d0a4fbd1e5df459f9932e3d3c92e5dfedfc13b1087713c5112c2acf2dfa716b63b84950a46d7889a973791c181f7095cc3de15a2205413b4fef4708e07248f95
7
- data.tar.gz: 1b202d59f4377fbdfe7898c5a2aa41a6c76b1e409037f05a928211e2dee7ad9b0141374bb24d3408634a1fac4a00f0b5e68a37a439de01bed4ac51dfc9eacafd
6
+ metadata.gz: 0b9b662c2a541fc3b316a3b5a3f8753e648d68101a353833527799466888d360a140de8934027b32165a17f0232b19bbf739cd1cd0d7aa2a1ea97e1192953e9b
7
+ data.tar.gz: 8e57ceabe73f98152ab8a032856b8100981cfa087060a7747453e3bbf2715bb75cd86ab04dc50549444433a5f6798eec64d79a06d44177c7b9405016de92e28b
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) {
@@ -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('-', '_'),
@@ -136,6 +146,7 @@ module Jekyll
136
146
  def robots_for(item, page_config, config)
137
147
  explicit = page_config['robots'] || item.data['robots']
138
148
  return clean_text(explicit) if explicit && explicit != true
149
+ return 'noindex,follow' if other_version_hidden?(item.site, config)
139
150
 
140
151
  site_index = !config.is_a?(Hash) || config.fetch('index', true) != false
141
152
  noindex = page_config['noindex'] == true || item.data['noindex'] == true || !site_index
@@ -530,6 +541,14 @@ module Jekyll
530
541
  nil
531
542
  end
532
543
 
544
+ # Next and older versions repeat most of the stable pages, so search
545
+ # engines should index only the stable docs unless the site opts in.
546
+ def other_version_hidden?(site, config)
547
+ return false if Versions.stable?(site)
548
+
549
+ !(config.is_a?(Hash) && config['index_versions'] == true)
550
+ end
551
+
533
552
  def sitemap_enabled?(config)
534
553
  config.fetch('index', true) != false && config.fetch('sitemap', true) != false
535
554
  end
@@ -1,5 +1,5 @@
1
1
  module Jekyll
2
2
  module VitePressTheme
3
- VERSION = "1.11.1".freeze
3
+ VERSION = "1.12.1".freeze
4
4
  end
5
5
  end
@@ -0,0 +1,486 @@
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 when they list any page, which
300
+ # they only do when `seo.index_versions` lets those versions be indexed.
301
+ def list_sitemaps(versions)
302
+ robots = File.join(destination, 'robots.txt')
303
+ return unless File.file?(robots) && File.read(robots).match?(/^Sitemap:/)
304
+
305
+ lines = versions.filter_map do |version|
306
+ sitemap = File.join(version.output, 'sitemap.xml')
307
+ next unless File.file?(sitemap) && File.read(sitemap).include?('<loc>')
308
+
309
+ "Sitemap: #{@site_url}#{baseurl}#{version.path}sitemap.xml"
310
+ end
311
+ File.open(robots, 'a') { |file| lines.each { |line| file.puts(line) } } unless lines.empty?
312
+ end
313
+
314
+ def guard_destination!
315
+ protected = [docs, @root, Dir.home, '/'].compact.map { |path| File.expand_path(path) }
316
+ return unless protected.include?(destination)
317
+
318
+ raise Error, "Refusing to replace #{destination} with the built site; pass a separate --destination"
319
+ end
320
+
321
+ # -- Serving --------------------------------------------------------
322
+
323
+ def serve_single(host, port)
324
+ command = ['bundle', 'exec', 'jekyll', 'serve', '--source', docs, '--destination', destination,
325
+ '--baseurl', baseurl, '--host', host, '--port', port.to_s, *@jekyll_args]
326
+ run!(command, chdir: docs, env: { 'BUNDLE_GEMFILE' => gemfile })
327
+ end
328
+
329
+ def watch(version, work)
330
+ output = File.join(destination, version.path)
331
+ configs = config_files(docs) + [File.join(work, "#{version.id}.yml")]
332
+ command = ['bundle', 'exec', 'jekyll', 'build', '--watch', '--source', docs, '--destination', output,
333
+ '--baseurl', version_baseurl(version), '--config', configs.join(','), *@jekyll_args]
334
+ say("Rebuilding #{version.path} when #{docs} changes")
335
+ Process.spawn({ 'BUNDLE_GEMFILE' => gemfile }, *command, chdir: docs)
336
+ end
337
+
338
+ def serve_directory(host, port)
339
+ require 'webrick'
340
+ server = WEBrick::HTTPServer.new(BindAddress: host, Port: port, AccessLog: [],
341
+ Logger: WEBrick::Log.new(File::NULL))
342
+ server.mount(baseurl.empty? ? '/' : baseurl, WEBrick::HTTPServlet::FileHandler, destination)
343
+ %w[INT TERM].each { |signal| trap(signal) { server.shutdown } }
344
+ say("Serving http://#{host}:#{port}#{baseurl}/")
345
+ server.start
346
+ end
347
+
348
+ def stop(pid)
349
+ return unless pid
350
+
351
+ Process.kill('TERM', pid)
352
+ Process.wait(pid)
353
+ rescue Errno::ESRCH, Errno::ECHILD
354
+ nil
355
+ end
356
+
357
+ # -- Hooks ----------------------------------------------------------
358
+
359
+ def build_hooks(config)
360
+ value = config.dig('jekyll_vitepress', 'build')
361
+ value.is_a?(Hash) ? value : {}
362
+ end
363
+
364
+ def run_hook(name, version)
365
+ Array(hooks[name]).each do |command|
366
+ say("Running #{name} for #{version.id}: #{command}")
367
+ # Hooks get the environment from before `bundle exec`, so a hook
368
+ # can run the repository's own bundle without inheriting the docs one.
369
+ with_original_env { run!(['sh', '-c', command.to_s], chdir: docs, env: hook_env(version)) }
370
+ end
371
+ end
372
+
373
+ def hook_env(version)
374
+ {
375
+ 'VITEPRESS_DOCS' => docs,
376
+ 'VITEPRESS_SITE' => destination,
377
+ 'VITEPRESS_VERSION_ID' => version.id,
378
+ 'VITEPRESS_VERSION_KIND' => version.kind,
379
+ 'VITEPRESS_VERSION_REF' => version.tag || 'HEAD',
380
+ 'VITEPRESS_VERSION_SOURCE' => version.source,
381
+ 'VITEPRESS_VERSION_ROOT' => version.root,
382
+ 'VITEPRESS_VERSION_OUTPUT' => version.output,
383
+ 'VITEPRESS_VERSION_BASEURL' => version.path ? version_baseurl(version) : baseurl,
384
+ 'VITEPRESS_VERSION_URL' => version.path ? "#{@site_url}#{version_url(version)}" : "#{@site_url}#{baseurl}/"
385
+ }.transform_values(&:to_s)
386
+ end
387
+
388
+ # -- Helpers --------------------------------------------------------
389
+
390
+ def site_config
391
+ path = CONFIG_FILES.map { |name| File.join(docs, name) }.find { |candidate| File.file?(candidate) }
392
+ raise Error, "No _config.yml in #{docs}" unless path
393
+ return {} if path.end_with?('.toml')
394
+
395
+ YAML.safe_load_file(path, permitted_classes: [Date, Time], aliases: true) || {}
396
+ end
397
+
398
+ def config_files(source)
399
+ CONFIG_FILES.map { |name| File.join(source, name) }.select { |path| File.file?(path) }
400
+ end
401
+
402
+ def gemfile
403
+ ENV['BUNDLE_GEMFILE'] || File.join(docs, 'Gemfile')
404
+ end
405
+
406
+ def with_original_env(&)
407
+ defined?(Bundler) ? Bundler.with_original_env(&) : yield
408
+ end
409
+
410
+ def remove_worktree(version)
411
+ return unless version.tag && version.root && File.directory?(version.root)
412
+
413
+ git(@root, 'worktree', 'remove', '--force', version.root, allow_failure: true)
414
+ end
415
+
416
+ def relative_docs_path
417
+ real_root = File.realpath(@root)
418
+ real_docs = File.realpath(docs)
419
+ real_docs == real_root ? '' : real_docs.delete_prefix("#{real_root}/")
420
+ end
421
+
422
+ def display_docs_path
423
+ @docs_path.empty? ? 'the repository root' : @docs_path
424
+ end
425
+
426
+ def branch_name
427
+ @branch_name ||= begin
428
+ name = git(@root, 'rev-parse', '--abbrev-ref', 'HEAD', allow_failure: true).to_s.strip
429
+ name = ENV['GITHUB_REF_NAME'].to_s if (name.empty? || name == 'HEAD') && ENV['GITHUB_REF_TYPE'] == 'branch'
430
+ name.empty? || name == 'HEAD' ? 'main' : name
431
+ end
432
+ end
433
+
434
+ def version_baseurl(version)
435
+ "#{baseurl}#{version.path.chomp('/')}"
436
+ end
437
+
438
+ def version_url(version)
439
+ "#{baseurl}#{version.path}"
440
+ end
441
+
442
+ def title_for(template, version, default)
443
+ template ? template.to_s.gsub(':version', version) : default
444
+ end
445
+
446
+ def hash_setting(value)
447
+ value.is_a?(Hash) ? value : {}
448
+ end
449
+
450
+ def normalize_path(value)
451
+ path = "/#{value.to_s.strip.delete_prefix('/')}"
452
+ path.end_with?('/') ? path : "#{path}/"
453
+ end
454
+
455
+ def normalize_baseurl(value)
456
+ value = value.to_s.strip
457
+ return '' if value.empty? || value == '/'
458
+
459
+ "/#{value.delete_prefix('/')}".sub(%r{/+\z}, '')
460
+ end
461
+
462
+ def warn_single(reason)
463
+ say("Building one version of the docs: #{reason}.")
464
+ nil
465
+ end
466
+
467
+ def say(message)
468
+ @out.puts("jekyll-vitepress: #{message}")
469
+ nil
470
+ end
471
+
472
+ def git(dir, *args, allow_failure: false)
473
+ output, status = Open3.capture2e('git', '-C', dir, *args)
474
+ return output if status.success?
475
+ return nil if allow_failure
476
+
477
+ raise Error, "git #{args.join(' ')} failed:\n#{output}"
478
+ end
479
+
480
+ def run!(command, chdir:, env: {})
481
+ success = system(env, *command, chdir: chdir)
482
+ raise Error, "#{command.first(4).join(' ')} … failed" unless success
483
+ end
484
+ end
485
+ end
486
+ 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.1
4
+ version: 1.12.1
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