iso-explainer 1.0.0 → 1.1.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 (31) hide show
  1. package/README.md +17 -8
  2. package/README.pt-BR.md +14 -13
  3. package/package.json +1 -1
  4. package/skills/iso-explainer/SKILL.md +24 -17
  5. package/skills/iso-explainer/assets/figure/figure.mjs +93 -0
  6. package/skills/iso-explainer/assets/runtime/ANATOMY-LICENSE.txt +21 -0
  7. package/skills/iso-explainer/assets/runtime/app.js +60 -20
  8. package/skills/iso-explainer/assets/runtime/engine.js +113 -66
  9. package/skills/iso-explainer/assets/runtime/kit.js +676 -0
  10. package/skills/iso-explainer/assets/runtime/looks-core.js +162 -0
  11. package/skills/iso-explainer/assets/runtime/looks.js +508 -0
  12. package/skills/iso-explainer/assets/runtime/styles.css +461 -447
  13. package/skills/iso-explainer/assets/templates/starter.course.json +6 -6
  14. package/skills/iso-explainer/examples/arquitetura-pedidos.docs.json +12 -10
  15. package/skills/iso-explainer/examples/catalogo-looks.course.json +599 -0
  16. package/skills/iso-explainer/examples/engenharia-na-pratica.course.json +11 -6
  17. package/skills/iso-explainer/examples/figures/token-bucket.build.mjs +111 -0
  18. package/skills/iso-explainer/examples/figures/token-bucket.html +959 -95
  19. package/skills/iso-explainer/examples/historia-pedidos.story.json +12 -10
  20. package/skills/iso-explainer/references/engine.md +1 -1
  21. package/skills/iso-explainer/references/entities.md +5 -3
  22. package/skills/iso-explainer/references/figure-craft.md +62 -0
  23. package/skills/iso-explainer/references/inside.md +20 -10
  24. package/skills/iso-explainer/references/layout.md +12 -0
  25. package/skills/iso-explainer/references/looks.md +60 -0
  26. package/skills/iso-explainer/references/story-mode.md +2 -2
  27. package/skills/iso-explainer/scripts/build.mjs +5 -3
  28. package/skills/iso-explainer/scripts/lib/layout.mjs +111 -0
  29. package/skills/iso-explainer/scripts/lib/resolve.mjs +20 -2
  30. package/skills/iso-explainer/scripts/snapshot.mjs +159 -97
  31. package/skills/iso-explainer/scripts/validate.mjs +33 -16
package/README.md CHANGED
@@ -6,9 +6,9 @@
6
6
 
7
7
  > 🇧🇷 [Leia em português](README.pt-BR.md)
8
8
 
9
- An **agent skill** that turns a system, an architecture or a project's history into an **animated, step-by-step isometric explainer**. Blocks drop onto the stage, links draw themselves, request packets flow, servers overheat and fail, HUD metrics count to their new values, and a side panel explains *why* each change happens.
9
+ An **agent skill** that turns a system, an architecture or a project's history into an **animated, step-by-step isometric explainer**. Every box is a small machine that does its job: the gateway's boom lifts for each request, the queue's conveyor carries the messages, the worker's press comes down for each job. Links draw themselves, packets flow, servers overheat and fail, HUD metrics count to their new values, and a side panel explains *why* each change happens.
10
10
 
11
- Your agent writes **one typed JSON file**. A deterministic compiler turns it into **one self-contained `index.html`** (~400 KB, with fonts, icons and engine inlined) that works offline and deploys anywhere.
11
+ Your agent writes **one typed JSON file**. A deterministic compiler turns it into **one self-contained `index.html`** (~450–600 KB, with fonts, icons and engine inlined) that works offline and deploys anywhere.
12
12
 
