jekyll-koziolekweb-tags 0.4.4 → 0.5.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: 2da371200ebcd6314f4a80855978f32793599b544f34101df51aedd00f4ce216
4
- data.tar.gz: a197e61ede1294520c1405e80844980fbb26b09db113c7588bda86cefe693fe2
3
+ metadata.gz: e0040c977984048a2dda4cd464f8af804a3d61de53c5a7438764bb499f7a8ead
4
+ data.tar.gz: 7371e6fbb25c5bb3a724592e2ed43918faa68aa286ecda5db1affcae615f0369
5
5
  SHA512:
6
- metadata.gz: 1eca45c74f60667e1599e86e175f56ac27d5b79be0225dbacf1c041d20e9d0e3a3051434f34b05846a30b49aa9891c1cb2cfd65666dcea4cda63a0b8d09d7b97
7
- data.tar.gz: bb3c317ddd89212d70ffc40376119d9d366a3cd3408999709b0a7f6a9e5f5abd9628e2d2dcb202a938e27ce27326888d4d819c4f22384f3bba883f141e19eb40
6
+ metadata.gz: 0e0328197b86d54de5ca06334e6bb82ae3778befe8c50a0a514450e875d21cbea64f91f23ac4df23bb615de6d87c9e3d291d63ef696dab4e8546a50e16913b6f
7
+ data.tar.gz: e0c56bbebbdaabd7dc669bf70f7ab8529e2e8296e5ced74461cf427204b8a2534b12265506dddb1bc5d0e3162ed8b69be78df08cd0857e8d2f5830c364815c47
data/CHANGELOG.md CHANGED
@@ -1,3 +1,18 @@
1
+ ## 0.5.0
2
+
3
+ * `listing`: the title is optional (`{% listing java %}` renders `Listing N.`) and `number:N` forces the number, numbering continues from it; automatic numbering stays the default
4
+ * new `embed` tag for Vimeo and Dailymotion: `{% embed vimeo 9498000 "Title" %}` renders `div.video` with a lazy, titled iframe (title required, optional `width:`/`height:`, unknown provider is an error)
5
+ * new `figure` tag: `{% figure "/img.jpg" alt:"..." caption:"..." width:320 height:240 link:"..." %}` renders `<figure>` with a lazy image, optional link and `<figcaption>` (replaces `span.pictit`)
6
+ * `wiki`: the link text may contain `acronym`, `abbr` (with `title`), `samp`, `em` and `strong`; everything else stays HTML-escaped
7
+ * `wiki`: the default `title` shows the article name with spaces instead of `_` (`href` is unchanged)
8
+ * `book`/`album`: optional `genre:"Viking Metal"` adds a row after the year (label from the dictionary key `genre`, default `Gatunek`); works with an empty ISBN/ISMN
9
+ * `book`/`album`: the year may carry a note after the four digits, e.g. `"2019 (2018 EN)"` (shown HTML-escaped); anything not starting with four digits and a space or end is still rejected
10
+ * new `wiki` tag: `{% wiki Article "text" lang:pl %}` renders a Wikipedia link with the "W" icon (`<sup class="wikiicon" role="img" aria-label="...">`); already encoded, parenthesised and diacritic article names are handled, title and icon label come from the dictionary (`wiki_title`, `wiki_icon_label`) with defaults
11
+ * `book`/`album`: cover `<img>` gets `loading="lazy"` and optional `width:`/`height:` (positive integers, each optional; no size attributes when omitted)
12
+ * `offtop`: direction can be given positionally, `{% offtop left %}` (was silently ignored); unknown or conflicting values raise `ArgumentError`
13
+ * `yt_video`: iframe gets `loading="lazy"`
14
+ * `yt_video`: optional title, `{% yt_video ID "Video title" %}` (default stays `Youtube Video`, title is HTML-escaped)
15
+
1
16
  ## 0.4.4
2
17
 
3
18
  * `album` tag (like `book`, but ISMN instead of ISBN, album cover alt text)
data/Gemfile.lock CHANGED
@@ -1,31 +1,31 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- jekyll-koziolekweb-tags (0.4.1)
4
+ jekyll-koziolekweb-tags (0.4.4)
5
5
  jekyll (>= 3.7, < 5.0)
6
6
 
7
7
  GEM
8
8
  remote: https://rubygems.org/
9
9
  specs:
10
- addressable (2.8.7)
11
- public_suffix (>= 2.0.2, < 7.0)
12
- base64 (0.2.0)
13
- bigdecimal (3.1.9)
10
+ addressable (2.10.0)
11
+ public_suffix (>= 2.0.2, < 8.0)
12
+ base64 (0.3.0)
13
+ bigdecimal (4.1.3)
14
14
  colorator (1.1.0)
15
- concurrent-ruby (1.3.5)
16
- csv (3.3.4)
15
+ concurrent-ruby (1.3.8)
16
+ csv (3.3.7)
17
17
  date (3.4.1)
18
18
  em-websocket (0.5.3)
19
19
  eventmachine (>= 0.12.9)
20
20
  http_parser.rb (~> 0)
21
21
  eventmachine (1.2.7)
22
- ffi (1.17.2-x86_64-linux-gnu)
22
+ ffi (1.17.4-x86_64-linux-gnu)
23
23
  forwardable-extended (2.6.0)
24
- google-protobuf (4.31.0-x86_64-linux-gnu)
24
+ google-protobuf (4.33.6-x86_64-linux-gnu)
25
25
  bigdecimal
