@bezda/rhp-mcp 0.1.8 → 0.1.10

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.
Files changed (47) hide show
  1. package/package.json +2 -2
  2. package/skill/SKILL.md +5 -5
  3. package/skill/recipes/area.html +349 -138
  4. package/skill/recipes/bar.html +349 -138
  5. package/skill/recipes/box-plot.html +349 -138
  6. package/skill/recipes/bubble.html +349 -138
  7. package/skill/recipes/bullet.html +349 -138
  8. package/skill/recipes/candlestick.html +349 -138
  9. package/skill/recipes/column.html +349 -138
  10. package/skill/recipes/dial.html +349 -138
  11. package/skill/recipes/diverging-bars.html +349 -138
  12. package/skill/recipes/donut.html +349 -138
  13. package/skill/recipes/dumbbell.html +349 -138
  14. package/skill/recipes/gantt.html +349 -138
  15. package/skill/recipes/grouped-bars.html +349 -138
  16. package/skill/recipes/heatmap.html +349 -138
  17. package/skill/recipes/histogram.html +349 -138
  18. package/skill/recipes/line.html +349 -138
  19. package/skill/recipes/live.html +349 -138
  20. package/skill/recipes/log-line.html +349 -138
  21. package/skill/recipes/lollipop.html +349 -138
  22. package/skill/recipes/multi-line.html +349 -138
  23. package/skill/recipes/pyramid.html +349 -138
  24. package/skill/recipes/race.html +363 -139
  25. package/skill/recipes/radial-bars.html +349 -138
  26. package/skill/recipes/scatter.html +349 -138
  27. package/skill/recipes/silhouettes.html +349 -138
  28. package/skill/recipes/slope.html +349 -138
  29. package/skill/recipes/sparklines.html +349 -138
  30. package/skill/recipes/stacked-100.html +349 -138
  31. package/skill/recipes/stacked-bars.html +349 -138
  32. package/skill/recipes/strip.html +349 -138
  33. package/skill/recipes/tape.html +415 -165
  34. package/skill/recipes/unit-stack.html +349 -138
  35. package/skill/recipes/violin.html +349 -138
  36. package/skill/recipes/waffle.html +349 -138
  37. package/skill/recipes/waterfall.html +349 -138
  38. package/skill/references/api.md +34 -6
  39. package/skill/references/design.md +18 -2
  40. package/skill/references/download.md +372 -140
  41. package/skill/references/environments.md +1 -1
  42. package/skill/references/interaction.md +2 -0
  43. package/skill/references/pitfalls.md +4 -3
  44. package/src/check/README.md +2 -1
  45. package/src/check/findings.js +2 -0
  46. package/src/check/inpage.js +9 -2
  47. package/src/guard/rhp.js +31 -11
@@ -167,7 +167,7 @@ render(() => html`<${SleepByAge} />`, document.getElementById("chart"));
167
167
  </script>
168
168
  <style id="poster-download-styles">
169
169
  .poster-download-tools { display: flex; justify-content: flex-end; align-items: center; margin: 0 auto 12px; max-width: 100%; }
