# 机理图谱 · Mechanism Atlas

A dependency-free, Chinese-language medication mechanism teaching simulator. Declarative JSON describes entities and a timeline. One SVG renderer supports receptor activation, enzyme inhibition, molecular movement, binding and signal propagation.

## Run and build

Requires Node.js 20+ for tests/build, and any static HTTP server to view. No npm installation is needed.

```sh
npm test
npm run build
npm run serve
# Open http://localhost:4173
```

Publish the complete contents of `dist/` to the site's static document root. It works at a subpath because all assets use relative URLs. Serve over HTTPS. Do not use `file://`: browser module security requires HTTP(S).

- `src/engine.js`: framework-independent scene validation and deterministic timeline evaluation.
- `src/renderer.js`: reusable SVG components and state rendering.
- `src/scenes.js`: three editorially prepared teaching examples and primary sources.
- `src/app.js`: controls, JSON editor, local question-to-preset demo and public API.
- `schema.json`: JSON Schema Draft 2020-12 for external authoring.
- `docs/SCENE_FORMAT.md`: scene format, action examples and limitations.
- `dist/examples/`: standalone scene JSON files after building.

## Educational scope

This is a qualitative mechanism diagram, NOT a pharmacokinetic, pharmacodynamic, anatomical or patient-specific simulation. Particle counts, animation durations, coordinates and visual strength do not encode dose, concentration or clinical effect. There are no prescribing, dosing or diagnosis features. No claim is made that a mechanism explanation reliably reduces an individual's anxiety.

Built-in examples:

1. Salbutamol: β₂ receptor → Gs / adenylate cyclase → cAMP / PKA → airway smooth muscle relaxation.
2. Omeprazole: absorption and distribution described in text → acidic activation at the parietal-cell secretory canaliculus → proton pump inhibition → reduced acid secretion. It is not direct neutralization of existing acid.
3. Ibuprofen: inhibition of intracellular COX-1 / COX-2 → less prostaglandin synthesis → analgesic, antipyretic and anti-inflammatory actions. Normal physiological functions and risks remain relevant.

Official reference links and teaching limitations are included in every scene and surfaced in the interface. These sources do not substitute for professional pharmaceutical review. Any externally loaded or edited scene is visibly labeled unreviewed even when structural validation succeeds.

## Interaction

Play/pause, reset, next step, seek, speed 0.5–2×, direct step navigation, preset switching, reduced-motion snapshots, JSON import/export/validate/preview. System reduced-motion preference is honored initially and on change. In reduced-motion mode, the image shows a discrete completed-state snapshot for each current step rather than interpolated molecular movement.

The question panel is explicitly a local, fixed-rule demonstration. It only matches the three built-in examples. It does not contact an LLM, transmit the question or generate a prescription. Unmatched questions receive an honest unsupported response; dosing/personalized questions are not answered.

## Future AI integration

An AI system should return structured scene JSON under a restricted schema, not arbitrary JavaScript, HTML, SVG markup or a script URL. Prefer an approved scene catalog for common medicines. Do not render a scene as clinical guidance merely because its schema is valid.

Browser API (available after module initialization):

```js
const report = window.MechanismSimulator.validateScene(candidate);
if (!report.valid) throw new Error(report.errors.join('\n'));
window.MechanismSimulator.loadScene(candidate); // always marked unreviewed
window.MechanismSimulator.play();
window.MechanismSimulator.pause();
window.MechanismSimulator.seek(12.5); // conceptual animation seconds
window.MechanismSimulator.getScene(); // defensive copy
window.MechanismSimulator.getState();
const unsubscribe = window.MechanismSimulator.on('stepchange', event => {
  // {sceneId, index, stepId}
});
unsubscribe();
```

Other events: `scenechange`, `play`, `ended`, `questionmatch`. `loadPreset(id)` accepts `salbutamol`, `omeprazole`, `ibuprofen`. `parseScene(jsonText)` parses and validates. The pure module can be imported directly in future applications:

```js
import { parseScene, validateScene, getSceneState } from './engine.js';
import { SceneRenderer } from './renderer.js';
const scene = parseScene(jsonText);
const renderer = new SceneRenderer(document.querySelector('svg'));
renderer.setScene(scene);
renderer.draw(getSceneState(scene, 10));
```

For production AI use, introduce an evidence retrieval layer, source validation, pharmaceutical review and a bounded approved component/action vocabulary. Keep provenance and review status outside model-controlled claims. Validate both syntax and scientific content. Do not append patient records or sensitive health details to a public scene. A clinical or prescribing product would require a separate safety, regulatory and data-protection design, not simply an LLM connection.

## Security and privacy

- All user/script-controlled strings use `textContent`; no `eval`, dynamic function construction or user HTML injection.
- No external runtime dependencies, remote fonts, tracking, cookies, API keys, network calls or persistent browser storage.
- Source URLs must use HTTPS; links open with `noopener noreferrer`.
- Schema/runtimes bound entity, step, action and source counts, coordinates, durations and JSON length (150,000 characters). Local file import additionally checks a 150,000-byte file size limit.
- Unknown properties and unsupported actions are rejected; entity references and unique IDs are validated by the runtime.
- Content Security Policy is embedded in the HTML. Recommended server headers: `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, `Content-Security-Policy: frame-ancestors 'none'` (unless an explicitly authorized embedding integration needs different framing).
- Built-in JSON samples are self-contained; opening references is the only intentional external navigation.

## Deployment safety

Back up an existing site before replacing its document root. Deploy `dist/` atomically or to a versioned release directory if possible. Keep server authentication and deployment secrets outside this repository and public document root. Configure appropriate MIME types for JavaScript, JSON and SVG. Verify desktop/mobile rendering and all controls on the actual HTTPS domain after deployment.
