iso-explainer 0.0.0-stage → 1.0.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.
Files changed (38) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +110 -2
  3. package/README.pt-BR.md +88 -0
  4. package/bin/iso-explainer.mjs +75 -0
  5. package/package.json +37 -4
  6. package/skills/iso-explainer/SKILL.md +92 -0
  7. package/skills/iso-explainer/assets/fonts/OFL.txt +93 -0
  8. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
  9. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
  10. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
  11. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
  12. package/skills/iso-explainer/assets/fonts/jetbrains-mono-latin-800-normal.woff2 +0 -0
  13. package/skills/iso-explainer/assets/runtime/LUCIDE-LICENSE.txt +43 -0
  14. package/skills/iso-explainer/assets/runtime/app.js +687 -0
  15. package/skills/iso-explainer/assets/runtime/engine.js +1177 -0
  16. package/skills/iso-explainer/assets/runtime/icons.js +205 -0
  17. package/skills/iso-explainer/assets/runtime/styles.css +447 -0
  18. package/skills/iso-explainer/assets/runtime/template.html +29 -0
  19. package/skills/iso-explainer/assets/templates/starter.course.json +134 -0
  20. package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +1743 -0
  21. package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +2074 -0
  22. package/skills/iso-explainer/examples/figures/token-bucket.html +98 -0
  23. package/skills/iso-explainer/examples/historia-pedidos.story.json +1872 -0
  24. package/skills/iso-explainer/references/architecture-mode.md +82 -0
  25. package/skills/iso-explainer/references/design-system.md +58 -0
  26. package/skills/iso-explainer/references/engine.md +64 -0
  27. package/skills/iso-explainer/references/entities.md +70 -0
  28. package/skills/iso-explainer/references/flows.md +67 -0
  29. package/skills/iso-explainer/references/inside.md +64 -0
  30. package/skills/iso-explainer/references/layout.md +122 -0
  31. package/skills/iso-explainer/references/schema.md +157 -0
  32. package/skills/iso-explainer/references/story-mode.md +72 -0
  33. package/skills/iso-explainer/references/storytelling.md +56 -0
  34. package/skills/iso-explainer/scripts/build.mjs +80 -0
  35. package/skills/iso-explainer/scripts/harvest.mjs +240 -0
  36. package/skills/iso-explainer/scripts/lib/resolve.mjs +251 -0
  37. package/skills/iso-explainer/scripts/snapshot.mjs +97 -0
  38. package/skills/iso-explainer/scripts/validate.mjs +41 -0
