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