26
26
  rake (>= 13)
27
- http_parser.rb (0.8.0)
28
- i18n (1.14.7)
27
+ http_parser.rb (0.8.1)
28
+ i18n (1.15.2)
29
29
  concurrent-ruby (~> 1.0)
30
30
  io-console (0.8.0)
31
31
  irb (1.15.2)
@@ -55,15 +55,17 @@ GEM
55
55
  sass-embedded (~> 1.75)
56
56
  jekyll-watch (2.2.1)
57
57
  listen (~> 3.0)
58
- json (2.12.0)
59
- kramdown (2.5.1)
60
- rexml (>= 3.3.9)
58
+ json (2.21.2)
59
+ kramdown (2.6.1)
60
+ rexml (>= 3.4.4)
61
61
  kramdown-parser-gfm (1.1.0)
62
62
  kramdown (~> 2.0)
63
63
  liquid (4.0.4)
64
- listen (3.9.0)
64
+ listen (3.10.1)
65
+ logger
65
66
  rb-fsevent (~> 0.10, >= 0.10.3)
66
67
  rb-inotify (~> 0.9, >= 0.9.10)
68
+ logger (1.7.0)
67
69
  mercenary (0.4.0)
68
70
  minitest (5.25.5)
69
71
  pathutil (0.16.2)
@@ -74,7 +76,7 @@ GEM
74
76
  psych (5.2.6)
75
77
  date
76
78
  stringio
77
- public_suffix (6.0.2)
79
+ public_suffix (7.1.0)
78
80
  rake (13.2.1)
79
81
  rb-fsevent (0.11.2)
80
82
  rb-inotify (0.11.1)
@@ -83,20 +85,20 @@ GEM
83
85
  psych (>= 4.0.0)
84
86
  reline (0.6.1)
85
87
  io-console (~> 0.5)
86
- rexml (3.4.1)
87
- rouge (4.5.2)
88
+ rexml (3.4.5)
89
+ rouge (4.7.0)
88
90
  rubygems-tasks (0.2.6)
89
91
  irb (~> 1.0)
90
92
  rake (>= 10.0.0)
91
93
  safe_yaml (1.0.5)
92
- sass-embedded (1.89.0-x86_64-linux-gnu)
94
+ sass-embedded (1.108.2-x86_64-linux-gnu)
93
95
  google-protobuf (~> 4.31)
94
96
  shellwords (0.2.2)
95
97
  stringio (3.1.7)
96
98
  terminal-table (3.0.2)
97
99
  unicode-display_width (>= 1.1.1, < 3)
98
100
  unicode-display_width (2.6.0)
99
- webrick (1.9.1)
101
+ webrick (1.9.2)
100
102
 
101
103
  PLATFORMS
102
104
  x86_64-linux
data/Jenkinsfile ADDED
@@ -0,0 +1,44 @@
1
+ // CI gema jekyll-koziolekweb-tags: zależności -> testy -> build gema (artefakt).
2
+ // Wydanie (tag, push, gem push) robi ręcznie ./release.sh, CI niczego nie publikuje.
3
+ //
4
+ // Job: Pipeline z SCM, repo na Forgejo, Script Path: Jenkinsfile.
5
+ // Wymaga: Ruby 3.4.3 (asdf) na kontrolerze (.tool-versions).
6
+ pipeline {
7
+ agent any
8
+
9
+ options {
10
+ timeout(time: 10, unit: 'MINUTES')
11
+ disableConcurrentBuilds()
12
+ buildDiscarder(logRotator(numToKeepStr: '10'))
13
+ }
14
+
15
+ environment {
16
+ TZ = 'UTC'
17
+ }
18
+
19
+ stages {
20
+ stage('Dependencies') {
21
+ steps {
22
+ sh 'bundle config set --local path vendor/bundle'
23
+ sh 'bundle install --jobs 4'
24
+ }
25
+ }
26
+
27
+ stage('Test') {
28
+ steps {
29
+ sh 'bundle exec rake test'
30
+ }
31
+ }
32
+
33
+ stage('Build gem') {
34
+ steps {
35
+ sh 'mkdir -p pkg && gem build *.gemspec --output pkg/build.gem'
36
+ archiveArtifacts artifacts: 'pkg/*.gem', fingerprint: true
37
+ }
38
+ }
39
+ }
40
+
41
+ post {
42
+ cleanup { deleteDir() }
43
+ }
44
+ }
data/README.md CHANGED
@@ -35,6 +35,9 @@ in md file, then it will generate:
35
35
  </aside>
36
36
  ```
37
37
 
38
+ `DIRECTION` is `left` or `right` (default `right`). Both `{% offtop left %}` and `{% offtop direction: left %}` work;
39
+ an unknown value raises `ArgumentError`.
40
+
38
41
  I don't want to suggest anything abut css, but:
39
42
 
40
43
  * `offtopic` class should define most of layout
@@ -61,6 +64,10 @@ Your code goes here
61
64
 
62
65
  and finally it will be processed by markdown engine to final form. `X` is an number of listing, starts from 1 and work in post context.
63
66
 
67
+ The title is optional: `{% listing LANG %}` renders just `Listing X.`. Numbering is automatic; the optional `number:N` argument
68
+ forces the number of that listing (`{% listing LANG 'TITLE' number:5 %}`, `N` is a positive integer) and the following listings are numbered from it
69
+ (5, 6, ...). Without `number:` nothing changes.
70
+
64
71
  ### yt_video
65
72
 
66
73
  This tag helps to embed youtube video:
@@ -73,10 +80,93 @@ will generate
73
80
 
74
81
  ```html
