visualci-gallery 0.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.
@@ -0,0 +1,325 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'uri'
6
+ require_relative 'gallery/version'
7
+
8
+ module VisualCI
9
+ # A screenshots page from a VisualCI public gallery manifest (https://visualci.com/docs/gallery/), rendered as the
10
+ # gallery contract's markup (clients/gallery/contract/SPEC.md in DocSpring/visualci), byte for byte what the
11
+ # visualci-gallery JS library renders and hydrates.
12
+ #
13
+ # manifest = VisualCI::Gallery.fetch('https://app.visualci.com/g/acme/web.json') # raises when it can't
14
+ # html = VisualCI::Gallery.render(manifest, title: nil, screens: { 'overview' => { title: 'Overview' } })
15
+ #
16
+ # In Rails, `visualci_gallery(manifest, **options)` in a view returns it html_safe, and the engine serves
17
+ # visualci_gallery.js (which sets window.VisualCIGallery) and visualci_gallery.css to Sprockets or Propshaft.
18
+ module Gallery
19
+ # A manifest that can't be read or shown, or options the contract refuses.
20
+ class Error < StandardError; end
21
+
22
+ # The folder holding the JS library's files, javascripts/visualci_gallery.js (the ES5 build, which sets
23
+ # window.VisualCIGallery) and stylesheets/visualci_gallery.css, for an app without the asset pipeline to serve.
24
+ ASSETS = File.expand_path('../../app/assets', __dir__)
25
+
26
+ DEFAULT_TITLE = 'Screenshots'
27
+ SEE_ALL_TEXT = 'See all screenshots'
28
+ SIZES = %w[desktop phone].freeze
29
+ THEMES = %w[light dark].freeze
30
+ # The largest width or height (SPEC.md, "Validation"): the density maths stays exact in every language.
31
+ MAX_SIZE = 1_000_000
32
+ SIZE_LABEL = { 'desktop' => 'Desktop', 'phone' => 'Phone' }.freeze
33
+
34
+ # Whole-string matches, ASCII digits, and `.` matching line breaks too (/m), as SPEC.md says.
35
+ EXTENSION = /\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z/
36
+ WIDTH_THEME = /\A([0-9]+)-(light|dark)(-2x)?\z/
37
+ SCREEN_THEME = /\A(.+?)-(light|dark)(?:-([0-9]+))?(-2x)?\z/m
38
+ ABSOLUTE = %r{\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z}
39
+ CONTROL = /[\x00-\x20\x7f]/
40
+ SCHEME = /\A[A-Za-z][A-Za-z0-9+.-]*:/
41
+ ID = /\A[A-Za-z][A-Za-z0-9_-]*\z/
42
+ UNSET = Object.new.freeze
43
+ private_constant :UNSET
44
+
45
+ module_function
46
+
47
+ # The manifest at `url`, parsed. Raises Error, naming the URL, when it can't be read (a network error, a timeout,
48
+ # a status other than 200, JSON that doesn't parse) after `attempts` tries.
49
+ def fetch(url, timeout: 20, attempts: 3)
50
+ last = nil
51
+ attempts = [attempts.to_i, 1].max
52
+ attempts.times do |i|
53
+ begin
54
+ response = get(URI(url), timeout)
55
+ raise "HTTP #{response.code}" unless response.code == '200'
56
+
57
+ return JSON.parse(response.body)
58
+ rescue StandardError => e
59
+ last = e
60
+ sleep(i + 1) if i + 1 < attempts
61
+ end
62
+ end
63
+ raise Error, "The screenshots gallery couldn't read #{url}: #{last.message}"
64
+ end
65
+
66
+ # A GET that follows up to 5 redirects, as browsers' fetch does.
67
+ def get(uri, timeout, redirects = 5)
68
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
69
+ open_timeout: timeout, read_timeout: timeout) do |http|
70
+ http.request(Net::HTTP::Get.new(uri))
71
+ end
72
+ return response unless response.is_a?(Net::HTTPRedirection) && response['location'] && redirects.positive?
73
+
74
+ get(uri + response['location'], timeout, redirects - 1)
75
+ end
76
+
77
+ # The gallery's HTML for a parsed manifest (a Hash, as JSON.parse gives it). Raises Error when the manifest or the
78
+ # options are invalid or nothing in the manifest can be shown.
79
+ def render(manifest, **options)
80
+ Renderer.new(model(manifest, **options)).call
81
+ end
82
+
83
+ # The model (SPEC.md, "The model") as a Hash with the same keys as the fixtures' model.json.
84
+ def model(manifest, title: UNSET, heading_level: nil, id: nil, screens: nil, order: nil, groups: nil,
85
+ group_order: nil, credit: nil, layout: nil, theme_switch: nil, see_all: nil)
86
+ check_manifest(manifest)
87
+ # Options in the contract's order (SPEC.md, "Validation"): the first problem is the error.
88
+ level = opt(heading_level, 'headingLevel') { |v| integral?(v) }
89
+ title = title.equal?(UNSET) ? DEFAULT_TITLE : opt(title, 'title') { |v| v.is_a?(String) }
90
+ id = opt(id, 'id') { |v| v.is_a?(String) && ID.match?(v) } || 'vg'
91
+ screens_opt = texts(screens, 'screens', %w[title caption])
92
+ groups_opt = group_options(groups)
93
+ order = strings(order, 'order')
94
+ group_order = strings(group_order, 'groupOrder')
95
+ credit = opt(credit, 'credit') { |v| boolean?(v) }
96
+ switch = opt(theme_switch, 'themeSwitch') { |v| boolean?(v) }
97
+ layout = opt(layout, 'layout') { |v| %w[grid strip].include?(v.to_s) }&.to_s || 'grid'
98
+ see_all = opt(see_all, 'seeAll') { |v| see_all?(v) }
99
+ model = {
100
+ 'layout' => layout,
101
+ 'themeSwitch' => layout == 'grid' && switch != false,
102
+ 'seeAll' => see_all && { 'href' => fetch_key(see_all, 'href'), 'text' => fetch_key(see_all, 'text') || SEE_ALL_TEXT },
103
+ 'title' => title,
104
+ 'label' => title || DEFAULT_TITLE,
105
+ 'headingLevel' => (level ? level.to_i : 2).clamp(1, 4),
106
+ 'id' => id,
107
+ 'credit' => credit.nil? ? true : credit,
108
+ 'groups' => build_groups(manifest, screens_opt, groups_opt, order, group_order)
109
+ }
110
+ raise Error, 'the gallery manifest has no screenshots to show' if model['groups'].empty?
111
+
112
+ model
113
+ end
114
+
115
+ # How a manifest name pairs (SPEC.md, "A shot's name"): key, theme (nil for both), size, 2x, CSS width.
116
+ def parse_shot(name, width, height, size = nil)
117
+ parts = name.sub(EXTENSION, '').split('/', -1)
118
+ parts = [''] if parts.empty? # "".split gives [] in Ruby, [""] in JavaScript
119
+ last = parts.pop
120
+ folder = parts.join('/')
121
+ sized = ->(w) { w ? (w.to_i < 768 ? 'phone' : 'desktop') : (size || (height > width ? 'phone' : 'desktop')) }
122
+ if folder != '' && (m = WIDTH_THEME.match(last))
123
+ return { key: folder, theme: m[2], size: sized.call(m[1]), x2: !m[3].nil?, css_width: m[1].to_i }
124
+ end
125
+ if (m = SCREEN_THEME.match(last))
126
+ key = folder == '' ? m[1] : "#{folder}/#{m[1]}"
127
+ return { key: key, theme: m[2], size: sized.call(m[3]), x2: !m[4].nil?, css_width: m[3]&.to_i }
128
+ end
129
+ { key: folder == '' ? last : "#{folder}/#{last}", theme: nil, size: sized.call(nil), x2: false, css_width: nil }
130
+ end
131
+
132
+ # `billing/free` → "Billing, free".
133
+ def humanize(segments)
134
+ text = segments.map { |s| s.gsub(/[-_]+/, ' ').gsub(/\A +| +\z/, '') }.join(', ')
135
+ return text if text.empty?
136
+
137
+ text[0].upcase + text[1..]
138
+ end
139
+
140
+ # A group's name as an id: ASCII lower case, runs of anything else as one hyphen.
141
+ def slugify(name)
142
+ slug = name.gsub(/[A-Z]/, &:downcase).gsub(/[^a-z0-9]+/, '-').gsub(/\A-+|-+\z/, '')
143
+ slug.empty? ? 'group' : slug
144
+ end
145
+
146
+ # & < > " ' as entities, and nothing else.
147
+ def escape(text)
148
+ text.to_s.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;').gsub("'", '&#39;')
149
+ end
150
+
151
+ def build_groups(manifest, screens_opt, groups_opt, order, group_order)
152
+ slugs = {}
153
+ groups = manifest['groups'].filter_map do |g|
154
+ set = groups_opt[g['name']] || {}
155
+ kept = pair(g['items'], set['size'])
156
+ # A screen shows both themes at each of its sizes: one theme's image never stands in for the other's.
157
+ kept.each do |key, variants|
158
+ variants.each do |v|
159
+ next if variants.any? { |o| o['size'] == v['size'] && o['theme'] != v['theme'] }
160
+
161
+ other = v['theme'] == 'light' ? 'dark' : 'light'
162
+ raise Error, "gallery screen #{key} in group #{g['name']} has a #{v['theme']} #{v['size']} screenshot but no #{other} one"
163
+ end
164
+ end
165
+ next if kept.empty?
166
+
167
+ prefix = common_folder(kept.map(&:first)).length
168
+ list = kept.map do |key, variants|
169
+ screen = screens_opt[key] || {}
170
+ { 'key' => key, 'title' => screen['title'] || humanize(key.split('/', -1).drop(prefix)),
171
+ 'caption' => screen['caption'], 'variants' => variants }
172
+ end
173
+ list = list.each_with_index.sort_by { |sc, i| [rank(order, sc['key']), sc['key'], i] }.map(&:first)
174
+ base = slugify(g['name'])
175
+ slug = base
176
+ n = 2
177
+ while slugs[slug]
178
+ slug = "#{base}-#{n}"
179
+ n += 1
180
+ end
181
+ slugs[slug] = true
182
+ { 'name' => g['name'], 'title' => set['title'] || g['title'] || g['name'],
183
+ 'slug' => slug, 'fit' => set['fit'] || 'cover', 'sizes' => SIZES.select { |s| list.any? { |sc| sc['variants'].any? { |v| v['size'] == s } } },
184
+ 'screens' => list }
185
+ end
186
+ groups.each_with_index.sort_by { |g, i| [rank(group_order, g['name']), i] }.map(&:first)
187
+ end
188
+
189
+ # [key, variants] for each screen with something to show, in manifest order.
190
+ def pair(items, size = nil)
191
+ screens = {}
192
+ items.each do |item|
193
+ width = item['width'].to_i
194
+ height = item['height'].to_i
195
+ shot = parse_shot(item['name'], width, height, size)
196
+ variants = (screens[shot[:key]] ||= {})
197
+ (shot[:theme] ? [shot[:theme]] : THEMES).each do |theme|
198
+ v = (variants["#{shot[:size]}-#{theme}"] ||= { 'size' => shot[:size], 'theme' => theme, 'url' => '',
199
+ 'url2x' => nil, 'width' => 0, 'height' => 0 })
200
+ if shot[:x2]
201
+ v['url2x'] ||= item['url']
202
+ elsif v['url'] == ''
203
+ w = shot[:css_width]
204
+ scaled = !w.nil? && width > w
205
+ v['url'] = item['url']
206
+ v['width'] = scaled ? w : width
207
+ v['height'] = scaled ? (2 * height * w + width) / (2 * width) : height
208
+ end
209
+ end
210
+ end
211
+ screens.filter_map do |key, variants|
212
+ list = variants.values.reject { |v| v['url'] == '' }
213
+ .sort_by { |v| [SIZES.index(v['size']), THEMES.index(v['theme'])] }
214
+ [key, list] unless list.empty?
215
+ end
216
+ end
217
+
218
+ def common_folder(keys)
219
+ folders = keys.map { |k| k.split('/', -1)[0...-1] }
220
+ folders.drop(1).reduce(folders.first) do |common, f|
221
+ i = 0
222
+ i += 1 while i < common.length && i < f.length && common[i] == f[i]
223
+ common.take(i)
224
+ end
225
+ end
226
+
227
+ def rank(list, key)
228
+ list.index(key) || list.length
229
+ end
230
+
231
+ def check_manifest(manifest)
232
+ raise Error, 'not a gallery manifest: it has no groups' unless manifest.is_a?(Hash) && manifest['groups'].is_a?(Array)
233
+
234
+ manifest['groups'].each_with_index do |g, i|
235
+ raise Error, "gallery manifest group #{i} has no name" unless g.is_a?(Hash) && g['name'].is_a?(String) && g['name'] != ''
236
+
237
+ name = g['name']
238
+ raise Error, "gallery manifest group #{name}: its title isn't a string" unless g['title'].nil? || g['title'].is_a?(String)
239
+ raise Error, "gallery manifest group #{name} has no items" unless g['items'].is_a?(Array)
240
+
241
+ g['items'].each_with_index do |item, j|
242
+ where = "gallery manifest group #{name}, item #{j}"
243
+ raise Error, "#{where} has no name" unless item.is_a?(Hash) && item['name'].is_a?(String) && item['name'] != ''
244
+ unless item['url'].is_a?(String) && ABSOLUTE.match?(item['url'])
245
+ raise Error, "#{where} (#{item['name']}): its url isn't an http(s) URL"
246
+ end
247
+ unless positive_integral?(item['width']) && positive_integral?(item['height'])
248
+ raise Error, "#{where} (#{item['name']}): its width and height aren't whole numbers from 1 to #{MAX_SIZE}"
249
+ end
250
+ end
251
+ end
252
+ end
253
+
254
+ # An integer, or a float with no fraction (JSON can't tell 1440 from 1440.0 in JavaScript).
255
+ # An integer as JSON has it, and as JavaScript reads it: one past a double's range is Infinity there, so not one.
256
+ def integral?(value)
257
+ (value.is_a?(Integer) && value.to_f.finite?) || (value.is_a?(Float) && value.finite? && value == value.floor)
258
+ end
259
+
260
+ def positive_integral?(value)
261
+ integral?(value) && value.positive? && value <= MAX_SIZE
262
+ end
263
+
264
+ def boolean?(value)
265
+ [true, false].include?(value)
266
+ end
267
+
268
+ def opt(value, name)
269
+ return nil if value.nil?
270
+ raise Error, "gallery option #{name} is invalid" unless yield(value)
271
+
272
+ value
273
+ end
274
+
275
+ def strings(value, name)
276
+ opt(value, name) { |v| v.is_a?(Array) && v.all?(String) } || []
277
+ end
278
+
279
+ # {"key" => {"title" => …, "caption" => …}} with string keys, values nil or strings.
280
+ GROUP_VALUES = { 'size' => SIZES, 'fit' => %w[cover contain] }.freeze
281
+
282
+ # groups: {name => {title, size, fit}}; size and fit take their words as strings or symbols.
283
+ def group_options(value)
284
+ opt(value, 'groups') do |v|
285
+ v.is_a?(Hash) && v.values.all? do |entry|
286
+ entry.is_a?(Hash) && entry.all? do |k, x|
287
+ k = k.to_s
288
+ (k == 'title' && (x.nil? || x.is_a?(String))) ||
289
+ (GROUP_VALUES.key?(k) && (x.nil? || ((x.is_a?(String) || x.is_a?(Symbol)) && GROUP_VALUES[k].include?(x.to_s))))
290
+ end
291
+ end
292
+ end.to_h { |k, entry| [k.to_s, entry.to_h { |ek, ev| [ek.to_s, ev.is_a?(Symbol) ? ev.to_s : ev] }] }
293
+ end
294
+
295
+ def texts(value, name, keys)
296
+ opt(value, name) do |v|
297
+ v.is_a?(Hash) && v.values.all? do |entry|
298
+ entry.is_a?(Hash) && entry.all? { |k, x| keys.include?(k.to_s) && (x.nil? || x.is_a?(String)) }
299
+ end
300
+ end.to_h { |k, entry| [k.to_s, entry.to_h { |ek, ev| [ek.to_s, ev] }] }
301
+ end
302
+
303
+ def fetch_key(hash, key)
304
+ hash.key?(key) ? hash[key] : hash[key.to_sym]
305
+ end
306
+
307
+ def see_all?(value)
308
+ return false unless value.is_a?(Hash)
309
+
310
+ href = fetch_key(value, 'href')
311
+ text = fetch_key(value, 'text')
312
+ href.is_a?(String) && safe_href?(href) && (text.nil? || text.is_a?(String))
313
+ end
314
+
315
+ def safe_href?(value)
316
+ ABSOLUTE.match?(value) || (value != '' && !CONTROL.match?(value) && !SCHEME.match?(value))
317
+ end
318
+
319
+ private_class_method :build_groups, :get, :pair, :common_folder, :rank, :check_manifest, :integral?,
320
+ :positive_integral?, :boolean?, :opt, :strings, :texts, :fetch_key, :see_all?, :safe_href?
321
+ end
322
+ end
323
+
324
+ require_relative 'gallery/renderer'
325
+ require_relative 'gallery/engine' if defined?(Rails::Engine)
metadata ADDED
@@ -0,0 +1,53 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: visualci-gallery
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - DocSpring
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Fetches a VisualCI public gallery manifest and renders a screenshots
13
+ page (tabs, light and dark, desktop and phone, a full-size view) as the markup the
14
+ visualci-gallery JS library hydrates. Includes a Rails helper and the library's
15
+ script and stylesheet for the asset pipeline.
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - app/assets/javascripts/visualci_gallery.js
23
+ - app/assets/stylesheets/visualci_gallery.css
24
+ - lib/visualci/gallery.rb
25
+ - lib/visualci/gallery/engine.rb
26
+ - lib/visualci/gallery/renderer.rb
27
+ - lib/visualci/gallery/version.rb
28
+ homepage: https://visualci.com/docs/gallery/
29
+ licenses:
30
+ - Apache-2.0
31
+ metadata:
32
+ homepage_uri: https://visualci.com/docs/gallery/
33
+ source_code_uri: https://github.com/DocSpring/visualci/tree/main/clients/gallery/ruby
34
+ bug_tracker_uri: https://github.com/DocSpring/visualci/issues
35
+ rubygems_mfa_required: 'true'
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '3.1'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubygems_version: 3.6.9
51
+ specification_version: 4
52
+ summary: A screenshots page from a VisualCI public gallery, rendered in Ruby or Rails
53
+ test_files: []