trmnl_preview 0.28.0 → 0.29.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: 73458f9c8bc2782cf56c7e5e2ceb2e9b06e16fdc865ee68787a90cd11ab3930d
4
- data.tar.gz: 59de88bc00c8168785fe2117b008eed21f4fac9b85d5ef32546882787060624b
3
+ metadata.gz: 323b81319ed9997a0d49fb77fbe563b30464e7b92ba533388f8d619b68d2426e
4
+ data.tar.gz: 4ebe10b57d8815de4efb146c3ad4fa2376f8723160f4ae83748162620d38b716
5
5
  SHA512:
6
- metadata.gz: 58865958ff6709443c7a8789757ce6b7951088561229edf1771db2c80c4dab318dabc6be36f81a75200878adc85111b025d0a36fb90ba74d72dae8adfaa5be7f
7
- data.tar.gz: 4e8e15211854ebae382e7f8deaacda24217e2e1a6f77c7aafafe0199e57c0919c4ac170ec7a38953fe2a5e59ac334b469e229b5bb19d0955cfeceace62f9df83
6
+ metadata.gz: 99afef29e4890046747621ad575e45b7d51fb93c676921f32efb35c585f84fbfe160839b3d1f77b3cce319699fe187c302f0e498bda27de56a1982a9bfdc81e1
7
+ data.tar.gz: 3190bf99270ccf553479edbb4f3bf97027216f0d147156a8c2ec57301ce533ed100bf0d9e4dd99cb876af740bee4ba0007ef433d6ad8670fb349b11f52c841fb
data/CHANGELOG.md CHANGED
@@ -1,6 +1,13 @@
1
1
 
2
2
  # Changelog
3
3
 
4
+ ## 0.29.0
5
+
6
+ - `trmnlp test` fails a screen that draws text over other text, or content text under the title bar, and names both texts, such as a name printed across the last line of a quote. Only glyphs that share inked pixels count, so a unit tucked against a number passes.
7
+ - `trmnlp test`'s publishable recipe group fails "has a mock for every request it makes" when the polling or the transform asks for a url no mock answers, and names each url without its query. Such a request is answered with status 599, so the screens drew the error state as if the API had failed. The matcher is `have_a_mock_for_every_request`.
8
+ - `trmnlp test` checks each view in dark mode on the TRMNL X: a view fails when its layout keeps less than half its content, as when text, lines or icons are drawn in a fixed black and stay black on the black screen. Pass `dark_mode_screen:` to the shared group to check another screen.
9
+ - `trmnlp test` fails a screen where the Framework clamped text whose full text fits on one line in the width its parent gives it, such as a chart title cut to `Egg Pric...`. It names the cut text and the full text.
10
+
4
11
  ## 0.28.0
5
12
 
6
13
  - `trmnlp test`, `serve` and `build --png` close their headless Firefox when they exit. Each run left one running, with nothing left to stop it, and a loop of runs could fill memory and swap.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'mini_magick'