170
- .poster-actions { display: flex; align-items: center; margin-left: auto; }
170
+ .poster-actions { position: relative; display: flex; align-items: center; margin-left: auto; }
171
171
  .poster-download, .poster-fit-toggle { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; width: 44px; height: 44px; padding: 10px; border: 0; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
172
172
  .poster-actions svg { display: block; width: 20px; height: 20px; }
173
173
  .poster-actions button:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
@@ -178,7 +178,14 @@ render(() => html`<${SleepByAge} />`, document.getElementById("chart"));
178
178
  .poster-fit-frame.is-fitted { display: block; margin: 0 auto; overflow: clip; }
179
179
  .poster-fit-frame.is-fitted > .poster-fit-content { display: block; transform-origin: top left; }
180
180
  .poster-download-error { margin: 8px auto; font: 14px/1.4 system-ui, sans-serif; color: inherit; }
181
- @media print { .poster-download-tools, .poster-actions, .poster-download-error { display: none !important; } }
181
+ .poster-download-progress { font: 600 11px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
182
+ .poster-download-menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: 20; display: grid; gap: 2px; min-width: 220px; padding: 6px; border: 1px solid color-mix(in srgb, currentColor 24%, transparent); border-radius: 8px; background: var(--poster-tools-ground, Canvas); box-shadow: 0 8px 24px rgb(0 0 0 / .28); }
183
+ .poster-download-menu[hidden] { display: none; }
184
+ .poster-download-menu button { display: grid; gap: 2px; width: 100%; padding: 8px 10px; border: 0; border-radius: 5px; background: none; color: inherit; font: 600 14px/1.3 system-ui, sans-serif; text-align: left; cursor: pointer; }
185
+ .poster-download-menu button span { font-weight: 400; font-size: 12.5px; opacity: .8; }
186
+ .poster-download-menu button:hover { background: color-mix(in srgb, currentColor 9%, transparent); }
187
+ .poster-download-menu button:focus-visible { outline: 2px solid currentColor; outline-offset: -2px; }
188
+ @media print { .poster-download-tools, .poster-actions, .poster-download-menu, .poster-download-error { display: none !important; } }
182
189
  </style>
183
190
  <script type="module" id="poster-download-script">
184
191
  function addPosterFit(poster, button, changed) {
@@ -256,6 +263,8 @@ function addPosterDownloads() {
256
263
  tools.style.color = light[0] * .2126 + light[1] * .7152 + light[2] * .0722 < .179 ? '#eef2f5' : '#1d1b17';
257
264
  }
258
265
  }
266
+ const ground = getComputedStyle(document.body).backgroundColor;
267
+ if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(ground)) tools.style.setProperty('--poster-tools-ground', ground);
259
268
  const button = document.createElement('button');
260
269
  button.type = 'button';
261
270
  button.className = 'poster-download';