75
82
  <div class="video">
76
- <iframe src="https://www.youtube-nocookie.com/embed/VIDEO_ID" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
83
+ <iframe title="Youtube Video" src="https://www.youtube-nocookie.com/embed/VIDEO_ID" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
84
+ </div>
85
+ ```
86
+
87
+ The iframe is lazy-loaded (`loading="lazy"`). An optional second argument sets the iframe `title`
88
+ (for screen readers), in single or double quotes. It is HTML-escaped; when omitted (or blank) the title is `Youtube Video`:
89
+
90
+ ```
91
+ {% yt_video VIDEO_ID "Video title" %}
92
+ ```
93
+
94
+ ### book / album
95
+
96
+ ```
97
+ {% book "Title" "Author" "2024" "ISBN" "/cover.jpg" lang:pl width:120 height:180 %}
98
+ {% album "Title" "Artist" "2024" "ISMN" "/cover.jpg" %}
99
+ ```
100
+
101
+ The year starts with four digits; a note may follow after a space, e.g. `"2019 (2018 EN)"` for a translated edition (quote it, it is HTML-escaped).
102
+
103
+ An optional `genre:"Viking Metal"` adds a row after the year (HTML-escaped, label from the dictionary key `genre`, default `Gatunek`; omitted or blank means no row).
104
+
105
+ The cover `<img>` is lazy-loaded (`loading="lazy"`). Optional `width:` and `height:` (positive integers, either one or both)
106
+ are rendered as attributes so the browser can reserve space and avoid layout shift. Without them no size attributes are added.
107
+
108
+ ### wiki
109
+
110
+ ```
111
+ {% wiki Fred_Brooks "Frederick Brooks" lang:pl %}
112
+ {% wiki "Złożoność cyklomatyczna" lang:pl %}
113
+ {% wiki Singleton_pattern lang:en %}
114
+ ```
115
+
116
+ generates a link to the Wikipedia article followed by the "W" icon:
117
+
118
+ ```html
119
+ <a href="https://pl.wikipedia.org/wiki/Fred_Brooks" title="From Wikipedia the definition of: Fred Brooks">Frederick Brooks</a><sup class="wikiicon" role="img" aria-label="Artykuł w Wikipedii"><em>W</em></sup>
120
+ ```
121
+
122
+ * the article name is as in the URL; spaces become `_`, parentheses and already percent-encoded names are kept, other characters (e.g. Polish letters) are encoded
123
+ * the link text is optional (default: the article name with spaces); it is HTML-escaped, except a few allowed tags: `<acronym>`, `<abbr>` (optionally with `title="..."` or `title='...'`), `<samp>`, `<em>` and `<strong>`, e.g. `{% wiki "Język_dziedzinowy" "<acronym title='Domain specific language'>DSLa</acronym>" %}`; other tags and attributes, and unbalanced allowed tags, stay escaped
124
+ * `lang:xx` selects the Wikipedia language edition; default is the site language from `_config.yml` (`en` when missing)
125
+ * `title` and the accessible icon label can be translated in `_data/lang/<lang>.yml` with the keys `wiki_title` (`%{title}` is the article name with spaces instead of `_`) and `wiki_icon_label`; defaults are `From Wikipedia the definition of: %{title}` and `Artykuł w Wikipedii`
126
+ * style the icon with `sup.wikiicon`
127
+
128
+ ### figure
129
+
130
+ ```
131
+ {% figure "/img/x.jpg" alt:"Opis obrazka" caption:"Podpis" width:320 height:240 link:"/img/x-full.jpg" %}
132
+ ```
133
+
134
+ generates
135
+
136
+ ```html
137
+ <figure>
138
+ <a href="/img/x-full.jpg"><img src="/img/x.jpg" alt="Opis obrazka" loading="lazy" width="320" height="240" /></a>
139
+ <figcaption>Podpis</figcaption>
140
+ </figure>
141
+ ```
142
+
143
+ * the image address is the only positional argument
144
+ * `alt` is required; use `alt:""` for a decorative image
145
+ * `caption` (the `<figcaption>`), `link` (wraps the image in a link) and `width` / `height` (positive integers) are optional; without them the corresponding element or attribute is not rendered
146
+ * all values are HTML-escaped and the image is always lazy-loaded
147
+ * put the tag in its own paragraph (blank lines around it)
148
+
149
+ ### embed
150
+
151
+ Videos from services other than YouTube (YouTube stays in `yt_video`):
152
+
153
+ ```
154
+ {% embed vimeo 9498000 "Samurai" %}
155
+ {% embed dailymotion x92k47 "Trailer 2 – The Hunt For Gollum" width:800 height:450 %}
156
+ ```
157
+
158
+ will generate
159
+
160
+ ```html
161
+ <div class="video">
162
+ <iframe title="Samurai" src="https://player.vimeo.com/video/9498000" loading="lazy" allowfullscreen></iframe>
77
163
  </div>