4
+
5
+ module TRMNLP
6
+ module Testing
7
+ # How many pixels of a PNG stand out from its background, the gray level most pixels have; area: a box
8
+ # counts only inside it.
9
+ class InkCount
10
+ # Half the gray scale: text and lines pass; a faint tint or frame does not, on white or on black.
11
+ MIN_DIFFERENCE = 128
12
+
13
+ def initialize(path, area: nil)
14
+ @path = path
15
+ @area = area
16
+ end
17
+
18
+ def pixels
19
+ levels = histogram
20
+ return 0 if levels.empty?
21
+
22
+ background = levels.max_by(&:last).first
23
+ levels.sum { |level, count| (level - background).abs > MIN_DIFFERENCE ? count : 0 }
24
+ end
25
+
26
+ private
27
+
28
+ # [gray level 0-255, pixel count] for each level the picture uses.
29
+ def histogram
30
+ output = MiniMagick.convert do |convert|
31
+ convert << @path
32
+ convert << '-crop' << crop_geometry << '+repage' if @area
33
+ convert << '-colorspace' << 'gray' << '-depth' << '8' << '-format' << '%c' << 'histogram:info:-'
34
+ end
35
+ output.lines.filter_map do |line|
36
+ (match = line.match(/\A\s*(\d+):\s*\(\s*(\d+)/)) && [match[2].to_i, match[1].to_i]
37
+ end
38
+ end
39
+
40
+ def crop_geometry = "#{@area.width.round}x#{@area.height.round}+#{@area.left.round}+#{@area.top.round}"
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,96 @@
1
+ const shown = (el) => el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
2
+ const intersect = (a, b) => ({ left: Math.max(a.left, b.left), top: Math.max(a.top, b.top),
3
+ right: Math.min(a.right, b.right), bottom: Math.min(a.bottom, b.bottom) });
4
+ const area = (r) => Math.max(0, r.right - r.left) * Math.max(0, r.bottom - r.top);
5
+ const covers = (a, b, share) => area(intersect(a, b)) > Math.min(area(a), area(b)) * share;
6
+ const visiblePart = (rect, el) => {
7
+ let part = rect;
8
+ for (let parent = el; parent; parent = parent.parentElement) {
9
+ if (getComputedStyle(parent).overflow !== 'visible') part = intersect(part, parent.getBoundingClientRect());
10
+ }
11
+ return part;
12
+ };
13
+ const textMeasuringContext = document.createElement('canvas').getContext('2d');
14
+ // A text range's box is as tall as its line, so the font's own box sits in the middle of it.
15
+ const baselineOf = (rect, metrics) => rect.top + metrics.fontBoundingBoxAscent +
16
+ (rect.height - metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2;
17
+ const inkOf = (rect, text, style, oneLine) => {
18
+ textMeasuringContext.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
19
+ const metrics = textMeasuringContext.measureText(text);
20
+ const baseline = baselineOf(rect, metrics);
21
+ const left = oneLine ? rect.left - metrics.actualBoundingBoxLeft : rect.left;
22
+ const right = oneLine ? rect.left + metrics.actualBoundingBoxRight : rect.right;
23
+ return { left, right, top: baseline - metrics.actualBoundingBoxAscent,
24
+ bottom: baseline + metrics.actualBoundingBoxDescent };
25
+ };
26
+ const texts = [];
27
+ const range = document.createRange();
28
+ const walker = document.createTreeWalker(document.querySelector('.view') || document.body, NodeFilter.SHOW_TEXT);
29
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
30
+ const owner = node.parentElement;
31
+ if (!node.data.trim() || owner instanceof SVGElement || owner.closest('script, style, svg') || !shown(owner)) continue;
32
+ range.selectNodeContents(node);
33
+ const style = getComputedStyle(owner);
34
+ const lines = [...range.getClientRects()];
35
+ lines.map((rect) => visiblePart(inkOf(rect, node.data.trim(), style, lines.length === 1), owner))
36
+ .filter((rect) => area(rect) > 4)
37
+ .forEach((rect) => texts.push({ node, owner, rect, text: node.data.trim().slice(0, 40) }));
38
+ }
39
+ const SHARED_INK_PIXELS = 4;
40
+ const glyphCache = new Map();
41
+ const glyphsOf = (node) => {
42
+ if (glyphCache.has(node)) return glyphCache.get(node);
43
+ const style = getComputedStyle(node.parentElement);
44
+ const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
45
+ const glyphs = [];
46
+ for (let start = 0; start < node.data.length;) {
47
+ const end = start + String.fromCodePoint(node.data.codePointAt(start)).length;
48
+ const glyph = node.data.slice(start, end);
49
+ if (glyph.trim()) {
50
+ range.setStart(node, start);
51
+ range.setEnd(node, end);
52
+ [...range.getClientRects()].forEach((rect) => {
53
+ textMeasuringContext.font = font;
54
+ const metrics = textMeasuringContext.measureText(glyph);
55
+ const box = visiblePart(inkOf(rect, glyph, style, false), node.parentElement);
56
+ if (area(box) > 1) glyphs.push({ glyph, font, box, x: rect.left, baseline: baselineOf(rect, metrics) });
57
+ });
58
+ }
59
+ start = end;
60
+ }
61
+ glyphCache.set(node, glyphs);
62
+ return glyphs;
63
+ };
64
+ // Draws each glyph where the page put it and counts the pixels both inked, so a glyph tucked into the
65
+ // empty corner of another glyph's box does not count.
66
+ const inkPixels = (glyph, region) => {
67
+ const canvas = document.createElement('canvas');
68
+ canvas.width = Math.ceil(region.right - region.left);
69
+ canvas.height = Math.ceil(region.bottom - region.top);
70
+ const context = canvas.getContext('2d');
71
+ context.font = glyph.font;
72
+ context.fillText(glyph.glyph, glyph.x - region.left, glyph.baseline - region.top);
73
+ const alpha = context.getImageData(0, 0, canvas.width, canvas.height).data;
74
+ const inked = new Set();
75
+ for (let i = 3; i < alpha.length; i += 4) if (alpha[i] > 127) inked.add(i);
76
+ return inked;
77
+ };
78
+ const inkOverlaps = (one, other) => {
79
+ const shared = intersect(one.box, other.box);
80
+ if (area(shared) < 1) return false;
81
+ const otherInk = inkPixels(other, shared);
82
+ return [...inkPixels(one, shared)].filter((pixel) => otherInk.has(pixel)).length >= SHARED_INK_PIXELS;
83
+ };
84
+ const inkTouches = (a, b) => glyphsOf(a.node).some((glyph) => glyphsOf(b.node).some((other) => inkOverlaps(glyph, other)));
85
+ const related = (a, b) => a === b || a.contains(b) || b.contains(a);
86
+ const found = [];
87
+ texts.forEach((a, i) => texts.slice(i + 1).forEach((b) => {
88
+ if (!related(a.owner, b.owner) && covers(a.rect, b.rect, 0) && inkTouches(a, b)) found.push(`"${a.text}" and "${b.text}"`);
89
+ }));
90
+ const titleBar = document.querySelector('.view .title_bar');
91
+ if (titleBar) {
92
+ const bar = titleBar.getBoundingClientRect();
93
+ texts.filter((t) => !titleBar.contains(t.owner) && covers(t.rect, bar, 1 / 3))
94
+ .forEach((t) => found.push(`"${t.text}" and the title bar`));
95
+ }
96
+ return [...new Set(found)];
@@ -18,6 +18,9 @@ module TRMNLP
18
18
  }.freeze
