jekyll-before-after 0.1.0 → 1.1.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: 8a21883c118e8086f562f69af0804ec131bf49ff1166485abe8e1f4b23c657e0
4
- data.tar.gz: 724bb4a84e30680bd90f347a1c6ce4596790d49bf113bc5243dc5376976903b7
3
+ metadata.gz: c42a5cb516fe5ac8d372d66c9119d622a3d7d52125082d784f588de665ecd290
4
+ data.tar.gz: 33620faaa38df743c8048fc8acedd86257ae30c1cb63ea1d9481d1259a2752f8
5
5
  SHA512:
6
- metadata.gz: ee01f6091029ec8d399a8331babc95b098135433ea150ebfae8cd7b5c77fc285e4cc6f03716e28d6d21ccf5947285c5473fab2878d102241b8315ecc2fb134fd
7
- data.tar.gz: 33bae04da7fe2bcd3ecb8762a75ade05ee4d32e885f99630b06853328bd7f418b241ac1eb461b1383f4ca915f3a91b16dd32d693ee447d595fb56696124f2c16
6
+ metadata.gz: cb70b8f431611814abd39a4aae1d33730e2fcee94049110349d448dc9c7b509ed16485a4204db0f78912646e2b0e70b8f23c1e960cc62546d1b940c88a391da3
7
+ data.tar.gz: 0bdd8c56827dbecd6b5040a9cb70701755e324a406dc146bc0dbbdf5c7f42487d797e7d513a3bf35bd7e237f9aa760b82c3f151aa0155f73cbcaa74c1a224560
data/CHANGELOG.md CHANGED
@@ -3,6 +3,60 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  This project adheres to [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
5
5
 
6
+ ## [1.1.0] - 2026-11-28
7
+
8
+ ### Fixed
9
+ - Pages with only vertical sliders now get the component script and stylesheet. The injector matched the exact string `<img-comparison-slider>` and missed `<img-comparison-slider direction="vertical">`.
10
+ - Attribute values are HTML-escaped. Before, a value like `before='/a" onerror="alert(1)'` could break out of the `src` attribute.
11
+ - Liquid variables now resolve (`before=page.before_image`, `before={{ x }}`). Before, `{{ x }}` rendered as `src="{{"`.
12
+ - Site-relative paths now get the site `baseurl`, like the `relative_url` filter. Full URLs are untouched.
13
+ - A missing or empty `before` or `after` logs a warning naming the page and renders nothing, instead of rendering an empty `src`. An invalid `start` logs a warning and uses the default position. Neither stops the build.
14
+ - The 1.0.0 changelog claim of "better accessibility" and the README's "fully accessible" wording overstated the component. See Added.
15
+
16
+ ### Added
17
+ - `alt_before` and `alt_after` (defaults `Before` and `After`), `width`, `height`, `loading` (default `lazy`), `start` (maps to the component's `value`) and `aria_label` options.
18
+ - `role="slider"`, `aria-valuemin`, `aria-valuemax`, `aria-valuenow` and `aria-orientation` on the slider, with `aria-valuenow` kept in step by a small script that listens for the component's `slide` event. The script is added once per page. It has not been tested in a browser or with a screen reader.
19
+ - `before_after:` settings in `_config.yml`: `inject`, `script_url`, `style_url`, `script_integrity`, `style_integrity`, `aria_sync`.
20
+ - Test suite for the current implementation, a `Rakefile` and a GitHub Actions workflow (Ruby 3.1 to 3.3).
21
+
22
+ ### Changed
23
+ - The component is pinned to img-comparison-slider 7.8.2 (was the floating `@7`) and loaded with `integrity` and `crossorigin="anonymous"`. Version 8.x uses the same markup, but 7.8.2 was kept because it hasn't been tried in a browser here.
24
+ - Images now carry `loading="lazy"` by default. Pass `loading=eager` for images above the fold.
25
+ - Minimum Ruby is 3.0 (was 2.7).
26
+ - README and gemspec no longer say the plugin has no external dependencies. It loads a third-party component from a CDN unless you self-host.
27
+
28
+ ### Removed
29
+ - `BeforeAfterGenerator` and the `site.data['before_after_css']` it set. Nothing used it, and it styled the removed 0.1.0 classes.
30
+ - `Gemfile.lock` from version control, and the nonexistent `_before-after.scss` from the gemspec file list.
31
+
32
+ ## [1.0.0] - 2026-08-29
33
+
34
+ ### Changed
35
+ - **MAJOR: Refactored to use [img-comparison-slider](https://github.com/sneas/img-comparison-slider) web component**
36
+ - Replaced custom JavaScript implementation with proven, battle-tested web component
37
+ - Dramatically simplified codebase (no custom JS initialization needed)
38
+ - Improved performance and reliability
39
+ - Better accessibility with native web component semantics
40
+
41
+ ### Added
42
+ - `orientation="vertical"` attribute for vertical comparisons
43
+ - Automatic CDN injection of img-comparison-slider library (no manual setup required)
44
+ - Full CSS custom property theming support via img-comparison-slider
45
+
46
+ ### Removed
47
+ - Custom JavaScript slider implementation
48
+ - `_before-after.scss` (styling now via CSS custom properties)
49
+ - Configurable start position, overlay labels, srcset attributes (use CSS for customization)
50
+ - ResizeObserver logic (handled by web component)
51
+
52
+ ### Migration Guide
53
+ If upgrading from 0.1.0:
54
+ - `before`, `after` and `orientation=vertical` keep working. These options were removed and are now ignored: `start`, `before_label`, `after_label`, `srcset_before`, `srcset_after` and `sizes` (`start` returned in 1.1.0).
55
+ - `orientation=vertical` now sets `direction="vertical"` on the component. Overlay labels are gone, so any `before_label` and `after_label` text no longer shows.
56
+ - `alt_before` and `alt_after` were ignored in 1.0.0 (alt text was always "Before" and "After"). Fixed in 1.1.0.
57
+ - The `.before-after` classes and `--ba-*` custom properties no longer exist. Style the component with its own properties (`--divider-width`, `--handle-width` and so on, see README).
58
+ - The page now loads a script and stylesheet from unpkg.com, so a strict Content Security Policy needs to allow that host.
59
+
6
60
  ## [0.1.0] - 2026-08-22
7
61
 
8
62
  ### Added
data/CONTRIBUTING.md CHANGED
@@ -8,7 +8,7 @@ Bug reports and pull requests are welcome on GitHub at https://github.com/jchanc
8
8
  git clone https://github.com/jchance/jekyll-before-after.git
9
9
  cd jekyll-before-after
10
10
  bundle install
11
- bundle exec ruby -Ilib:test test/test_before_after_tag.rb
11
+ bundle exec rake
12
12
  ```
13
13
 
14
14
  ## Pull Requests
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # jekyll-before-after
2
2
 
3
- A Jekyll plugin providing a `{% before_after %}` Liquid tag for rendering a polished, accessible drag-to-reveal image comparison slider. Supports horizontal and vertical orientations, overlay labels, responsive images, keyboard navigation, and full CSS custom property theming. Pure vanilla JS — no external dependencies, GitHub Pages compatible.
3
+ A Jekyll plugin that adds a `{% before_after %}` Liquid tag for drag-to-reveal image comparisons. It renders the [img-comparison-slider](https://github.com/sneas/img-comparison-slider) web component (pinned to version 7.8.2) and adds its script and stylesheet to any page that uses a slider. The component is loaded from the unpkg CDN with Subresource Integrity, or from your own files if you self-host (see [Configuration](#configuration)). The plugin works on GitHub Pages only when the site is built by a GitHub Action, since GitHub's own builder doesn't run custom plugins.
4
4
 
5
5
  ## Installation
6
6
 
@@ -17,117 +17,124 @@ plugins:
17
17
  - jekyll-before-after
18
18
  ```
19
19
 
20
- Copy `_before-after.scss` to your site's CSS directory and import it.
21
-
22
20
  Run `bundle install`.
23
21
 
24
22
  ## Usage
25
23
 
26
24
  ```liquid
27
25
  {% before_after
28
- before="/images/main-street-2018.jpg"
29
- after="/images/main-street-2024.jpg"
30
- before_label="2018"
31
- after_label="2024"
26
+ before="/images/before.jpg"
27
+ after="/images/after.jpg"
32
28
  %}
33
29
  ```
34
30
 
35
- ### All options
31
+ ### Options
36
32
 
37
33
  | Option | Default | Description |
38
34
  |--------|---------|-------------|
39
- | `before` | _(required)_ | Path to the "before" image |
40
- | `after` | _(required)_ | Path to the "after" image |
41
- | `before_label` | `"Before"` | Label overlaid on the before side |
42
- | `after_label` | `"After"` | Label overlaid on the after side |
43
- | `start` | `50` | Initial slider position (0–100) |
35
+ | `before` | _(required)_ | Image shown on the left (horizontal) or top (vertical) |
36
+ | `after` | _(required)_ | Image shown on the right (horizontal) or bottom (vertical) |
44
37
  | `orientation` | `horizontal` | `horizontal` or `vertical` |
45
- | `alt_before` | `""` | Alt text for the before image |
46
- | `alt_after` | `""` | Alt text for the after image |
47
- | `srcset_before` | `""` | `srcset` value for responsive before image |
48
- | `srcset_after` | `""` | `srcset` value for responsive after image |
49
- | `sizes` | `"(max-width: 768px) 100vw, 100vw"` | `sizes` attribute when using srcset |
38
+ | `start` | `50` | Starting divider position, 0 to 100 |
39
+ | `alt_before` | `Before` | Alt text for the first image (use `""` for a decorative image) |
40
+ | `alt_after` | `After` | Alt text for the second image |
41
+ | `aria_label` | `Before and after image comparison` | Accessible name for the slider |
42
+ | `width`, `height` | _(none)_ | Added to both images, to reserve space and avoid layout shift |
43
+ | `loading` | `lazy` | `lazy` or `eager` |
50
44
 
51
- ### Responsive images
45
+ Quoted values (`before="/a.jpg"`) are literal. Unquoted values are Liquid variables, so `before=page.before_image` and `before={{ page.before_image }}` both work. Unquoted words such as `orientation=vertical` also work. Every value is HTML-escaped. Paths that start with `/` get your site's `baseurl` added, the same way the `relative_url` filter does. Full URLs are left alone.
52
46
 
53
- Pass `srcset_before` and `srcset_after` to render a `<picture>` element:
47
+ If `before` or `after` is missing or empty, the tag logs a warning that names the page and renders nothing. The build carries on.
48
+
49
+ ### Examples
50
+
51
+ #### Horizontal comparison
54
52
 
55
53
  ```liquid
56
54
  {% before_after
57
- before="/images/street-before.jpg"
58
- after="/images/street-after.jpg"
59
- srcset_before="/images/street-before-480.jpg 480w, /images/street-before-960.jpg 960w"
60
- srcset_after="/images/street-after-480.jpg 480w, /images/street-after-960.jpg 960w"
61
- sizes="(max-width: 600px) 100vw, 80vw"
55
+ before="/images/main-street-2018.jpg"
56
+ after="/images/main-street-2024.jpg"
62
57
  %}
63
58
  ```
64
59
 
65
- ### Vertical orientation
60
+ #### Vertical comparison
66
61
 
67
62
  ```liquid
68
63
  {% before_after
69
64
  before="/images/building-2015.jpg"
70
65
  after="/images/building-2025.jpg"
71
- orientation=vertical
72
- before_label="2015"
73
- after_label="2025"
66
+ orientation="vertical"
74
67
  %}
75
68
  ```
76
69
 
77
- ### Multiple sliders
70
+ #### Multiple sliders
71
+
72
+ You can put several sliders on one page. The script and stylesheet are added once.
73
+
74
+ ## Styling
75
+
76
+ All visual properties are controlled via CSS custom properties. Target the `img-comparison-slider` element:
77
+
78
+ ```css
79
+ img-comparison-slider {
80
+ --divider-width: 4px;
81
+ --divider-color: #fff;
82
+ --handle-width: 60px;
83
+ --handle-height: 60px;
84
+ --handle-opacity: 0.3;
85
+ --handle-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
86
+ }
87
+ ```
78
88
 
79
- Multiple sliders on the same page are fully supported. The JavaScript block is emitted only once per page regardless of how many sliders you include.
89
+ See [img-comparison-slider docs](https://img-comparison-slider.sneas.io/) for all available CSS custom properties.
80
90
 
81
91
  ## Configuration
82
92
 
83
- Set site-wide defaults in `_config.yml`:
93
+ All settings are optional. Add them under `before_after:` in `_config.yml`:
84
94
 
85
95
  ```yaml
86
96
  before_after:
87
- start: 50
88
- orientation: horizontal
89
- before_label: "Before"
90
- after_label: "After"
97
+ inject: true # false: don't add the component script and stylesheet
98
+ script_url: https://unpkg.com/img-comparison-slider@7.8.2/dist/index.js
99
+ style_url: https://unpkg.com/img-comparison-slider@7.8.2/dist/styles.css
100
+ script_integrity: "" # sha384-... for your script_url
101
+ style_integrity: "" # sha384-... for your style_url
102
+ aria_sync: true # false: don't add the aria-valuenow script
91
103
  ```
92
104
 
93
- ## Styling
105
+ The built-in URLs come with `integrity` and `crossorigin="anonymous"`. If you set your own `script_url` or `style_url`, the plugin leaves integrity off unless you give it a matching hash. To self-host, copy `dist/index.js` and `dist/styles.css` from the npm package into your site and point the two URLs at them. To load everything yourself, set `inject: false` and include both files in your layout.
94
106
 
95
- Copy `_before-after.scss` to your project and import it. All visual properties are controlled via CSS custom properties:
96
-
97
- | Variable | Default | Description |
98
- |----------|---------|-------------|
99
- | `--ba-handle-color` | `#fff` | Handle line and knob color |
100
- | `--ba-knob-size` | `2.75rem` | Drag knob diameter |
101
- | `--ba-knob-icon-color` | `#333` | Arrow icon color inside knob |
102
- | `--ba-line-width` | `2px` | Divider line thickness |
103
- | `--ba-label-bg` | `rgba(0,0,0,0.55)` | Label background |
104
- | `--ba-label-color` | `#fff` | Label text color |
105
- | `--ba-label-radius` | `3px` | Label border radius |
106
- | `--ba-radius` | `4px` | Container border radius |
107
- | `--ba-focus-ring` | `rgba(255,255,255,0.8)` | Keyboard focus ring color |
108
-
109
- ### Example override
110
-
111
- ```scss
112
- .before-after {
113
- --ba-handle-color: #e67e22;
114
- --ba-knob-size: 3rem;
115
- --ba-label-bg: rgba(0, 0, 0, 0.75);
116
- }
117
- ```
107
+ ## Accessibility
108
+
109
+ The component makes the slider focusable and handles the left and right arrow keys. It doesn't add any slider semantics, so the plugin does:
110
+
111
+ - `role="slider"`, `aria-valuemin="0"`, `aria-valuemax="100"` and `aria-orientation` on the element
112
+ - an accessible name from `aria_label`
113
+ - `aria-valuenow`, set from `start` in the HTML and kept in step with the divider by a small inline script that listens for the component's `slide` event
114
+ - alt text on both images from `alt_before` and `alt_after`
115
+
116
+ The component handles arrow keys in both orientations as left and right only, and it has no visible text labels. Write alt text that says what each image shows. If you set `inject: false` and `aria_sync: false`, `aria-valuenow` stays at the starting value. This hasn't been tested with a screen reader.
118
117
 
119
118
  ## Interaction
120
119
 
121
- - **Drag** the handle to reveal
122
- - **Click** anywhere on the image to jump the slider to that position
123
- - **Keyboard**: focus the handle and use arrow keys (5% steps; hold Shift for 1% steps)
124
- - **Touch** and stylus supported via Pointer Events API
120
+ - Drag the divider, or click anywhere on the image to jump there
121
+ - Focus the slider and use the arrow keys
122
+ - Touch and mouse are supported
123
+
124
+ The component also supports hover-to-slide (`hover`) and handle-only dragging (`handle`), and lets you replace the handle with a `slot="handle"` element. The plugin doesn't pass these through yet. Overlay labels and `srcset` aren't supported.
125
+
126
+ ## How it works
127
+
128
+ The tag renders an `<img-comparison-slider>` element with two images. After each page renders, the plugin looks for that element (with or without attributes) and adds the script, the stylesheet and the ARIA script to the `<head>` once.
125
129
 
126
130
  ## Requirements
127
131
 
128
132
  - Jekyll >= 3.9
129
- - Ruby >= 2.7
133
+ - Ruby >= 3.0
134
+ - Modern browser with Web Components support (all modern browsers)
130
135
 
131
136
  ## License
132
137
 
133
138
  MIT — see [LICENSE.txt](LICENSE.txt).
139
+
140
+ The plugin wraps [img-comparison-slider](https://github.com/sneas/img-comparison-slider) by sneas, also licensed under MIT.
@@ -2,18 +2,18 @@
2
2
 
3
3
  Gem::Specification.new do |spec|
4
4
  spec.name = "jekyll-before-after"
5
- spec.version = "0.1.0"
5
+ spec.version = "1.1.0"
6
6
  spec.authors = ["Jason Chance"]
7
7
  spec.email = ["jason@jasonchance.com"]
8
8
 
9
9
  spec.summary = "Jekyll plugin providing a before_after Liquid tag for drag-to-reveal image comparison sliders."
10
- spec.description = "A Jekyll plugin that provides a {% before_after %} Liquid tag for rendering a polished, accessible drag-to-reveal image comparison slider. Supports horizontal and vertical orientations, configurable start position, overlay labels, responsive images, keyboard navigation, and full CSS custom property theming. Pure vanilla JS, no external dependencies, GitHub Pages compatible."
10
+ spec.description = "A Jekyll plugin that provides a {% before_after %} Liquid tag for drag-to-reveal image comparisons, built on the img-comparison-slider web component (loaded from a CDN with Subresource Integrity, or self-hosted). Supports horizontal and vertical orientations, start position, alt text, ARIA slider attributes, and Liquid variables and baseurl in image paths."
11
11
  spec.homepage = "https://jasonchance.com/projects/jekyll-before-after/"
12
12
  spec.license = "MIT"
13
13
 
14
- spec.required_ruby_version = ">= 2.7"
14
+ spec.required_ruby_version = ">= 3.0"
15
15
 
16
- spec.files = Dir["lib/**/*", "*.md", "*.txt", "*.gemspec", "_before-after.scss"]
16
+ spec.files = Dir["lib/**/*", "*.md", "*.txt", "*.gemspec"]
17
17
  spec.require_paths = ["lib"]
18
18
 
19
19
  spec.add_runtime_dependency "jekyll", ">= 3.9", "< 5.0"
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi"
4
+
5
+ module Jekyll
6
+ module BeforeAfter
7
+ COMPONENT_VERSION = "7.8.2"
8
+ DEFAULT_SCRIPT_URL = "https://unpkg.com/img-comparison-slider@#{COMPONENT_VERSION}/dist/index.js"
9
+ DEFAULT_STYLE_URL = "https://unpkg.com/img-comparison-slider@#{COMPONENT_VERSION}/dist/styles.css"
10
+ # sha384 of the files at the URLs above (img-comparison-slider 7.8.2).
11
+ DEFAULT_SCRIPT_INTEGRITY = "sha384-c68xRjt7GB42rgPGgUu/Ks4w+AeRgR/cI9xt3K0YxBBt5yXJYE1VBq39ilNnpqEp"
12
+ DEFAULT_STYLE_INTEGRITY = "sha384-TYCxyqTqCrHZ0yHG2B7VENYnxnIBGWt8GHLLkGegAYCw+1UkvUd0YpsVPrt+8//z"
13
+ DEFAULT_ARIA_LABEL = "Before and after image comparison"
14
+
15
+ # Reads the optional `before_after:` block of _config.yml.
16
+ class Config
17
+ def initialize(site)
18
+ raw = site && site.config["before_after"]
19
+ @raw = raw.is_a?(Hash) ? raw : {}
20
+ end
21
+
22
+ # Add the stylesheet and component script to pages that use a slider.
23
+ def inject?
24
+ @raw["inject"] != false
25
+ end
26
+
27
+ # Add the small script that keeps aria-valuenow in step with the slider.
28
+ def aria_sync?
29
+ @raw["aria_sync"] != false
30
+ end
31
+
32
+ def script_url
33
+ @raw["script_url"] || DEFAULT_SCRIPT_URL
34
+ end
35
+
36
+ def style_url
37
+ @raw["style_url"] || DEFAULT_STYLE_URL
38
+ end
39
+
40
+ # The built-in hashes only describe the built-in files, so a custom URL
41
+ # gets an integrity value only if the site supplies one.
42
+ def script_integrity
43
+ @raw["script_integrity"] || (@raw["script_url"] ? nil : DEFAULT_SCRIPT_INTEGRITY)
44
+ end
45
+
46
+ def style_integrity
47
+ @raw["style_integrity"] || (@raw["style_url"] ? nil : DEFAULT_STYLE_INTEGRITY)
48
+ end
49
+ end
50
+
51
+ def self.escape(value)
52
+ CGI.escapeHTML(value.to_s)
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jekyll"
4
+ require_relative "before_after_config"
5
+
6
+ module Jekyll
7
+ # Adds the img-comparison-slider assets and the ARIA sync script to rendered
8
+ # pages that contain a slider.
9
+ class BeforeAfterScriptInjector
10
+ MARKER = "<!-- img-comparison-slider-injected -->"
11
+ # Matches the opening tag whatever its attributes (e.g. direction="vertical").
12
+ SLIDER_RE = %r{<img-comparison-slider[\s/>]}.freeze
13
+
14
+ # The component sets tabindex and arrow-key handling but no slider
15
+ # semantics. This mirrors its position into aria-valuenow. The component
16
+ # fires a non-bubbling "slide" event, so listen in the capture phase.
17
+ ARIA_SCRIPT = <<~JS
18
+ (function () {
19
+ var sel = 'img-comparison-slider';
20
+ function sync(el) {
21
+ var v = Number(el.value);
22
+ if (isFinite(v)) el.setAttribute('aria-valuenow', String(Math.round(v)));
23
+ }
24
+ document.addEventListener('slide', function (e) {
25
+ if (e.target && e.target.matches && e.target.matches(sel)) sync(e.target);
26
+ }, true);
27
+ function init() {
28
+ var ready = window.customElements ? customElements.whenDefined(sel) : Promise.resolve();
29
+ ready.then(function () {
30
+ Array.prototype.forEach.call(document.querySelectorAll(sel), sync);
31
+ });
32
+ }
33
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
34
+ else init();
35
+ })();
36
+ JS
37
+
38
+ def call(doc)
39
+ output = doc.output
40
+ return if output.nil? || !output.match?(SLIDER_RE)
41
+ return if output.include?(MARKER)
42
+
43
+ config = Jekyll::BeforeAfter::Config.new(doc.site)
44
+ html = build(config)
45
+ return if html.empty?
46
+
47
+ doc.output = output.sub("</head>") { "#{MARKER}\n#{html}</head>" } if output.include?("</head>")
48
+ end
49
+
50
+ private
51
+
52
+ def build(config)
53
+ html = +""
54
+ if config.inject?
55
+ html << "<script type=\"module\" src=\"#{esc(config.script_url)}\"#{sri(config.script_integrity)}></script>\n"
56
+ html << "<link rel=\"stylesheet\" href=\"#{esc(config.style_url)}\"#{sri(config.style_integrity)}>\n"
57
+ end
58
+ html << "<script>\n#{ARIA_SCRIPT}</script>\n" if config.aria_sync?
59
+ html
60
+ end
61
+
62
+ def sri(integrity)
63
+ return "" if integrity.nil? || integrity.to_s.empty?
64
+
65
+ " integrity=\"#{esc(integrity)}\" crossorigin=\"anonymous\""
66
+ end
67
+
68
+ def esc(value)
69
+ Jekyll::BeforeAfter.escape(value)
70
+ end
71
+ end
72
+
73
+ Jekyll::Hooks.register :pages, :post_render do |doc|
74
+ Jekyll::BeforeAfterScriptInjector.new.call(doc)
75
+ end
76
+
77
+ Jekyll::Hooks.register :documents, :post_render do |doc|
78
+ Jekyll::BeforeAfterScriptInjector.new.call(doc)
79
+ end
80
+ end
@@ -1,191 +1,147 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "jekyll"
4
+ require_relative "before_after_config"
4
5
 
5
6
  module Jekyll
6
- BEFORE_AFTER_ATTR_RE = /(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/
7
+ # key=value pairs: "double", 'single', {{ liquid }} or a bare word/variable.
8
+ BEFORE_AFTER_ATTR_RE = /([A-Za-z_]\w*)\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\{(.*?)\}\}|(\S+))/m.freeze
7
9
 
10
+ # Returns { "key" => [text, kind] } where kind is :literal (quoted) or
11
+ # :variable (bare or {{ }}, resolved against the Liquid context at render).
8
12
  def self.parse_ba_attrs(markup)
9
13
  attrs = {}
10
- markup.scan(BEFORE_AFTER_ATTR_RE) do |key, double, single, bare|
11
- attrs[key] = double || single || bare
14
+ markup.scan(BEFORE_AFTER_ATTR_RE) do |key, double, single, braces, bare|
15
+ attrs[key] =
16
+ if double || single
17
+ [double || single, :literal]
18
+ else
19
+ [(braces || bare).strip, :variable]
20
+ end
12
21
  end
13
22
  attrs
14
23
  end
15
24
 
16
- # Dedup script: only emit the JS block once per page
17
- BEFORE_AFTER_SCRIPT_FLAG = :before_after_script_emitted
18
-
19
25
  class BeforeAfterTag < Liquid::Tag
20
- def initialize(tag_name, markup, tokens)
26
+ # Options whose bare values may be plain words (orientation=vertical)
27
+ # rather than variable names.
28
+ WORD_OPTIONS = %w[orientation loading start width height].freeze
29
+ ABSOLUTE_URL_RE = %r{\A(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//)}.freeze
30
+
31
+ def initialize(tag_name, markup, parse_context)
21
32
  super
33
+ @parse_context = parse_context
22
34
  @attributes = Jekyll.parse_ba_attrs(markup)
23
35
  end
24
36
 
25
37
  def render(context)
26
- config = context.registers[:site]&.config&.dig("before_after") || {}
27
- before = @attributes["before"] || ""
28
- after = @attributes["after"] || ""
29
- b_label = @attributes["before_label"] || config["before_label"] || "Before"
30
- a_label = @attributes["after_label"] || config["after_label"] || "After"
31
- start = (@attributes["start"] || config["start"] || 50).to_i
32
- orient = @attributes["orientation"] || config["orientation"] || "horizontal"
33
- alt_b = @attributes["alt_before"] || ""
34
- alt_a = @attributes["alt_after"] || ""
35
- srcset_b = @attributes["srcset_before"] || ""
36
- srcset_a = @attributes["srcset_after"] || ""
37
- sizes = @attributes["sizes"] || "(max-width: 768px) 100vw, 100vw"
38
-
39
- before_img = build_img(before, alt_b, srcset_b, sizes)
40
- after_img = build_img(after, alt_a, srcset_a, sizes)
41
-
42
- script_block = emit_script(context)
38
+ before = image_url(context, "before")
39
+ after = image_url(context, "after")
40
+ # Without both images there is nothing to compare. Warn and print
41
+ # nothing, so a stray or half-written tag doesn't stop the build.
42
+ return "" if before.nil? || after.nil?
43
+
44
+ vertical = value(context, "orientation") == "vertical"
45
+ start = start_position(context)
46
+ esc = Jekyll::BeforeAfter.method(:escape)
47
+
48
+ attrs = []
49
+ attrs << 'direction="vertical"' if vertical
50
+ attrs << %(value="#{esc.call(start)}") if start
51
+ attrs << 'role="slider"'
52
+ attrs << %(aria-label="#{esc.call(value(context, "aria_label") || Jekyll::BeforeAfter::DEFAULT_ARIA_LABEL)}")
53
+ attrs << 'aria-valuemin="0"' << 'aria-valuemax="100"'
54
+ attrs << %(aria-valuenow="#{esc.call(start || 50)}")
55
+ attrs << %(aria-orientation="#{vertical ? "vertical" : "horizontal"}")
56
+
57
+ size = ""
58
+ %w[width height].each do |dim|
59
+ v = value(context, dim)
60
+ size += %( #{dim}="#{esc.call(v)}") unless v.nil? || v.empty?
61
+ end
62
+ loading = value(context, "loading")
63
+ loading = "lazy" if loading.nil? || loading.empty?
43
64
 
44
65
  <<~HTML
45
- <div class="before-after" data-orientation="#{orient}" data-start="#{start}">
46
- <div class="before-after__before">
47
- #{before_img}
48
- #{b_label.empty? ? "" : %(<span class="before-after__label before-after__label--before">#{b_label}</span>)}
49
- </div>
50
- <div class="before-after__after">
51
- #{after_img}
52
- #{a_label.empty? ? "" : %(<span class="before-after__label before-after__label--after">#{a_label}</span>)}
53
- </div>
54
- <div class="before-after__handle"
55
- role="slider"
56
- aria-label="Image comparison slider"
57
- aria-valuenow="#{start}"
58
- aria-valuemin="0"
59
- aria-valuemax="100"
60
- tabindex="0">
61
- <div class="before-after__handle-line"></div>
62
- <div class="before-after__handle-knob">
63
- <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
64
- <path d="M8 5l-5 7 5 7M16 5l5 7-5 7" stroke="currentColor" stroke-width="2"
65
- stroke-linecap="round" stroke-linejoin="round" fill="none"/>
66
- </svg>
67
- </div>
68
- </div>
69
- </div>
70
- #{script_block}
66
+ <img-comparison-slider #{attrs.join(" ")}>
67
+ <img slot="first" src="#{esc.call(before)}" alt="#{esc.call(alt(context, "alt_before", "Before"))}"#{size} loading="#{esc.call(loading)}">
68
+ <img slot="second" src="#{esc.call(after)}" alt="#{esc.call(alt(context, "alt_after", "After"))}"#{size} loading="#{esc.call(loading)}">
69
+ </img-comparison-slider>
71
70
  HTML
72
71
  end
73
72
 
74
73
  private
75
74
 
76
- def build_img(src, alt, srcset, sizes)
77
- if srcset && !srcset.empty?
78
- %(<picture><source srcset="#{srcset}" sizes="#{sizes}"><img src="#{src}" alt="#{alt}" loading="lazy" draggable="false"></picture>)
79
- else
80
- %(<img src="#{src}" alt="#{alt}" loading="lazy" draggable="false">)
75
+ def start_given?
76
+ @attributes.key?("start")
77
+ end
78
+
79
+ def start_position(context)
80
+ return nil unless start_given?
81
+
82
+ raw = value(context, "start").to_s.strip
83
+ number = Float(raw, exception: false)
84
+ unless number && number >= 0 && number <= 100
85
+ warn(context, "`start` must be a number from 0 to 100, got #{raw.inspect}; using the default position")
86
+ return nil
87
+ end
88
+
89
+ number == number.to_i ? number.to_i : number
90
+ end
91
+
92
+ # Logs a warning that names the page the tag is on.
93
+ def warn(context, message)
94
+ page = context.registers[:page]
95
+ path = page && page["path"]
96
+ Jekyll.logger.warn "before_after:", [path, message].compact.join(": ")
97
+ end
98
+
99
+ def alt(context, key, default)
100
+ v = value(context, key)
101
+ v.nil? ? default : v
102
+ end
103
+
104
+ # Resolved string for an option, or nil if it was not given (or unset).
105
+ def value(context, key)
106
+ text, kind = @attributes[key]
107
+ return nil if text.nil?
108
+ return text if kind == :literal
109
+
110
+ resolved = Liquid::Variable.new(text, @parse_context).render(context)
111
+ resolved = resolved.to_s unless resolved.nil?
112
+ if (resolved.nil? || resolved.empty?) && WORD_OPTIONS.include?(key) && text.match?(/\A\w+\z/)
113
+ return text
114
+ end
115
+
116
+ resolved
117
+ end
118
+
119
+ def image_url(context, key)
120
+ raw = value(context, key).to_s.strip
121
+ if raw.empty?
122
+ given = @attributes[key]
123
+ reason = given.nil? ? "is missing" : "is empty (#{given[0].inspect} resolved to nothing)"
124
+ warn(context, "`#{key}` #{reason}; skipping this slider " \
125
+ '(e.g. {% before_after before="/a.jpg" after="/b.jpg" %})')
126
+ return nil
81
127
  end
128
+
129
+ return raw unless raw.start_with?("/") && !raw.start_with?("//")
130
+
131
+ site = context.registers[:site]
132
+ return raw unless site
133
+
134
+ Jekyll::BeforeAfterTag::Url.new(context).relative_url(raw)
82
135
  end
83
136
 
84
- def emit_script(context)
85
- return "" if context.registers[BEFORE_AFTER_SCRIPT_FLAG]
86
- context.registers[BEFORE_AFTER_SCRIPT_FLAG] = true
87
- <<~JS
88
- <script>
89
- (function() {
90
- function initSlider(el) {
91
- var orientation = el.dataset.orientation === "vertical" ? "vertical" : "horizontal";
92
- var handle = el.querySelector(".before-after__handle");
93
- var beforePane = el.querySelector(".before-after__before");
94
- var start = parseFloat(el.dataset.start) || 50;
95
- var dragging = false;
96
-
97
- function setPosition(pct) {
98
- pct = Math.min(100, Math.max(0, pct));
99
- if (orientation === "vertical") {
100
- beforePane.style.clipPath = "inset(0 0 " + (100 - pct) + "% 0)";
101
- handle.style.top = pct + "%";
102
- handle.style.left = "";
103
- } else {
104
- beforePane.style.clipPath = "inset(0 " + (100 - pct) + "% 0 0)";
105
- handle.style.left = pct + "%";
106
- handle.style.top = "";
107
- }
108
- handle.setAttribute("aria-valuenow", Math.round(pct));
109
- }
110
-
111
- function pctFromEvent(e) {
112
- var rect = el.getBoundingClientRect();
113
- if (orientation === "vertical") {
114
- return ((e.clientY - rect.top) / rect.height) * 100;
115
- } else {
116
- return ((e.clientX - rect.left) / rect.width) * 100;
117
- }
118
- }
119
-
120
- handle.addEventListener("pointerdown", function(e) {
121
- dragging = true;
122
- handle.setPointerCapture(e.pointerId);
123
- el.classList.add("before-after--dragging");
124
- e.preventDefault();
125
- });
126
-
127
- handle.addEventListener("pointermove", function(e) {
128
- if (!dragging) return;
129
- setPosition(pctFromEvent(e));
130
- });
131
-
132
- handle.addEventListener("pointerup", function() {
133
- dragging = false;
134
- el.classList.remove("before-after--dragging");
135
- });
136
-
137
- handle.addEventListener("pointercancel", function() {
138
- dragging = false;
139
- el.classList.remove("before-after--dragging");
140
- });
141
-
142
- // Keyboard support
143
- handle.addEventListener("keydown", function(e) {
144
- var step = e.shiftKey ? 1 : 5;
145
- var cur = parseFloat(handle.getAttribute("aria-valuenow")) || 50;
146
- if (e.key === "ArrowRight" || e.key === "ArrowDown") {
147
- setPosition(cur + step);
148
- e.preventDefault();
149
- } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
150
- setPosition(cur - step);
151
- e.preventDefault();
152
- }
153
- });
154
-
155
- // Click anywhere on container to jump
156
- el.addEventListener("pointerdown", function(e) {
157
- if (e.target === handle || handle.contains(e.target)) return;
158
- setPosition(pctFromEvent(e));
159
- });
160
-
161
- // Recalculate on resize
162
- if (window.ResizeObserver) {
163
- new ResizeObserver(function() {
164
- var cur = parseFloat(handle.getAttribute("aria-valuenow")) || start;
165
- setPosition(cur);
166
- }).observe(el);
167
- }
168
-
169
- setPosition(start);
170
- }
171
-
172
- function init() {
173
- document.querySelectorAll(".before-after").forEach(function(el) {
174
- if (!el.dataset.baInit) {
175
- el.dataset.baInit = "1";
176
- initSlider(el);
177
- }
178
- });
179
- }
180
-
181
- if (document.readyState === "loading") {
182
- document.addEventListener("DOMContentLoaded", init);
183
- } else {
184
- init();
185
- }
186
- })();
187
- </script>
188
- JS
137
+ # Reuses Jekyll's own relative_url filter so baseurl handling matches
138
+ # the rest of the site.
139
+ class Url
140
+ include Jekyll::Filters::URLFilters
141
+
142
+ def initialize(context)
143
+ @context = context
144
+ end
189
145
  end
190
146
  end
191
147
  end
@@ -1,3 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "jekyll/before_after_config"
3
4
  require "jekyll/before_after_tag"
5
+ require "jekyll/before_after_injector"
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-before-after
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Chance
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-08-22 00:00:00.000000000 Z
10
+ date: 2026-11-29 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: jekyll
@@ -29,11 +29,11 @@ dependencies:
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
31
  version: '5.0'
32
- description: A Jekyll plugin that provides a {% before_after %} Liquid tag for rendering
33
- a polished, accessible drag-to-reveal image comparison slider. Supports horizontal
34
- and vertical orientations, configurable start position, overlay labels, responsive
35
- images, keyboard navigation, and full CSS custom property theming. Pure vanilla
36
- JS, no external dependencies, GitHub Pages compatible.
32
+ description: A Jekyll plugin that provides a {% before_after %} Liquid tag for drag-to-reveal
33
+ image comparisons, built on the img-comparison-slider web component (loaded from
34
+ a CDN with Subresource Integrity, or self-hosted). Supports horizontal and vertical
35
+ orientations, start position, alt text, ARIA slider attributes, and Liquid variables
36
+ and baseurl in image paths.
37
37
  email:
38
38
  - jason@jasonchance.com
39
39
  executables: []
@@ -44,9 +44,10 @@ files:
44
44
  - CONTRIBUTING.md
45
45
  - LICENSE.txt
46
46
  - README.md
47
- - _before-after.scss
48
47
  - jekyll-before-after.gemspec
49
48
  - lib/jekyll-before-after.rb
49
+ - lib/jekyll/before_after_config.rb
50
+ - lib/jekyll/before_after_injector.rb
50
51
  - lib/jekyll/before_after_tag.rb
51
52
  homepage: https://jasonchance.com/projects/jekyll-before-after/
52
53
  licenses:
@@ -59,7 +60,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
59
60
  requirements:
60
61
  - - ">="
61
62
  - !ruby/object:Gem::Version
62
- version: '2.7'
63
+ version: '3.0'
63
64
  required_rubygems_version: !ruby/object:Gem::Requirement
64
65
  requirements:
65
66
  - - ">="
data/_before-after.scss DELETED
@@ -1,144 +0,0 @@
1
- // jekyll-before-after — copy to your site's CSS/SCSS directory and @import or @use it.
2
-
3
- .before-after {
4
- position: relative;
5
- overflow: hidden;
6
- cursor: col-resize;
7
- user-select: none;
8
- touch-action: none;
9
- border-radius: var(--ba-radius, 4px);
10
- background: var(--ba-bg, #000);
11
-
12
- &[data-orientation="vertical"] {
13
- cursor: row-resize;
14
- }
15
-
16
- &--dragging {
17
- cursor: grabbing;
18
- }
19
- }
20
-
21
- // After pane: normal flow — its img drives the container height
22
- .before-after__after {
23
- position: relative;
24
- display: block;
25
-
26
- img,
27
- picture img {
28
- display: block;
29
- width: 100%;
30
- height: auto;
31
- pointer-events: none;
32
- }
33
- }
34
-
35
- // Before pane: absolutely stacked on top, clipped by JS
36
- .before-after__before {
37
- position: absolute;
38
- inset: 0;
39
- z-index: 1;
40
- clip-path: inset(0 50% 0 0); // overridden by JS on init
41
-
42
- img,
43
- picture img {
44
- display: block;
45
- width: 100%;
46
- height: 100%;
47
- object-fit: cover;
48
- pointer-events: none;
49
- }
50
- }
51
-
52
- // Labels
53
- .before-after__label {
54
- position: absolute;
55
- bottom: 0.75rem;
56
- z-index: 2;
57
- padding: 0.25rem 0.6rem;
58
- font-size: 0.75rem;
59
- font-weight: 600;
60
- letter-spacing: 0.04em;
61
- text-transform: uppercase;
62
- background: var(--ba-label-bg, rgba(0, 0, 0, 0.55));
63
- color: var(--ba-label-color, #fff);
64
- border-radius: var(--ba-label-radius, 3px);
65
- pointer-events: none;
66
-
67
- &--before {
68
- left: 0.75rem;
69
- }
70
-
71
- &--after {
72
- right: 0.75rem;
73
- }
74
- }
75
-
76
- // Handle
77
- .before-after__handle {
78
- position: absolute;
79
- top: 50%;
80
- left: 50%; // overridden by JS
81
- transform: translate(-50%, -50%);
82
- z-index: 10;
83
- display: flex;
84
- align-items: center;
85
- justify-content: center;
86
- outline: none;
87
-
88
- &:focus-visible .before-after__handle-knob {
89
- box-shadow: 0 0 0 3px var(--ba-focus-ring, rgba(255, 255, 255, 0.8));
90
- }
91
- }
92
-
93
- .before-after__handle-line {
94
- position: absolute;
95
- background: var(--ba-handle-color, #fff);
96
- opacity: 0.85;
97
-
98
- .before-after:not([data-orientation="vertical"]) & {
99
- width: var(--ba-line-width, 2px);
100
- top: -200%;
101
- bottom: -200%;
102
- left: 50%;
103
- transform: translateX(-50%);
104
- }
105
-
106
- [data-orientation="vertical"] & {
107
- height: var(--ba-line-width, 2px);
108
- left: -200%;
109
- right: -200%;
110
- top: 50%;
111
- transform: translateY(-50%);
112
- }
113
- }
114
-
115
- .before-after__handle-knob {
116
- position: relative;
117
- z-index: 1;
118
- width: var(--ba-knob-size, 2.75rem);
119
- height: var(--ba-knob-size, 2.75rem);
120
- border-radius: 50%;
121
- background: var(--ba-handle-color, #fff);
122
- color: var(--ba-knob-icon-color, #333);
123
- display: flex;
124
- align-items: center;
125
- justify-content: center;
126
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
127
- transition: transform 0.15s ease, box-shadow 0.15s ease;
128
- cursor: grab;
129
-
130
- svg {
131
- width: 1.1rem;
132
- height: 1.1rem;
133
- }
134
-
135
- .before-after--dragging & {
136
- cursor: grabbing;
137
- transform: scale(1.12);
138
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.45);
139
- }
140
-
141
- [data-orientation="vertical"] & svg {
142
- transform: rotate(90deg);
143
- }
144
- }