78
164
  ```
79
165
 
166
+ * providers: `vimeo` (numeric ID) and `dailymotion` (alphanumeric ID, optionally with a `_slug` suffix); an unknown provider or a malformed ID raises `Liquid::SyntaxError`
167
+ * the title is required (accessible name of the iframe) and is HTML-escaped
168
+ * `width` / `height` (positive integers) are optional iframe attributes; the default 16:9 size comes from the `div.video` wrapper, as in `yt_video`
169
+
80
170
  ## Development
81
171
 
82
172
  After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to
@@ -3,7 +3,7 @@
3
3
  module Jekyll
4
4
  module Koziolekweb
5
5
  module Tags
6
- VERSION = "0.4.4"
6
+ VERSION = "0.5.0"
7
7
  end
8
8
  end
9
9
  end
@@ -10,17 +10,36 @@ require_relative "tags/version"
10
10
 
11
11
  module Koziolekweb
12
12
  module Tags
13
+ # Wspólne parsowanie opcjonalnych wymiarów obrazka: width:120 / height:180 (liczba całkowita > 0).
14
+ module Dimensions
15
+ private
16
+
17
+ def parse_dimension(args, name)
18
+ arg = args.find { |s| s.start_with?("#{name}:") }
19
+ return nil unless arg
20
+
21
+ value = arg.split(":", 2).last
22
+ unless value.match?(/\A[1-9]\d*\z/)
23
+ raise Liquid::SyntaxError, "Invalid #{name}: #{value.inspect}"
24
+ end
25
+ value
26
+ end
27
+ end
28
+
13
29
  class Listing < Liquid::Block
14
30
  def initialize(tag_name, markup, tokens)
15
31
  super
16
- matched = markup.strip.match(/\A(\w+)\s+["'](.+?)["']\z/)
32
+ matched = markup.strip.match(/\A(\w+)(?:\s+["'](.+?)["'])?(?:\s+number:([1-9]\d*))?\z/)
17
33
  if matched
18
34
  @lang = matched[1]
19
35
  @title = matched[2]
36
+ @number = matched[3]&.to_i
20
37
  else
21
38
  raise Liquid::SyntaxError, <<~ERROR.strip
22
39
  Invalid parameters for listing. Usage:
23
40
  {% listing lang 'title' %}
41
+ {% listing lang %}
42
+ {% listing lang 'title' number:5 %}
24
43
  code goes here
25
44
  {% endlisting %}
26
45
  Got:
@@ -36,16 +55,18 @@ module Koziolekweb
36
55
  current_file ||= "__global__"
37
56
  context.registers[:listing_count] ||= {}
38
57
  context.registers[:listing_count][current_file] ||= 0
39
- listing_number = (context.registers[:listing_count][current_file] += 1)
58
+ # number: wymusza numer i od niego liczymy dalej; bez niego numeracja jest automatyczna.
59
+ listing_number = @number || (context.registers[:listing_count][current_file] + 1)
60
+ context.registers[:listing_count][current_file] = listing_number
40
61
  content = super.chomp
41
62
 
42
63
  markdown_converter = context.registers[:site].find_converter_instance(Jekyll::Converters::Markdown)
43
- title_html = markdown_converter.convert(@title).strip.sub(%r{\A<p>(.*)</p>\z}, '\1')
64
+ title_html = @title && markdown_converter.convert(@title).strip.sub(%r{\A<p>(.*)</p>\z}, '\1')
44
65
  markdown_code = "```#{@lang}\n#{content}\n```"
45
66
  code_html = markdown_converter.convert(markdown_code).strip
46
67
 
47
68
  <<~HTML
48
- <p class='listing'> Listing #{listing_number}. #{title_html}</p>
69
+ <p class='listing'> Listing #{listing_number}.#{title_html ? " #{title_html}" : ""}</p>
49
70
  #{code_html}
50
71
  HTML
51
72
  end
@@ -53,12 +74,20 @@ module Koziolekweb
53
74
 
54
75
  class Offtop < Liquid::Block
55
76
  VALID_DIRECTIONS = %w[right left].freeze
77
+ PARAM = /(\w+)\s*:\s*("[^"]*"|\S+)/
56
78
 
79
+ # Kierunek: {% offtop left %} albo {% offtop direction: left %}
57
80
  def initialize(tag_name, markup, tokens)
58
81
  super
59
82
  @params = parse_params(markup)
83
+ positional = parse_positional(markup)
60
84
 
61
- @direction = @params.fetch('direction', 'right').strip
85
+ named = @params['direction']&.strip
86
+ if positional && named && positional != named
87
+ raise ArgumentError, "Conflicting directions '#{positional}' and '#{named}'"
88
+ end
89
+
90
+ @direction = positional || named || 'right'
62
91
 
63
92
  unless self.class::VALID_DIRECTIONS.include?(@direction)
64
93
  raise ArgumentError, "Invalid direction '#{@direction}'. Allowed values are: #{VALID_DIRECTIONS.join(', ')}"
@@ -72,9 +101,17 @@ module Koziolekweb
72
101
 
73
102
  private
74
103
 
104
+ # Wolne słowa poza parami key: value; więcej niż jedno to błąd.
105
+ def parse_positional(text)
106
+ words = text.gsub(PARAM, ' ').split
107
+ raise ArgumentError, "Unexpected arguments: #{words.join(' ')}" if words.size > 1
108
+
109
+ words.first
110
+ end
111
+
75
112
  def parse_params(text)
76
113
  params = {}