19
19
  # A field with more options than this is drawn with its first and last.
20
20
  PUBLISHABLE_RECIPE_MAX_OPTIONS = 20
21
+ # Share of a layout's ink its dark mode render must keep. Of 17 recipes measured on 10-13, those that draw
22
+ # well in dark mode kept 85% or more; those whose text turned black on black kept 0% to 15%.
23
+ DARK_MODE_MIN_INK_KEPT = 0.5
21
24
 
22
25
  # Each select field's keyname and the values its options save, from the plugin's settings.yml.
23
26
  def self.select_field_values
@@ -32,14 +35,18 @@ module TRMNLP
32
35
  end
33
36
 
34
37
  # rubocop:disable-next Metrics/BlockLength -- one shared group, one check per example
35
- RSpec.shared_examples 'a publishable recipe' do |screens: TRMNLP::Testing::PUBLISHABLE_RECIPE_SCREENS|
38
+ RSpec.shared_examples 'a publishable recipe' do |screens: TRMNLP::Testing::PUBLISHABLE_RECIPE_SCREENS,
39
+ dark_mode_screen: { device: 'v2' }|
36
40
  let(:recipe_inputs) do
37
41
  { mocks: respond_to?(:mocks) ? mocks : {}, custom_fields: respond_to?(:custom_fields) ? custom_fields : {},
38
42
  variables: respond_to?(:variables) ? variables : {}, now: respond_to?(:now) ? now : nil,
39
43
  data: respond_to?(:data) ? data : nil }
40
44
  end
41
45
 
42
- def draw_cleanly = have_no_problems.and(have_no_leaked_text)
46
+ def draw_cleanly
47
+ have_no_problems.and(have_no_leaked_text)
48
+ .and(have_no_text_clamped_with_room_to_spare).and(have_no_overlapping_text)
49
+ end
43
50
 
44
51
  TRMNLP::Testing::PUBLISHABLE_RECIPE_VIEWS.product(screens).each do |view, screen|
45
52
  device = screen[:device].is_a?(Hash) ? screen[:device][:model] : screen[:device]
@@ -51,6 +58,13 @@ RSpec.shared_examples 'a publishable recipe' do |screens: TRMNLP::Testing::PUBLI
51
58
  end
52
59
  end
53
60
 