13
13
  **[▶ Live demos](https://actus7.github.io/iso-explainer/)** (the examples are in Portuguese; the UI also ships in English and Spanish)
14
14
 
@@ -43,7 +43,13 @@ Requires Node.js ≥ 18. Visual QA (`snapshot`) also needs Playwright *or* an in
43
43
  | **Docs** (`mode: "docs"`) | showing how an existing system works, flow by flow, focusing on one part per step | [Plataforma de Pedidos: architecture](https://actus7.github.io/iso-explainer/arquitetura.html) |
44
44
  | **Story** (`mode: "story"`) | why the system is the way it is: each decision with context, rejected alternatives, consequences and sources (ADRs, RFCs, PRs, agent sessions) | [Plataforma de Pedidos: the story](https://actus7.github.io/iso-explainer/historia.html) |
45
45
 
46
- In every mode, a box can have an **`inside`**: a magnifier appears on it and clicking dives the camera into an internal view. That view is either a mini diagram with its own steps or an interactive mechanism figure (token bucket, LSM tree, circuit breaker…).
46
+ ## Boxes that show what they do
47
+
48
+ Blocks are drawn as **objects whose working is the component's job**, in the style of the [anatomy](https://github.com/wheresryan22/anatomy) skill (whose MIT kit is bundled): many small precise parts, four-tone shading, one lit moving part, calm motion driven by the scene. Twelve looks ship: `gateway`, `queue`, `server`, `balancer`, `worker`, `database`, `cache`, `external`, `dlq`, `scheduler`, `llm`, `webhook`. A block picks one from its icon, or by `"look"`; `"look": "box"` keeps the classic cube. **[▶ Catalogue](https://actus7.github.io/iso-explainer/catalogo.html)**
49
+
50
+ ![The 12 looks](docs/img/catalogo.png)
51
+
52
+ In every mode, a box can have an **`inside`**: a magnifier appears on it and clicking dives the camera into an internal view. That view is either a mini diagram with its own steps or an interactive **mechanism figure** built as a real object (the token bucket is a coin tube with a dispenser and a turnstile), made with `assets/figure/figure.mjs`. Figures follow the host theme without reloading, `Esc` closes them from inside, and `#/lesson/step/box` links straight to an open view.
47
53
 
48
54
  <p>
49
55
  <img src="docs/img/curso.png" width="49%" alt="Course mode"> <img src="docs/img/historia.png" width="49%" alt="Story mode with a decision record">
@@ -87,10 +93,11 @@ skills/iso-explainer/
87
93
  references/ schema, entities, layout, flows, storytelling, docs, story, inside, design system, engine
88
94
  scripts/validate.mjs validates the course (JSON-path errors, geometry, text length)
89
95
  scripts/build.mjs course → single index.html
90
- scripts/snapshot.mjs per-step screenshots + layout audit (Playwright or installed Chrome/Edge)
96
+ scripts/snapshot.mjs per-step screenshots (+ every inside view) and layout audit (Playwright or Chrome/Edge)
91
97
  scripts/harvest.mjs chronological dossier from ADRs, RFCs, git and Claude Code/Codex sessions (secrets masked)
92
- assets/runtime/ isometric engine, shell, styles, icons
93
- examples/ a course, an architecture tour, a project story and a mechanism figure
98
+ assets/runtime/ isometric engine, shell, the 12 looks, the anatomy kit (MIT), styles, icons
99
+ assets/figure/ page builder for mechanism figures
100
+ examples/ a course, an architecture tour, a project story, the looks catalogue and a figure
94
101
  ```
95
102
 
96
103
  The scripts are plain Node with zero dependencies.
@@ -98,14 +105,16 @@ The scripts are plain Node with zero dependencies.
98
105
  ## Development
99
106
 
100
107
  ```bash
101
- npm test # validates and builds every example and tests the installer
108
+ npm test # validates and builds every example, checks docs/ is current, tests the installer
102
109
  ```
103
110
 
111
+ After changing the runtime or an example, rebuild the gallery (`npx iso-explainer build skills/iso-explainer/examples/<example>.json -o docs/<page>.html`; `npm test` names the command) and refresh the README images with `node scripts/readme-images.mjs`.
112
+
104
113
  Before opening a PR that touches the runtime, build an example and run `snapshot` on it at every viewport, in both themes.
105
114
 
106
115
  Releasing: bump `version` in `package.json`, update `CHANGELOG.md`, then `git tag vX.Y.Z && git push --tags` (attaches the claude.ai ZIP) and `npm publish`.
107
116
 
108
117
  ## License
109
118
 
110
- MIT. [Lucide](https://lucide.dev) icons (ISC) and [JetBrains Mono](https://www.jetbrains.com/lp/mono/) (OFL) keep their own licenses.
119
+ MIT. [Lucide](https://lucide.dev) icons (ISC), [JetBrains Mono](https://www.jetbrains.com/lp/mono/) (OFL) and the [anatomy](https://github.com/wheresryan22/anatomy) kit (MIT, © 2026 Ryan) keep their own licenses.
111
120
  Inspired by the visual language of interactive system design courses and by [Archify](https://github.com/tt-a1i/archify)'s JSON → HTML flow. No code from those projects was copied.
package/README.pt-BR.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 🇺🇸 [Read in English](README.md)
4
4
 
5
- **Skill para agentes de IA que transforma sistemas, arquiteturas e a história de um projeto em diagramas isométricos animados, passo a passo.**
5
+ **Skill para agentes de IA que transforma sistemas, arquiteturas e a história de um projeto em diagramas isométricos animados, passo a passo.** Cada caixa é uma pequena máquina que faz o seu papel: a cancela do gateway sobe a cada requisição, a esteira da fila leva as mensagens, a prensa do worker desce a cada job.
6
6
 
7
7
  O agente escreve um JSON tipado; um compilador gera **um único `index.html`** autocontido, que funciona offline e pode ser publicado em qualquer lugar.
8
8
 
@@ -29,13 +29,7 @@ npx skills add actus7/iso-explainer -g
29
29
 
30
30
  **Manual**: copie `skills/iso-explainer/` para a pasta de skills do seu agente (ex.: `~/.claude/skills/iso-explainer`).
31
31
 
32
- Requer Node.js ≥ 18 para os scripts. Playwright é opcional (só para a conferência visual).
33
-
34
- Para figuras de mecanismos dentro das caixas, instale também a skill irmã [anatomy](https://github.com/wheresryan22/anatomy):
35
-
36
- ```bash
37
- npx skills add wheresryan22/anatomy -g
38
- ```
32
+ Requer Node.js ≥ 18 para os scripts. Para a conferência visual, Playwright **ou** um Chrome/Edge instalado.
39
33
 
40
34
  ## Três modos
41
35
 
@@ -45,7 +39,13 @@ npx skills add wheresryan22/anatomy -g
45
39
  | **Documentação** (`mode: "docs"`) | mostrar como um sistema existente funciona, fluxo por fluxo, com foco no trecho de cada passo | [Plataforma de Pedidos: arquitetura](https://actus7.github.io/iso-explainer/arquitetura.html) |
46
40
  | **História** (`mode: "story"`) | contar por que o sistema é assim: cada decisão com contexto, alternativas descartadas, consequências e fontes (ADRs, RFCs, PRs, sessões de agentes) | [Plataforma de Pedidos: a história](https://actus7.github.io/iso-explainer/historia.html) |
47
41
 
48
- Em qualquer modo, uma caixa pode ter **`inside`**: uma lupa aparece nela e, ao clicar, a câmera mergulha e abre a visão interna. Pode ser um mini-diagrama com passos próprios ou uma figura interativa de mecanismo feita com o anatomy.
42
+ ## Caixas que mostram o que fazem
43
+
44
+ Os blocos são desenhados como **objetos cujo funcionamento é o papel do componente**, no estilo da skill [anatomy](https://github.com/wheresryan22/anatomy) (cujo kit, MIT, vem embutido): muitas peças pequenas e precisas, sombreamento em quatro tons, uma peça acesa que se move, movimento calmo guiado pela cena. São 12 looks: `gateway`, `queue`, `server`, `balancer`, `worker`, `database`, `cache`, `external`, `dlq`, `scheduler`, `llm`, `webhook`. A caixa escolhe pelo ícone ou por `"look"`; `"look": "box"` mantém o cubo clássico. **[▶ Catálogo](https://actus7.github.io/iso-explainer/catalogo.html)**
45
+
46
+ ![Os 12 looks](docs/img/catalogo.png)
47
+
48
+ Em qualquer modo, uma caixa pode ter **`inside`**: uma lupa aparece nela e, ao clicar, a câmera mergulha e abre a visão interna. Pode ser um mini-diagrama com passos próprios ou uma **figura de mecanismo** construída como objeto real (o token bucket é um tubo de fichas com dispensador e catraca), feita com `assets/figure/figure.mjs`. A figura segue o tema sem recarregar, `Esc` fecha de dentro dela, e `#/lição/passo/caixa` abre a visão direto.
49
49
 
50
50
  <p>
51
51
  <img src="docs/img/curso.png" width="49%" alt="Modo curso"> <img src="docs/img/historia.png" width="49%" alt="Modo história com registro de decisão">
@@ -76,13 +76,14 @@ skills/iso-explainer/
76
76
  references/ esquema, entidades, layout, fluxos, roteiro, docs, história, inside, design system, motor
77
77
  scripts/validate.mjs valida o curso (erros com caminho JSON, geometria, textos)
78
78
  scripts/build.mjs curso → index.html único
79
- scripts/snapshot.mjs screenshots por passo + auditoria de layout (Playwright)
79
+ scripts/snapshot.mjs screenshots por passo (+ cada visão interna) e auditoria de layout (Playwright ou Chrome/Edge)
80
80
  scripts/harvest.mjs dossiê cronológico de ADRs, RFCs, git e sessões do Claude Code/Codex (segredos mascarados)
81
- assets/runtime/ motor isométrico, shell, estilos, ícones
82
- examples/ um curso, um tour de arquitetura, uma história e uma figura de mecanismo
81
+ assets/runtime/ motor isométrico, shell, os 12 looks, o kit do anatomy (MIT), estilos, ícones
82
+ assets/figure/ construtor de páginas de figura de mecanismo
83
+ examples/ um curso, um tour de arquitetura, uma história, o catálogo de looks e uma figura
83
84
  ```
84
85
 
85
86
  ## Licença
86
87
 
87
- MIT. Ícones [Lucide](https://lucide.dev) (ISC) e fonte [JetBrains Mono](https://www.jetbrains.com/lp/mono/) (OFL) mantêm suas licenças.
88
+ MIT. Ícones [Lucide](https://lucide.dev) (ISC), fonte [JetBrains Mono](https://www.jetbrains.com/lp/mono/) (OFL) e o kit do [anatomy](https://github.com/wheresryan22/anatomy) (MIT, © 2026 Ryan) mantêm suas licenças.
88
89
  Inspirado na linguagem visual de cursos interativos de system design e no fluxo JSON → HTML do [Archify](https://github.com/tt-a1i/archify). Nenhum código desses projetos foi copiado.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iso-explainer",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Agent skill that turns a system, an architecture or a project's history into an animated, step-by-step isometric explainer: one self-contained HTML file from typed JSON.",
5
5
  "keywords": [
6
6
  "agent-skill",
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: iso-explainer
3
- description: "Diagramas isométricos animados passo a passo (JSON → um HTML): ensinar system design, documentar a arquitetura de um repo ou contar a história das decisões. Use para explicar fluxos e pipelines."
3
+ description: "Diagramas isométricos animados passo a passo (JSON → um HTML offline): ensinar system design, documentar a arquitetura de um repo ou contar a história das decisões. Use para explicar fluxos, pipelines, filas, cache, escala, incidentes e antes/depois. Animated step-by-step isometric diagrams: explain an architecture, teach system design, give a repo architecture tour, tell the story of design decisions (ADRs), visualize a request flow or pipeline."
4
4
  ---
5
5
 
6
6
  # iso-explainer
7
7
 
8
- Transforma um sistema, uma arquitetura ou um fluxo de trabalho em uma **aula interativa**: cada ideia é um diagrama isométrico animado que a pessoa percorre passo a passo. Blocos caem na cena, links se desenham, pacotes de requisição circulam, servidores esquentam e caem, métricas do HUD contam até o novo valor, e um painel lateral narra o porquê de cada mudança.
8
+ Transforma um sistema, uma arquitetura ou um fluxo de trabalho em uma **aula interativa**: cada ideia é um diagrama isométrico animado que a pessoa percorre passo a passo. Cada caixa é um **objeto que faz o seu papel** — a cancela do gateway sobe a cada requisição, a esteira da fila anda, a prensa do worker desce a cada job —, links se desenham, pacotes circulam, servidores esquentam e caem, métricas do HUD contam até o novo valor, e um painel lateral narra o porquê de cada mudança.
9
9
 
10
- O agente escreve **um JSON tipado** (o curso). Um compilador determinístico gera **um único `index.html`** autocontido (fontes, ícones e motor embutidos, ~350 KB), pronto para abrir offline, publicar como artifact ou fazer deploy na Vercel/Netlify/GitHub Pages.
10
+ O agente escreve **um JSON tipado** (o curso). Um compilador determinístico gera **um único `index.html`** autocontido (fontes, ícones e motor embutidos, ~450–600 KB), pronto para abrir offline, publicar como artifact ou fazer deploy na Vercel/Netlify/GitHub Pages.
11
11
 
12
12
  Use quando pedirem: explicar uma arquitetura, "mostrar como o fluxo funciona", demonstrar um pipeline (webhook → fila → worker, CI/CD, agente com ferramentas, ETL), comparar antes/depois de uma refatoração, ensinar system design, documentar um incidente passo a passo, ou "fazer algo tipo o archify / designed-to-scale".
13
13
 
@@ -15,16 +15,16 @@ Use quando pedirem: explicar uma arquitetura, "mostrar como o fluxo funciona", d
15
15
 
16
16
  - **Curso** (padrão): ensina um conceito. Arco problema → técnica → solução → trade-off → resumo. Progresso, lições concluídas, "Você vai aprender".
17
17
  - **Documentação** (`"meta": { "mode": "docs" }`): **mostra como um sistema existente funciona** — para chefe, time, cliente, onboarding, revisão de arquitetura. Mesmo visual; vocabulário vira Sistema / Visões / Neste fluxo / Pontos-chave, some o que é de curso, capítulos de arquitetura (visão geral, componente, fluxo, dados, integração, falha, decisão, risco, proposta) e o padrão de **foco** (`dim`) para destacar um trecho por passo. Leia `references/architecture-mode.md`.
18
-
19
18
  - **História** (`"meta": { "mode": "story" }`): **conta como o sistema chegou até aqui** — cada passo é um momento datado (incidente, motivação, decisão, consequência) com o registro da decisão (contexto, alternativas descartadas, consequências) e as **fontes** citadas; a arquitetura no palco é a daquela época. Material vem de `scripts/harvest.mjs` (ADRs, RFCs, git, sessões do Claude Code/Codex, exports). Leia `references/story-mode.md`.
20
19
 
21
- Nos três modos, qualquer caixa pode ter **`inside`**: uma lupa aparece nela e, ao clicar, a câmera mergulha e abre a visão interna — um mini-diagrama com passos próprios ou uma figura interativa de mecanismo feita com a skill **anatomy** (token bucket, LSM tree, circuit breaker…). Leia `references/inside.md`.
20
+ Nos três modos, qualquer caixa pode ter **`inside`**: uma lupa aparece nela e, ao clicar, a câmera mergulha e abre a visão interna — um mini-diagrama com passos próprios ou uma figura interativa que constrói o mecanismo como um objeto real (token bucket, LSM tree, circuit breaker…), feita com o kit do [anatomy](https://github.com/wheresryan22/anatomy) embutido aqui. Leia `references/inside.md`.
22
21
 
23
22
  Escolha pelo pedido: "explicar/ensinar X" → curso; "mostrar/documentar/apresentar o nosso sistema / como ficou a arquitetura" → docs; "contar a história / por que decidimos / evolução / onboarding com contexto" → história.
24
23
 
25
24
  ## O que o resultado tem (já pronto, não reimplemente)
26
25
 
27
- - Palco isométrico SVG com 8 entidades: `block` (serviço), `device` (laptop/celular), `db` (cilindro com nível), `crowd` (multidão), `queue` (fila de bolinhas), `zone` (região tracejada), `ghost` (planejado), `panel` (cartão de informações ancorado num canto).
26
+ - Palco isométrico SVG com 8 entidades: `block` (serviço), `device` (laptop/celular), `db` (banco), `crowd` (multidão), `queue` (fila de bolinhas), `zone` (região tracejada), `ghost` (planejado), `panel` (cartão de informações ancorado num canto).
27
+ - **12 looks** para `block`/`db` — gateway, queue, server, balancer, worker, database, cache, external, dlq, scheduler, llm, webhook —, escolhidos pelo `glyph` ou por `look`, animados pelo tráfego e pela `cpu` (`references/looks.md`).
28
28
  - Transições automáticas entre passos: o que sai some, o que muda é interpolado, o que entra cai com bounce e escalonamento, links se desenham, a câmera reenquadra sozinha e destaca o que é novo.
29
29
  - Pacotes animados em rotas de links: requisição/resposta (`bounce`), espera (`hold`), falha probabilística (`fail`), rodízio ou pesos entre rotas, fan-out, 14 tipos visuais.
30
30
  - Estados de entidade: `cpu` (medidor), `heat` (sobrecarga pulsando), `dead` (cinza com X), `dim`, `tags` (pílulas), `lift`.
@@ -37,22 +37,23 @@ Escolha pelo pedido: "explicar/ensinar X" → curso; "mostrar/documentar/apresen
37
37
  0. **Modo história?** Rode primeiro `node SKILL_DIR/scripts/harvest.mjs <repo> --out dossier` e leia `dossier.md` (ver `references/story-mode.md`).
38
38
  1. **Entenda o sistema e o objetivo da aula.** Uma lição responde *uma* pergunta ("por que precisamos de fila?"). Se o material for um repositório, leia o código antes de desenhar — nunca invente componentes.
39
39
  2. **Escreva o roteiro antes do JSON.** Curso: 6–12 passos no arco *problema → técnica(s) → solução → trade-off → resumo* (`references/storytelling.md`). Docs: visão geral completa → um passo de foco por fluxo/componente → decisões (`references/architecture-mode.md`). Cada passo muda **uma** coisa visível.
40
- 3. **Profundidade:** em docs/história, **toda caixa principal** ganha `inside`; em curso, as peças cujo mecanismo é o assunto. Sistema interno → visão nativa; mecanismo/algoritmo → figura do anatomy.
41
- 4. **Planeje o layout.** Escolha coordenadas com as receitas de `references/layout.md` (eixos isométricos, espaçamentos, roteamento de links). Desenhe a cena *final* primeiro e derive as anteriores removendo peças — assim nada precisa mudar de lugar.
40
+ 3. **Objetos e profundidade.** Dê a cada componente o `look` que diz a verdade sobre o seu papel (ou o `glyph` que o escolhe); estados e camadas de código ficam `"look": "box"` (`references/looks.md`). Em docs/história, **toda caixa principal** ganha `inside`; em curso, as peças cujo mecanismo é o assunto. Sistema interno → visão nativa; mecanismo/algoritmo → figura construída com `assets/figure/figure.mjs` (`references/inside.md`, `references/figure-craft.md`).
41
+ 4. **Layout: omita `x`/`y`.** Entidades sem posição são colocadas pelo layout automático (exceto `queue`, que precisa de `x`/`y`, e `zone`/`crowd`/`panel`, que têm geometria própria) (colunas na ordem do fluxo dos `links`, folhas ao lado do seu componente, espaço para rótulos) — é o caminho padrão e o mais seguro. Declare todas as entidades da lição em `defs` (a cena *final*) e derive os passos mostrando/ocultando peças, assim nada muda de lugar. Só fixe coordenadas quando a posição *é* a explicação (zonas, regiões, antes/depois), usando as receitas de `references/layout.md`. Passos que esmaecem o resto (`dim`) fazem a câmera aproximar do que ficou em foco.
42
42
  5. **Escreva o curso.** Comece de `assets/templates/starter.course.json` (ou de `examples/engenharia-na-pratica.course.json`, que mostra tudo). Use `defs` + herança entre passos para manter o JSON curto. Esquema completo em `references/schema.md`; entidades em `references/entities.md`.
43
- 6. **Valide:** `node SKILL_DIR/scripts/validate.mjs curso.json` — corrija todos os erros e leia os avisos (sobreposições, textos longos, rotas inválidas).
43
+ 6. **Valide:** `node SKILL_DIR/scripts/validate.mjs curso.json` — corrija todos os erros **e todos os avisos de geometria** (objetos sobrepostos, link curto demais para o rótulo). A correção mais simples quase sempre é apagar `x`/`y` das entidades envolvidas.
44
44
  7. **Compile:** `node SKILL_DIR/scripts/build.mjs curso.json -o dist/index.html`
45
- 8. **Confira visualmente** (se houver Playwright/Chromium): `node SKILL_DIR/scripts/snapshot.mjs dist/index.html --out shots --viewport all --theme both`. Abra os PNGs, leia `shots/report.json` (sobreposições de rótulos, coisas sob o HUD, erros de console) e ajuste coordenadas até ficar limpo. O script usa o Chromium do Playwright ou, na falta dele, o Chrome/Edge instalado (ou `CHROME_PATH`). Sem Playwright, abra o HTML num navegador e percorra os passos.
46
- 9. **Entregue** o `index.html` (ou publique). Deploy: `references/engine.md#deploy`.
45
+ 8. **Audite até zerar** (obrigatório quando houver Playwright ou Chrome/Edge): `node SKILL_DIR/scripts/snapshot.mjs dist/index.html --out shots --viewport all --theme both --insides`. O script sai com código 1 enquanto houver erro de console ou problema de layout: rótulos sobrepostos (`overlap`), rótulo sobre outro objeto (`covers`), rótulo fora do palco (`clipped`) ou sob o HUD (`hud`), e botão que não recebe clique (`blocked`). Corrija e repita 6–8 até a última linha ser `✓ no console errors, no layout issues`. Abra também alguns PNGs: a auditoria não julga se a cena *explica*. O script usa o Chromium do Playwright ou o Chrome/Edge instalado (ou `CHROME_PATH`); `--lenient` só serve para explorar. Sem navegador, diga isso ao usuário e percorra os passos à mão.
46
+ 9. **Entregue** o `index.html` (ou publique) só depois da auditoria limpa. Deploy: `references/engine.md#deploy`.
47
47
 
48
48
  ## Regras de qualidade (o que separa uma aula boa de um diagrama qualquer)
49
49
 
50
50
  - **Um conceito por passo.** Se o "o que mudou" tem mais de 3 linhas, divida o passo.
51
+ - **O objeto é a explicação.** Uma caixa que é um objeto (cancela, esteira, prensa) ensina antes do texto; só mostre tráfego onde o objeto deve trabalhar, e deixe em repouso o que o passo não discute.
51
52
  - **Mostre, depois explique.** A cena tem que tornar o problema *visível* (pacotes lentos, `heat`, `dead`, falhas `fail`, fila crescendo) antes do texto dar a solução.
52
53
  - **Números contam a história.** 3–5 métricas no HUD que mudam de forma significativa entre passos (latência, vazão, erros, custo, profundidade da fila). Use `good`/`warn` para colorir.
53
54
  - **Texto curto.** Título ≤ 48 caracteres; `body` = 1–2 parágrafos, ≤ 70 palavras; `short` ≤ 14 caracteres; rótulos de link ≤ 28; no máximo um `callout`.
54
55
  - **Até ~12 entidades por cena** e ≤ 8 pílulas no total. Detalhe vai para o texto ou para um `panel`.
55
- - **Espaço:** ≥ 3 unidades de grade entre footprints; ≥ 6 quando houver pílulas/rótulos entre eles. Pílulas `tags`/`cpu` ficam *acima* do bloco — deixe espaço em cima ou use `"pills": "below"`.
56
+ - **Espaço:** com coordenadas manuais, ≥ 3 unidades de grade entre footprints; ≥ 6 quando houver pílulas/rótulos entre eles. Pílulas `tags`/`cpu` ficam *acima* do bloco — deixe espaço em cima ou use `"pills": "below"`. Rótulo de link em cima de um objeto: mova-o ao longo da linha com `labelAt` (0–1).
56
57
  - Curso: **primeiro passo = problema**, último = **resumo** (com `panel`). Docs: **primeiro = visão geral** com a cena completa, último = decisões/resumo. Metas (`goals`) apontam para os passos onde cada ideia aparece.
57
58
  - Docs: **fidelidade** — só componentes e nomes que existem no código/infra; números só se medidos (senão omita `metrics`).
58
59
  - **Consistência espacial:** uma entidade mantém o id e a posição ao longo da lição; mude estado (`cpu`, `dead`, `tags`), não lugar — salvo quando o movimento *é* a explicação.
@@ -66,7 +67,9 @@ Escolha pelo pedido: "explicar/ensinar X" → curso; "mostrar/documentar/apresen
66
67
  | `references/entities.md` | Ao escolher/configurar entidades, cores, glifos (ícones Lucide), estados e tamanhos. |
67
68
  | `references/layout.md` | Ao posicionar: sistema de coordenadas, receitas (pipeline, fan-out, camadas, zonas), roteamento de links e rótulos, câmera. |
68
69
  | `references/storytelling.md` | Ao roteirizar um curso: arco da lição, capítulos, padrões de passo, como escrever, como escolher métricas, anti-padrões. |
69
- | `references/inside.md` | Ao dar profundidade a uma caixa: `inside` nativo (passos internos) ou figura HTML/SVG da skill anatomy. |
70
+ | `references/looks.md` | Ao escolher o objeto de cada caixa: catálogo dos 12 looks, inferência pelo glyph, o que anima, layout, criar um look novo. |
71
+ | `references/inside.md` | Ao dar profundidade a uma caixa: `inside` nativo (passos internos) ou figura (`figure.mjs`), contrato host ↔ figura, rota direta. |
72
+ | `references/figure-craft.md` | Ao construir uma figura ou um look: "o objeto é a explicação", lista de peças, ordem de pintura, acabamento, receitas do kit. |
70
73
  | `references/story-mode.md` | Ao contar a evolução/decisões de um projeto: `mode: "story"`, coletor `harvest.mjs`, registro de decisão, fontes, como narrar. |
71
74
  | `references/architecture-mode.md` | Ao documentar/apresentar um sistema existente: `mode: "docs"`, visões recomendadas, capítulos de arquitetura, padrão de foco, fidelidade ao código. |
72
75
  | `references/flows.md` | Ao animar tráfego: rotas, tipos de pacote, `bounce`/`hold`/`fail`/pesos/fan-out, estilos de link. |
@@ -79,14 +82,18 @@ Escolha pelo pedido: "explicar/ensinar X" → curso; "mostrar/documentar/apresen
79
82
  SKILL.md
80
83
  scripts/validate.mjs valida o curso (erros com caminho JSON + checagens de geometria)
81
84
  scripts/build.mjs curso → HTML único (--fonts inline|google|none, --force)
82
- scripts/snapshot.mjs screenshots por passo + auditoria de layout (Playwright)
85
+ scripts/snapshot.mjs screenshots por passo (+ --insides) e auditoria de layout (Playwright ou Chrome/Edge)
83
86
  scripts/harvest.mjs dossiê cronológico de ADRs/RFCs/git/sessões de agentes (segredos mascarados)
84
- scripts/lib/resolve.mjs expansão de defs/herança/coordenadas (usado pelos dois acima)
85
- assets/runtime/ motor (engine.js), shell (app.js), styles.css, icons.js, template.html
87
+ scripts/lib/resolve.mjs expansão de defs/herança/coordenadas (usado por validate e build)
88
+ scripts/lib/layout.mjs layout automático das entidades sem x/y
89
+ assets/runtime/ motor (engine.js), shell (app.js), looks (looks.js, looks-core.js), kit do anatomy (kit.js, MIT),
90
+ styles.css, icons.js, template.html
91
+ assets/figure/figure.mjs página de figura para `inside` (cartão compacto, tema do host, loop, controles)
86
92
  assets/fonts/ JetBrains Mono (OFL)
87
93
  assets/templates/starter.course.json ponto de partida mínimo
88
94
  examples/engenharia-na-pratica.course.json curso completo com 2 lições (system design + workflow)
89
95
  examples/arquitetura-pedidos.docs.json tour de arquitetura em modo docs (foco, falhas, decisões)
90
96
  examples/historia-pedidos.story.json a história do mesmo sistema em modo story (ADRs, fontes, datas)
91
- examples/figures/token-bucket.html figura de mecanismo usada como `inside` (no lugar de uma figura do anatomy)
97
+ examples/catalogo-looks.course.json os 12 looks com tráfego
98
+ examples/figures/token-bucket.build.mjs figura de mecanismo (tubo de fichas) → token-bucket.html, usada como `inside`
92
99
  ```
@@ -0,0 +1,93 @@
1
+ // iso-explainer · figure.mjs
2
+ // Build "inside" figures in the anatomy style: a real object, drawn with the same kit and painters
3
+ // as the stage looks, framed as a compact card that fits the inside dialog (no page margins), in the
4
+ // stage's warm palette, following the host theme without reloading.
5
+ //
6
+ // import { figurePage, runtime } from '<skill>/assets/figure/figure.mjs';
7
+ // fs.writeFileSync('figures/x.html', figurePage({ title, hint, svg, live, ... }));
8
+ //
9
+ // `live` is plain JS run in the page after the kit and the painters (every export of kit.js and
10
+ // looks-core.js is in scope), plus: P (your projection), put(id, svg), readout(text), loop(fn),
11
+ // reduced (bool), onTheme(fn), $ (querySelector). See references/inside.md.
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const RT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'runtime');
17
+ export * as kit from '../runtime/kit.js';
18
+ export * as paint from '../runtime/looks-core.js';
19
+
20
+ const strip = (file) => fs.readFileSync(path.join(RT, file), 'utf8').replace(/^import .*$/gm, '').replace(/^export /gm, '');
21
+ /** The kit and the painters as one script body (no modules), for the page. */
22
+ export const runtime = () => strip('kit.js') + '\n' + strip('looks-core.js');
23
+
24
+ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
25
+
26
+ const CSS = `
27
+ :root{--page:#f4ebe0;--ink:#211e1b;--muted:#6f6961;--line:#ddd3c5;--accent:#5fae57;color-scheme:light}
28
+ :root[data-theme=dark]{--page:#1e1b18;--ink:#efe6d6;--muted:#a3998b;--line:#4f473d;--accent:#7fc278;color-scheme:dark}
29
+ *{box-sizing:border-box}
30
+ html,body{margin:0;height:100%;background:var(--page);color:var(--ink);font:12px/1.45 "JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
31
+ .fig{height:100%;display:grid;grid-template-rows:auto minmax(0,1fr) auto auto;gap:4px;padding:12px 16px 12px}
32
+ .row{display:flex;justify-content:space-between;align-items:baseline;gap:12px;color:var(--muted);font-size:10.5px;letter-spacing:.09em;text-transform:uppercase}
33
+ .row b{color:var(--ink);font-weight:700}
34
+ .readout{color:var(--ink);font-weight:700;letter-spacing:.02em;text-transform:none;font-variant-numeric:tabular-nums;text-align:right}
35
+ .stage{min-height:0;display:grid;outline:none}
36
+ .stage svg{width:100%;height:100%;display:block}
37
+ .controls{display:flex;flex-wrap:wrap;gap:6px 18px;align-items:center;color:var(--muted);font-size:11px}
38
+ .controls label{display:flex;gap:8px;align-items:center}
39
+ .controls output{color:var(--ink);font-weight:700;min-width:4ch;font-variant-numeric:tabular-nums}
40
+ input[type=range]{accent-color:var(--accent);width:120px}
41
+ .caption{margin:2px 0 0;color:var(--muted);font-size:11px;line-height:1.5}
42
+ @media (max-width:520px){.fig{padding:10px}.row{font-size:9.5px}input[type=range]{width:90px}}
43
+ `;
44
+
45
+ // Page runtime: theme remap (same rule as the stage: lowercase hex → darkHex), live groups, the loop.
46
+ const PAGE_JS = `
47
+ const $ = (s) => document.querySelector(s);
48
+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
49
+ const isDarkNow = () => document.documentElement.dataset.theme === 'dark';
50
+ const themed = (s) => (isDarkNow() ? String(s).replace(/#[0-9a-f]{6}\\b|#[0-9a-f]{3}\\b/g, darkHex) : s);
51
+ const ART = $('#art'), ART_LIGHT = ART.innerHTML, LIVE = {}, themeCbs = [];
52
+ const put = (id, svg) => { LIVE[id] = svg; const n = document.getElementById(id); if (n) n.innerHTML = themed(svg); };
53
+ const readout = (t) => { $('#readout').textContent = t; $('#stage').setAttribute('aria-valuetext', t); };
54
+ const onTheme = (f) => themeCbs.push(f);
55
+ function retheme() { ART.innerHTML = themed(ART_LIGHT); for (const id in LIVE) put(id, LIVE[id]); themeCbs.forEach((f) => f()); }
56
+ new MutationObserver(retheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
57
+ let visible = true;
58
+ new IntersectionObserver(([e]) => { visible = e.isIntersecting; }).observe($('#stage'));
59
+ // loop(fn): fn(dt, t) every frame while visible; once (dt = 0) under reduced motion.
60
+ function loop(fn) {
61
+ if (reduced) { fn(0, 0); return; }
62
+ let last = performance.now(), t = 0;
63
+ const tick = (now) => { const dt = Math.min(0.05, (now - last) / 1000); last = now; if (visible && !document.hidden) { t += dt; fn(dt, t); } requestAnimationFrame(tick); };
64
+ requestAnimationFrame(tick);
65
+ }
66
+ if (isDarkNow()) retheme();
67
+ `;
68
+
69
+ /**
70
+ * @param {object} o
71
+ * @param {string} o.title short title (top right)
72
+ * @param {string} [o.fig] figure tag (top left), e.g. "Fig 2"
73
+ * @param {string} [o.hint] interaction hint (bottom left)
74
+ * @param {string} [o.readout] initial live readout (bottom right)
75
+ * @param {string} o.svg static art: SVG markup for inside <g id="art">, plus live slots <g id="…"></g>
76
+ * @param {number[]} o.view [width, height] of the viewBox
77
+ * @param {string} [o.controls] HTML for the control row (range inputs…)
78
+ * @param {string} [o.caption] one true sentence under the figure
79
+ * @param {object} o.P the projection used to draw (passed to the live code)
80
+ * @param {string} [o.live] live code (see header)
81
+ * @param {string} [o.lang]
82
+ */
83
+ export function figurePage({ title, fig = 'Fig', hint = '', readout = '', svg, view = [640, 360], controls = '', caption = '', P, live = '', lang = 'pt-BR' }) {
84
+ const [w, h] = view;
85
+ const script = `(()=>{\n${runtime()}\nconst P = ${JSON.stringify(P)};\n${PAGE_JS}\n${live}\n})();`.replace(/<\/(script)/gi, '<\\/$1');
86
+ return `<!doctype html><html lang="${esc(lang)}" data-theme="light"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title><style>${CSS}</style></head>
87
+ <body><main class="fig">
88
+ <div class="row"><span>${esc(fig)}</span><b>${esc(title)}</b></div>
89
+ <div class="stage" id="stage" tabindex="0" role="img" aria-label="${esc(title)}"><svg viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg"><g id="art">${svg}</g></svg></div>
90
+ <div class="row"><span>${esc(hint)}</span><span class="readout" id="readout" aria-live="polite">${esc(readout)}</span></div>
91
+ ${controls ? `<div class="controls">${controls}</div>` : ''}${caption ? `<p class="caption">${caption}</p>` : ''}
92
+ </main><script>${script}</script></body></html>`;
93
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ryan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -198,7 +198,7 @@ document.querySelector('#app').innerHTML = `
198
198
  ${tabs.length ? `<nav class="drawer-nav">${navHTML('')}</nav>` : ''}
199
199
  <div class="tree-root">
200
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>
201
+ <span>${t('course')}</span><span class="tree-root__meta">${t('lessons', { n: playable.length })}</span>
202
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
203
  </div>
204
204
  <nav class="course" id="course"></nav>
@@ -266,7 +266,7 @@ new ResizeObserver(syncHud).observe($('#legend'));
266
266
  // Phones: size the stage to the lesson's widest scene so the diagram fills the width instead of floating in empty space.
267
267
  function fitStageHeight() {
268
268
  const el = $('#stage'), L = LESSONS[X.lessonId];
269
- if (document.documentElement.dataset.layout !== 'stack' || !L) { el.style.height = ''; return; }
269
+ if (document.documentElement.dataset.layout !== 'stack' || el.classList.contains('is-full') || !L) { el.style.height = ''; return; }
270
270
  let aspect = 0.45;
271
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
272
  const w = el.clientWidth - 12, want = Math.round(w * aspect * 1.08 + 64 + 46);
@@ -286,7 +286,11 @@ function setTheme(theme) {
286
286
  $('#theme-btn').innerHTML = I(theme === 'dark' ? 'sun' : 'moon', { size: 17, stroke: 2 });
287
287
  const m = document.querySelector('meta[name="theme-color"]'); if (m) m.content = theme === 'dark' ? '#211e1a' : '#f4ebe0';
288
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); }
289
+ if (typeof inspect !== 'undefined' && inspect) {
290
+ inspect.stage?.retheme();
291
+ const fr = $('#inspect-body iframe');
292
+ if (fr) { if (inspect.data.htmlDark) fr.srcdoc = figureDoc(inspect.data); else fr.contentWindow?.postMessage({ isx: 'theme', dark: theme === 'dark' }, '*'); }
293
+ }
290
294
  }
291
295
  $('#theme-btn').onclick = () => setTheme(document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark');
292
296
  setTheme(document.documentElement.dataset.theme || 'light');
@@ -499,15 +503,15 @@ function go(lessonId, step) {
499
503
  location.hash = `#/${lessonId}/${step + 1}`;
500
504
  }
501
505
  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)) };
506
+ const m = /^#\/([\w-]+)\/(\d+)(?:\/([\w-]+))?$/.exec(location.hash); // #/lesson/step[/entity-with-inside]
507
+ if (m && LESSONS[m[1]]) return { lessonId: m[1], step: Math.max(0, Math.min(LESSONS[m[1]].steps.length - 1, m[2] - 1)), open: m[3] || null };
504
508
  const last = store.get('last', null);
505
509
  if (last && LESSONS[last.lessonId]) return last;
506
510
  return { lessonId: playable[0].id, step: 0 };
507
511
  }
508
512
  function route() {
509
513
  closeInside(true);
510
- const { lessonId, step } = parseHash();
514
+ const { lessonId, step, open } = parseHash();
511
515
  const L = LESSONS[lessonId], info = FLAT.find((l) => l.id === lessonId), fresh = lessonId !== X.lessonId, prev = X.step;
512
516
  X.lessonId = lessonId; X.step = step; store.set('last', { lessonId, step });
513
517
  X.seen[lessonId] = Math.max(X.seen[lessonId] ?? -1, step); store.set('seen', X.seen);
@@ -524,6 +528,7 @@ function route() {
524
528
  updateHud(L, L.steps[step].metrics, !fresh);
525
529
  document.title = `${L.title} · ${META.title || brand.name}`;
526
530
  speakStep();
531
+ if (open) scheduleInsideOpen(() => { const e = stage.ents.get(open)?.cur; if (e?.inside) openInside(open, e); }, reduced ? 0 : 900);
527
532
  }
528
533
  addEventListener('hashchange', route);
529
534
 
@@ -537,10 +542,17 @@ function replay() {
537
542
  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
543
  const togglePause = () => { stage.paused = !stage.paused; syncPause(); };
539
544
  $('#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 }); };
545
+ $('#expand').onclick = () => {
546
+ const on = $('#stage').classList.toggle('is-full'), button = $('#expand');
547
+ document.documentElement.classList.toggle('stage-full', on);
548
+ button.setAttribute('aria-pressed', String(on));
549
+ button.innerHTML = I(on ? 'minimize-2' : 'maximize-2', { size: 15, stroke: 2 });
550
+ fitStageHeight();
551
+ };
541
552
  addEventListener('keydown', (ev) => {
542
553
  if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'k') { ev.preventDefault(); openPalette(); return; }
543
554
  if (!$('#palette').hidden || ev.target.closest('input, textarea')) return;
555
+ if (ev.key === 'Escape' && insideOpenTimer !== null && !inspect) { closeInside(); return; }
544
556
  if (inspect) {
545
557
  if (ev.key === 'Escape') closeInside();
546
558
  else if (inspect.stage && ev.key === 'ArrowRight') { ev.preventDefault(); insideGo(inspect.step + 1); }
@@ -559,6 +571,16 @@ addEventListener('keydown', (ev) => {
559
571
  /* ───────────── inside: drill-down into an entity ───────────── */
560
572
  const INS = C.insides || {};
561
573
  var inspect = null; // { data, stage?, step, trail }
574
+ var opener = null; // id of the stage box whose inside is open (focus returns to it)
575
+ let insideOpenTimer = null;
576
+ function scheduleInsideOpen(open, delay) {
577
+ clearTimeout(insideOpenTimer);
578
+ const hash = location.hash;
579
+ insideOpenTimer = setTimeout(() => {
580
+ insideOpenTimer = null;
581
+ if (location.hash === hash) open();
582
+ }, delay);
583
+ }
562
584
  const entLabel = (e) => (Array.isArray(e?.label) ? e.label.join(' ') : e?.label) || '';
563
585
  function insideList(st) {
564
586
  const list = Object.entries(st.scene.entities || {}).filter(([, e]) => e.inside && INS[e.inside]);
@@ -574,8 +596,11 @@ function openInside(id, ent, nested = false) {
574
596
  const data = INS[ent?.inside]; if (!data) return;
575
597
  const trail = nested && inspect ? [...inspect.trail, entLabel(ent) || id] : [entLabel(ent) || id];
576
598
  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);
599
+ if (!nested) {
600
+ opener = id;
601
+ history.replaceState(null, '', `#/${X.lessonId}/${X.step + 1}/${id}`); // shareable: the link reopens this view
602
+ stage.focusOn(id); scheduleInsideOpen(() => showInside(data, trail), reduced ? 0 : 340);
603
+ } else showInside(data, trail);
579
604
  }
580
605
  function showInside(data, trail) {
581
606
  const box = $('#inspect'), body = $('#inspect-body');
@@ -584,13 +609,10 @@ function showInside(data, trail) {
584
609
  $('#inspect-title').textContent = data.title || trail.at(-1);
585
610
  body.className = `inspect__body inspect__body--${data.kind}`;
586
611
  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}`;
612
+ if (data.kind === 'html' || data.kind === 'svg') { // figures run sandboxed: their ids, CSS and scripts can't touch ours
613
+ body.innerHTML = `<iframe class="inspect__frame" sandbox="allow-scripts" title="${esc(data.title || '')}"${data.height ? ` style="height:${+data.height}px"` : ''}></iframe>${caption}`;
589
614
  body.querySelector('iframe').srcdoc = figureDoc(data);
590
615
  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
616
  } else {
595
617
  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
618
  const st = new Stage($('#inspect-canvas'), { reducedMotion: reduced });
@@ -602,13 +624,24 @@ function showInside(data, trail) {
602
624
  }
603
625
  setTimeout(() => $('#inspect-close').focus({ preventScroll: true }), 30);
604
626
  }
605
- // Embedded figures can't see our theme: use htmlDark if given, else tell the page via data-theme on its root.
627
+ // Embedded figures run in a sandboxed iframe. A small bridge goes in first: it sets data-theme on the
628
+ // figure's <html> (and on <body class="iso"> for anatomy-kit pages), follows theme changes sent by
629
+ // postMessage without reloading, and hands Esc back to us so the dialog closes from inside the figure.
630
+ const FIGURE_BRIDGE = (theme) => `<script>(function(){var d=document.documentElement;function th(k){d.dataset.theme=k;d.style.colorScheme=k;var b=document.body;if(b&&b.classList.contains('iso'))b.dataset.theme=k}th(${JSON.stringify(theme)});addEventListener('DOMContentLoaded',function(){th(d.dataset.theme)});addEventListener('message',function(e){var m=e.data;if(m&&m.isx==='theme')th(m.dark?'dark':'light')});addEventListener('keydown',function(e){if(e.key==='Escape')parent.postMessage({isx:'key',key:e.key},'*')})})()</` + 'script>';
606
631
  function figureDoc(data) {
607
632
  const dark = document.documentElement.dataset.theme === 'dark';
608
633
  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
- }
634
+ const html = data.kind === 'svg'
635
+ ? `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;height:100%}body{display:grid;place-items:center}svg{width:100%;height:100%}</style>${data.svg}`
636
+ : data.html;
637
+ const tag = FIGURE_BRIDGE(dark ? 'dark' : 'light');
638
+ return /<head[^>]*>/i.test(html) ? html.replace(/<head[^>]*>/i, (m) => m + tag) : tag + html;
639
+ }
640
+ addEventListener('message', (ev) => {
641
+ const fr = $('#inspect-body iframe');
642
+ if (!fr || ev.source !== fr.contentWindow || ev.data?.isx !== 'key') return;
643
+ if (ev.data.key === 'Escape') closeInside();
644
+ });
612
645
  function insideGo(i) {
613
646
  if (!inspect?.stage) return;
614
647
  const d = inspect.data, n = d.steps.length;
@@ -639,12 +672,19 @@ $('#inspect-body').addEventListener('click', (ev) => {
639
672
  else if (c && inspect?.stage) openInside(c.dataset.inspect, inspect.stage.ents.get(c.dataset.inspect)?.cur, true);
640
673
  });
641
674
  function closeInside(instant = false) {
642
- if (!inspect) return;
643
- inspect.stage?.destroy(); inspect = null;
675
+ const pending = insideOpenTimer !== null;
676
+ clearTimeout(insideOpenTimer); insideOpenTimer = null;
677
+ if (!inspect && !pending) return;
678
+ inspect?.stage?.destroy(); inspect = null;
644
679
  const box = $('#inspect'); box.classList.remove('is-on');
645
680
  const done = () => { if (!inspect) { box.hidden = true; $('#inspect-body').innerHTML = ''; } };
646
681
  instant ? done() : setTimeout(done, 240);
647
682
  stage.setView(null, !instant);
683
+ if (!instant && (opener || parseHash().open)) {
684
+ history.replaceState(null, '', `#/${X.lessonId}/${X.step + 1}`);
685
+ stage.ents.get(opener)?.el.focus?.({ preventScroll: true }); // focus goes back to the box that opened it
686
+ }
687
+ opener = null;
648
688
  }
649
689
  $('#inspect-close').onclick = () => closeInside();
650
690
  $('#inspect').addEventListener('click', (ev) => { if (ev.target === $('#inspect')) closeInside(); });