77
- text.scan(/(\w+)\s*:\s*("[^"]*"|\S+)/).each do |key, val|
114
+ text.scan(PARAM).each do |key, val|
78
115
  val = val.delete_prefix('"').delete_suffix('"') if val.start_with?('"')
79
116
  params[key] = val
80
117
  end
@@ -83,20 +120,28 @@ module Koziolekweb
83
120
  end
84
121
 
85
122
  class YtVideo < Liquid::Tag
86
- def initialize(tag_name, video_id, tokens)
123
+ DEFAULT_TITLE = "Youtube Video"
124
+ # ID, opcjonalnie tytuł w cudzysłowie: {% yt_video ID "Tytuł" %}
125
+ MARKUP = /\A\s*(\S*)(?:\s+(?:"(.*)"|'(.*)'))?\s*\z/m
126
+
127
+ def initialize(tag_name, markup, tokens)
87
128
  super
88
- @video_id = video_id.strip
129
+ match = MARKUP.match(markup)
130
+ raise Liquid::SyntaxError, "Invalid yt_video syntax: #{markup.inspect}" unless match
131
+
132
+ @video_id = match[1]
133
+ title = (match[2] || match[3]).to_s.strip
134
+ @title = title.empty? ? DEFAULT_TITLE : title
89
135
 
90
136
  if @video_id.empty? || !valid_video_id?(@video_id)
91
137
  raise Liquid::SyntaxError, "Invalid video ID: #{@video_id.inspect}"
92
138
  end
93
-
94
139
  end
95
140
 
96
141
  def render(_context)
97
142
  <<~HTML
98
143
  <div class="video">
99
- <iframe title="Youtube Video" src="https://www.youtube-nocookie.com/embed/#{@video_id}" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
144
+ <iframe title="#{CGI.escapeHTML(@title)}" src="https://www.youtube-nocookie.com/embed/#{@video_id}" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
100
145
  </div>
101
146
  HTML
102
147
  end
@@ -117,10 +162,17 @@ module Koziolekweb
117
162
  # Optional language parameter:
118
163
  # {% book "Title" "Author" "2024" "1234567890" "https://example.com/cover.jpg" lang:pl %}
119
164
  #
165
+ # Optional genre (extra row after the year, label from the dictionary key `genre`, default "Gatunek"):
166
+ # {% book "Title" "Author" "2024" "" "/cover.jpg" genre:"Viking Metal" %}
167
+ #
168
+ # Optional cover size (reserves space, avoids layout shift); the cover is always lazy-loaded:
169
+ # {% book "Title" "Author" "2024" "1234567890" "/cover.jpg" width:120 height:180 %}
170
+ #
120
171
  # The tag requires:
121
172
  # - Title (in quotes)
122
173
  # - Author (in quotes)
123
- # - Publication year (4 digits)
174
+ # - Publication year: starts with 4 digits, anything after a space is allowed
175
+ # and shown as is (HTML-escaped), e.g. "2019 (2018 EN)"
124
176
  # - ISBN (can be empty string)
125
177
  # - Cover image URL
126
178
  #
@@ -129,8 +181,12 @@ module Koziolekweb
129
181
  # - Language files should be in _data/lang/[lang_code].yml
130
182
  # - Language codes must be 2 letters (e.g. en, pl, de)
131
183
  class Book < Liquid::Tag
184
+ include Dimensions
185
+
132
186
  # Minimum number of required arguments (title, author, year, isbn, cover_url)
133
187
  MIN_ARGS = 5
188
+ # Rok: cztery cyfry, opcjonalnie spacja i dowolny dopisek, np. "2019 (2018 EN)"
189
+ YEAR_FORMAT = /\A\d{4}(?:\s.*)?\z/m
134
190
 
135
191
  def initialize(tag_name, markup, tokens)
136
192
  super
@@ -140,7 +196,7 @@ module Koziolekweb
140
196
 
141
197
  @title, @author, @year, @isbn, @cover_url = args[0..4].map { _1.delete('"') }
142
198
 
143
- unless @year.match?(/\A\d{4}\z/)
199
+ unless @year.match?(YEAR_FORMAT)
144
200
  raise Liquid::SyntaxError, "Invalid publication year: #{@year.inspect}"
145
201
  end
146
202
 
@@ -150,6 +206,13 @@ module Koziolekweb
150
206
  unless @lang.match?(/\A[a-z]{2}\z/i)
151
207
  raise Liquid::SyntaxError, "Invalid language code: #{@lang.inspect}"
152
208
  end
209
+
210
+ @genre = args[5..].to_a.find { |a| a.start_with?("genre:") }&.split(":", 2)&.last.to_s.strip
211
+ @genre = nil if @genre&.empty?
212
+
213
+ @width = parse_dimension(args, "width")
214
+ @height = parse_dimension(args, "height")
215
+
153
216
  # Inicjalizacja LanguageManager
154
217
  lang_data_path = File.join(Dir.pwd, '_data', 'lang') # Katalog z plikami językowymi
155
218
  config_path = File.join(Dir.pwd, '_config.yml') # Ścieżka do pliku `_config.yml`
@@ -165,18 +228,20 @@ module Koziolekweb
165
228
  label_author = @language_manager.translate('author', @lang, 'Autor')
166
229
  label_year = @language_manager.translate('year', @lang, 'Rok')
167
230
  label_isbn = @language_manager.translate(identifier_key, @lang, identifier_label)
231
+ label_genre = @language_manager.translate('genre', @lang, 'Gatunek')
168
232
  cover_alt = @language_manager.translate(cover_alt_key, @lang, cover_alt_default)
169
233
  .gsub('%{title}', @title)
170
234
  .gsub('%{author}', @author)
171
235
 
172
236
  <<~HTML
173
237
  <div class="book">
174
- <img src="#{@cover_url}" alt="#{cover_alt}" title="#{@title}" class="cover" />
238
+ <img src="#{@cover_url}" alt="#{cover_alt}" title="#{@title}" class="cover" loading="lazy"#{dimension_attrs} />
175
239
  <div class="book_desc">
176
240
  <ul>
177
241
  <li><span>#{label_title}: </span>#{title_html}</li>
178
242
  <li><span>#{label_author}: </span>#{author_html}</li>
179
243
  <li><span>#{label_year}: </span>#{year_html}</li>
244
+ #{@genre ? "<li><span>#{label_genre}: </span>#{CGI.escapeHTML(@genre)}</li>" : ""}
180
245
  #{@isbn.to_s.empty? ? "" : "<li><span>#{label_isbn}: </span>#{isbn_html}</li>"}
181
246
  </ul>
182
247
  </div>
@@ -186,6 +251,13 @@ module Koziolekweb
186
251
 
187
252
  private
188
253
 
254
+ def dimension_attrs
255
+ attrs = +""
256
+ attrs << %( width="#{@width}") if @width
257
+ attrs << %( height="#{@height}") if @height
258
+ attrs
259
+ end
260
+
189
261
  # Klucz słownika i domyślna etykieta identyfikatora (nadpisywane w Album).
190
262
  def identifier_key = 'isbn'
191
263
  def identifier_label = 'ISBN'
@@ -203,7 +275,7 @@ module Koziolekweb
203
275
  # {% album "Title" "Artist" "2024" "" "https://example.com/cover.jpg" lang:pl %}
204
276
  #
205
277
  # The ISMN may be an empty string - the ISMN row is then omitted.
206
- # Dictionary keys: title, author, year, ismn, album_cover_alt.
278
+ # Dictionary keys: title, author, year, genre, ismn, album_cover_alt.
207
279
  class Album < Book
208
280
  private
209
281
 
@@ -213,6 +285,246 @@ module Koziolekweb
213
285
  def cover_alt_key = 'album_cover_alt'
214
286
  def cover_alt_default = 'Okładka albumu %{title} wykonawcy %{author}'
215
287
  end
288
+
289
+ # Osadzony film z serwisu innego niż YouTube (YouTube zostaje w yt_video).
290
+ #
291
+ # Usage:
292
+ # {% embed vimeo 9498000 "Samurai" %}
293
+ # {% embed dailymotion x92k47 "Trailer 2 – The Hunt For Gollum" %}
294
+ # {% embed vimeo 9498000 "Samurai" width:800 height:450 %}
295
+ #
296
+ # - serwis: vimeo albo dailymotion (nieznany rzuca Liquid::SyntaxError; nowy = wpis w PROVIDERS)
297
+ # - id filmu: liczba dla vimeo, dla dailymotion znaki alfanumeryczne (opcjonalnie z końcówką `_slug`)
298
+ # - tytuł: wymagany (WCAG 4.1.2), escapowany HTML
299
+ # - width / height (opcjonalne): liczby całkowite > 0, atrybuty iframe; domyślny rozmiar 16:9
300
+ # wynika z kontenera div.video, tak samo jak w yt_video
301
+ #
302
+ # Iframe ma zawsze loading="lazy" i allowfullscreen.
303
+ class Embed < Liquid::Tag
304
+ include Dimensions
305
+
306
+ PROVIDERS = {
307
+ "vimeo" => { url: "https://player.vimeo.com/video/%{id}", id: /\A\d+\z/ },
308
+ "dailymotion" => { url: "https://www.dailymotion.com/embed/video/%{id}", id: /\A[a-z0-9]+(?:_[\w-]+)?\z/i }
309
+ }.freeze
310
+
311
+ def initialize(tag_name, markup, tokens)
312
+ super
313
+
314
+ begin
315
+ args = Shellwords.split(markup)
316
+ rescue ArgumentError => e
317
+ raise Liquid::SyntaxError, "Invalid embed syntax: #{e.message}"
318
+ end
319
+
320
+ positional = args.reject { |a| a.start_with?("width:", "height:") }
321
+ unless positional.size == 3
322
+ raise Liquid::SyntaxError, 'Invalid usage: {% embed vimeo 123456 "Title" %}'
323
+ end
324
+
325
+ provider, @video_id, title = positional.map(&:strip)
326
+ @provider = PROVIDERS[provider.downcase]
327
+ unless @provider
328
+ raise Liquid::SyntaxError, "Unknown embed provider #{provider.inspect} (allowed: #{PROVIDERS.keys.join(', ')})"
329
+ end
330
+
331
+ unless @video_id.match?(@provider[:id])
332
+ raise Liquid::SyntaxError, "Invalid #{provider.downcase} video ID: #{@video_id.inspect}"
333
+ end
334
+
335
+ raise Liquid::SyntaxError, "Missing title (required for accessibility)" if title.empty?
336
+
337
+ @title = title
338
+ @width = parse_dimension(args, "width")
339
+ @height = parse_dimension(args, "height")
340
+ end
341
+
342
+ def render(_context)
343
+ src = format(@provider[:url], id: @video_id)
344
+ size = +""
345
+ size << %( width="#{@width}") if @width
346
+ size << %( height="#{@height}") if @height
347
+
348
+ <<~HTML
349
+ <div class="video">
350
+ <iframe title="#{CGI.escapeHTML(@title)}" src="#{src}" loading="lazy"#{size} allowfullscreen></iframe>
351
+ </div>
352
+ HTML
353
+ end
354
+ end
355
+
356
+ # Obraz z podpisem (zamiast span.pictit).
357
+ #
358
+ # Usage:
359
+ # {% figure "/img/x.jpg" alt:"Opis obrazka" caption:"Podpis" width:320 height:240 link:"/img/x-full.jpg" %}
360
+ # {% figure "/img/x.jpg" alt:"" %}
361
+ #
362
+ # - adres obrazka: pierwszy argument (wymagany)
363
+ # - alt: wymagany, pusty ciąg dozwolony dla obrazków dekoracyjnych
364
+ # - caption (opcjonalny): podpis w <figcaption>, escapowany HTML
365
+ # - link (opcjonalny): adres, do którego prowadzi obrazek
366
+ # - width / height (opcjonalne): liczby całkowite > 0
367
+ #
368
+ # Obrazek ma zawsze loading="lazy". Tag umieszczaj w osobnej linii z pustymi liniami wokół.
369
+ class Figure < Liquid::Tag
370
+ include Dimensions
371
+
372
+ OPTIONS = %w[alt caption link width height].freeze
373
+
374
+ def initialize(tag_name, markup, tokens)
375
+ super
376
+
377
+ begin
378
+ args = Shellwords.split(markup)
379
+ rescue ArgumentError => e
380
+ raise Liquid::SyntaxError, "Invalid figure syntax: #{e.message}"
381
+ end
382
+
383
+ positional = args.reject { |a| OPTIONS.any? { |o| a.start_with?("#{o}:") } }
384
+ unless positional.size == 1 && !positional.first.strip.empty?
385
+ raise Liquid::SyntaxError, 'Invalid usage: {% figure "/img.jpg" alt:"..." caption:"..." %}'
386
+ end
387
+
388
+ @src = positional.first.strip
389
+ @alt = option(args, "alt")
390
+ raise Liquid::SyntaxError, "Missing alt (use alt:\"\" for a decorative image)" if @alt.nil?
391
+
392
+ @caption = option(args, "caption")&.strip
393
+ @caption = nil if @caption&.empty?
394
+ @link = option(args, "link")&.strip
395
+ @link = nil if @link&.empty?
396
+ @width = parse_dimension(args, "width")
397
+ @height = parse_dimension(args, "height")
398
+ end
399
+
400
+ def render(_context)
401
+ img = %(<img src="#{CGI.escapeHTML(@src)}" alt="#{CGI.escapeHTML(@alt)}" loading="lazy"#{size_attrs} />)
402
+ img = %(<a href="#{CGI.escapeHTML(@link)}">#{img}</a>) if @link
403
+ caption = @caption ? "\n <figcaption>#{CGI.escapeHTML(@caption)}</figcaption>" : ""
404
+
405
+ "<figure>\n #{img}#{caption}\n</figure>\n"
406
+ end
407
+
408
+ private
409
+
410
+ # Wartość opcji name:... (nil, gdy jej nie ma; pusty ciąg dla name:"").
411
+ def option(args, name)
412
+ arg = args.find { |a| a.start_with?("#{name}:") }
413
+ arg&.split(":", 2)&.last
414
+ end
415
+
416
+ def size_attrs
417
+ attrs = +""
418
+ attrs << %( width="#{@width}") if @width
419
+ attrs << %( height="#{@height}") if @height
420
+ attrs
421
+ end
422
+ end
423
+
424
+ # Link do artykułu na Wikipedii z ikoną "W".
425
+ #
426
+ # Usage:
427
+ # {% wiki Fred_Brooks "Frederick Brooks" %}
428
+ # {% wiki "Złożoność cyklomatyczna" "złożoność" lang:pl %}
429
+ # {% wiki Heinrich_Ignaz_Biber lang:en %}
430
+ #
431
+ # - artykuł: nazwa jak w URL-u (spacje zamieniane na `_`, już zakodowane `%XX`,
432
+ # polskie znaki i nawiasy zostają bez zmian)
433
+ # - tekst linku (opcjonalny): domyślnie nazwa artykułu ze spacjami; jest escapowany HTML,
434
+ # poza dozwolonymi znacznikami (ALLOWED_TAGS), np. <acronym title='...'>DSL</acronym>
435
+ # - lang:xx (opcjonalny): wersja językowa Wikipedii, domyślnie język strony z _config.yml
436
+ #
437
+ # Klucze słownika (_data/lang/<lang>.yml): wiki_title (domyślnie angielskie
438
+ # "From Wikipedia the definition of: %{title}", %{title} to nazwa artykułu ze spacjami zamiast `_`), wiki_icon_label (domyślnie "Artykuł w Wikipedii").
439
+ class Wiki < Liquid::Tag
440
+ DEFAULT_TITLE = "From Wikipedia the definition of: %{title}"
441
+ DEFAULT_ICON_LABEL = "Artykuł w Wikipedii"
442
+ # Znaki, które zostają w URL-u bez kodowania (w tym już zakodowane %XX).
443
+ URL_SAFE = /[A-Za-z0-9\-._~!*'():@\/]/
444
+ # Znaczniki dozwolone w tekście linku; title (w cudzysłowie) tylko dla acronym i abbr.
445
+ ALLOWED_TAGS = %w[acronym abbr samp em strong].freeze
446
+ TITLED_TAGS = %w[acronym abbr].freeze
447
+
448
+ def initialize(tag_name, markup, tokens)
449
+ super
450
+
451
+ begin
452
+ args = Shellwords.split(markup)
453
+ rescue ArgumentError => e
454
+ raise Liquid::SyntaxError, "Invalid wiki syntax: #{e.message}"
455
+ end
456
+
457
+ lang_arg = args.find { |s| s.start_with?("lang:") }
458
+ args.delete(lang_arg) if lang_arg
459
+ raise Liquid::SyntaxError, "Invalid usage: {% wiki Article \"text\" lang:pl %}" unless (1..2).cover?(args.size)
460
+
461
+ @article = args[0].strip.tr(" ", "_")
462
+ raise Liquid::SyntaxError, "Missing article name" if @article.empty?
463
+
464
+ @text = args[1]&.strip
465
+ @lang = lang_arg&.split(":", 2)&.last
466
+
467
+ if @lang && !@lang.match?(/\A[a-z]{2,3}\z/i)
468
+ raise Liquid::SyntaxError, "Invalid language code: #{@lang.inspect}"
469
+ end
470
+
471
+ lang_data_path = File.join(Dir.pwd, '_data', 'lang')
472
+ config_path = File.join(Dir.pwd, '_config.yml')
473
+ @language_manager = Koziolekweb::LanguageSupport::LanguageManager.new(config_path, lang_data_path)
474
+ end
475
+
476
+ def render(_context)
477
+ lang = (@lang || @language_manager.default_language).downcase
478
+ readable = decode(@article).tr("_", " ")
479
+ text = @text.nil? || @text.empty? ? readable : @text
480
+ title = @language_manager.translate('wiki_title', lang, DEFAULT_TITLE).gsub('%{title}') { readable }
481
+ icon_label = @language_manager.translate('wiki_icon_label', lang, DEFAULT_ICON_LABEL)
482
+ href = "https://#{lang}.wikipedia.org/wiki/#{encode(@article)}"
483
+
484
+ %(<a href="#{CGI.escapeHTML(href)}" title="#{CGI.escapeHTML(title)}">#{safe_text(text)}</a>) +
485
+ %(<sup class="wikiicon" role="img" aria-label="#{CGI.escapeHTML(icon_label)}"><em>W</em></sup>)
486
+ end
487
+
488
+ private
489
+
490
+ # Koduje tylko to, co nie jest jeszcze bezpieczne; istniejące %XX zostają.
491
+ def encode(article)
492
+ article.gsub(/%\h\h|./m) do |chunk|
493
+ if chunk.length == 3 && chunk.start_with?("%") || chunk.match?(URL_SAFE)
494
+ chunk
495
+ else
496
+ chunk.bytes.map { |b| format("%%%02X", b) }.join
497
+ end
498
+ end
499
+ end
500
+
501
+ # Escapuje tekst, a potem przywraca tylko dozwolone znaczniki (bez atrybutów, a dla
502
+ # acronym/abbr także z title). Gdy znaczniki są niezbalansowane, wszystko zostaje escapowane.
503
+ def safe_text(text)
504
+ escaped = CGI.escapeHTML(text)
505
+ tags = ALLOWED_TAGS.join("|")
506
+ titled = TITLED_TAGS.join("|")
507
+ opening = /&lt;(#{tags})&gt;/
508
+ opening_titled = /&lt;(#{titled})\s+title=(&quot;|&#39;)(.*?)\2&gt;/
509
+ closing = %r{&lt;/(#{tags})&gt;}
510
+
511
+ opens = Hash.new(0)
512
+ closes = Hash.new(0)
513
+ result = escaped
514
+ .gsub(opening_titled) { opens[$1] += 1; %(<#{$1} title="#{$3}">) }
515
+ .gsub(opening) { opens[$1] += 1; "<#{$1}>" }
516
+ .gsub(closing) { closes[$1] += 1; "</#{$1}>" }
517
+
518
+ ALLOWED_TAGS.all? { |tag| opens[tag] == closes[tag] } ? result : escaped
519
+ end
520
+
521
+ # Czytelna nazwa artykułu (do tytułu i domyślnego tekstu linku).
522
+ def decode(article)
523
+ article.gsub(/(?:%\h\h)+/) do |m|
524
+ [m.delete("%")].pack("H*").force_encoding("UTF-8").scrub
525
+ end
526
+ end
527
+ end
216
528
  end
217
529
 
218
530
  module LanguageSupport
@@ -260,7 +572,7 @@ module Koziolekweb
260
572
  end
261
573
  end
262
574
 
263
- %w[listing offtop yt_video book album].each do |tag|
575
+ %w[listing offtop yt_video book album wiki figure embed].each do |tag|
264
576
  class_name = tag.split('_').map(&:capitalize).join
265
577
  begin
266
578
  klass = Koziolekweb::Tags.const_get(class_name)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-koziolekweb-tags
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.4
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Koziolek
@@ -41,6 +41,7 @@ files:
41
41
  - CHANGELOG.md
42
42
  - Gemfile
43
43
  - Gemfile.lock
44
+ - Jenkinsfile
44
45
  - README.md
45
46
  - Rakefile
46
47
  - jekyll-koziolekweb-tags.gemspec