61
+ TRMNLP::Testing::PUBLISHABLE_RECIPE_VIEWS.each do |view|
62
+ it "keeps the #{view} view's content in dark mode" do
63
+ light = trmnl.render(view:, **dark_mode_screen, **recipe_inputs)
64
+ expect(trmnl.render(view:, **dark_mode_screen, **recipe_inputs, dark_mode: true)).to keep_the_content_of(light)
65
+ end
66
+ end
67
+
54
68
  TRMNLP::Testing::PUBLISHABLE_RECIPE_API_FAILURES.each do |failure, answer|
55
69
  it "draws the full view when the API #{failure}" do
56
70
  screen = trmnl.render(**screens.first, **recipe_inputs, mocks: { '*' => answer })
@@ -67,6 +81,10 @@ RSpec.shared_examples 'a publishable recipe' do |screens: TRMNLP::Testing::PUBLI
67
81
  end
68
82
  end
69
83
 
84
+ it 'has a mock for every request it makes' do
85
+ expect(trmnl.transform(device: screens.first[:device], **recipe_inputs)).to have_a_mock_for_every_request
86
+ end
87
+
70
88
  it 'runs its transform without error' do
71
89
  expect(trmnl.transform(device: screens.first[:device], **recipe_inputs).error).to be_nil
72
90
  end
@@ -10,6 +10,7 @@ require_relative '../browser_pool'
10
10
  require_relative '../firefox_driver'
11
11
  require_relative 'browser'
12
12
  require_relative 'certificate_authority'
13
+ require_relative 'ink_count'
13
14
  require_relative 'page_server'
14
15
  require_relative 'plugin'
15
16
  require_relative 'report'
@@ -75,6 +76,49 @@ RSpec::Matchers.define :have_no_transform_error do
75
76
  failure_message { |screen| "expected the transform to run without error, but: #{screen.result.error}" }
76
77
  end
77
78
 
79
+ # A request no mock answers gets status 599, which draws the plugin's error screen as if its API failed.
80
+ RSpec::Matchers.define :have_a_mock_for_every_request do
81
+ def unmocked(run) = run.requests.reject { it[:mocked] }.map { "#{it[:method]} #{it[:url].split('?', 2).first}" }.uniq
82
+
83
+ match { |run| unmocked(run).empty? }
84
+ failure_message do |run|
85
+ "expected a mock for every request, but none answers: #{unmocked(run).join(', ')}. " \
86
+ 'Add them to tests/mocks.json; without one the screen shows the error state.'
87
+ end
88
+ end
89
+
90
+ # Dark mode recolors the Framework's text and lines; anything drawn in a fixed black stays black on the black screen.
91
+ RSpec::Matchers.define :keep_the_content_of do |light|
92
+ match do |dark|
93
+ @light, @dark = [light, dark].map { TRMNLP::Testing::InkCount.new(it.png_path, area: content_box(it)).pixels }
94
+ @light.zero? || @dark >= @light * TRMNLP::Testing::DARK_MODE_MIN_INK_KEPT
95
+ end
96
+ # The layout only: a mashup slot's frame is too faint to count on white but stands out on black.
97
+ def content_box(screen) = screen.has_css?('.layout', wait: false) ? screen.box('.layout') : nil
98
+
99
+ failure_message do |dark|
100
+ "expected #{dark.inspect} in dark mode to keep its content, but it keeps #{(100 * @dark / @light).round}% of " \
101
+ "it (#{@dark} of #{@light} pixels that stand out): text, lines or icons drawn in a fixed black (#000, black) " \
102
+ 'stay black on the black screen. Use currentColor or Framework classes.'
103
+ end
104
+ end
105
+
106
+ RSpec::Matchers.define :have_no_text_clamped_with_room_to_spare do
107
+ match { |screen| screen.clamped_with_room.empty? }
108
+ failure_message do |screen|
109
+ "expected no text cut short with room to spare on #{screen.inspect}, but it cuts: " \
110
+ "#{screen.clamped_with_room.join('; ')}."
111
+ end
112
+ end
113
+
114
+ RSpec::Matchers.define :have_no_overlapping_text do
115
+ match { |screen| screen.overlapping_text.empty? }
116
+ failure_message do |screen|
117
+ "expected no text drawn over other text on #{screen.inspect}, but it draws #{screen.overlapping_text.join('; ')} " \
118
+ 'over each other.'
119
+ end
120
+ end
121
+
78
122
  RSpec::Matchers.define :have_no_problems do