@@ -0,0 +1,687 @@
1
+ // iso-explainer · app.js — the course shell around the Stage.
2
+ // Reads the compiled course from window.__COURSE__ (produced by scripts/build.mjs).
3
+ import { Stage, iconHTML, renderPanel, themed, withDefaults } from './engine.js';
4
+
5
+ /* ───────────── strings ───────────── */
6
+ const STRINGS = {
7
+ en: {
8
+ course: 'Course', lessons: '{n} lessons', lessonOf: 'Lesson {i} of {n}', min: '{n} min', steps: '{n} steps',
9
+ beginner: 'Beginner', intermediate: 'Intermediate', advanced: 'Advanced',
10
+ stepOf: 'Step {n} / {total}', inThisLesson: 'In this lesson', stepCount: 'Step {n} of {total}',
11
+ back: 'Back', next: 'Next: {title}', nextLesson: 'Next lesson', finish: 'Finish lesson', finishCourse: 'Finish course',
12
+ whatChanged: 'What changed', youLearn: 'You’ll learn', progress: 'Progress',
13
+ replay: 'Replay', pause: 'Pause', play: 'Play', fit: 'Fit', full: 'Full screen',
14
+ hint: '<kbd>←</kbd> <kbd>→</kbd> step · <kbd>R</kbd> replay · <kbd>Space</kbd> pause',
15
+ search: 'Search lessons & concepts…', noResults: 'Nothing found', soon: 'Coming soon', soonToast: '“{title}” is coming soon',
16
+ done: 'Lesson complete', courseDone: 'Course complete — nice work!', readAloud: 'Read aloud', stopReading: 'Stop reading',
17
+ theme: 'Toggle theme', menu: 'Open the course menu', close: 'Close',
18
+ warn: 'Watch out', tip: 'Good to know', insight: 'Key idea', next_: 'Coming up',
19
+ setup: 'Setup', problem: 'Problem', technique: 'Technique', solution: 'Solution', tradeoff: 'Trade-off', recap: 'Recap', case: 'Case',
20
+ req: 'request', res: 'response', slow: 'slow request', heavy: 'heavy request', mine: 'your request', write: 'write', kill: 'invalidate',
21
+ msg: 'message', poison: 'poison message', push: 'server push', empty: 'empty response', ping: 'health check', fail: 'failed request',
22
+ retry: 'retry', event: 'event', inside: 'inside', seeInside: 'Look inside', noInside: '“{name}” has no inside view — try a box with a magnifier', insideHint: 'Click a box with a magnifier to see how it works inside',
23
+ overview: 'Overview', component: 'Component', flow: 'Flow', data: 'Data', integration: 'Integration', failure: 'Failure', decision: 'Decision', risk: 'Risk', proposal: 'Proposal',
24
+ metricLabels: { latency: 'Latency', p50: 'p50 latency', p99: 'p99 latency', throughput: 'Throughput', errors: 'Errors', cost: 'Cost / month', servers: 'Servers', uptime: 'Uptime', util: 'Utilization', hitRate: 'Cache hit rate', queue: 'Queue depth' },
25
+ },
26
+ 'pt-BR': {
27
+ course: 'Curso', lessons: '{n} lições', lessonOf: 'Lição {i} de {n}', min: '{n} min', steps: '{n} passos',
28
+ beginner: 'Iniciante', intermediate: 'Intermediário', advanced: 'Avançado',
29
+ stepOf: 'Passo {n} / {total}', inThisLesson: 'Nesta lição', stepCount: 'Passo {n} de {total}',
30
+ back: 'Voltar', next: 'Próximo: {title}', nextLesson: 'Próxima lição', finish: 'Concluir lição', finishCourse: 'Concluir curso',
31
+ whatChanged: 'O que mudou', youLearn: 'Você vai aprender', progress: 'Progresso',
32
+ replay: 'Repetir', pause: 'Pausar', play: 'Continuar', fit: 'Ajustar', full: 'Tela cheia',
33
+ hint: '<kbd>←</kbd> <kbd>→</kbd> passo · <kbd>R</kbd> repetir · <kbd>Espaço</kbd> pausar',
34
+ search: 'Buscar lições e conceitos…', noResults: 'Nada encontrado', soon: 'Em breve', soonToast: '“{title}” chega em breve',
35
+ done: 'Lição concluída', courseDone: 'Curso concluído — mandou bem!', readAloud: 'Ler em voz alta', stopReading: 'Parar leitura',
36
+ theme: 'Alternar tema', menu: 'Abrir o menu do curso', close: 'Fechar',
37
+ warn: 'Atenção', tip: 'Bom saber', insight: 'Ideia-chave', next_: 'A seguir',
38
+ setup: 'Contexto', problem: 'Problema', technique: 'Técnica', solution: 'Solução', tradeoff: 'Trade-off', recap: 'Resumo', case: 'Caso',
39
+ req: 'requisição', res: 'resposta', slow: 'requisição lenta', heavy: 'requisição pesada', mine: 'sua requisição', write: 'escrita', kill: 'invalidação',
40
+ msg: 'mensagem', poison: 'mensagem venenosa', push: 'push do servidor', empty: 'resposta vazia', ping: 'health check', fail: 'falha',
41
+ retry: 'nova tentativa', event: 'evento', inside: 'por dentro', seeInside: 'Ver por dentro', noInside: '“{name}” não tem visão interna — clique numa caixa com lupa', insideHint: 'Clique numa caixa com lupa para ver como ela funciona por dentro',
42
+ overview: 'Visão geral', component: 'Componente', flow: 'Fluxo', data: 'Dados', integration: 'Integração', failure: 'Falha', decision: 'Decisão', risk: 'Risco', proposal: 'Proposta',
43
+ metricLabels: { latency: 'Latência', p50: 'Latência p50', p99: 'Latência p99', throughput: 'Vazão', errors: 'Erros', cost: 'Custo / mês', servers: 'Servidores', uptime: 'Disponibilidade', util: 'Utilização', hitRate: 'Acerto no cache', queue: 'Fila' },
44
+ },
45
+ es: {
46
+ course: 'Curso', lessons: '{n} lecciones', lessonOf: 'Lección {i} de {n}', min: '{n} min', steps: '{n} pasos',
47
+ beginner: 'Principiante', intermediate: 'Intermedio', advanced: 'Avanzado',
48
+ stepOf: 'Paso {n} / {total}', inThisLesson: 'En esta lección', stepCount: 'Paso {n} de {total}',
49
+ back: 'Atrás', next: 'Siguiente: {title}', nextLesson: 'Siguiente lección', finish: 'Terminar lección', finishCourse: 'Terminar curso',
50
+ whatChanged: 'Qué cambió', youLearn: 'Aprenderás', progress: 'Progreso',
51
+ replay: 'Repetir', pause: 'Pausa', play: 'Seguir', fit: 'Ajustar', full: 'Pantalla completa',
52
+ hint: '<kbd>←</kbd> <kbd>→</kbd> paso · <kbd>R</kbd> repetir · <kbd>Espacio</kbd> pausa',
53
+ search: 'Buscar lecciones y conceptos…', noResults: 'Sin resultados', soon: 'Pronto', soonToast: '“{title}” llega pronto',
54
+ done: 'Lección completada', courseDone: '¡Curso completado!', readAloud: 'Leer en voz alta', stopReading: 'Detener lectura',
55
+ theme: 'Cambiar tema', menu: 'Abrir el menú', close: 'Cerrar',
56
+ warn: 'Cuidado', tip: 'Bueno saber', insight: 'Idea clave', next_: 'A continuación',
57
+ setup: 'Contexto', problem: 'Problema', technique: 'Técnica', solution: 'Solución', tradeoff: 'Compromiso', recap: 'Resumen', case: 'Caso',
58
+ req: 'petición', res: 'respuesta', slow: 'petición lenta', heavy: 'petición pesada', mine: 'tu petición', write: 'escritura', kill: 'invalidación',
59
+ msg: 'mensaje', poison: 'mensaje venenoso', push: 'push del servidor', empty: 'respuesta vacía', ping: 'health check', fail: 'fallo',
60
+ retry: 'reintento', event: 'evento', inside: 'por dentro', seeInside: 'Ver por dentro', noInside: '“{name}” no tiene vista interna — prueba una caja con lupa', insideHint: 'Haz clic en una caja con lupa para ver cómo funciona por dentro',
61
+ overview: 'Visión general', component: 'Componente', flow: 'Flujo', data: 'Datos', integration: 'Integración', failure: 'Fallo', decision: 'Decisión', risk: 'Riesgo', proposal: 'Propuesta',
62
+ metricLabels: { latency: 'Latencia', p50: 'Latencia p50', p99: 'Latencia p99', throughput: 'Rendimiento', errors: 'Errores', cost: 'Costo / mes', servers: 'Servidores', uptime: 'Disponibilidad', util: 'Utilización', hitRate: 'Aciertos de caché', queue: 'Cola' },
63
+ },
64
+ };
65
+
66
+ // meta.mode "docs": same look, vocabulary of an architecture walkthrough instead of a course.
67
+ const DOCS_STRINGS = {
68
+ en: { whatChanged: 'In this step', course: 'System', lessons: '{n} views', lessonOf: 'View {i} of {n}', inThisLesson: 'In this walkthrough', youLearn: 'Key points', nextLesson: 'Next view', finishCourse: 'End of tour', courseDone: 'End of the architecture tour', search: 'Search components & flows…' },
69
+ 'pt-BR': { whatChanged: 'Neste passo', course: 'Sistema', lessons: '{n} visões', lessonOf: 'Visão {i} de {n}', inThisLesson: 'Neste fluxo', youLearn: 'Pontos-chave', nextLesson: 'Próxima visão', finishCourse: 'Fim do tour', courseDone: 'Fim do tour pela arquitetura', search: 'Buscar componentes e fluxos…' },
70
+ es: { whatChanged: 'En este paso', course: 'Sistema', lessons: '{n} vistas', lessonOf: 'Vista {i} de {n}', inThisLesson: 'En este recorrido', youLearn: 'Puntos clave', nextLesson: 'Siguiente vista', finishCourse: 'Fin del recorrido', courseDone: 'Fin del recorrido por la arquitectura', search: 'Buscar componentes y flujos…' },
71
+ };
72
+ // meta.mode "story": the project's history — each step is a decision/event with its motivation and sources.
73
+ const STORY_STRINGS = {
74
+ en: { course: 'Project', lessons: '{n} chapters', lessonOf: 'Chapter {i} of {n}', inThisLesson: 'Timeline', youLearn: 'Decisions in this phase', whatChanged: 'In the architecture', nextLesson: 'Next chapter', finishCourse: 'The end (so far)', courseDone: 'That is the story so far', search: 'Search decisions, flows and sources…' },
75
+ 'pt-BR': { course: 'Projeto', lessons: '{n} capítulos', lessonOf: 'Capítulo {i} de {n}', inThisLesson: 'Linha do tempo', youLearn: 'Decisões desta fase', whatChanged: 'Na arquitetura', nextLesson: 'Próximo capítulo', finishCourse: 'Fim (até aqui)', courseDone: 'Essa é a história até aqui', search: 'Buscar decisões, fluxos e fontes…' },
76
+ es: { course: 'Proyecto', lessons: '{n} capítulos', lessonOf: 'Capítulo {i} de {n}', inThisLesson: 'Línea de tiempo', youLearn: 'Decisiones de esta fase', whatChanged: 'En la arquitectura', nextLesson: 'Siguiente capítulo', finishCourse: 'Fin (por ahora)', courseDone: 'Esta es la historia hasta ahora', search: 'Buscar decisiones, flujos y fuentes…' },
77
+ };
78
+ const RECORD_STRINGS = {
79
+ en: { context: 'Context', decision: 'Decision', alternatives: 'Alternatives considered', consequences: 'Consequences', sources: 'Sources', accepted: 'accepted', proposed: 'proposed', superseded: 'superseded', rejected: 'rejected', deprecated: 'deprecated', motivation: 'Motivation', alternative: 'Alternative', consequence: 'Consequence', incident: 'Incident', migration: 'Migration', milestone: 'Milestone', learning: 'Lesson learned' },
80
+ 'pt-BR': { context: 'Contexto', decision: 'Decisão', alternatives: 'Alternativas consideradas', consequences: 'Consequências', sources: 'Fontes', accepted: 'aceita', proposed: 'proposta', superseded: 'substituída', rejected: 'rejeitada', deprecated: 'obsoleta', motivation: 'Motivação', alternative: 'Alternativa', consequence: 'Consequência', incident: 'Incidente', migration: 'Migração', milestone: 'Marco', learning: 'Aprendizado' },
81
+ es: { context: 'Contexto', decision: 'Decisión', alternatives: 'Alternativas consideradas', consequences: 'Consecuencias', sources: 'Fuentes', accepted: 'aceptada', proposed: 'propuesta', superseded: 'reemplazada', rejected: 'rechazada', deprecated: 'obsoleta', motivation: 'Motivación', alternative: 'Alternativa', consequence: 'Consecuencia', incident: 'Incidente', migration: 'Migración', milestone: 'Hito', learning: 'Aprendizaje' },
82
+ };
83
+ const C = window.__COURSE__;
84
+ const META = C.meta || {};
85
+ const LOCALE = META.locale || 'en';
86
+ const STORY = META.mode === 'story';
87
+ const DOCS = META.mode === 'docs' || STORY; // story shares docs behaviour (no course progress)
88
+ const pickLocale = (table) => table[LOCALE] || table[LOCALE.split('-')[0]] || {};
89
+ const S = {
90
+ ...STRINGS.en, ...pickLocale(STRINGS), ...RECORD_STRINGS.en, ...pickLocale(RECORD_STRINGS),
91
+ ...(DOCS && !STORY ? { ...DOCS_STRINGS.en, ...pickLocale(DOCS_STRINGS) } : {}),
92
+ ...(STORY ? { ...STORY_STRINGS.en, ...pickLocale(STORY_STRINGS) } : {}),
93
+ ...(META.strings || {}),
94
+ };
95
+ const t = (k, vars) => (S[k] ?? k).replace(/\{(\w+)\}/g, (m, v) => (vars && v in vars ? vars[v] : m));
96
+ const nf = (v, o) => new Intl.NumberFormat(LOCALE, o).format(v);
97
+ const $ = (s, r = document) => r.querySelector(s);
98
+ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
99
+ const I = iconHTML;
100
+
101
+ /* ───────────── storage ───────────── */
102
+ const NS = `isx:${META.id || 'course'}:`;
103
+ const store = {
104
+ get: (k, d) => { try { return JSON.parse(localStorage.getItem(NS + k)) ?? d; } catch { return d; } },
105
+ set: (k, v) => { try { localStorage.setItem(NS + k, JSON.stringify(v)); } catch {} },
106
+ };
107
+
108
+ /* ───────────── course index ───────────── */
109
+ const MODULES = C.modules;
110
+ const FLAT = MODULES.flatMap((m) => m.lessons.map((l, i) => ({ ...l, module: m, index: i + 1, of: m.lessons.length })));
111
+ const LESSONS = C.lessons;
112
+ const playable = FLAT.filter((l) => LESSONS[l.id]);
113
+ const nextLessonOf = (id) => { const i = playable.findIndex((l) => l.id === id); return playable[i + 1] || null; };
114
+ const CHAPTER = {
115
+ setup: 'sand', problem: 'red', technique: 'blue', solution: 'green', tradeoff: 'amber', insight: 'violet', recap: 'ink', case: 'rose',
116
+ overview: 'sand', component: 'blue', flow: 'violet', data: 'teal', integration: 'sand', failure: 'red', decision: 'amber', risk: 'rose', proposal: 'green',
117
+ context: 'sand', motivation: 'red', alternative: 'violet', consequence: 'blue', incident: 'red', migration: 'teal', milestone: 'green', learning: 'violet',
118
+ ...Object.fromEntries(Object.entries(META.chapters || {}).map(([k, v]) => [k, v.tone || 'blue'])),
119
+ };
120
+ for (const [k, v] of Object.entries(META.chapters || {})) if (v.label) S[k] = v.label;
121
+ const CALLOUT_ICON = { warn: 'alert', tip: 'lightbulb', insight: 'sparkles', next: 'arrow-right' };
122
+
123
+ /* ───────────── metrics ───────────── */
124
+ const BUILTIN_METRICS = {
125
+ latency: { label: 'Latency', icon: 'timer', format: 'ms', good: 200, warn: 800 },
126
+ p50: { label: 'p50 latency', icon: 'timer', format: 'ms', good: 250, warn: 800 },
127
+ p99: { label: 'p99 latency', icon: 'timer', format: 'ms', good: 400, warn: 1200 },
128
+ throughput: { label: 'Throughput', icon: 'activity', format: 'rps' },
129
+ errors: { label: 'Errors', icon: 'alert', format: 'percent', good: 0.5, warn: 2 },
130
+ cost: { label: 'Cost / month', icon: 'wallet', format: 'money' },
131
+ servers: { label: 'Servers', icon: 'server', format: 'number' },
132
+ uptime: { label: 'Uptime', icon: 'shield-check', format: 'percent', higher: true, good: 99.9, warn: 99 },
133
+ util: { label: 'Utilization', icon: 'gauge', format: 'percent', good: 60, warn: 85 },
134
+ hitRate: { label: 'Cache hit rate', icon: 'zap', format: 'percent', higher: true, good: 80, warn: 50 },
135
+ queue: { label: 'Queue depth', icon: 'list', format: 'number', good: 100, warn: 1000 },
136
+ };
137
+ for (const [k, v] of Object.entries(S.metricLabels || {})) if (BUILTIN_METRICS[k]) BUILTIN_METRICS[k].label = v;
138
+ const MDEF = { ...BUILTIN_METRICS, ...(C.metricDefs || {}) };
139
+ const fmtMs = (v) => (v >= 1000 ? `${nf(v / 1000, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} s` : `${nf(Math.round(v))} ms`);
140
+ const fmtBytes = (v) => { const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; } return `${nf(v, { maximumFractionDigits: v < 10 ? 1 : 0 })} ${u[i]}`; };
141
+ function fmtMetric(def, v) {
142
+ if (v == null) return '—';
143
+ if (typeof v === 'string') return v;
144
+ switch (def.format) {
145
+ case 'ms': return fmtMs(v);
146
+ case 'percent': return `${nf(v, { maximumFractionDigits: v < 10 && v % 1 ? 2 : 1 })}%`;
147
+ case 'rps': return `${nf(Math.round(v))} req/s`;
148
+ case 'money': return new Intl.NumberFormat(LOCALE, { style: 'currency', currency: META.currency || 'USD', maximumFractionDigits: 0 }).format(v);
149
+ case 'bytes': return fmtBytes(v);
150
+ case 'x': return `${nf(v, { maximumFractionDigits: 1 })}×`;
151
+ default: return def.unit ? `${nf(v, { maximumFractionDigits: 2 })} ${def.unit}` : nf(v, { maximumFractionDigits: 2 });
152
+ }
153
+ }
154
+ function levelOf(def, v) {
155
+ if (v == null) return 'none';
156
+ if (typeof v === 'string') return def.levels?.[v] || 'none';
157
+ if (def.good == null) return 'none';
158
+ return def.higher ? (v >= def.good ? 'good' : v >= (def.warn ?? -Infinity) ? 'warn' : 'bad') : v <= def.good ? 'good' : v <= (def.warn ?? Infinity) ? 'warn' : 'bad';
159
+ }
160
+
161
+ /* ───────────── state ───────────── */
162
+ const X = {
163
+ lessonId: null, step: null, metrics: {},
164
+ done: new Set(store.get('done', [])), seen: store.get('seen', {}),
165
+ open: new Set(), speak: store.get('speak', false),
166
+ };
167
+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
168
+
169
+ /* ───────────── shell ───────────── */
170
+ const brand = META.brand || { name: META.title || 'Course' };
171
+ const brandName = (() => {
172
+ const n = esc(brand.name || META.title), h = brand.highlight;
173
+ return h && n.includes(esc(h)) ? n.replace(esc(h), `<span>${esc(h)}</span>`) : n;
174
+ })();
175
+ const logo = META.logo || `<svg class="logo" width="30" height="30" viewBox="0 0 32 32" aria-hidden="true">
176
+ <path d="M5 21.5 16 27l11-5.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/>
177
+ <path d="M5 16.5 16 22l11-5.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round" opacity=".55"/>
178
+ <path d="M16 5 27 10.5 16 16 5 10.5Z" fill="#fcd4ad" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
179
+ <path d="M16 16v-3.2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>`;
180
+ const tabs = META.tabs || [];
181
+ const credit = META.credit ? `<a class="credit" href="${esc(META.credit.url || '#')}" target="_blank" rel="noopener"><span class="credit__icon">${I(META.credit.icon || 'user', { size: 13, stroke: 2.2 })}</span><span class="credit__text"><small>${esc(META.credit.small || '')}</small><b>${esc(META.credit.label)}</b></span></a>` : '';
182
+ const navHTML = (cls) => tabs.map((tb, i) => `<button class="nav__item ${tb.active ? 'btn-pop is-active' : ''} ${cls}" type="button" data-tab="${i}">${I(tb.icon || 'book-open', { size: 17 })}<span>${esc(tb.label)}</span></button>`).join('');
183
+ const mod = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘K' : 'Ctrl K';
184
+
185
+ document.querySelector('#app').innerHTML = `
186
+ <div class="window">
187
+ <header class="topbar">
188
+ <button class="icon-btn menu-btn" id="menu-btn" type="button" aria-label="${t('menu')}" aria-expanded="false">${I('menu', { size: 19, stroke: 2.2 })}</button>
189
+ <a class="brand" href="#/" aria-label="${esc(META.title)}">${logo}<span class="brand__name">${brandName}</span></a>
190
+ <nav class="nav">${navHTML('')}</nav>
191
+ <button class="search" id="search-open" type="button" aria-label="${t('search')}">${I('search', { size: 16, stroke: 2 })}<span class="search__hint">${t('search')}</span><kbd>${mod}</kbd></button>
192
+ <button class="icon-btn search-btn" id="search-open-2" type="button" aria-label="${t('search')}">${I('search', { size: 18, stroke: 2.2 })}</button>
193
+ <button class="icon-btn theme-btn" id="theme-btn" type="button" aria-label="${t('theme')}"></button>
194
+ ${credit}
195
+ </header>
196
+ <div class="body">
197
+ <aside class="sidebar" id="sidebar" aria-label="${t('course')}">
198
+ ${tabs.length ? `<nav class="drawer-nav">${navHTML('')}</nav>` : ''}
199
+ <div class="tree-root">
200
+ <svg width="22" height="18" viewBox="0 0 20 16" aria-hidden="true"><path d="M1 3a2 2 0 0 1 2-2h4.3l2 2.2H17a2 2 0 0 1 2 2V13a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2Z" fill="currentColor"/></svg>
201
+ <span>${t('course')}</span><span class="tree-root__meta">${t('lessons', { n: FLAT.length })}</span>
202
+ <button class="icon-btn drawer-close" id="drawer-close" type="button" aria-label="${t('close')}">${I('x', { size: 18, stroke: 2.2 })}</button>
203
+ </div>
204
+ <nav class="course" id="course"></nav>
205
+ <section class="card progress" id="progress"></section>
206
+ </aside>
207
+ <div class="drawer-backdrop" id="drawer-backdrop"></div>
208
+ <main class="sheet">
209
+ <div class="lesson-head" id="head"></div>
210
+ <section class="card stage" id="stage">
211
+ <div class="stage__hud" id="hud"></div>
212
+ <div class="stage__tools">
213
+ <button class="tool tool--fit" id="fit" title="${t('fit')} (0)" hidden>${I('zoom-out', { size: 15, stroke: 2 })}<span>${t('fit')}</span></button>
214
+ <button class="tool" id="replay" title="${t('replay')} (R)">${I('rotate-ccw', { size: 15, stroke: 2 })}<span>${t('replay')}</span></button>
215
+ <button class="tool" id="pause" title="${t('pause')} (Space)"></button>
216
+ <button class="tool tool--expand" id="expand" title="${t('full')}" aria-label="${t('full')}">${I('maximize-2', { size: 15, stroke: 2 })}</button>
217
+ </div>
218
+ <div class="stage__canvas" id="canvas"></div>
219
+ <div class="stage__legend" id="legend"></div>
220
+ </section>
221
+ <section class="card timeline" id="timeline"></section>
222
+ </main>
223
+ <aside class="rail">
224
+ <section class="card guide" id="guide"></section>
225
+ <section class="card goals" id="goals"></section>
226
+ </aside>
227
+ <div class="inspect" id="inspect" hidden>
228
+ <div class="inspect__box" role="dialog" aria-modal="true" aria-labelledby="inspect-title">
229
+ <header class="inspect__head">
230
+ <span class="inspect__crumb">${I('scan', { size: 15, stroke: 2.2 })}<b id="inspect-of"></b><span>/</span>${t('inside')}</span>
231
+ <h3 class="inspect__title" id="inspect-title"></h3>
232
+ <button class="icon-btn" id="inspect-close" type="button" aria-label="${t('close')} (Esc)">${I('x', { size: 17, stroke: 2.2 })}</button>
233
+ </header>
234
+ <div class="inspect__body" id="inspect-body"></div>
235
+ </div>
236
+ </div>
237
+
238
+ </div>
239
+ <nav class="mobile-nav" id="mobile-nav"></nav>
240
+ <div class="toast" id="toast" role="status" aria-live="polite"></div>
241
+ <div class="palette" id="palette" hidden>
242
+ <div class="palette__box card" role="dialog" aria-modal="true" aria-label="${t('search')}">
243
+ <label class="palette__field">${I('search', { size: 17, stroke: 2 })}<input id="palette-input" type="search" autocomplete="off" placeholder="${t('search')}"/><kbd>Esc</kbd></label>
244
+ <ul class="palette__list" id="palette-list" role="listbox"></ul>
245
+ </div>
246
+ </div>
247
+ </div>`;
248
+
249
+ const stage = new Stage($('#canvas'), { reducedMotion: reduced });
250
+ stage.onCards = (show) => document.documentElement.classList.toggle('cards-inline', !show);
251
+ stage.onView = (z) => { $('#fit').hidden = !z; };
252
+ stage.onSwipe = (dir) => go(X.lessonId, X.step + dir);
253
+ function syncHud() {
254
+ const hud = $('#hud'), canvas = $('#canvas'), tools = $('.stage__tools');
255
+ const stack = document.documentElement.dataset.layout === 'stack', stageEl = $('#stage');
256
+ // if the metric chips need a second row, drop the tool labels (icons only) and try again
257
+ stageEl.classList.remove('tools-compact');
258
+ hud.style.insetInlineEnd = stack ? '' : `${tools.offsetWidth + 24}px`;
259
+ if (!stack && hud.offsetHeight > 56) { stageEl.classList.add('tools-compact'); hud.style.insetInlineEnd = `${tools.offsetWidth + 24}px`; }
260
+ canvas.style.top = stack ? '' : `${Math.max(58, hud.offsetTop + hud.offsetHeight + 10)}px`;
261
+ const legend = $('#legend'); // a wrapped legend pushes the canvas up instead of sitting under docked cards
262
+ canvas.style.bottom = stack ? '' : `${Math.max(34, legend.offsetHeight + 18)}px`;
263
+ }
264
+ new ResizeObserver(syncHud).observe($('#hud'));
265
+ new ResizeObserver(syncHud).observe($('#legend'));
266
+ // Phones: size the stage to the lesson's widest scene so the diagram fills the width instead of floating in empty space.
267
+ function fitStageHeight() {
268
+ const el = $('#stage'), L = LESSONS[X.lessonId];
269
+ if (document.documentElement.dataset.layout !== 'stack' || !L) { el.style.height = ''; return; }
270
+ let aspect = 0.45;
271
+ for (const s of L.steps) { const b = stage.plans.get(s.scene)?.bounds; if (b) aspect = Math.max(aspect, (b[3] - b[1]) / Math.max(1, b[2] - b[0])); }
272
+ const w = el.clientWidth - 12, want = Math.round(w * aspect * 1.08 + 64 + 46);
273
+ el.style.height = `${Math.max(300, Math.min(want, Math.round(innerHeight * 0.66)))}px`;
274
+ }
275
+
276
+ /* ───────────── layout & theme ───────────── */
277
+ function fitWindow() {
278
+ const w = innerWidth, h = innerHeight;
279
+ const layout = w >= 1200 && h >= 560 ? 'desktop' : w >= 960 && h >= 600 ? 'tablet' : 'stack';
280
+ if (document.documentElement.dataset.layout !== layout) document.documentElement.dataset.layout = layout;
281
+ }
282
+ addEventListener('resize', () => { fitWindow(); syncHud(); fitStageHeight(); }); fitWindow();
283
+ function setTheme(theme) {
284
+ document.documentElement.dataset.theme = theme;
285
+ store.set('theme', theme);
286
+ $('#theme-btn').innerHTML = I(theme === 'dark' ? 'sun' : 'moon', { size: 17, stroke: 2 });
287
+ const m = document.querySelector('meta[name="theme-color"]'); if (m) m.content = theme === 'dark' ? '#211e1a' : '#f4ebe0';
288
+ stage.retheme(); renderInlineCard();
289
+ if (typeof inspect !== 'undefined' && inspect) { inspect.stage?.retheme(); if (inspect.data.kind === 'html') $('#inspect-body iframe').srcdoc = figureDoc(inspect.data); }
290
+ }
291
+ $('#theme-btn').onclick = () => setTheme(document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark');
292
+ setTheme(document.documentElement.dataset.theme || 'light');
293
+
294
+ /* ───────────── sidebar ───────────── */
295
+ const folder = (c) => `<svg class="folder folder--${c}" width="20" height="16" viewBox="0 0 20 16" aria-hidden="true"><path d="M1.2 3.2A2 2 0 0 1 3.2 1.2h4.1l2 2.2h7.5a2 2 0 0 1 2 2v8.4a2 2 0 0 1-2 2H3.2a2 2 0 0 1-2-2Z"/><path class="folder__lip" d="M1.2 6.2h17.6"/></svg>`;
296
+ const mark = (id) => !DOCS && X.done.has(id) ? I('circle-check', { size: 16, stroke: 2, cls: 'lesson__mark lesson__mark--done' }) : I(LESSONS[id] ? 'file' : 'lock', { size: 15, stroke: 1.5, cls: 'lesson__mark' });
297
+ function renderCourse() {
298
+ $('#course').innerHTML = MODULES.map((m) => `
299
+ <section class="mod ${X.open.has(m.id) ? 'is-open' : ''}" data-mod="${m.id}">
300
+ <button class="mod__head" data-mod="${m.id}" aria-expanded="${X.open.has(m.id)}">
301
+ ${I('chevron-right', { size: 15, stroke: 2.2, cls: 'mod__chev' })}${folder(m.color || 'sand')}
302
+ <span class="mod__title">${esc(m.num ? `${m.num}. ` : '')}${esc(m.title)}</span>
303
+ <span class="mod__count">${DOCS ? m.lessons.length : `${m.lessons.filter((l) => X.done.has(l.id)).length}/${m.lessons.length}`}</span>
304
+ </button>
305
+ <div class="mod__body"><div class="mod__clip"><ul class="mod__lessons">
306
+ ${m.lessons.map((l) => `<li class="lesson ${LESSONS[l.id] ? '' : 'is-soon'} ${l.id === X.lessonId ? 'is-current' : ''}" data-lesson="${l.id}">
307
+ <a href="${LESSONS[l.id] ? `#/${l.id}/1` : '#'}" data-lesson="${l.id}"><span class="lesson__markbox">${mark(l.id)}</span><span class="lesson__title">${esc(l.title)}</span>${LESSONS[l.id] ? '' : `<span class="soon">${t('soon')}</span>`}</a>
308
+ </li>`).join('')}
309
+ </ul></div></div>
310
+ </section>`).join('');
311
+ $('#progress').hidden = DOCS;
312
+ const done = playable.filter((l) => X.done.has(l.id)).length, pct = playable.length ? Math.round((done / playable.length) * 100) : 0;
313
+ $('#progress').innerHTML = `<div class="progress__head"><span class="eyebrow">${t('progress')}</span><span class="progress__pct">${done} / ${playable.length}</span></div>
314
+ <div class="bar"><span style="width:${pct}%"></span></div>`;
315
+ }
316
+ $('#course').addEventListener('click', (ev) => {
317
+ const head = ev.target.closest('.mod__head');
318
+ if (head) { const id = head.dataset.mod; X.open.has(id) ? X.open.delete(id) : X.open.add(id); renderCourse(); return; }
319
+ const a = ev.target.closest('a[data-lesson]');
320
+ if (a && !LESSONS[a.dataset.lesson]) { ev.preventDefault(); toast(t('soonToast', { title: FLAT.find((l) => l.id === a.dataset.lesson).title }), 'clock'); return; }
321
+ if (a) closeDrawer();
322
+ });
323
+ const openDrawer = () => { document.documentElement.classList.add('drawer-open'); $('#menu-btn').setAttribute('aria-expanded', 'true'); };
324
+ const closeDrawer = () => { document.documentElement.classList.remove('drawer-open'); $('#menu-btn').setAttribute('aria-expanded', 'false'); };
325
+ $('#menu-btn').onclick = openDrawer; $('#drawer-close').onclick = closeDrawer; $('#drawer-backdrop').onclick = closeDrawer;
326
+ document.querySelectorAll('[data-tab]').forEach((b) => (b.onclick = () => {
327
+ const tb = tabs[+b.dataset.tab];
328
+ if (tb.href) location.href = tb.href; else if (!tb.active) toast(t('soonToast', { title: tb.label }), tb.icon || 'sparkles');
329
+ }));
330
+
331
+ /* ───────────── lesson chrome ───────────── */
332
+ function renderHead(L, info) {
333
+ $('#head').innerHTML = `
334
+ <div class="crumb">${esc(info.module.num ? `${info.module.num}. ` : '')}${esc(info.module.title)}<span>/</span>${t('lessonOf', { i: info.index, n: info.of })}</div>
335
+ <div class="lesson-head__row">
336
+ <h1 class="title">${esc(L.title)}</h1>
337
+ <div class="tags">
338
+ ${L.minutes ? `<span class="tag tag--sand">${I('clock', { size: 13, stroke: 2.2 })}${t('min', { n: L.minutes })}</span>` : ''}
339
+ ${L.level ? `<span class="tag tag--mint">${I('chart-column', { size: 13, stroke: 2.2 })}${t(L.level)}</span>` : ''}
340
+ ${L.badge ? `<span class="tag tag--mint">${I(L.badge.icon || 'tag', { size: 13, stroke: 2.2 })}${esc(L.badge.text)}</span>` : ''}
341
+ <span class="tag tag--violet">${I('list-checks', { size: 13, stroke: 2.2 })}${t('steps', { n: L.steps.length })}</span>
342
+ </div>
343
+ </div>
344
+ ${L.summary ? `<p class="subtitle">${esc(L.summary)}</p>` : ''}`;
345
+ }
346
+ function renderLegend(L) {
347
+ const items = (L.legend || ['req', 'res']).map((x) => {
348
+ const [kind, label] = Array.isArray(x) ? x : [x, (C.legendDefs || {})[x] || t(x)];
349
+ const lg = kind === 'fail' ? `<i class="lg lg--fail">×</i>` : `<i class="lg lg--${kind}"></i>`;
350
+ return `<span>${lg}${esc(label)}</span>`;
351
+ });
352
+ $('#legend').innerHTML = items.join('');
353
+ }
354
+ function renderTimeline(L, step) {
355
+ const n = L.steps.length;
356
+ $('#timeline').style.setProperty('--n', n);
357
+ $('#timeline').innerHTML = `
358
+ <div class="timeline__head"><span class="eyebrow">${t('inThisLesson')}</span><span class="timeline__count">${t('stepCount', { n: step + 1, total: n })}</span></div>
359
+ <div class="timeline__track">
360
+ <div class="timeline__rail"><span style="width:${n > 1 ? (step / (n - 1)) * 100 : 0}%"></span></div>
361
+ <ol class="timeline__steps">${L.steps.map((s, i) => `<li class="${i < step ? 'is-done' : ''} ${i === step ? 'is-current' : ''}"><button type="button" data-step="${i}" aria-label="${esc(s.title)}"><span class="timeline__dot">${i + 1}</span><span class="timeline__label">${esc(s.short || '')}${s.date ? `<small>${esc(s.date)}</small>` : ''}</span></button></li>`).join('')}</ol>
362
+ </div>`;
363
+ }
364
+ $('#timeline').addEventListener('click', (ev) => { const b = ev.target.closest('[data-step]'); if (b) go(X.lessonId, +b.dataset.step); });
365
+ function renderGoals(L, step) {
366
+ const goals = L.goals || [];
367
+ $('#goals').hidden = !goals.length;
368
+ $('#goals').innerHTML = `<div class="eyebrow">${t('youLearn')}</div><ul>${goals.map((g) => `<li class="${step >= g.step ? 'is-hit' : ''}"><span class="check ${step >= g.step ? 'is-on' : ''}">${I('check', { size: 11, stroke: 3 })}</span>${esc(g.text)}</li>`).join('')}</ul>`;
369
+ }
370
+ function renderHud(L) {
371
+ $('#hud').innerHTML = (L.metrics || []).map((k) => {
372
+ const d = MDEF[k] || { label: k, icon: 'activity' };
373
+ return `<div class="chip" data-k="${k}"><span class="chip__label">${I(d.icon || 'activity', { size: 12, stroke: 2 })}${esc(d.label)}</span><span class="chip__value">–</span></div>`;
374
+ }).join('');
375
+ X.metrics = {};
376
+ }
377
+ function updateHud(L, values, animate) {
378
+ for (const k of L.metrics || []) {
379
+ const d = MDEF[k] || {}, chip = document.querySelector(`.chip[data-k="${k}"]`); if (!chip) continue;
380
+ const val = chip.querySelector('.chip__value'), v = values?.[k] ?? null, prev = X.metrics[k];
381
+ chip.dataset.level = levelOf(d, v); X.metrics[k] = v;
382
+ const changed = prev !== undefined && prev !== v;
383
+ if (changed && animate) { chip.classList.remove('is-changed'); void chip.offsetWidth; chip.classList.add('is-changed'); }
384
+ const w0 = chip.offsetWidth; chip.style.width = ''; val.textContent = fmtMetric(d, v); const w1 = chip.offsetWidth;
385
+ const count = animate && typeof prev === 'number' && typeof v === 'number' && prev !== v && !reduced;
386
+ if (!animate || (!count && w0 === w1)) { chip.anim = null; continue; }
387
+ if (count) val.textContent = fmtMetric(d, prev); else if (changed) { val.classList.remove('is-swap'); void val.offsetWidth; val.classList.add('is-swap'); }
388
+ chip.style.width = `${w0}px`;
389
+ const token = (chip.anim = {}), t0 = performance.now(), dur = count ? 900 : 480;
390
+ const run = (now) => {
391
+ if (chip.anim !== token) return;
392
+ const p = Math.min(1, (now - t0) / dur), e = 1 - (1 - p) ** 3;
393
+ if (count) val.textContent = fmtMetric(d, Number.isInteger(prev) && Number.isInteger(v) ? Math.round(prev + (v - prev) * e) : prev + (v - prev) * e);
394
+ chip.style.width = `${w0 + (w1 - w0) * e}px`;
395
+ if (p < 1) requestAnimationFrame(run); else { chip.style.width = ''; val.textContent = fmtMetric(d, v); }
396
+ };
397
+ requestAnimationFrame(run);
398
+ }
399
+ }
400
+ const changeLine = (s) => {
401
+ const kind = s.startsWith('+') ? 'add' : s.startsWith('-') || s.startsWith('−') ? 'del' : 'mod';
402
+ return `<li class="chg chg--${kind}"><b>${{ add: '+', del: '−', mod: '~' }[kind]}</b><span>${s.replace(/^[+~\-−]\s?/, '')}</span></li>`;
403
+ };
404
+ const BLOCK = /^<(p|ul|ol|table|div|figure|pre|h\d|blockquote)\b/i;
405
+ function inlineCard(step) {
406
+ const p = Object.values(step.scene.entities || {}).find((e) => e.type === 'panel');
407
+ if (!p) return '';
408
+ const r = renderPanel(withDefaults(p));
409
+ return `<figure class="guide__card"><svg viewBox="-2 -2 ${r.size.w + 6} ${r.size.h + 8}" width="${r.size.w + 6}" role="img" aria-label="${esc(p.title)}">${themed(r.over)}</svg></figure>`;
410
+ }
411
+ const SOURCE_ICON = { adr: 'file-text', rfc: 'scroll', session: 'bot', commit: 'git-commit-horizontal', pr: 'git-pull-request', issue: 'bug', incident: 'alert', postmortem: 'alert', doc: 'book-open', chat: 'message-circle', meeting: 'users', metric: 'activity', link: 'link' };
412
+ const STATUS_TONE = { accepted: 'green', aceita: 'green', proposed: 'blue', proposta: 'blue', superseded: 'amber', 'substituída': 'amber', rejected: 'red', rejeitada: 'red', deprecated: 'gray', obsoleta: 'gray' };
413
+ function decisionCard(d) {
414
+ if (!d) return '';
415
+ const row = (label, html) => (html ? `<div class="adr__row"><span class="adr__k">${esc(label)}</span><div class="adr__v">${html}</div></div>` : '');
416
+ const alts = (d.alternatives || []).map((a) => typeof a === 'string' ? `<li>${a}</li>` : `<li><b>${esc(a.name)}</b>${a.why ? ` — ${a.why}` : ''}</li>`).join('');
417
+ const cons = (d.consequences || []).map(changeLine).join('');
418
+ const status = d.status ? `<span class="adr__status adr__status--${STATUS_TONE[d.status] || 'gray'}">${esc(S[d.status] || d.status)}</span>` : '';
419
+ return `<section class="adr">
420
+ <header class="adr__head">${I('scale', { size: 14, stroke: 2 })}<b>${esc(d.id || t('decision'))}</b>${d.date ? `<span class="adr__date">${esc(d.date)}</span>` : ''}${status}</header>
421
+ ${row(t('context'), d.context)}${row(t('decision'), d.decision)}
422
+ ${alts ? row(t('alternatives'), `<ul class="adr__alts">${alts}</ul>`) : ''}
423
+ ${cons ? row(t('consequences'), `<ul class="adr__cons">${cons}</ul>`) : ''}
424
+ </section>`;
425
+ }
426
+ function sourcesList(list) {
427
+ if (!list?.length) return '';
428
+ return `<div class="sources"><div class="eyebrow">${t('sources')}</div><ul>${list.map((x) => {
429
+ const src = typeof x === 'string' ? { label: x } : x, ic = I(SOURCE_ICON[src.kind] || 'link', { size: 13, stroke: 2 });
430
+ const inner = `${ic}<span>${esc(src.label)}</span>${src.note ? `<small>${esc(src.note)}</small>` : ''}`;
431
+ return `<li>${src.url ? `<a href="${esc(src.url)}" target="_blank" rel="noopener">${inner}</a>` : `<span class="sources__item">${inner}</span>`}</li>`;
432
+ }).join('')}</ul></div>`;
433
+ }
434
+ function renderInlineCard() {
435
+ const f = $('#guide .guide__card'), L = LESSONS[X.lessonId];
436
+ if (f && L) f.outerHTML = inlineCard(L.steps[X.step]);
437
+ }
438
+ function renderGuide(L, i, dir) {
439
+ const st = L.steps[i], n = L.steps.length, last = i === n - 1, nl = nextLessonOf(L.id);
440
+ const label = last ? (nl ? `${t('nextLesson')}: ${nl.title}` : t('finishCourse')) : t('next', { title: L.steps[i + 1].short || L.steps[i + 1].title });
441
+ const ch = st.chapter || 'technique';
442
+ const glossary = C.glossary || {};
443
+ const body = (st.body || []).map((p) => (BLOCK.test(p) ? p : `<p>${p}</p>`)).join('')
444
+ .replace(/<span class="term">([^<]+)<\/span>/g, (m, term) => { const d = glossary[term] || glossary[term.toLowerCase()]; return d ? `<span class="term" tabindex="0" data-tip="${esc(d)}">${term}</span>` : m; });
445
+ const callout = st.callout ? `<div class="callout callout--${st.callout.kind || 'insight'}"><div class="callout__icon">${I(CALLOUT_ICON[st.callout.kind] || 'sparkles', { size: 16, stroke: 2 })}</div><div><div class="callout__title">${esc(st.callout.title || t(st.callout.kind === 'next' ? 'next_' : st.callout.kind || 'insight'))}</div><p>${st.callout.text}</p></div></div>` : '';
446
+ const changes = st.changes?.length ? `<div class="changes"><div class="eyebrow">${t('whatChanged')}</div><ul>${st.changes.map(changeLine).join('')}</ul></div>` : '';
447
+ const speakBtn = 'speechSynthesis' in window ? `<button class="speak ${X.speak ? 'is-on' : ''}" id="speak" type="button" aria-pressed="${X.speak}" title="${X.speak ? t('stopReading') : t('readAloud')}">${I(X.speak ? 'volume-2' : 'mic', { size: 14, stroke: 2 })}</button>` : '';
448
+ $('#guide').innerHTML = `
449
+ <div class="guide__meta"><span class="eyebrow">${t('stepOf', { n: i + 1, total: n })}${st.date ? `<span class="guide__date">${I('calendar', { size: 12, stroke: 2 })}${esc(st.date)}</span>` : ''}</span><div class="guide__meta-end">${speakBtn}<span class="chapter chapter--${CHAPTER[ch] || 'blue'}">${esc(t(ch))}</span></div></div>
450
+ <div class="guide__content" style="--slide:${dir * 36}px">
451
+ <h2 class="guide__title">${st.title}</h2>
452
+ <div class="guide__body">${body}</div>
453
+ ${decisionCard(st.decision)}${inlineCard(st)}${callout}${changes}${insideList(st)}${sourcesList(st.sources)}
454
+ </div>
455
+ <div class="guide__nav">
456
+ <button class="btn-ghost" id="back" type="button" ${i === 0 ? 'disabled' : ''}>${I('arrow-left', { size: 15, stroke: 2.2 })}${t('back')}</button>
457
+ <button class="btn-pop btn-next" id="next" type="button"><span class="btn-next__label">${esc(label)}</span>${I(last && !nl ? 'check' : 'arrow-right', { size: 15, stroke: 2.2 })}</button>
458
+ </div>
459
+ <div class="guide__hint">${I('keyboard', { size: 14, stroke: 1.8 })}<span>${t('hint')}</span></div>`;
460
+ const content = $('#guide .guide__content');
461
+ if (dir) requestAnimationFrame(() => content.classList.add('is-in')); else content.classList.add('is-in', 'no-slide');
462
+ $('#back').onclick = () => go(L.id, i - 1);
463
+ $('#next').onclick = () => advance();
464
+ const sp = $('#speak'); if (sp) sp.onclick = () => { X.speak = !X.speak; store.set('speak', X.speak); X.speak ? speakStep() : speechSynthesis.cancel(); renderGuide(L, i, 0); };
465
+ $('#mobile-nav').innerHTML = `<button class="btn-ghost" type="button" ${i === 0 ? 'disabled' : ''} data-go="-1">${I('arrow-left', { size: 15, stroke: 2.2 })}${t('back')}</button>
466
+ <button class="btn-pop btn-next" type="button" data-go="1"><span class="btn-next__label">${esc(label)}</span>${I(last && !nl ? 'check' : 'arrow-right', { size: 15, stroke: 2.2 })}</button>`;
467
+ }
468
+ $('#mobile-nav').addEventListener('click', (ev) => { const b = ev.target.closest('[data-go]'); if (!b) return; +b.dataset.go < 0 ? go(X.lessonId, X.step - 1) : advance(); });
469
+ function advance() {
470
+ const L = LESSONS[X.lessonId];
471
+ if (X.step < L.steps.length - 1) return go(L.id, X.step + 1);
472
+ const nl = nextLessonOf(L.id);
473
+ if (nl) go(nl.id, 0); else { toast(t('courseDone'), 'award'); }
474
+ }
475
+
476
+ /* ───────────── read aloud ───────────── */
477
+ function speakStep() {
478
+ if (!X.speak || !('speechSynthesis' in window)) return;
479
+ speechSynthesis.cancel();
480
+ const g = $('#guide .guide__content'); if (!g) return;
481
+ const text = [...g.querySelectorAll('.guide__title, .guide__body p, .guide__body li, .adr__v, .callout p')].map((n) => n.textContent).join('. ');
482
+ const u = new SpeechSynthesisUtterance(text); u.lang = LOCALE; u.rate = 1.02;
483
+ const v = speechSynthesis.getVoices().find((x) => x.lang.replace('_', '-').startsWith(LOCALE.split('-')[0])); if (v) u.voice = v;
484
+ speechSynthesis.speak(u);
485
+ }
486
+
487
+ /* ───────────── toast ───────────── */
488
+ let toastTimer = 0;
489
+ function toast(msg, icon = 'sparkles') {
490
+ const el = $('#toast'); el.innerHTML = `<span class="toast__icon">${I(icon, { size: 16, stroke: 2 })}</span><b class="toast__text">${esc(msg)}</b>`;
491
+ el.classList.remove('is-on'); void el.offsetWidth; el.classList.add('is-on');
492
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('is-on'), 2800);
493
+ }
494
+
495
+ /* ───────────── routing ───────────── */
496
+ function go(lessonId, step) {
497
+ const L = LESSONS[lessonId]; if (!L) return;
498
+ step = Math.max(0, Math.min(L.steps.length - 1, step));
499
+ location.hash = `#/${lessonId}/${step + 1}`;
500
+ }
501
+ function parseHash() {
502
+ const m = /^#\/([\w-]+)\/(\d+)$/.exec(location.hash);
503
+ if (m && LESSONS[m[1]]) return { lessonId: m[1], step: Math.max(0, Math.min(LESSONS[m[1]].steps.length - 1, m[2] - 1)) };
504
+ const last = store.get('last', null);
505
+ if (last && LESSONS[last.lessonId]) return last;
506
+ return { lessonId: playable[0].id, step: 0 };
507
+ }
508
+ function route() {
509
+ closeInside(true);
510
+ const { lessonId, step } = parseHash();
511
+ const L = LESSONS[lessonId], info = FLAT.find((l) => l.id === lessonId), fresh = lessonId !== X.lessonId, prev = X.step;
512
+ X.lessonId = lessonId; X.step = step; store.set('last', { lessonId, step });
513
+ X.seen[lessonId] = Math.max(X.seen[lessonId] ?? -1, step); store.set('seen', X.seen);
514
+ if (!DOCS && step === L.steps.length - 1 && !X.done.has(lessonId)) { X.done.add(lessonId); store.set('done', [...X.done]); setTimeout(() => toast(t('done'), 'circle-check'), 900); }
515
+ if (fresh) {
516
+ X.open.add(info.module.id);
517
+ renderHead(L, info); renderLegend(L); renderHud(L);
518
+ for (const s of ['#head', '#legend', '#hud', '#timeline', '#goals']) { const n = $(s); n.classList.remove('is-fresh'); void n.offsetWidth; n.classList.add('is-fresh'); }
519
+ stage.clear(); stage.frame(L.steps.map((s) => s.scene)); fitStageHeight(); stage.goTo(L.steps[step].scene);
520
+ } else if (step !== prev) stage.goTo(L.steps[step].scene);
521
+ renderCourse(); renderTimeline(L, step); renderGoals(L, step);
522
+ const dir = fresh || prev == null ? 0 : Math.sign(step - prev);
523
+ renderGuide(L, step, dir);
524
+ updateHud(L, L.steps[step].metrics, !fresh);
525
+ document.title = `${L.title} · ${META.title || brand.name}`;
526
+ speakStep();
527
+ }
528
+ addEventListener('hashchange', route);
529
+
530
+ /* ───────────── tools & keys ───────────── */
531
+ function replay() {
532
+ const L = LESSONS[X.lessonId], i = X.step;
533
+ stage.clear(); stage.frame(L.steps.map((s) => s.scene));
534
+ if (i > 0) stage.goTo(L.steps[i - 1].scene, { instant: true });
535
+ stage.goTo(L.steps[i].scene);
536
+ }
537
+ function syncPause() { $('#pause').innerHTML = `${I(stage.paused ? 'play' : 'pause', { size: 15, stroke: 2 })}<span>${stage.paused ? t('play') : t('pause')}</span>`; $('#pause').classList.toggle('is-on', stage.paused); }
538
+ const togglePause = () => { stage.paused = !stage.paused; syncPause(); };
539
+ $('#replay').onclick = replay; $('#pause').onclick = togglePause; $('#fit').onclick = () => stage.fit(); syncPause();
540
+ $('#expand').onclick = () => { const on = !$('#stage').classList.contains('is-full'); $('#stage').classList.toggle('is-full', on); document.documentElement.classList.toggle('stage-full', on); $('#expand').innerHTML = I(on ? 'minimize-2' : 'maximize-2', { size: 15, stroke: 2 }); };
541
+ addEventListener('keydown', (ev) => {
542
+ if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'k') { ev.preventDefault(); openPalette(); return; }
543
+ if (!$('#palette').hidden || ev.target.closest('input, textarea')) return;
544
+ if (inspect) {
545
+ if (ev.key === 'Escape') closeInside();
546
+ else if (inspect.stage && ev.key === 'ArrowRight') { ev.preventDefault(); insideGo(inspect.step + 1); }
547
+ else if (inspect.stage && ev.key === 'ArrowLeft') { ev.preventDefault(); insideGo(inspect.step - 1); }
548
+ return;
549
+ }
550
+ if (ev.key === 'Escape') { if ($('#stage').classList.contains('is-full')) $('#expand').click(); closeDrawer(); return; }
551
+ if (ev.key === '/') { ev.preventDefault(); openPalette(); return; }
552
+ if (ev.key === 'ArrowRight') { ev.preventDefault(); X.step < LESSONS[X.lessonId].steps.length - 1 ? go(X.lessonId, X.step + 1) : advance(); }
553
+ else if (ev.key === 'ArrowLeft') { ev.preventDefault(); go(X.lessonId, X.step - 1); }
554
+ else if (ev.key === 'r' || ev.key === 'R') replay();
555
+ else if (ev.key === '0') stage.fit();
556
+ else if (ev.key === ' ') { ev.preventDefault(); togglePause(); }
557
+ });
558
+
559
+ /* ───────────── inside: drill-down into an entity ───────────── */
560
+ const INS = C.insides || {};
561
+ var inspect = null; // { data, stage?, step, trail }
562
+ const entLabel = (e) => (Array.isArray(e?.label) ? e.label.join(' ') : e?.label) || '';
563
+ function insideList(st) {
564
+ const list = Object.entries(st.scene.entities || {}).filter(([, e]) => e.inside && INS[e.inside]);
565
+ if (!list.length) return '';
566
+ return `<div class="inside-list"><div class="eyebrow">${t('seeInside')}</div><div>${list.map(([id, e]) => `<button class="inside-chip" type="button" data-inspect="${id}">${I('zoom-in', { size: 13, stroke: 2.4 })}${esc(INS[e.inside].title || entLabel(e) || id)}</button>`).join('')}</div></div>`;
567
+ }
568
+ $('#guide').addEventListener('click', (ev) => {
569
+ const b = ev.target.closest('[data-inspect]'); if (!b) return;
570
+ const id = b.dataset.inspect, cur = stage.ents.get(id)?.cur || LESSONS[X.lessonId].steps[X.step].scene.entities[id];
571
+ openInside(id, cur);
572
+ });
573
+ function openInside(id, ent, nested = false) {
574
+ const data = INS[ent?.inside]; if (!data) return;
575
+ const trail = nested && inspect ? [...inspect.trail, entLabel(ent) || id] : [entLabel(ent) || id];
576
+ if (inspect) { inspect.stage?.destroy(); inspect = null; }
577
+ if (!nested) { stage.focusOn(id); setTimeout(() => showInside(data, trail), reduced ? 0 : 340); }
578
+ else showInside(data, trail);
579
+ }
580
+ function showInside(data, trail) {
581
+ const box = $('#inspect'), body = $('#inspect-body');
582
+ box.hidden = false; requestAnimationFrame(() => box.classList.add('is-on'));
583
+ $('#inspect-of').textContent = trail.join(' / ');
584
+ $('#inspect-title').textContent = data.title || trail.at(-1);
585
+ body.className = `inspect__body inspect__body--${data.kind}`;
586
+ const caption = data.summary ? `<p class="inspect__caption">${data.summary}</p>` : '';
587
+ if (data.kind === 'html') {
588
+ body.innerHTML = `<iframe class="inspect__frame" sandbox="allow-scripts" title="${esc(data.title || '')}"></iframe>${caption}`;
589
+ body.querySelector('iframe').srcdoc = figureDoc(data);
590
+ inspect = { data, trail };
591
+ } else if (data.kind === 'svg') {
592
+ body.innerHTML = `<div class="inspect__svg">${data.svg}</div>${caption}`;
593
+ inspect = { data, trail };
594
+ } else {
595
+ body.innerHTML = `<div class="inspect__stage"><div class="inspect__chips" id="inspect-chips"></div><div class="inspect__canvas" id="inspect-canvas"></div><div class="stage__legend inspect__legend" id="inspect-legend"></div></div><aside class="inspect__text" id="inspect-text"></aside>`;
596
+ const st = new Stage($('#inspect-canvas'), { reducedMotion: reduced });
597
+ st.onSwipe = (d) => insideGo(inspect.step + d);
598
+ st.onInspect = (id, e) => openInside(id, e, true);
599
+ inspect = { data, trail, stage: st, step: -1 };
600
+ $('#inspect-legend').innerHTML = (data.legend || []).map((x) => { const [k, l] = Array.isArray(x) ? x : [x, (C.legendDefs || {})[x] || t(x)]; return `<span>${k === 'fail' ? '<i class="lg lg--fail">×</i>' : `<i class="lg lg--${k}"></i>`}${esc(l)}</span>`; }).join('');
601
+ requestAnimationFrame(() => { if (inspect?.stage !== st) return; st.frame(data.steps.map((x) => x.scene)); insideGo(0); });
602
+ }
603
+ setTimeout(() => $('#inspect-close').focus({ preventScroll: true }), 30);
604
+ }
605
+ // Embedded figures can't see our theme: use htmlDark if given, else tell the page via data-theme on its root.
606
+ function figureDoc(data) {
607
+ const dark = document.documentElement.dataset.theme === 'dark';
608
+ if (dark && data.htmlDark) return data.htmlDark;
609
+ const tag = `<script>document.documentElement.dataset.theme=${JSON.stringify(dark ? 'dark' : 'light')};document.documentElement.style.colorScheme=${JSON.stringify(dark ? 'dark' : 'light')}</` + 'script>';
610
+ return /<head[^>]*>/i.test(data.html) ? data.html.replace(/<head[^>]*>/i, (m) => m + tag) : tag + data.html;
611
+ }
612
+ function insideGo(i) {
613
+ if (!inspect?.stage) return;
614
+ const d = inspect.data, n = d.steps.length;
615
+ i = Math.max(0, Math.min(n - 1, i));
616
+ if (i === inspect.step) return;
617
+ const dir = inspect.step < 0 ? 0 : Math.sign(i - inspect.step);
618
+ inspect.step = i;
619
+ const st = d.steps[i];
620
+ inspect.stage.goTo(st.scene);
621
+ $('#inspect-chips').innerHTML = (d.metrics || []).map((k) => { const def = MDEF[k] || { label: k, icon: 'activity' }, v = st.metrics?.[k] ?? null; return `<span class="mini-chip" data-level="${levelOf(def, v)}">${I(def.icon || 'activity', { size: 11, stroke: 2.2 })}${esc(def.label)}<b>${esc(fmtMetric(def, v))}</b></span>`; }).join('');
622
+ const body = (st.body || []).map((p) => (BLOCK.test(p) ? p : `<p>${p}</p>`)).join('');
623
+ const callout = st.callout ? `<div class="callout callout--${st.callout.kind || 'insight'}"><div class="callout__icon">${I(CALLOUT_ICON[st.callout.kind] || 'sparkles', { size: 16, stroke: 2 })}</div><div><div class="callout__title">${esc(st.callout.title || t(st.callout.kind === 'next' ? 'next_' : st.callout.kind || 'insight'))}</div><p>${st.callout.text}</p></div></div>` : '';
624
+ const changes = st.changes?.length ? `<div class="changes"><div class="eyebrow">${t('whatChanged')}</div><ul>${st.changes.map(changeLine).join('')}</ul></div>` : '';
625
+ const ch = st.chapter;
626
+ $('#inspect-text').innerHTML = `
627
+ <div class="guide__meta"><span class="eyebrow">${t('stepOf', { n: i + 1, total: n })}</span>${ch ? `<span class="chapter chapter--${CHAPTER[ch] || 'blue'}">${esc(t(ch))}</span>` : ''}</div>
628
+ <div class="inspect__content is-in" style="--slide:${dir * 24}px"><h4 class="guide__title">${st.title}</h4><div class="guide__body">${body}</div>${callout}${changes}${insideList(st)}</div>
629
+ ${n > 1 ? `<div class="inspect__nav">
630
+ <button class="btn-ghost" type="button" data-ins="-1" ${i === 0 ? 'disabled' : ''} aria-label="${t('back')}">${I('arrow-left', { size: 15, stroke: 2.2 })}</button>
631
+ <div class="inspect__dots">${d.steps.map((x, k) => `<button type="button" class="${k === i ? 'is-current' : k < i ? 'is-done' : ''}" data-ins-go="${k}" aria-label="${esc(strip(x.title))}"></button>`).join('')}</div>
632
+ <button class="btn-pop" type="button" data-ins="1" ${i === n - 1 ? 'disabled' : ''} aria-label="${t('next', { title: '' })}">${I('arrow-right', { size: 15, stroke: 2.2 })}</button>
633
+ </div>` : ''}`;
634
+ }
635
+ $('#inspect-body').addEventListener('click', (ev) => {
636
+ const a = ev.target.closest('[data-ins]'), g = ev.target.closest('[data-ins-go]'), c = ev.target.closest('[data-inspect]');
637
+ if (a) insideGo(inspect.step + +a.dataset.ins);
638
+ else if (g) insideGo(+g.dataset.insGo);
639
+ else if (c && inspect?.stage) openInside(c.dataset.inspect, inspect.stage.ents.get(c.dataset.inspect)?.cur, true);
640
+ });
641
+ function closeInside(instant = false) {
642
+ if (!inspect) return;
643
+ inspect.stage?.destroy(); inspect = null;
644
+ const box = $('#inspect'); box.classList.remove('is-on');
645
+ const done = () => { if (!inspect) { box.hidden = true; $('#inspect-body').innerHTML = ''; } };
646
+ instant ? done() : setTimeout(done, 240);
647
+ stage.setView(null, !instant);
648
+ }
649
+ $('#inspect-close').onclick = () => closeInside();
650
+ $('#inspect').addEventListener('click', (ev) => { if (ev.target === $('#inspect')) closeInside(); });
651
+ stage.onInspect = (id, e) => openInside(id, e);
652
+ // When the presentation has drill-downs, clicking a box without one says so instead of doing nothing.
653
+ stage.onPlainClick = (id, e) => { if (Object.keys(INS).length) toast(t('noInside', { name: entLabel(e) || id }), 'scan'); };
654
+
655
+ /* ───────────── search palette ───────────── */
656
+ const strip = (h) => String(h).replace(/<[^>]+>/g, '');
657
+ const INDEX = playable.flatMap((l) => [
658
+ { lessonId: l.id, step: 0, title: LESSONS[l.id].title, sub: `${l.module.title}`, hay: `${LESSONS[l.id].title} ${LESSONS[l.id].summary || ''}`.toLowerCase(), kind: 'lesson' },
659
+ ...LESSONS[l.id].steps.map((s, i) => ({ lessonId: l.id, step: i, title: strip(s.title), sub: `${LESSONS[l.id].title} · ${i + 1}`, hay: `${strip(s.title)} ${(s.body || []).map(strip).join(' ')} ${s.decision ? strip(JSON.stringify(s.decision)) : ''} ${(s.sources || []).map((x) => (typeof x === 'string' ? x : `${x.label} ${x.note || ''}`)).join(' ')} ${s.date || ''}`.toLowerCase(), kind: 'step' })),
660
+ ]);
661
+ const norm = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '');
662
+ let palSel = 0, palItems = [];
663
+ function renderPalette(q) {
664
+ const words = norm(q.toLowerCase()).split(/\s+/).filter(Boolean);
665
+ palItems = (words.length ? INDEX.filter((x) => words.every((w) => norm(x.hay).includes(w))) : INDEX.filter((x) => x.kind === 'lesson')).slice(0, 12);
666
+ palSel = Math.min(palSel, Math.max(0, palItems.length - 1));
667
+ $('#palette-list').innerHTML = palItems.length ? palItems.map((x, i) => `<li role="option" class="${i === palSel ? 'is-sel' : ''}" data-i="${i}">${I(x.kind === 'lesson' ? 'book-open' : 'file-text', { size: 15, stroke: 2 })}<span><b>${esc(x.title)}</b><small>${esc(x.sub)}</small></span></li>`).join('') : `<li class="is-empty">${t('noResults')}</li>`;
668
+ }
669
+ function openPalette() { $('#palette').hidden = false; const i = $('#palette-input'); i.value = ''; palSel = 0; renderPalette(''); setTimeout(() => i.focus(), 10); }
670
+ const closePalette = () => { $('#palette').hidden = true; };
671
+ const choose = (i) => { const x = palItems[i]; if (!x) return; closePalette(); closeDrawer(); go(x.lessonId, x.step); };
672
+ $('#search-open').onclick = openPalette; $('#search-open-2').onclick = openPalette;
673
+ $('#palette').addEventListener('click', (ev) => { if (ev.target === $('#palette')) closePalette(); const li = ev.target.closest('[data-i]'); if (li) choose(+li.dataset.i); });
674
+ $('#palette-input').addEventListener('input', (ev) => { palSel = 0; renderPalette(ev.target.value); });
675
+ $('#palette-input').addEventListener('keydown', (ev) => {
676
+ if (ev.key === 'Escape') closePalette();
677
+ else if (ev.key === 'ArrowDown') { ev.preventDefault(); palSel = Math.min(palItems.length - 1, palSel + 1); renderPalette(ev.target.value); }
678
+ else if (ev.key === 'ArrowUp') { ev.preventDefault(); palSel = Math.max(0, palSel - 1); renderPalette(ev.target.value); }
679
+ else if (ev.key === 'Enter') choose(palSel);
680
+ });
681
+
682
+ /* ───────────── boot ───────────── */
683
+ // Automation hook (used by scripts/snapshot.mjs; handy for embedding/recording too).
684
+ window.__isx = { stage, go, replay, course: C, get state() { return { lessonId: X.lessonId, step: X.step, animating: !!stage.anim }; } };
685
+ document.fonts?.ready.then(() => stage.refit());
686
+ route();
687
+ document.documentElement.removeAttribute('data-booting');