@@ -301,154 +310,356 @@ function addPosterDownloads() {
301
310
  for (const type of ['keydown', 'keyup']) actions.addEventListener(type, event => {
302
311
  if (event.key === 'Enter' || event.key === ' ') event.stopPropagation();
303
312
  });
304
- let exporter, retries = 0, busy = false;
305
- button.addEventListener('click', async event => {
306
- event.stopPropagation();
307
- if (busy) return;
313
+ // A poster that plays through its data gives itself a playback ({ duration, position, seek }): its download then
314
+ // offers the poster as it is now, a PNG, or the whole playback, an animated GIF
315
+ let exporter, encoder, retries = 0, busy = false, making = null, cancelled = false;
316
+ const playable = () => typeof poster.playback?.seek === 'function';
317
+ const icon = button.innerHTML;
318
+ const menu = document.createElement('div');
319
+ menu.className = 'poster-download-menu';
320
+ menu.setAttribute('role', 'menu');
321
+ menu.setAttribute('aria-label', 'Download poster');
322
+ menu.hidden = true;
323
+ menu.innerHTML = '<button type="button" role="menuitem" data-format="png">PNG image<span>The poster as it is now</span></button>'
324
+ + '<button type="button" role="menuitem" data-format="gif">Animated GIF<span>The whole playback</span></button>';
325
+ const items = [...menu.querySelectorAll('[role="menuitem"]')];
326
+ actions.append(menu);
327
+ const label = text => { button.setAttribute('aria-label', text); button.title = text; };
328
+ const rest = () => {
329
+ label(playable() ? 'Download poster' : 'Download poster as PNG');
330
+ if (playable()) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', String(!menu.hidden)); }
331
+ };
332
+ rest();
333
+ const closeMenu = focus => {
334
+ if (menu.hidden) return;
335
+ menu.hidden = true;
336
+ rest();
337
+ if (focus) button.focus();
338
+ };
339
+ const openMenu = focus => {
340
+ menu.hidden = false;
341
+ rest();
342
+ if (focus) items[0].focus();
343
+ };
344
+ document.addEventListener('pointerdown', event => { if (!actions.contains(event.target)) closeMenu(false); }, true);
345
+ menu.addEventListener('keydown', event => {
346
+ const at = items.indexOf(document.activeElement);
347
+ const to = { ArrowDown: at + 1, ArrowUp: at - 1, Home: 0, End: items.length - 1 }[event.key];
348
+ if (to !== undefined) { event.preventDefault(); items[(to + items.length) % items.length].focus(); }
349
+ else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(true); }
350
+ else if (event.key === 'Tab') closeMenu(false);
351
+ });
352
+ menu.addEventListener('focusout', event => { if (!menu.contains(event.relatedTarget) && event.relatedTarget !== button) closeMenu(false); });
353
+ // The capture options, made once for a download and for every frame of a GIF
354
+ const loadExporter = () => (exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : '')));
355
+ async function captureOptions() {
356
+ await document.fonts.ready;
357
+ // Preserve author layout rules where computed styles lose the grid's used geometry.
358
+ // Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
359
+ const autoMargins = new Set(), positioned = new Set();
360
+ const isMargin = name => name === 'margin' || name.startsWith('margin-');
361
+ const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
362
+ const layoutRules = rules => [...rules].map(rule => {
363
+ if (rule.selectorText && rule.style) {
364
+ const margins = [...rule.style].filter(isMargin);
365
+ if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
366
+ const insets = [...rule.style].filter(isInset);
367
+ if (insets.length) positioned.add(rule.selectorText);
368
+ const layout = [...margins, ...insets];
369
+ return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
370
+ }
371
+ if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
372
+ if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
373
+ if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
374
+ return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
375
+ }).join('\n');
376
+ const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
377
+ const layout = sheets.map(sheet => {
378
+ try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
379
+ }).join('\n');
380
+ // Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
381
+ const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
382
+ const restoreLayout = (source, clone) => {
383
+ if (clone.style && source !== poster) {
384
+ const margins = [...autoMargins].some(selector => source.matches(selector));
385
+ const computed = getComputedStyle(source);
386
+ const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
387
+ const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
388
+ [...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
389
+ [...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
390
+ if (insets) {
391
+ // Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
392
+ // Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
393
+ const axis = source.getAttribute('data-rhp-o');
394
+ const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
395
+ fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
396
+ }
397
+ }
398
+ const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
399
+ [...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
400
+ };
401
+ // Cross-origin font stylesheets are readable through fetch, but not through cssRules.
402
+ const fontFiles = new Map();
403
+ const fontRules = await Promise.all(sheets.map(async sheet => {
404
+ let css;
405
+ try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
406
+ catch (cause) {
407
+ if (!sheet.href) return '';
408
+ const response = await fetch(sheet.href);
409
+ if (!response.ok) throw new Error('Font stylesheet could not be loaded');
410
+ css = await response.text();
411
+ }
412
+ const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
413
+ return (await Promise.all(rules.map(async rule => {
414
+ for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
415
+ const source = new URL(match[1], sheet.href || document.baseURI).href;
416
+ if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
417
+ const response = await fetch(source);
418
+ if (!response.ok) throw new Error('Font could not be loaded');
419
+ const blob = await response.blob();
420
+ return new Promise((resolve, reject) => {
421
+ const reader = new FileReader();
422
+ reader.onload = () => resolve(reader.result);
423
+ reader.onerror = reject;
424
+ reader.readAsDataURL(blob);
425
+ });
426
+ })());
427
+ rule = rule.replace(match[1], await fontFiles.get(source));
428
+ }
429
+ return rule;
430
+ }))).join('\n');
431
+ }));
432
+ // Rasterize SVG paper textures before nesting them inside the exporter's SVG.
433
+ // This keeps SVG filter fragment references local to their own image.
434
+ const textures = new Map();
435
+ const embedTexture = async (node) => {
436
+ if (!node.style) return;
437
+ let background = node.style.backgroundImage;
438
+ for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
439
+ if (!textures.has(source)) textures.set(source, (async () => {
440
+ const image = new Image();
441
+ image.src = source;
442
+ await image.decode();
443
+ const canvas = document.createElement('canvas');
444
+ canvas.width = image.naturalWidth;
445
+ canvas.height = image.naturalHeight;
446
+ canvas.getContext('2d').drawImage(image, 0, 0);
447
+ return canvas.toDataURL();
448
+ })());
449
+ background = background.replace(source, await textures.get(source));
450
+ }
451
+ node.style.backgroundImage = background;
452
+ };
453
+ return {
454
+ ...fit.dimensions(), style: { margin: '0' }, filter: includeNode,
455
+ font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
456
+ onCloneNode: clone => {
457
+ restoreLayout(poster, clone);
458
+ const style = document.createElement('style');
459
+ style.textContent = layout;
460
+ clone.prepend(style);
461
+ },
462
+ // CSS content's alternative text follows a slash and must not be painted.
463
+ onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
464
+ style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
465
+ }),
466
+ };
467
+ }
468
+ let url;
469
+ const save = (blob, extension) => {
470
+ url = URL.createObjectURL(blob);
471
+ const link = document.createElement('a');
472
+ const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
473
+ link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.' + extension;
474
+ link.href = url;
475
+ link.addEventListener('click', event => event.stopPropagation(), { once: true });
476
+ document.body.append(link);
477
+ link.click();
478
+ link.remove();
479
+ };
480
+ const begin = kind => {
308
481
  busy = true;
309
- button.setAttribute('aria-disabled', 'true');
482
+ making = kind;
310
483
  button.setAttribute('aria-busy', 'true');
311
484
  fitButton.setAttribute('aria-disabled', 'true');
312
- button.setAttribute('aria-label', 'Preparing poster PNG');
485
+ // A GIF takes a while: the button shows its progress and cancels it
486
+ if (kind === 'gif') label('Cancel the GIF');
487
+ else { button.setAttribute('aria-disabled', 'true'); label('Preparing poster PNG'); }
313
488
  error.hidden = true;
314
- let url;
489
+ };
490
+ const end = () => {
491
+ if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
492
+ url = null;
493
+ busy = false;
494
+ making = null;
495
+ cancelled = false;
496
+ button.innerHTML = icon;
497
+ button.removeAttribute('aria-disabled');
498
+ button.removeAttribute('aria-busy');
499
+ fitButton.removeAttribute('aria-disabled');
500
+ rest();
501
+ };
502
+ const fail = message => {
503
+ exporter = null;
504
+ encoder = null;
505
+ retries++;
506
+ error.textContent = message;
507
+ error.hidden = false;
508
+ };
509
+ async function savePng() {
510
+ begin('png');
315
511
  try {
316
- exporter ||= import('https://cdn.jsdelivr.net/npm/modern-screenshot@4.7.0/+esm' + (retries ? `?retry=${retries}` : ''));
317
- const { domToBlob } = await exporter;
318
- await document.fonts.ready;
319
- // Preserve author layout rules where computed styles lose the grid's used geometry.
320
- // Safari misreports percentage insets in subgrids, and grid auto margins resolve to zero.
321
- const autoMargins = new Set(), positioned = new Set();
322
- const isMargin = name => name === 'margin' || name.startsWith('margin-');
323
- const isInset = name => name === 'inset' || name.startsWith('inset-') || ['top', 'right', 'bottom', 'left'].includes(name);
324
- const layoutRules = rules => [...rules].map(rule => {
325
- if (rule.selectorText && rule.style) {
326
- const margins = [...rule.style].filter(isMargin);
327
- if (margins.some(name => /\bauto\b/.test(rule.style.getPropertyValue(name)))) autoMargins.add(rule.selectorText);
328
- const insets = [...rule.style].filter(isInset);
329
- if (insets.length) positioned.add(rule.selectorText);
330
- const layout = [...margins, ...insets];
331
- return layout.length ? `${rule.selectorText} { ${layout.map(name => `${name}: ${rule.style.getPropertyValue(name)}${rule.style.getPropertyPriority(name) ? ' !important' : ''};`).join(' ')} }` : '';
332
- }
333
- if (!rule.cssRules) return /^@layer\b/.test(rule.cssText) ? rule.cssText : '';
334
- if (rule instanceof CSSMediaRule) return matchMedia(rule.conditionText).matches ? layoutRules(rule.cssRules) : '';
335
- if (rule instanceof CSSSupportsRule) return CSS.supports(rule.conditionText) ? layoutRules(rule.cssRules) : '';
336
- return rule.cssText.slice(0, rule.cssText.indexOf('{') + 1) + layoutRules(rule.cssRules) + '}';
337
- }).join('\n');
338
- const sheets = [...document.styleSheets, ...document.adoptedStyleSheets];
339
- const layout = sheets.map(sheet => {
340
- try { return layoutRules(sheet.cssRules); } catch (cause) { return ''; }
341
- }).join('\n');
342
- // Omit display-none HTML subtrees, such as collapsed chart rows, from the image and its SVG payload.
343
- const includeNode = node => !(node instanceof HTMLElement) || getComputedStyle(node).display !== 'none';
344
- const restoreLayout = (source, clone) => {
345
- if (clone.style && source !== poster) {
346
- const margins = [...autoMargins].some(selector => source.matches(selector));
347
- const computed = getComputedStyle(source);
348
- const insets = computed.position === 'absolute' && [...positioned].some(selector => source.matches(selector));
349
- const restore = name => (margins && isMargin(name)) || (insets && isInset(name));
350
- [...clone.style].filter(restore).forEach(name => clone.style.removeProperty(name));
351
- [...source.style].filter(restore).forEach(name => clone.style.setProperty(name, source.style.getPropertyValue(name), source.style.getPropertyPriority(name)));
352
- if (insets) {
353
- // Only the scaled axis needs its percentage rule. Freeze the other axis in pixels:
354
- // Firefox does not reevaluate container queries reliably inside an SVG foreignObject.
355
- const axis = source.getAttribute('data-rhp-o');
356
- const fixed = axis === 'h' ? ['top', 'bottom'] : axis === 'v' ? ['left', 'right'] : ['top', 'right', 'bottom', 'left'];
357
- fixed.forEach(name => clone.style.setProperty(name, computed.getPropertyValue(name), 'important'));
512
+ const { domToBlob } = await loadExporter();
513
+ const blob = await domToBlob(poster, { ...(await captureOptions()), scale: 2 });
514
+ if (!blob) throw new Error('No PNG was created');
515
+ save(blob, 'png');
516
+ } catch (cause) {
517
+ fail('The PNG could not be saved. Check your connection and try again.');
518
+ } finally {
519
+ end();
520
+ }
521
+ }
522
+ // The GIF's clock: while it is made, rhp's motion (performance.now and animation frames) and the page's CSS
523
+ // animations run on a time of their own, which only moves on when a frame asks it to, so every frame shows the chart
524
+ // exactly as it is that many milliseconds into playing, its glides and slides included
525
+ const gifClock = () => {
526
+ const raf = window.requestAnimationFrame, caf = window.cancelAnimationFrame;
527
+ const queue = new Map(), started = new Map();
528
+ let time = performance.now(), id = 0, pump = 0;
529
+ const flush = () => {
530
+ const due = [...queue.values()];
531
+ queue.clear();
532
+ due.forEach(callback => { try { callback(time); } catch (cause) { reportError(cause); } });
533
+ };
534
+ // Callbacks still run every real frame, at the clock's time, so whatever waits for a frame is not held up
535
+ const loop = () => { flush(); pump = raf.call(window, loop); };
536
+ window.requestAnimationFrame = callback => { queue.set(++id, callback); return id; };
537
+ window.cancelAnimationFrame = n => queue.delete(n);
538
+ performance.now = () => time;
539
+ pump = raf.call(window, loop);
540
+ return {
541
+ // Two of the browser's frames: callbacks that were already waiting for one (rhp's ticker) come over to the clock
542
+ ready: new Promise(resolve => raf.call(window, () => raf.call(window, resolve))),
543
+ advance(ms, steps = 1) {
544
+ for (let i = 0; i < steps; i++) {
545
+ time += ms / steps;
546
+ // A frame's motion, then the style writes it schedules
547
+ flush(); flush(); flush();
548
+ for (const animation of document.getAnimations()) {
549
+ if (!started.has(animation)) started.set(animation, time - (animation.currentTime ?? 0));
550
+ animation.pause();
551
+ animation.currentTime = time - started.get(animation);
358
552
  }
359
553
  }
360
- const children = [...source.children].filter(node => !['STYLE', 'SCRIPT'].includes(node.tagName) && includeNode(node));
361
- [...clone.children].forEach((child, i) => { if (children[i]) restoreLayout(children[i], child); });
554
+ },
555
+ stop() {
556
+ caf.call(window, pump);
557
+ window.requestAnimationFrame = raf;
558
+ window.cancelAnimationFrame = caf;
559
+ delete performance.now;
560
+ for (const callback of queue.values()) raf.call(window, callback);
561
+ started.forEach((_, animation) => animation.play());
562
+ },
563
+ };
564
+ };
565
+ // The GIF: the playback at its own pace, 25 frames a second, at most 1200 pixels wide. One palette from the
566
+ // first and the last frame serves every frame; its last color is never drawn and marks the pixels a frame leaves as
567
+ // the frame before had them, so each frame stores only what changed.
568
+ async function saveGif() {
569
+ const playback = poster.playback;
570
+ const from = playback.position();
571
+ let clock = null;
572
+ begin('gif');
573
+ try {
574
+ encoder ||= import('https://cdn.jsdelivr.net/npm/gifenc@1.0.3/+esm' + (retries ? `?retry=${retries}` : ''));
575
+ const [{ domToCanvas }, { GIFEncoder, quantize, applyPalette }] = await Promise.all([loadExporter(), encoder]);
576
+ const options = await captureOptions();
577
+ const scale = Math.min(1, 1200 / options.width);
578
+ // The GIF plays at the chart's own pace: its playback's duration, in frames 40 ms apart
579
+ const step = 40, count = Math.max(2, Math.round((playback.duration ?? 15000) / step) + 1);
580
+ const capture = async () => {
581
+ const canvas = await domToCanvas(poster, { ...options, scale });
582
+ return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
362
583
  };
363
- // Cross-origin font stylesheets are readable through fetch, but not through cssRules.
364
- const fontFiles = new Map();
365
- const fontRules = await Promise.all(sheets.map(async sheet => {
366
- let css;
367
- try { css = [...sheet.cssRules].map(rule => rule.cssText).join('\n'); }
368
- catch (cause) {
369
- if (!sheet.href) return '';
370
- const response = await fetch(sheet.href);
371
- if (!response.ok) throw new Error('Font stylesheet could not be loaded');
372
- css = await response.text();
373
- }
374
- const rules = css.match(/@font-face\s*\{[^}]*\}/g) || [];
375
- return (await Promise.all(rules.map(async rule => {
376
- for (const match of [...rule.matchAll(/url\(["']?([^"')]+)["']?\)/g)]) {
377
- const source = new URL(match[1], sheet.href || document.baseURI).href;
378
- if (!fontFiles.has(source)) fontFiles.set(source, (async () => {
379
- const response = await fetch(source);
380
- if (!response.ok) throw new Error('Font could not be loaded');
381
- const blob = await response.blob();
382
- return new Promise((resolve, reject) => {
383
- const reader = new FileReader();
384
- reader.onload = () => resolve(reader.result);
385
- reader.onerror = reject;
386
- reader.readAsDataURL(blob);
387
- });
388
- })());
389
- rule = rule.replace(match[1], await fontFiles.get(source));
390
- }
391
- return rule;
392
- }))).join('\n');
393
- }));
394
- // Rasterize SVG paper textures before nesting them inside the exporter's SVG.
395
- // This keeps SVG filter fragment references local to their own image.
396
- const textures = new Map();
397
- const embedTexture = async (node) => {
398
- if (!node.style) return;
399
- let background = node.style.backgroundImage;
400
- for (const [, source] of background.matchAll(/url\("(data:image\/svg\+xml[^"]+)"\)/g)) {
401
- if (!textures.has(source)) textures.set(source, (async () => {
402
- const image = new Image();
403
- image.src = source;
404
- await image.decode();
405
- const canvas = document.createElement('canvas');
406
- canvas.width = image.naturalWidth;
407
- canvas.height = image.naturalHeight;
408
- canvas.getContext('2d').drawImage(image, 0, 0);
409
- return canvas.toDataURL();
410
- })());
411
- background = background.replace(source, await textures.get(source));
584
+ clock = gifClock();
585
+ await clock.ready;
586
+ // The end and the start, each given a second to settle, for the palette; the start is also the first frame
587
+ playback.seek(1);
588
+ clock.advance(1000, 25);
589
+ const last = await capture();
590
+ playback.seek(0);
591
+ clock.advance(1000, 25);
592
+ const first = await capture();
593
+ const both = new Uint8ClampedArray(first.data.length + last.data.length);
594
+ both.set(first.data);
595
+ both.set(last.data, first.data.length);
596
+ const palette = quantize(both, 255), kept = palette.length;
597
+ // A flat color that fills a part of the poster keeps its exact value: it takes the nearest palette entry
598
+ const counts = new Map(), taken = new Set();
599
+ for (let j = 0; j < both.length; j += 4) {
600
+ const color = (both[j] << 16) | (both[j + 1] << 8) | both[j + 2];
601
+ counts.set(color, (counts.get(color) ?? 0) + 1);
602
+ }
603
+ for (const [color] of [...counts].filter(([, n]) => n > both.length / 8000).sort((a, b) => b[1] - a[1])) {
604
+ const rgb = [color >> 16, (color >> 8) & 255, color & 255];
605
+ let nearest = -1, distance = Infinity;
606
+ palette.forEach((entry, k) => {
607
+ const d = (entry[0] - rgb[0]) ** 2 + (entry[1] - rgb[1]) ** 2 + (entry[2] - rgb[2]) ** 2;
608
+ if (!taken.has(k) && d < distance) { nearest = k; distance = d; }
609
+ });
610
+ if (nearest >= 0) { palette[nearest] = rgb; taken.add(nearest); }
611
+ }
612
+ palette.push([255, 0, 255]);
613
+ const gif = GIFEncoder();
614
+ let previous = null;
615
+ for (let i = 0; i < count; i++) {
616
+ if (cancelled) return;
617
+ if (i > 0) {
618
+ playback.seek(i / (count - 1));
619
+ clock.advance(step);
620
+ // The last frame is held: it shows the end settled
621
+ if (i === count - 1) clock.advance(1000, 25);
412
622
  }
413
- node.style.backgroundImage = background;
414
- };
415
- const blob = await domToBlob(poster, {
416
- ...fit.dimensions(), scale: 2, style: { margin: '0' }, filter: includeNode,
417
- font: { cssText: fontRules.join('\n') }, onCloneEachNode: embedTexture,
418
- onCloneNode: clone => {
419
- restoreLayout(poster, clone);
420
- const style = document.createElement('style');
421
- style.textContent = layout;
422
- clone.prepend(style);
423
- },
424
- // CSS content's alternative text follows a slash and must not be painted.
425
- onCreateForeignObjectSvg: svg => svg.querySelectorAll('style').forEach(style => {
426
- style.textContent = style.textContent.replace(/(content:\s*')([^']*)(')/g, (_, start, text, end) => start + text.split(' / ')[0] + end);
427
- }),
428
- });
429
- if (!blob) throw new Error('No PNG was created');
430
- url = URL.createObjectURL(blob);
431
- const link = document.createElement('a');
432
- const title = poster.querySelector('.headline')?.textContent || document.title || 'poster';
433
- link.download = (title.trim().toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '').slice(0, 100) || 'poster') + '.png';
434
- link.href = url;
435
- link.addEventListener('click', event => event.stopPropagation(), { once: true });
436
- document.body.append(link);
437
- link.click();
438
- link.remove();
623
+ const image = i === 0 ? first : await capture();
624
+ const index = applyPalette(image.data, palette.slice(0, kept));
625
+ const pixels = previous ? index.map((p, j) => (p === previous[j] ? kept : p)) : index;
626
+ gif.writeFrame(pixels, image.width, image.height, {
627
+ palette: i === 0 ? palette : undefined, delay: i === 0 ? 1000 : i === count - 1 ? 3000 : step,
628
+ transparent: i > 0, transparentIndex: kept, dispose: 1,
629
+ });
630
+ previous = index;
631
+ const done = Math.round(((i + 1) / count) * 100);
632
+ button.innerHTML = `<span class="poster-download-progress" aria-hidden="true">${done}%</span>`;
633
+ label(`Cancel the GIF, ${done}% made`);
634
+ }
635
+ gif.finish();
636
+ save(new Blob([gif.bytes()], { type: 'image/gif' }), 'gif');
439
637
  } catch (cause) {
440
- exporter = null;
441
- retries++;
442
- error.textContent = 'The PNG could not be saved. Check your connection and try again.';
443
- error.hidden = false;
638
+ fail('The GIF could not be made. Check your connection and try again.');
444
639
  } finally {
445
- if (url) setTimeout(() => URL.revokeObjectURL(url), 60000);
446
- busy = false;
447
- button.removeAttribute('aria-disabled');
448
- button.removeAttribute('aria-busy');
449
- fitButton.removeAttribute('aria-disabled');
450
- button.setAttribute('aria-label', 'Download poster as PNG');
640
+ clock?.stop();
641
+ playback.seek(from);
642
+ end();
643
+ }
644
+ }
645
+ button.addEventListener('click', event => {
646
+ event.stopPropagation();
647
+ if (busy) {
648
+ if (making === 'gif') cancelled = true;
649
+ return;
451
650
  }
651
+ if (!playable()) return savePng();
652
+ // A key press is a click with no pointer detail: it opens the menu on its first item
653
+ if (menu.hidden) openMenu(event.detail === 0);
654
+ else closeMenu(event.detail === 0);
655
+ });
656
+ menu.addEventListener('click', event => {
657
+ const item = event.target.closest('[data-format]');
658
+ if (!item) return;
659
+ event.stopPropagation();
660
+ closeMenu(event.detail === 0);
661
+ if (item.dataset.format === 'gif') saveGif();
662
+ else savePng();
452
663
  });
453
664
  tools.append(actions);
454
665
  });