79
123
  match { |screen| screen.problems.empty? }
80
124
  failure_message { |screen| "expected no problems on #{screen.inspect}, but: #{screen.problems.join('; ')}" }
@@ -87,6 +87,34 @@ module TRMNLP
87
87
  }).map(describe);
88
88
  JS
89
89
 
90
+ # Each element the Framework clamped although its full text fits on one line of the width its parent gives it.
91
+ CLAMPED_WITH_ROOM_SCRIPT = <<~JS
92
+ const textMeasuringContext = document.createElement('canvas').getContext('2d');
93
+ const px = (value) => parseFloat(value) || 0;
94
+ const sharesItsRow = (style) => style.display.includes('grid') ||
95
+ (style.display.includes('flex') && !style.flexDirection.startsWith('column'));
96
+ const fullTextWidth = (el, text) => {
97
+ const style = getComputedStyle(el);
98
+ textMeasuringContext.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
99
+ const shown = style.textTransform === 'uppercase' ? text.toUpperCase() : text;
100
+ return textMeasuringContext.measureText(shown).width + px(style.letterSpacing) * shown.length +
101
+ px(style.paddingLeft) + px(style.paddingRight) + px(style.marginLeft) + px(style.marginRight);
102
+ };
103
+ return [...document.querySelectorAll('.view [data-clamp-original]')].filter((el) => {
104
+ const original = el.getAttribute('data-clamp-original').trim();
105
+ const parent = el.parentElement;
106
+ if (!original || el.innerText.trim() === original || !el.getClientRects().length || !parent) return false;
107
+ const parentStyle = getComputedStyle(parent);
108
+ if (sharesItsRow(parentStyle)) return false;
109
+ const room = parent.clientWidth - px(parentStyle.paddingLeft) - px(parentStyle.paddingRight);
110
+ return fullTextWidth(el, original) <= room - 2;
111
+ }).map((el) => `"${el.innerText.trim()}" (all of "${el.getAttribute('data-clamp-original').trim()}" fits)`);
112
+ JS
113
+
114
+ # Pairs of text whose ink is drawn over each other, and text drawn under the title bar. Each line's ink is cut
115
+ # to what its clipping parents show; two count when their glyphs share inked pixels.
116
+ OVERLAPPING_TEXT_SCRIPT = File.read(File.join(__dir__, 'overlapping_text.js')).freeze
117
+
90
118
  HIDDEN_MARK = 'data-trmnlp-hidden'
91
119
  # The DOM with every element Firefox does not draw marked, so Capybara's visible text is what is on screen.
92
120
  DRAWN_DOM_SCRIPT = <<~JS.freeze
@@ -126,6 +154,9 @@ module TRMNLP
126
154
 
127
155
  def overflowing(except: nil) = @browser.on(self) { it.execute_script(OVERFLOW_SCRIPT, except) }
128
156
 
157
+ def clamped_with_room = @browser.on(self) { it.execute_script(CLAMPED_WITH_ROOM_SCRIPT) }
158
+ def overlapping_text = @browser.on(self) { it.execute_script(OVERLAPPING_TEXT_SCRIPT) }
159
+
129
160
  # Script errors, unhandled rejections, console.error lines and files that failed to load.
130
161
  def problems = evaluate('window.__trmnlpProblems || []')
131
162
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module TRMNLP
4
- VERSION = '0.28.0'
4
+ VERSION = '0.29.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: trmnl_preview
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.28.0
4
+ version: 0.29.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rockwell Schrock
@@ -480,10 +480,12 @@ files:
480
480
  - lib/trmnlp/testing/certificate_authority.rb
481
481
  - lib/trmnlp/testing/device_models.rb
482
482
  - lib/trmnlp/testing/frozen_clock.rb
483
+ - lib/trmnlp/testing/ink_count.rb
483
484
  - lib/trmnlp/testing/memory_sampler.rb
484
485
  - lib/trmnlp/testing/mock_proxy.rb
485
486
  - lib/trmnlp/testing/mock_table.rb
486
487
  - lib/trmnlp/testing/node_version.rb
488
+ - lib/trmnlp/testing/overlapping_text.js
487
489
  - lib/trmnlp/testing/page_server.rb
488
490
  - lib/trmnlp/testing/plugin.rb
489
491
  - lib/trmnlp/testing/publishable_recipe.rb