adapt-canvas.mjs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Explicit authoring helper. It never runs during pack loading or changes the source template.
  2. import { createHash } from 'node:crypto';
  3. import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
  4. import { dirname, extname, resolve } from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. const sourcePath = fileURLToPath(new URL('../design-resources/skills/infinite-canvas/assets/infinite-canvas-template.html', import.meta.url));
  7. const sourceSha256 = '50228cdd4d4b7a2584f8d66e1cbd64cd06c4718005dcbdb2332c997ee7c665d1';
  8. export function adaptCanvasTemplate(html) {
  9. if (createHash('sha256').update(html, 'utf8').digest('hex') !== sourceSha256) {
  10. throw new Error('Canvas source changed; review the adaptations and update the pinned source hash before generating a draft.');
  11. }
  12. const edits = [
  13. ['</style>', '@media (prefers-reduced-motion: reduce) {\n *, *::before, *::after { animation: none !important; transition: none !important; }\n }\n</style>'],
  14. ["'Undo / Redo'", "'Undo layout changes'"],
  15. ["kbdHints: [['Scroll', 'pan'], ['\\u2318Scroll', 'zoom'], ['\\u2318Z', 'undo']],", "kbdHints: [['Scroll', 'pan'], ['Ctrl / ⌘ + Scroll', 'zoom'], ['Ctrl / ⌘ + Z', 'undo']],"],
  16. ["document.addEventListener('keydown', (e) => {", "document.addEventListener('keydown', (e) => {\n if (e.target instanceof Element && e.target.closest('input, textarea, select, [contenteditable]')) return;"],
  17. ['if (e.button !== 0) return;', "if (e.button !== 0 || (e.target instanceof Element && e.target.closest('button, a, input, textarea, select, [contenteditable]'))) return;"],
  18. ];
  19. for (const [before, after] of edits) {
  20. if (html.split(before).length !== 2) throw new Error('Canvas adaptation anchor must occur exactly once.');
  21. html = html.replace(before, after);
  22. }
  23. return html;
  24. }
  25. // Stdin and synthetic entry paths need not resolve when this helper is imported.
  26. const scriptPath = process.argv[1];
  27. const entryPath = scriptPath === undefined ? undefined : await realpath(scriptPath).catch(() => undefined);
  28. if (entryPath === fileURLToPath(import.meta.url)) {
  29. try {
  30. if (process.argv.length !== 3 || extname(process.argv[2]).toLowerCase() !== '.html') {
  31. throw new Error('Usage: node adapt-canvas.mjs <new-output.html>');
  32. }
  33. const outputPath = resolve(process.argv[2]);
  34. const html = adaptCanvasTemplate(await readFile(sourcePath, 'utf8'));
  35. await mkdir(dirname(outputPath), { recursive: true });
  36. await writeFile(outputPath, html, { encoding: 'utf8', flag: 'wx' });
  37. console.log(outputPath);
  38. } catch (error) {
  39. console.error(error instanceof Error ? error.message : String(error));
  40. process.exitCode = 1;
  41. }
  42. }