reactive-md 0.5.2 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG-ch.md +11 -0
- package/CHANGELOG.md +11 -0
- package/README-ch.md +7 -7
- package/README-en.md +8 -8
- package/README.md +8 -8
- package/cli/build.mjs +1 -1
- package/cli/package.mjs +1 -0
- package/dist-library/authoring-DJJjKYg9.js +842 -0
- package/dist-library/{runtime-UiQPz5ZV.js → compiler-UyPwGzJZ.js} +5631 -5389
- package/dist-library/react-fizgU3i8.js +12764 -0
- package/dist-library/reactive-md-authoring.js +1514 -0
- package/dist-library/reactive-md-editor.js +577 -571
- package/dist-library/reactive-md-print.css +284 -0
- package/dist-library/reactive-md-react-unstyled.js +1 -0
- package/dist-library/reactive-md-react.js +1 -13208
- package/dist-library/reactive-md.css +1 -1
- package/dist-library/reactive-md.js +244 -1062
- package/dist-library/runtime-DXtle_6c.js +498 -0
- package/dist-library/types/authoring/index.d.ts +24 -0
- package/dist-library/types/editor/command-types.d.ts +10 -0
- package/dist-library/types/editor/editor-commands.d.ts +2 -2
- package/dist-library/types/editor/editor-i18n.d.ts +1 -1
- package/dist-library/types/editor/native-components.d.ts +1 -1
- package/dist-library/types/editor/source-authoring.d.ts +5 -3
- package/dist-library/types/editor/types.d.ts +5 -10
- package/dist-library/types/local/LocalDocumentView.d.ts +4 -2
- package/dist-library/types/local/authoring.d.ts +9 -5
- package/dist-library/types/local/diagnostics.d.ts +40 -0
- package/dist-library/types/local/index.d.ts +1 -0
- package/dist-library/types/local/math-display.d.ts +72 -0
- package/dist-library/types/local/math-view.d.ts +2 -0
- package/dist-library/types/local/options.d.ts +3 -1
- package/dist-library/types/local/types.d.ts +10 -0
- package/dist-library/types/local/worker.d.ts +3 -2
- package/dist-library/types/react/index.d.ts +1 -1
- package/dist-standalone/reactive-md-standalone.js +54 -50
- package/docs/author-tools-ch.md +11 -5
- package/docs/author-tools-en.md +11 -5
- package/docs/editor-ch.md +237 -235
- package/docs/editor-en.md +237 -235
- package/docs/local-integration-ch.md +392 -390
- package/docs/local-integration-en.md +392 -390
- package/docs/release-0.5.3-ch.md +25 -0
- package/docs/release-0.5.3-en.md +25 -0
- package/package.json +12 -2
|
@@ -1,390 +1,392 @@
|
|
|
1
|
-
# Local mode integration
|
|
2
|
-
|
|
3
|
-
Local interaction mode uses HTML-style tags, in-place parameters and `{{ expressions }}`. Author rules are in the [beginner guide](local-guide-en.md) and the [syntax specification](local-interaction-syntax-en.md); complete documents are in the [example index](../examples/local/README.md). Hosts explicitly select this mode through the `Local` APIs. See [Source revisions and migration](source-versioning-en.md) for the optional revision directive, upgrade checks and `migrateLocalSource`, and [0.4.0 release and migration](release-0.4.0-en.md) for the upgrade checklist.
|
|
4
|
-
|
|
5
|
-
## Runtime and entries
|
|
6
|
-
|
|
7
|
-
See [HTML compatibility](html-compatibility-en.md) for the next release's P0 HTML support and host capability options. The temporary routing policy sends the entire document to native HTML when author CSS, JavaScript or extended HTML is enabled. Markdown and ReactiveMD interpretation stop in that path.
|
|
8
|
-
|
|
9
|
-
| Entry | Contents | Dependency |
|
|
10
|
-
| --- | --- | --- |
|
|
11
|
-
| `reactive-md` | `compileLocal`, `createLocalRuntime`, expression and math utilities | No React dependency |
|
|
12
|
-
| `reactive-md/react` | `LocalReactiveDocument`, `LocalDocumentView` | React 19 |
|
|
13
|
-
| `reactive-md/styles.css` | Component, theme and document styles | Explicitly imported by the host |
|
|
14
|
-
|
|
15
|
-
The package ships ESM only. Node.js 22.12+ can be used for development and Node-side compilation and runtime. Local browser checks use Edge; static SSR is covered by the packed check; see [Versions and compatibility](compatibility-en.md) for the full matrix. Copyable projects are in [Standalone integration examples](../examples/integration/README.md). For single-file HTML, state files and the standalone browser runtime, see [Shareable documents and static export](shareable-export-en.md).
|
|
16
|
-
|
|
17
|
-
## React
|
|
18
|
-
|
|
19
|
-
Install React in a host that already has Reactive MD; when using TypeScript, also install the matching type packages:
|
|
20
|
-
|
|
21
|
-
```sh
|
|
22
|
-
npm install react@19 react-dom@19
|
|
23
|
-
npm install --save-dev @types/react@19 @types/react-dom@19
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
```tsx
|
|
27
|
-
import { LocalReactiveDocument } from 'reactive-md/react';
|
|
28
|
-
import 'reactive-md/styles.css';
|
|
29
|
-
|
|
30
|
-
const source = `# Cost estimate
|
|
31
|
-
|
|
32
|
-
<panel title="Adjust the plan">
|
|
33
|
-
<slider bind="people" label="People" initial="2" min="1" max="20">
|
|
34
|
-
<toggle bind="annual" label="Annual billing">
|
|
35
|
-
</panel>
|
|
36
|
-
|
|
37
|
-
Monthly cost: **{{ people * (annual ? 80 : 100) }} USD**.`;
|
|
38
|
-
|
|
39
|
-
export function Article() {
|
|
40
|
-
return <LocalReactiveDocument source={source} />;
|
|
41
|
-
}
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
| Prop | Type | Component | Notes |
|
|
45
|
-
| --- | --- | --- | --- |
|
|
46
|
-
| `source` | `string` | `LocalReactiveDocument` | Recompiles and creates a new runtime when the source changes; old instance state is not kept. See [Keeping values when source changes](#keeping-values-when-source-changes) |
|
|
47
|
-
| `compileOptions` | `LocalCompileOptions` | `LocalReactiveDocument` | Per-compilation limits, HTML capability flags and host component schemas; omitted options use the default ReactiveMD path |
|
|
48
|
-
| `document` | `LocalDocument` | `LocalDocumentView` | Compiled document; compiled once by the host |
|
|
49
|
-
| `runtime` | `LocalRuntime` | `LocalDocumentView` | Created by the host, which is responsible for disposal |
|
|
50
|
-
| `onDiagnostics` | `(diagnostics: Diagnostic[]) => void` | Both | Receives compile diagnostics and runtime diagnostics when control writes are rejected |
|
|
51
|
-
| `urlPolicy` | `(url: string, kind: 'image' \| 'link') => boolean` | Both | Decides whether to allow an image or link after protocol checks |
|
|
52
|
-
| `locale` | `'en' \| 'zh'` | Both | Language for built-in labels, controls and displayed diagnostics; defaults to `'en'`. Callbacks keep structured diagnostics |
|
|
53
|
-
| `themes` | `readonly LocalThemeDefinition[]` | Both | Host registrations; CSS loads separately; built-in `default` is always available |
|
|
54
|
-
| `colorScheme` | `'light' \| 'dark' \| 'auto'` | Both | Defaults to `auto`, following the nearest explicit ancestor preference or the system |
|
|
55
|
-
| `hostData` | `Readonly<Record<string, unknown>>` | Both | JSON-safe host data keyed `${kind}:${ref}` for `hostComponent` nodes; never enters the worker |
|
|
56
|
-
| `hostRenderer` | `LocalHostRenderer` | Both | Client-only renderer for `hostComponent` nodes; a missing renderer or data renders a visible placeholder |
|
|
57
|
-
|
|
58
|
-
Neither component has `className`, `style` or slot props. `LocalReactiveDocument` renders `<article class="md-document local-document">`; `LocalDocumentView` uses the same document container. See below for style overrides.
|
|
59
|
-
|
|
60
|
-
Each component instance manages in-memory state independently. Changing the source recompiles and starts from initial values; disposing an instance clears subscriptions and timers. To carry values across a source change, use the retention helpers or manage the runtime yourself; see [Keeping values when source changes](#keeping-values-when-source-changes). A panel reset in the document restores its internal parameters, input drafts and component state, and displays of same-name parameters outside the panel update as well.
|
|
61
|
-
|
|
62
|
-
When a host React root shares a page with the standalone IIFE, give the host root a distinct `identifierPrefix`, for example `createRoot(container, { identifierPrefix: 'host-' })`. The bundles own separate React instances, so their default `useId` counters can overlap. Independent server-rendered roots need matching unique prefixes on the server and client too.
|
|
63
|
-
|
|
64
|
-
When compilation fails, the component renders a disabled notice and the diagnostics list, and `onDiagnostics` also receives the diagnostics. Local computation errors during runtime are displayed near the corresponding content while the rest keeps updating.
|
|
65
|
-
|
|
66
|
-
### Headings and table-of-contents links
|
|
67
|
-
|
|
68
|
-
Documents can use Markdown table-of-contents links directly, for example `[Parameter description](#parameter-description)` targeting `## Parameter description`. The renderer generates anchors from heading text, appends `-1`, `-2` and so on to duplicate headings, and handles collisions with existing heading names. Emphasis and inline code in headings participate in naming as text; both Chinese and percent-encoded fragment links work.
|
|
69
|
-
|
|
70
|
-
Each document instance has its own anchor prefix, and matching table-of-contents links target the current instance. The same page can embed multiple copies of the same source. Links still go through protocol checks and the host `urlPolicy` first; the policy receives the raw address written by the author.
|
|
71
|
-
|
|
72
|
-
Anchors for dynamic headings are computed from source initial values, and parameter changes only update the displayed heading text. Rendered DOM IDs belong to the current mounted instance; when saving a table of contents, keep the fragment links from the source.
|
|
73
|
-
|
|
74
|
-
## Core API
|
|
75
|
-
|
|
76
|
-
```ts
|
|
77
|
-
import { compileLocal, createLocalRuntime } from 'reactive-md';
|
|
78
|
-
|
|
79
|
-
const result = compileLocal(source);
|
|
80
|
-
if (result.ok) {
|
|
81
|
-
const runtime = createLocalRuntime(result.document);
|
|
82
|
-
const unsubscribe = runtime.subscribe(() => {
|
|
83
|
-
console.log(runtime.snapshot());
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
console.log(runtime.evaluate('people * 100'));
|
|
87
|
-
console.log(runtime.text('People: {{ people }}'));
|
|
88
|
-
|
|
89
|
-
unsubscribe();
|
|
90
|
-
runtime.dispose();
|
|
91
|
-
} else {
|
|
92
|
-
console.log(result.diagnostics);
|
|
93
|
-
}
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### `compileLocal(source: string, options?: LocalCompileOptions)`
|
|
97
|
-
|
|
98
|
-
`source` is the `.reactive.md` source. The return value is a union:
|
|
99
|
-
|
|
100
|
-
- Success: `{ ok: true; document: LocalDocument; diagnostics: Diagnostic[] }`
|
|
101
|
-
- Failure: `{ ok: false; diagnostics: Diagnostic[] }`
|
|
102
|
-
|
|
103
|
-
Syntax problems are returned through diagnostics; the current build accepts only `local-draft-2`. An explicit older revision directive is rejected with a `local.version.*` diagnostic; an unversioned source keeps current-revision behavior. The source limit is 1,000,000 characters. `document` is a current runtime object and should not be treated as a persistence format.
|
|
104
|
-
|
|
105
|
-
Hosts can set the syntax node budget for a single compilation:
|
|
106
|
-
|
|
107
|
-
```ts
|
|
108
|
-
import { compileLocal, type LocalCompileOptions } from 'reactive-md';
|
|
109
|
-
|
|
110
|
-
const options: LocalCompileOptions = {
|
|
111
|
-
limits: { maxSyntaxNodes: 50_000 },
|
|
112
|
-
};
|
|
113
|
-
const result = compileLocal(source, options);
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
`limits.maxSyntaxNodes` defaults to 10,000 and accepts integers from `1` to `Number.MAX_SAFE_INTEGER`. Omitting the options, `limits` or `maxSyntaxNodes` uses the default. `0`, negative numbers, decimals, `NaN`, infinity, strings, `null` and malformed option containers return a `local.options.invalid` diagnostic; exceeding the valid node budget returns a `local.budget` diagnostic.
|
|
117
|
-
|
|
118
|
-
The budget counts `LocalNode` instances created cumulatively during parsing, including Markdown text, paragraphs, lists, tables, interpolations, components and some intermediate nodes, so it may exceed the final syntax tree node count. The setting affects only this compilation, leaves the options object untouched, and keeps other resource limits such as arrays independent. The budget comes from the host; document content cannot raise it on its own.
|
|
119
|
-
|
|
120
|
-
To use a custom budget in React, call `compileLocal` first and pass the compiled document and runtime to `LocalDocumentView`. `LocalReactiveDocument` and the Playground compilation thread use the default budget. After raising the node budget, hosts should measure memory and preview rendering time with their actual documents.
|
|
121
|
-
|
|
122
|
-
### Host components
|
|
123
|
-
|
|
124
|
-
A host can register leaf tags for one compilation without changing the `local-draft-2` syntax revision:
|
|
125
|
-
|
|
126
|
-
```ts
|
|
127
|
-
import { compileLocal, type LocalHostComponentSchema } from 'reactive-md';
|
|
128
|
-
|
|
129
|
-
const hostComponents: LocalHostComponentSchema[] = [
|
|
130
|
-
{
|
|
131
|
-
name: 'host-weather',
|
|
132
|
-
form: 'leaf',
|
|
133
|
-
props: {
|
|
134
|
-
kind: { kind: 'enum', required: true, enum: ['weather'] },
|
|
135
|
-
ref: { kind: 'string', required: true, pattern: '^[a-z-]+$' },
|
|
136
|
-
},
|
|
137
|
-
},
|
|
138
|
-
];
|
|
139
|
-
const result = compileLocal(source, { hostComponents });
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
Without `hostComponents`, those tags remain unknown and fall back to source. Names must be unique lowercase kebab-case and cannot reuse one of the 48 author tag names, a P0 HTML tag name or `theme`; at most 32 schemas are accepted. `pattern` accepts only a linear-time-safe regex subset (no backreferences, lookarounds, named groups, nested quantifiers or quantified alternation). An invalid schema returns `local.options.invalid`, and an invalid authored attribute returns `local.host.attribute`. A valid host node counts as one syntax node. Pass `hostData`, keyed `${kind}:${ref}`, and `hostRenderer` to `LocalDocumentView`; neither enters the worker. A missing renderer, missing data or a throwing renderer renders a visible placeholder instead of failing the document. `mode="static"` uses the same dispatch and passes `ctx.mode` to the renderer.
|
|
143
|
-
|
|
144
|
-
### Version inspection and migration
|
|
145
|
-
|
|
146
|
-
Three pure functions inspect and migrate source without creating a runtime. They are exported from `reactive-md`:
|
|
147
|
-
|
|
148
|
-
```ts
|
|
149
|
-
import {
|
|
150
|
-
checkLocalUpgrade,
|
|
151
|
-
inspectLocalSourceVersion,
|
|
152
|
-
migrateLocalSource,
|
|
153
|
-
} from 'reactive-md';
|
|
154
|
-
|
|
155
|
-
const info = inspectLocalSourceVersion(source);
|
|
156
|
-
const check = checkLocalUpgrade(source, { fromVersion: 'local-draft-1' });
|
|
157
|
-
const migrated = migrateLocalSource(source, { fromVersion: 'local-draft-1' });
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
`inspectLocalSourceVersion` reports the declared and effective revision, whether this compiler supports it, the directive range and version diagnostics. `checkLocalUpgrade` reports `ok`, `fromVersion`, `toVersion`, `needsMigration` and diagnostics. `migrateLocalSource` adds `source`, `changed` and precise `edits`.
|
|
161
|
-
|
|
162
|
-
`LocalUpgradeOptions` supplies `fromVersion` and `allowSemanticChanges`. An unversioned historical document needs `fromVersion: 'local-draft-1'`. An explicit `fromVersion` that disagrees with the declaration is rejected. Only `local-draft-1` and `local-draft-2` are accepted migration sources.
|
|
163
|
-
|
|
164
|
-
Migration changes only the metadata directive, preserves body bytes, BOM and CRLF, and is idempotent. It blocks reserved bindings, newly recognized tags, compile errors and text-control length changes before producing output. See [Source revisions and migration](source-versioning-en.md) for the exact checks and the CLI.
|
|
165
|
-
|
|
166
|
-
### `createLocalRuntime(document: LocalDocument)`
|
|
167
|
-
|
|
168
|
-
Named read-only values are described by `LocalComputation` in the optional `document.computations` record. `bindings` and `initialState` remain writable controls; `snapshot().state` also includes successful calculated values for its revision. Read a named value with `evaluate(name)` to preserve expression errors; failed values are absent from snapshots. See [calculation and error semantics](computations-formatting-en.md).
|
|
169
|
-
|
|
170
|
-
Creates an independent in-memory runtime for a compiled document. Throws if `document` is not a local mode document, if initial values exceed budgets, or if the structure is invalid. Each instance has independent state; the runtime never stores or transmits state by itself.
|
|
171
|
-
|
|
172
|
-
### `LocalRuntime`
|
|
173
|
-
|
|
174
|
-
`validate(): Diagnostic[]` reads advisory cross-field failures for the current revision. It preserves editability and returns copies of cached diagnostics. `document.validations?: LocalValidation[]` holds the serializable rule declarations. Numeric collections add `number[]` to `LocalValue` and `number-array` to `LocalValueKind`; existing writable selection controls keep string arrays. See [constraints and collections](constraints-collections-en.md).
|
|
175
|
-
|
|
176
|
-
| Member | Parameters | Returns | Behavior |
|
|
177
|
-
| --- | --- | --- | --- |
|
|
178
|
-
| `document` | — | `LocalDocument` | The compiled result used at creation |
|
|
179
|
-
| `snapshot()` | — | `{ revision: number; state: Readonly<Record<string, LocalValue>> }` | Returns the same snapshot object when state is unchanged; state is frozen |
|
|
180
|
-
| `get(node, slot?)` | `LocalNode`, optional slot | `LocalValue` | Reads the value bound to the control; `slot` selects `start`/`end` or `x`/`y`; returns `null` for no binding or an unknown node; arrays are copies |
|
|
181
|
-
| `set(node, value, slot?)` | `LocalNode`, `LocalValue`, optional slot | `Diagnostic[]` | Validates all shared controls; returns an empty array and commits once on success; does not increment revision on failure |
|
|
182
|
-
| `setMany(node, values)` | `LocalNode`, slot values | `Diagnostic[]` | Atomically writes several slots of one multi-slot control; invalid batches leave state and revision unchanged |
|
|
183
|
-
| `validate()` | — | `Diagnostic[]` | Returns copies of the current advisory validation failures; does not change or reject state |
|
|
184
|
-
| `parameterNames()` | — | `readonly string[]` | Sorted public binding names; internal `@` bindings excluded |
|
|
185
|
-
| `getParameter(name)` | `string` | `LocalValue \| undefined` | Value of a public binding; `undefined` for unknown or internal names; arrays are copies |
|
|
186
|
-
| `getParameters()` | — | `Readonly<Record<string, LocalValue>>` | Frozen public-only snapshot; internal `@` keys are never included |
|
|
187
|
-
| `setParameter(name, value)` | `string`, `LocalValue` | `Diagnostic[]` | Validates every control sharing the binding; commits once; state unchanged on failure |
|
|
188
|
-
| `setParameters(values)` | `Readonly<Record<string, LocalValue>>` | `Diagnostic[]` | Validates every public value and multi-slot relation, then commits all or nothing; unknown or internal names return `local.runtime.parameter`; invalid values return `local.runtime.value`; unchanged values do not bump the revision |
|
|
189
|
-
| `evaluate(expression)` | `string` | `LocalValue` | Evaluates with current state; throws `LocalExpressionError` on failure; arrays are copies |
|
|
190
|
-
| `text(template)` | `string` | `string` | Renders text containing `{{ }}`; throws on failure |
|
|
191
|
-
| `reset(node)` | `LocalNode` | `void` | Restores parameters and component state within the node's subtree in one commit, notifying once |
|
|
192
|
-
| `resetToken(node)` | `LocalNode` | `number` | Incrementing token for a control's internal state, so renderers can detect resets |
|
|
193
|
-
| `subscribe(listener)` | `() => void` | `() => void` | Calls the listener on every commit; returns an unsubscribe function |
|
|
194
|
-
| `dispose()` | — | `void` | Idempotent; clears subscriptions, expression caches and reset tokens; other members throw afterwards |
|
|
195
|
-
|
|
196
|
-
`set` relies on the controls registered in the document; node metadata passed by the caller cannot loosen constraints. `disabled` and conditional hiding are for interactive display only; the host still enforces business permissions and server-side data validation.
|
|
197
|
-
|
|
198
|
-
### Parameters by name
|
|
199
|
-
|
|
200
|
-
Name-based access is for hosts that keep their own parameter values, such as a form or a URL. Only public bindings are visible: `parameterNames()` returns sorted names, `getParameter(name)` returns `undefined` for an unknown or internal name, and `getParameters()` returns a frozen public-only record. Anonymous `@` bindings never appear, and arrays returned by `getParameter` are copies.
|
|
201
|
-
|
|
202
|
-
Writes validate every control sharing the binding, including multi-slot relations, and commit once. A failed call returns diagnostics and leaves the state unchanged; unchanged values do not increase the revision. Unknown or internal names return `local.runtime.parameter`; invalid values return `local.runtime.value`.
|
|
203
|
-
|
|
204
|
-
```ts
|
|
205
|
-
const names = runtime.parameterNames(); // e.g. ['annual', 'people']
|
|
206
|
-
const people = runtime.getParameter('people'); // 2
|
|
207
|
-
|
|
208
|
-
runtime.setParameter('people', 7);
|
|
209
|
-
const diagnostics = runtime.setParameters({ people: 8, annual: true });
|
|
210
|
-
if (diagnostics.length) {
|
|
211
|
-
// Nothing was written.
|
|
212
|
-
}
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
### State export and import
|
|
216
|
-
|
|
217
|
-
`exportLocalState(runtime, generator?)` writes the public parameters to a `reactive-md-state/v1` file. The file carries the document identity in `sourceDigest`, the language revision in `syntax`, and an optional generator name and version. Anonymous `@` bindings from `snapshot().state` are excluded, so a raw snapshot should not be stored as a long-term protocol. The [shareable export guide](shareable-export-en.md#starting-values-and-state-files) documents the format used by the CLI and standalone runtime.
|
|
218
|
-
|
|
219
|
-
`importLocalState(runtime, input, options?)` accepts serialized JSON or an already parsed file. It parses the payload, checks the source digest, syntax revision and exact public parameter set, validates every value, and applies the result; a failed import returns diagnostics and leaves the runtime unchanged. `options.maxLength` limits the serialized payload in bytes and defaults to 1 MiB.
|
|
220
|
-
|
|
221
|
-
```ts
|
|
222
|
-
import { exportLocalState, importLocalState } from 'reactive-md';
|
|
223
|
-
|
|
224
|
-
const file = exportLocalState(runtime, { name: 'my-host', version: '1.0.0' });
|
|
225
|
-
const saved = JSON.stringify(file);
|
|
226
|
-
|
|
227
|
-
const diagnostics = importLocalState(runtime, saved);
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
The lower-level `createLocalStateFile`, `parseLocalState`, `resolveLocalState`, `applyLocalState` and `serializeLocalState` remain available. Use `resolveLocalState(document, input)` for validation that does not touch a live runtime.
|
|
231
|
-
|
|
232
|
-
### Keeping values when source changes
|
|
233
|
-
|
|
234
|
-
`LocalReactiveDocument` still creates a new runtime from initial values when `source` changes. Hosts that manage the runtime themselves can carry compatible values over:
|
|
235
|
-
|
|
236
|
-
```ts
|
|
237
|
-
import {
|
|
238
|
-
applyLocalStateRetention,
|
|
239
|
-
compileLocal,
|
|
240
|
-
createLocalRuntime,
|
|
241
|
-
planLocalStateRetention,
|
|
242
|
-
} from 'reactive-md';
|
|
243
|
-
|
|
244
|
-
const next = compileLocal(nextSource);
|
|
245
|
-
if (!next.ok) throw new Error('Fix the compile diagnostics first');
|
|
246
|
-
|
|
247
|
-
const plan = planLocalStateRetention({
|
|
248
|
-
previous: previousRuntime.document,
|
|
249
|
-
state: previousRuntime.snapshot().state,
|
|
250
|
-
next: next.document,
|
|
251
|
-
});
|
|
252
|
-
const runtime = createLocalRuntime(next.document);
|
|
253
|
-
const { retained, dropped, diagnostics } = applyLocalStateRetention(runtime, plan);
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
`planLocalStateRetention` returns the values to reuse, the retained parameter names, and dropped entries with a name and reason. A parameter is retained only when:
|
|
257
|
-
|
|
258
|
-
- its name exists as a public binding in both documents;
|
|
259
|
-
- both bindings are safely retainable: the binding has controls, every control is bound to the name, and no control is a timer or checklist;
|
|
260
|
-
- its type and initial definition are unchanged, including the effective initial value and any explicit `initial` attribute values.
|
|
261
|
-
|
|
262
|
-
Anonymous `@` bindings, removed or renamed parameters, timers and positional checklists are dropped. Each retained value is revalidated against the new document's constraints; a rejected value falls back to the new initial value and is reported as `invalid`. Drop reasons are `internal`, `unknown`, `unretainable`, `type`, `initial` and `invalid`.
|
|
263
|
-
|
|
264
|
-
`applyLocalStateRetention` first tries one atomic write so multi-slot relations stay consistent, then falls back to writing parameters individually, so one stale value does not block the others. `diagnostics` describe values rejected by the new document.
|
|
265
|
-
|
|
266
|
-
### Background compilation in a Worker
|
|
267
|
-
|
|
268
|
-
Worker support is host-provided: create the worker entry with your bundler and keep `compileLocal` as the fallback. A copyable browser example is in [Standalone integration examples](../examples/integration/README.md).
|
|
269
|
-
|
|
270
|
-
```ts
|
|
271
|
-
// compile.worker.ts
|
|
272
|
-
import { startLocalCompileWorker } from 'reactive-md';
|
|
273
|
-
|
|
274
|
-
startLocalCompileWorker();
|
|
275
|
-
```
|
|
276
|
-
|
|
277
|
-
`startLocalCompileWorker()` installs the handler on the current worker global. Pass a scope explicitly only when testing or wrapping another message host.
|
|
278
|
-
|
|
279
|
-
```ts
|
|
280
|
-
// main.ts
|
|
281
|
-
import { LocalCompileScheduler } from 'reactive-md';
|
|
282
|
-
|
|
283
|
-
const scheduler = new LocalCompileScheduler({
|
|
284
|
-
createWorker: () => new Worker(new URL('./compile.worker.ts', import.meta.url), { type: 'module' }),
|
|
285
|
-
onResult: ({ source, result, mode }) => render(source, result, mode),
|
|
286
|
-
onPendingChange: (pending) => showSpinner(pending),
|
|
287
|
-
onModeChange: (mode, detail) => console.log('compile mode', mode, detail),
|
|
288
|
-
});
|
|
289
|
-
|
|
290
|
-
scheduler.schedule(source);
|
|
291
|
-
```
|
|
292
|
-
|
|
293
|
-
`LocalCompileScheduler` coalesces edits for `LOCAL_COMPILE_DELAY_MS` (150 ms; override with `delay`), keeps one compile in flight plus only the latest queued source, and discards results that a newer edit has superseded. When no worker is available, or after a worker error, it compiles on the main thread with `fallbackCompile`, which defaults to `compileLocal`; a worker failure switches permanently to this fallback and reports it through `onModeChange`. Failures thrown by the worker or during fallback compilation use the `local.worker.compile` diagnostic code.
|
|
294
|
-
|
|
295
|
-
`onResult` receives `LocalCompileOutcome` (`source`, `result`, `duration`, `mode`), `onPendingChange` reports whether work is queued or in flight, and `dispose()` stops the timer, terminates the worker and suppresses later callbacks.
|
|
296
|
-
|
|
297
|
-
### Other core exports
|
|
298
|
-
|
|
299
|
-
- `LOCAL_SYNTAX_VERSION`: currently the literal `'local-draft-2'`. Use it to record the syntax revision a document uses.
|
|
300
|
-
- `compileExpression(source: string)`: returns an object with `source`, `dependencies`, `evaluate(env)` and `inferType(env)`; throws `LocalExpressionError` on failure.
|
|
301
|
-
- `LocalExpressionError`: contains `code` and `offset`.
|
|
302
|
-
- `compileLatex(source: string)`: returns an object with `source`, `dependencies` and `evaluate(x, env, budget?)`; throws an error with `code` and `offset` on failure.
|
|
303
|
-
- `samplePlot(expression, env, min, max, samples = 200, sharedBudget?)`: returns `{ points: { x: number; y: number | null }[]; endpoint: number | null }`; throws when the range, sample count or budget is invalid.
|
|
304
|
-
- State files: `exportLocalState`, `importLocalState`, `createLocalStateFile`, `parseLocalState`, `resolveLocalState`, `applyLocalState` and `serializeLocalState`; `LOCAL_STATE_FORMAT` is `'reactive-md-state/v1'`.
|
|
305
|
-
- Source revisions: `inspectLocalSourceVersion`, `checkLocalUpgrade` and `migrateLocalSource`; `LocalUpgradeOptions` configures the source revision and semantic-change allowance.
|
|
306
|
-
- Retention: `planLocalStateRetention` and `applyLocalStateRetention`.
|
|
307
|
-
- Background compilation: `LocalCompileScheduler`, `LOCAL_COMPILE_DELAY_MS` and `startLocalCompileWorker`.
|
|
308
|
-
- Type exports: `Diagnostic`, `SourceRange`, `LocalValue`, `LocalValueKind`, `LocalNode`, `LocalBinding`, `LocalComputation`, `LocalValidation`, `LocalDocument`, `LocalCompileLimits`, `LocalCompileOptions`, `LocalCompileResult`, `LocalHostPropKind`, `LocalHostPropSchema`, `LocalHostComponentSchema`, `LocalUpgradeOptions`, `LocalRuntime`, `LocalSnapshot`, `LocalStateFile`, `LocalStateGenerator`, `LocalStateParseResult`, `LocalStateResolution`, `LocalRetainedState`, `LocalStateRetentionReason`, `LocalStateRetentionDrop`, `LocalStateRetentionInput`, `LocalStateRetentionResult`, `LocalCompileWorker`, `LocalCompileWorkerScope`, `LocalCompileRequest`, `LocalCompileResponse`, `LocalCompileOutcome`, `LocalCompileMode`, `LocalCompileSchedulerOptions`.
|
|
309
|
-
|
|
310
|
-
`compileExpression`, `compileLatex` and `samplePlot` are lower-level utilities with the same stability level as the core API; usually only `compileLocal` and `createLocalRuntime` are needed.
|
|
311
|
-
|
|
312
|
-
## Diagnostics
|
|
313
|
-
|
|
314
|
-
The fields and stability levels of `Diagnostic` are described in the diagnostics contract in [Versions and compatibility](compatibility-en.md). Key points: `line`, `column` and `range` are for programmatic location; `code` can be used for coarse classification in the current version, but 0.x does not promise cross-version stability; `message` is display text and should not be parsed.
|
|
315
|
-
|
|
316
|
-
`onDiagnostics` receives compile diagnostics when the compilation result changes, and runtime diagnostics when control writes are rejected. Documents with compile errors do not activate interaction; runtime local errors replace only the corresponding content.
|
|
317
|
-
|
|
318
|
-
## State, instances and cleanup
|
|
319
|
-
|
|
320
|
-
- `LocalReactiveDocument` recompiles and creates a runtime when `source` changes, cleaning up the old instance; React StrictMode is supported.
|
|
321
|
-
- When managing the lifecycle yourself, render with `<LocalDocumentView document={result.document} runtime={runtime} />` and call `runtime.dispose()` on unmount.
|
|
322
|
-
- `subscribe()` returns an unsubscribe function. `dispose()` clears remaining subscriptions; calling other runtime methods afterwards throws.
|
|
323
|
-
- `snapshot()` returns the same object until state changes, which is useful for external store subscriptions. `reset(panelNode)` commits once for the panel subtree, and subscribers receive one notification; hidden controls inside the panel are also within reset scope.
|
|
324
|
-
- Document state lives only in memory; the runtime never writes storage, cookies or the network. Refreshing, remounting or replacing the source starts from initial values. Persistence is an explicit host action through `exportLocalState` and `importLocalState`; the [retention helpers](#keeping-values-when-source-changes) can carry compatible values into a new runtime.
|
|
325
|
-
- Hidden regions keep parameters, tab selection and checklist state; timers in hidden regions pause and stay paused when shown again until the reader starts them. Disposing an instance releases timers and subscriptions.
|
|
326
|
-
|
|
327
|
-
## Image and link policy
|
|
328
|
-
|
|
329
|
-
Images are not loaded by default, including relative-path images, so documents do not automatically request host APIs or external sites. Hosts can explicitly allow image sources through `urlPolicy`; both `LocalReactiveDocument` and `LocalDocumentView` accept this prop. Links keep safe protocol checks by default.
|
|
330
|
-
|
|
331
|
-
```tsx
|
|
332
|
-
import type { LocalUrlPolicy } from 'reactive-md/react';
|
|
333
|
-
|
|
334
|
-
const urlPolicy: LocalUrlPolicy = (raw, kind) => {
|
|
335
|
-
if (kind === 'link') return true;
|
|
336
|
-
try {
|
|
337
|
-
const url = new URL(raw);
|
|
338
|
-
return url.protocol === 'https:' && url.origin === 'https://images.example.com';
|
|
339
|
-
} catch {
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
|
|
344
|
-
<LocalReactiveDocument source={source} urlPolicy={urlPolicy} />;
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
| Target | Without a policy | With a policy |
|
|
348
|
-
| --- | --- | --- |
|
|
349
|
-
| Images | All rejected, including relative addresses | Protocol-bearing addresses are checked first and only HTTP(S) is allowed; relative addresses are decided by the policy |
|
|
350
|
-
| Links | Relative addresses and `http`, `https`, `mailto`, `tel` allowed | Decided by the policy after protocol checks; external HTTP(S) links get `_blank` and `noopener noreferrer` |
|
|
351
|
-
|
|
352
|
-
The policy receives the raw URL with leading and trailing whitespace removed, and `'image' | 'link'`. If the policy throws, the address is rejected. The renderer always checks the protocol first; even if the policy allows it, `javascript:` or dangerous `data:` addresses cannot be used. Images allowed to load use `referrerPolicy="no-referrer"`; same-origin requests may still carry cookies, so image allowlists should avoid business API paths.
|
|
353
|
-
|
|
354
|
-
`urlPolicy` controls only rendered links and images; it is not server-side authorization or a sandbox. Hosts still need to handle CSP, network egress and isolation policies for untrusted authors.
|
|
355
|
-
|
|
356
|
-
## Theme and style scoping
|
|
357
|
-
|
|
358
|
-
`reactive-md/styles.css` is a global stylesheet, not isolated through Shadow DOM or CSS Modules. Hosts should import it explicitly once; the `reactive-md/react` library build extracts styles into this file and does not inject them automatically when importing JavaScript.
|
|
359
|
-
|
|
360
|
-
- Style selectors are mainly `.md-document`, `.local-document` and `.md-*`, `.local-*` class names. The document root rendered by components is `.md-document.local-document`.
|
|
361
|
-
- Theme variables are declared on `.md-document` and `.reactive-md-theme`, including `--ink`, `--surface`, `--line`, `--blue`, `--teal`, `--danger`, `--radius-*` and font variables. Override them after the library styles with rules such as `.my-article .md-document { --blue: #245c98; }`; the document root carries default values, so setting variables only on an ancestor container will not override same-name values on the root.
|
|
362
|
-
- Documents may start with `<theme name="default">`; omission selects `default`. Register custom themes through `themes`; see the [theme protocol](theme-protocol-en.md).
|
|
363
|
-
- `colorScheme` forces light or dark mode. The default `auto` reads the nearest ancestor's `data-color-scheme` or legacy `data-theme`, then the system preference. Each document exposes independent `data-rmd-theme` and resolved `data-color-scheme` attributes.
|
|
364
|
-
- Documents default to `max-width: 720px` and are horizontally centered. To fill the host container, override the width and margins of `.md-document` within your own scope.
|
|
365
|
-
- Prefer public variables for theme styling. Component outer `.md-*` and `.local-*` classes and semantic state attributes are theme hooks; internal node ordering is not an extension API. See the theme protocol for compatibility requirements.
|
|
366
|
-
- Neither React component accepts `className` or `style`. For local overrides, scope them with the host's own wrapper element.
|
|
367
|
-
|
|
368
|
-
## Resource limits
|
|
369
|
-
|
|
370
|
-
A single string is limited to 100,000 characters, an array to 10,000 items, and the total string length within an array to 100,000 characters. Email validation uses a length-limited linear check. The runtime rejects writes over a limit and keeps the last valid state.
|
|
371
|
-
|
|
372
|
-
A single document source is limited to 1,000,000 characters. There are at most 100 diagnostics, and a single message is at most 2,000 characters.
|
|
373
|
-
|
|
374
|
-
Each plot component has at most 16 curves; the whole document requests at most 20,000 curve sample points, including hidden regions. Plotting computation is also limited by a shared execution budget of 2,000,000 steps. A document has at most 100 validation rules. Generated `data-table` rows, columns and text have per-table and whole-document budgets described in [constraints and collections](constraints-collections-en.md). Documents over a limit receive diagnostics; expression and math rendering also have their own depth and token budgets.
|
|
375
|
-
|
|
376
|
-
These limits bound the work for a single document; they do not replace host control over request size, concurrency and execution time. See the [security policy](../SECURITY.md) for the full threat boundary.
|
|
377
|
-
|
|
378
|
-
## Version pinning and upgrades
|
|
379
|
-
|
|
380
|
-
- During 0.x, pin the exact package version and commit the lockfile. `^0.3.0` allows only patch versions, but production integrations should still pin the version or the tarball SHA256.
|
|
381
|
-
- Use one package version for both the core and React entries; do not mix different versions of `reactive-md` and `reactive-md/react`.
|
|
382
|
-
- Record `LOCAL_SYNTAX_VERSION` in application configuration or document metadata, alongside the persisted `.reactive.md` source. Migrate according to [Versions and compatibility](compatibility-en.md) when the syntax revision changes.
|
|
383
|
-
- After upgrading, recompile your own documents and check `result.diagnostics`, rendered output and browser interactions. Do not depend on the text of diagnostic `message`.
|
|
384
|
-
|
|
385
|
-
## Features not provided
|
|
386
|
-
|
|
387
|
-
The default ReactiveMD path supports P0 HTML. Host options for author CSS, JavaScript and extended HTML use the separate native HTML path described in [HTML compatibility](html-compatibility-en.md). Local mode still provides no automatic state persistence or unrestricted network access, plugins or custom component registration, external data APIs, Vue support, React 18 support or a CommonJS entry. State export and import are explicit host calls. `LocalReactiveDocument` starts from initial values when the source changes; use retention helpers or manage the runtime and document yourself.
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
See [local-draft-2 components and migration](local-components-v2-en.md) for new tags, colors and slot state, and [0.4.0 release and migration](release-0.4.0-en.md) for the upgrade checklist. `0.4.0` is the preview release on the `next` channel.
|
|
1
|
+
# Local mode integration
|
|
2
|
+
|
|
3
|
+
Local interaction mode uses HTML-style tags, in-place parameters and `{{ expressions }}`. Author rules are in the [beginner guide](local-guide-en.md) and the [syntax specification](local-interaction-syntax-en.md); complete documents are in the [example index](../examples/local/README.md). Hosts explicitly select this mode through the `Local` APIs. See [Source revisions and migration](source-versioning-en.md) for the optional revision directive, upgrade checks and `migrateLocalSource`, and [0.4.0 release and migration](release-0.4.0-en.md) for the upgrade checklist.
|
|
4
|
+
|
|
5
|
+
## Runtime and entries
|
|
6
|
+
|
|
7
|
+
See [HTML compatibility](html-compatibility-en.md) for the next release's P0 HTML support and host capability options. The temporary routing policy sends the entire document to native HTML when author CSS, JavaScript or extended HTML is enabled. Markdown and ReactiveMD interpretation stop in that path.
|
|
8
|
+
|
|
9
|
+
| Entry | Contents | Dependency |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| `reactive-md` | `compileLocal`, `createLocalRuntime`, expression and math utilities | No React dependency |
|
|
12
|
+
| `reactive-md/react` | `LocalReactiveDocument`, `LocalDocumentView` | React 19 |
|
|
13
|
+
| `reactive-md/styles.css` | Component, theme and document styles | Explicitly imported by the host |
|
|
14
|
+
|
|
15
|
+
The package ships ESM only. Node.js 22.12+ can be used for development and Node-side compilation and runtime. Local browser checks use Edge; static SSR is covered by the packed check; see [Versions and compatibility](compatibility-en.md) for the full matrix. Copyable projects are in [Standalone integration examples](../examples/integration/README.md). For single-file HTML, state files and the standalone browser runtime, see [Shareable documents and static export](shareable-export-en.md).
|
|
16
|
+
|
|
17
|
+
## React
|
|
18
|
+
|
|
19
|
+
Install React in a host that already has Reactive MD; when using TypeScript, also install the matching type packages:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install react@19 react-dom@19
|
|
23
|
+
npm install --save-dev @types/react@19 @types/react-dom@19
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```tsx
|
|
27
|
+
import { LocalReactiveDocument } from 'reactive-md/react';
|
|
28
|
+
import 'reactive-md/styles.css';
|
|
29
|
+
|
|
30
|
+
const source = `# Cost estimate
|
|
31
|
+
|
|
32
|
+
<panel title="Adjust the plan">
|
|
33
|
+
<slider bind="people" label="People" initial="2" min="1" max="20">
|
|
34
|
+
<toggle bind="annual" label="Annual billing">
|
|
35
|
+
</panel>
|
|
36
|
+
|
|
37
|
+
Monthly cost: **{{ people * (annual ? 80 : 100) }} USD**.`;
|
|
38
|
+
|
|
39
|
+
export function Article() {
|
|
40
|
+
return <LocalReactiveDocument source={source} />;
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Prop | Type | Component | Notes |
|
|
45
|
+
| --- | --- | --- | --- |
|
|
46
|
+
| `source` | `string` | `LocalReactiveDocument` | Recompiles and creates a new runtime when the source changes; old instance state is not kept. See [Keeping values when source changes](#keeping-values-when-source-changes) |
|
|
47
|
+
| `compileOptions` | `LocalCompileOptions` | `LocalReactiveDocument` | Per-compilation limits, HTML capability flags and host component schemas; omitted options use the default ReactiveMD path |
|
|
48
|
+
| `document` | `LocalDocument` | `LocalDocumentView` | Compiled document; compiled once by the host |
|
|
49
|
+
| `runtime` | `LocalRuntime` | `LocalDocumentView` | Created by the host, which is responsible for disposal |
|
|
50
|
+
| `onDiagnostics` | `(diagnostics: Diagnostic[]) => void` | Both | Receives compile diagnostics and runtime diagnostics when control writes are rejected |
|
|
51
|
+
| `urlPolicy` | `(url: string, kind: 'image' \| 'link') => boolean` | Both | Decides whether to allow an image or link after protocol checks |
|
|
52
|
+
| `locale` | `'en' \| 'zh'` | Both | Language for built-in labels, controls and displayed diagnostics; defaults to `'en'`. Callbacks keep structured diagnostics |
|
|
53
|
+
| `themes` | `readonly LocalThemeDefinition[]` | Both | Host registrations; CSS loads separately; built-in `default` is always available |
|
|
54
|
+
| `colorScheme` | `'light' \| 'dark' \| 'auto'` | Both | Defaults to `auto`, following the nearest explicit ancestor preference or the system |
|
|
55
|
+
| `hostData` | `Readonly<Record<string, unknown>>` | Both | JSON-safe host data keyed `${kind}:${ref}` for `hostComponent` nodes; never enters the worker |
|
|
56
|
+
| `hostRenderer` | `LocalHostRenderer` | Both | Client-only renderer for `hostComponent` nodes; a missing renderer or data renders a visible placeholder |
|
|
57
|
+
|
|
58
|
+
Neither component has `className`, `style` or slot props. `LocalReactiveDocument` renders `<article class="md-document local-document">`; `LocalDocumentView` uses the same document container. See below for style overrides.
|
|
59
|
+
|
|
60
|
+
Each component instance manages in-memory state independently. Changing the source recompiles and starts from initial values; disposing an instance clears subscriptions and timers. To carry values across a source change, use the retention helpers or manage the runtime yourself; see [Keeping values when source changes](#keeping-values-when-source-changes). A panel reset in the document restores its internal parameters, input drafts and component state, and displays of same-name parameters outside the panel update as well.
|
|
61
|
+
|
|
62
|
+
When a host React root shares a page with the standalone IIFE, give the host root a distinct `identifierPrefix`, for example `createRoot(container, { identifierPrefix: 'host-' })`. The bundles own separate React instances, so their default `useId` counters can overlap. Independent server-rendered roots need matching unique prefixes on the server and client too.
|
|
63
|
+
|
|
64
|
+
When compilation fails, the component renders a disabled notice and the diagnostics list, and `onDiagnostics` also receives the diagnostics. Local computation errors during runtime are displayed near the corresponding content while the rest keeps updating.
|
|
65
|
+
|
|
66
|
+
### Headings and table-of-contents links
|
|
67
|
+
|
|
68
|
+
Documents can use Markdown table-of-contents links directly, for example `[Parameter description](#parameter-description)` targeting `## Parameter description`. The renderer generates anchors from heading text, appends `-1`, `-2` and so on to duplicate headings, and handles collisions with existing heading names. Emphasis and inline code in headings participate in naming as text; both Chinese and percent-encoded fragment links work.
|
|
69
|
+
|
|
70
|
+
Each document instance has its own anchor prefix, and matching table-of-contents links target the current instance. The same page can embed multiple copies of the same source. Links still go through protocol checks and the host `urlPolicy` first; the policy receives the raw address written by the author.
|
|
71
|
+
|
|
72
|
+
Anchors for dynamic headings are computed from source initial values, and parameter changes only update the displayed heading text. Rendered DOM IDs belong to the current mounted instance; when saving a table of contents, keep the fragment links from the source.
|
|
73
|
+
|
|
74
|
+
## Core API
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { compileLocal, createLocalRuntime } from 'reactive-md';
|
|
78
|
+
|
|
79
|
+
const result = compileLocal(source);
|
|
80
|
+
if (result.ok) {
|
|
81
|
+
const runtime = createLocalRuntime(result.document);
|
|
82
|
+
const unsubscribe = runtime.subscribe(() => {
|
|
83
|
+
console.log(runtime.snapshot());
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
console.log(runtime.evaluate('people * 100'));
|
|
87
|
+
console.log(runtime.text('People: {{ people }}'));
|
|
88
|
+
|
|
89
|
+
unsubscribe();
|
|
90
|
+
runtime.dispose();
|
|
91
|
+
} else {
|
|
92
|
+
console.log(result.diagnostics);
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### `compileLocal(source: string, options?: LocalCompileOptions)`
|
|
97
|
+
|
|
98
|
+
`source` is the `.reactive.md` source. The return value is a union:
|
|
99
|
+
|
|
100
|
+
- Success: `{ ok: true; document: LocalDocument; diagnostics: Diagnostic[] }`
|
|
101
|
+
- Failure: `{ ok: false; diagnostics: Diagnostic[] }`
|
|
102
|
+
|
|
103
|
+
Syntax problems are returned through diagnostics; the current build accepts only `local-draft-2`. An explicit older revision directive is rejected with a `local.version.*` diagnostic; an unversioned source keeps current-revision behavior. The source limit is 1,000,000 characters. `document` is a current runtime object and should not be treated as a persistence format.
|
|
104
|
+
|
|
105
|
+
Hosts can set the syntax node budget for a single compilation:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { compileLocal, type LocalCompileOptions } from 'reactive-md';
|
|
109
|
+
|
|
110
|
+
const options: LocalCompileOptions = {
|
|
111
|
+
limits: { maxSyntaxNodes: 50_000 },
|
|
112
|
+
};
|
|
113
|
+
const result = compileLocal(source, options);
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`limits.maxSyntaxNodes` defaults to 10,000 and accepts integers from `1` to `Number.MAX_SAFE_INTEGER`. Omitting the options, `limits` or `maxSyntaxNodes` uses the default. `0`, negative numbers, decimals, `NaN`, infinity, strings, `null` and malformed option containers return a `local.options.invalid` diagnostic; exceeding the valid node budget returns a `local.budget` diagnostic.
|
|
117
|
+
|
|
118
|
+
The budget counts `LocalNode` instances created cumulatively during parsing, including Markdown text, paragraphs, lists, tables, interpolations, components and some intermediate nodes, so it may exceed the final syntax tree node count. The setting affects only this compilation, leaves the options object untouched, and keeps other resource limits such as arrays independent. The budget comes from the host; document content cannot raise it on its own.
|
|
119
|
+
|
|
120
|
+
To use a custom budget in React, call `compileLocal` first and pass the compiled document and runtime to `LocalDocumentView`. `LocalReactiveDocument` and the Playground compilation thread use the default budget. After raising the node budget, hosts should measure memory and preview rendering time with their actual documents.
|
|
121
|
+
|
|
122
|
+
### Host components
|
|
123
|
+
|
|
124
|
+
A host can register leaf tags for one compilation without changing the `local-draft-2` syntax revision:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import { compileLocal, type LocalHostComponentSchema } from 'reactive-md';
|
|
128
|
+
|
|
129
|
+
const hostComponents: LocalHostComponentSchema[] = [
|
|
130
|
+
{
|
|
131
|
+
name: 'host-weather',
|
|
132
|
+
form: 'leaf',
|
|
133
|
+
props: {
|
|
134
|
+
kind: { kind: 'enum', required: true, enum: ['weather'] },
|
|
135
|
+
ref: { kind: 'string', required: true, pattern: '^[a-z-]+$' },
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
];
|
|
139
|
+
const result = compileLocal(source, { hostComponents });
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Without `hostComponents`, those tags remain unknown and fall back to source. Names must be unique lowercase kebab-case and cannot reuse one of the 48 author tag names, a P0 HTML tag name or `theme`; at most 32 schemas are accepted. `pattern` accepts only a linear-time-safe regex subset (no backreferences, lookarounds, named groups, nested quantifiers or quantified alternation). An invalid schema returns `local.options.invalid`, and an invalid authored attribute returns `local.host.attribute`. A valid host node counts as one syntax node. Pass `hostData`, keyed `${kind}:${ref}`, and `hostRenderer` to `LocalDocumentView`; neither enters the worker. A missing renderer, missing data or a throwing renderer renders a visible placeholder instead of failing the document. `mode="static"` uses the same dispatch and passes `ctx.mode` to the renderer.
|
|
143
|
+
|
|
144
|
+
### Version inspection and migration
|
|
145
|
+
|
|
146
|
+
Three pure functions inspect and migrate source without creating a runtime. They are exported from `reactive-md`:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import {
|
|
150
|
+
checkLocalUpgrade,
|
|
151
|
+
inspectLocalSourceVersion,
|
|
152
|
+
migrateLocalSource,
|
|
153
|
+
} from 'reactive-md';
|
|
154
|
+
|
|
155
|
+
const info = inspectLocalSourceVersion(source);
|
|
156
|
+
const check = checkLocalUpgrade(source, { fromVersion: 'local-draft-1' });
|
|
157
|
+
const migrated = migrateLocalSource(source, { fromVersion: 'local-draft-1' });
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`inspectLocalSourceVersion` reports the declared and effective revision, whether this compiler supports it, the directive range and version diagnostics. `checkLocalUpgrade` reports `ok`, `fromVersion`, `toVersion`, `needsMigration` and diagnostics. `migrateLocalSource` adds `source`, `changed` and precise `edits`.
|
|
161
|
+
|
|
162
|
+
`LocalUpgradeOptions` supplies `fromVersion` and `allowSemanticChanges`. An unversioned historical document needs `fromVersion: 'local-draft-1'`. An explicit `fromVersion` that disagrees with the declaration is rejected. Only `local-draft-1` and `local-draft-2` are accepted migration sources.
|
|
163
|
+
|
|
164
|
+
Migration changes only the metadata directive, preserves body bytes, BOM and CRLF, and is idempotent. It blocks reserved bindings, newly recognized tags, compile errors and text-control length changes before producing output. See [Source revisions and migration](source-versioning-en.md) for the exact checks and the CLI.
|
|
165
|
+
|
|
166
|
+
### `createLocalRuntime(document: LocalDocument)`
|
|
167
|
+
|
|
168
|
+
Named read-only values are described by `LocalComputation` in the optional `document.computations` record. `bindings` and `initialState` remain writable controls; `snapshot().state` also includes successful calculated values for its revision. Read a named value with `evaluate(name)` to preserve expression errors; failed values are absent from snapshots. See [calculation and error semantics](computations-formatting-en.md).
|
|
169
|
+
|
|
170
|
+
Creates an independent in-memory runtime for a compiled document. Throws if `document` is not a local mode document, if initial values exceed budgets, or if the structure is invalid. Each instance has independent state; the runtime never stores or transmits state by itself.
|
|
171
|
+
|
|
172
|
+
### `LocalRuntime`
|
|
173
|
+
|
|
174
|
+
`validate(): Diagnostic[]` reads advisory cross-field failures for the current revision. It preserves editability and returns copies of cached diagnostics. `document.validations?: LocalValidation[]` holds the serializable rule declarations. Numeric collections add `number[]` to `LocalValue` and `number-array` to `LocalValueKind`; existing writable selection controls keep string arrays. See [constraints and collections](constraints-collections-en.md).
|
|
175
|
+
|
|
176
|
+
| Member | Parameters | Returns | Behavior |
|
|
177
|
+
| --- | --- | --- | --- |
|
|
178
|
+
| `document` | — | `LocalDocument` | The compiled result used at creation |
|
|
179
|
+
| `snapshot()` | — | `{ revision: number; state: Readonly<Record<string, LocalValue>> }` | Returns the same snapshot object when state is unchanged; state is frozen |
|
|
180
|
+
| `get(node, slot?)` | `LocalNode`, optional slot | `LocalValue` | Reads the value bound to the control; `slot` selects `start`/`end` or `x`/`y`; returns `null` for no binding or an unknown node; arrays are copies |
|
|
181
|
+
| `set(node, value, slot?)` | `LocalNode`, `LocalValue`, optional slot | `Diagnostic[]` | Validates all shared controls; returns an empty array and commits once on success; does not increment revision on failure |
|
|
182
|
+
| `setMany(node, values)` | `LocalNode`, slot values | `Diagnostic[]` | Atomically writes several slots of one multi-slot control; invalid batches leave state and revision unchanged |
|
|
183
|
+
| `validate()` | — | `Diagnostic[]` | Returns copies of the current advisory validation failures; does not change or reject state |
|
|
184
|
+
| `parameterNames()` | — | `readonly string[]` | Sorted public binding names; internal `@` bindings excluded |
|
|
185
|
+
| `getParameter(name)` | `string` | `LocalValue \| undefined` | Value of a public binding; `undefined` for unknown or internal names; arrays are copies |
|
|
186
|
+
| `getParameters()` | — | `Readonly<Record<string, LocalValue>>` | Frozen public-only snapshot; internal `@` keys are never included |
|
|
187
|
+
| `setParameter(name, value)` | `string`, `LocalValue` | `Diagnostic[]` | Validates every control sharing the binding; commits once; state unchanged on failure |
|
|
188
|
+
| `setParameters(values)` | `Readonly<Record<string, LocalValue>>` | `Diagnostic[]` | Validates every public value and multi-slot relation, then commits all or nothing; unknown or internal names return `local.runtime.parameter`; invalid values return `local.runtime.value`; unchanged values do not bump the revision |
|
|
189
|
+
| `evaluate(expression)` | `string` | `LocalValue` | Evaluates with current state; throws `LocalExpressionError` on failure; arrays are copies |
|
|
190
|
+
| `text(template)` | `string` | `string` | Renders text containing `{{ }}`; throws on failure |
|
|
191
|
+
| `reset(node)` | `LocalNode` | `void` | Restores parameters and component state within the node's subtree in one commit, notifying once |
|
|
192
|
+
| `resetToken(node)` | `LocalNode` | `number` | Incrementing token for a control's internal state, so renderers can detect resets |
|
|
193
|
+
| `subscribe(listener)` | `() => void` | `() => void` | Calls the listener on every commit; returns an unsubscribe function |
|
|
194
|
+
| `dispose()` | — | `void` | Idempotent; clears subscriptions, expression caches and reset tokens; other members throw afterwards |
|
|
195
|
+
|
|
196
|
+
`set` relies on the controls registered in the document; node metadata passed by the caller cannot loosen constraints. `disabled` and conditional hiding are for interactive display only; the host still enforces business permissions and server-side data validation.
|
|
197
|
+
|
|
198
|
+
### Parameters by name
|
|
199
|
+
|
|
200
|
+
Name-based access is for hosts that keep their own parameter values, such as a form or a URL. Only public bindings are visible: `parameterNames()` returns sorted names, `getParameter(name)` returns `undefined` for an unknown or internal name, and `getParameters()` returns a frozen public-only record. Anonymous `@` bindings never appear, and arrays returned by `getParameter` are copies.
|
|
201
|
+
|
|
202
|
+
Writes validate every control sharing the binding, including multi-slot relations, and commit once. A failed call returns diagnostics and leaves the state unchanged; unchanged values do not increase the revision. Unknown or internal names return `local.runtime.parameter`; invalid values return `local.runtime.value`.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
const names = runtime.parameterNames(); // e.g. ['annual', 'people']
|
|
206
|
+
const people = runtime.getParameter('people'); // 2
|
|
207
|
+
|
|
208
|
+
runtime.setParameter('people', 7);
|
|
209
|
+
const diagnostics = runtime.setParameters({ people: 8, annual: true });
|
|
210
|
+
if (diagnostics.length) {
|
|
211
|
+
// Nothing was written.
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### State export and import
|
|
216
|
+
|
|
217
|
+
`exportLocalState(runtime, generator?)` writes the public parameters to a `reactive-md-state/v1` file. The file carries the document identity in `sourceDigest`, the language revision in `syntax`, and an optional generator name and version. Anonymous `@` bindings from `snapshot().state` are excluded, so a raw snapshot should not be stored as a long-term protocol. The [shareable export guide](shareable-export-en.md#starting-values-and-state-files) documents the format used by the CLI and standalone runtime.
|
|
218
|
+
|
|
219
|
+
`importLocalState(runtime, input, options?)` accepts serialized JSON or an already parsed file. It parses the payload, checks the source digest, syntax revision and exact public parameter set, validates every value, and applies the result; a failed import returns diagnostics and leaves the runtime unchanged. `options.maxLength` limits the serialized payload in bytes and defaults to 1 MiB.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { exportLocalState, importLocalState } from 'reactive-md';
|
|
223
|
+
|
|
224
|
+
const file = exportLocalState(runtime, { name: 'my-host', version: '1.0.0' });
|
|
225
|
+
const saved = JSON.stringify(file);
|
|
226
|
+
|
|
227
|
+
const diagnostics = importLocalState(runtime, saved);
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
The lower-level `createLocalStateFile`, `parseLocalState`, `resolveLocalState`, `applyLocalState` and `serializeLocalState` remain available. Use `resolveLocalState(document, input)` for validation that does not touch a live runtime.
|
|
231
|
+
|
|
232
|
+
### Keeping values when source changes
|
|
233
|
+
|
|
234
|
+
`LocalReactiveDocument` still creates a new runtime from initial values when `source` changes. Hosts that manage the runtime themselves can carry compatible values over:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import {
|
|
238
|
+
applyLocalStateRetention,
|
|
239
|
+
compileLocal,
|
|
240
|
+
createLocalRuntime,
|
|
241
|
+
planLocalStateRetention,
|
|
242
|
+
} from 'reactive-md';
|
|
243
|
+
|
|
244
|
+
const next = compileLocal(nextSource);
|
|
245
|
+
if (!next.ok) throw new Error('Fix the compile diagnostics first');
|
|
246
|
+
|
|
247
|
+
const plan = planLocalStateRetention({
|
|
248
|
+
previous: previousRuntime.document,
|
|
249
|
+
state: previousRuntime.snapshot().state,
|
|
250
|
+
next: next.document,
|
|
251
|
+
});
|
|
252
|
+
const runtime = createLocalRuntime(next.document);
|
|
253
|
+
const { retained, dropped, diagnostics } = applyLocalStateRetention(runtime, plan);
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
`planLocalStateRetention` returns the values to reuse, the retained parameter names, and dropped entries with a name and reason. A parameter is retained only when:
|
|
257
|
+
|
|
258
|
+
- its name exists as a public binding in both documents;
|
|
259
|
+
- both bindings are safely retainable: the binding has controls, every control is bound to the name, and no control is a timer or checklist;
|
|
260
|
+
- its type and initial definition are unchanged, including the effective initial value and any explicit `initial` attribute values.
|
|
261
|
+
|
|
262
|
+
Anonymous `@` bindings, removed or renamed parameters, timers and positional checklists are dropped. Each retained value is revalidated against the new document's constraints; a rejected value falls back to the new initial value and is reported as `invalid`. Drop reasons are `internal`, `unknown`, `unretainable`, `type`, `initial` and `invalid`.
|
|
263
|
+
|
|
264
|
+
`applyLocalStateRetention` first tries one atomic write so multi-slot relations stay consistent, then falls back to writing parameters individually, so one stale value does not block the others. `diagnostics` describe values rejected by the new document.
|
|
265
|
+
|
|
266
|
+
### Background compilation in a Worker
|
|
267
|
+
|
|
268
|
+
Worker support is host-provided: create the worker entry with your bundler and keep `compileLocal` as the fallback. A copyable browser example is in [Standalone integration examples](../examples/integration/README.md).
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
// compile.worker.ts
|
|
272
|
+
import { startLocalCompileWorker } from 'reactive-md';
|
|
273
|
+
|
|
274
|
+
startLocalCompileWorker();
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`startLocalCompileWorker()` installs the handler on the current worker global. Pass a scope explicitly only when testing or wrapping another message host.
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
// main.ts
|
|
281
|
+
import { LocalCompileScheduler } from 'reactive-md';
|
|
282
|
+
|
|
283
|
+
const scheduler = new LocalCompileScheduler({
|
|
284
|
+
createWorker: () => new Worker(new URL('./compile.worker.ts', import.meta.url), { type: 'module' }),
|
|
285
|
+
onResult: ({ source, result, mode }) => render(source, result, mode),
|
|
286
|
+
onPendingChange: (pending) => showSpinner(pending),
|
|
287
|
+
onModeChange: (mode, detail) => console.log('compile mode', mode, detail),
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
scheduler.schedule(source);
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
`LocalCompileScheduler` coalesces edits for `LOCAL_COMPILE_DELAY_MS` (150 ms; override with `delay`), keeps one compile in flight plus only the latest queued source, and discards results that a newer edit has superseded. When no worker is available, or after a worker error, it compiles on the main thread with `fallbackCompile`, which defaults to `compileLocal`; a worker failure switches permanently to this fallback and reports it through `onModeChange`. Failures thrown by the worker or during fallback compilation use the `local.worker.compile` diagnostic code.
|
|
294
|
+
|
|
295
|
+
`onResult` receives `LocalCompileOutcome` (`source`, `result`, `duration`, `mode`), `onPendingChange` reports whether work is queued or in flight, and `dispose()` stops the timer, terminates the worker and suppresses later callbacks.
|
|
296
|
+
|
|
297
|
+
### Other core exports
|
|
298
|
+
|
|
299
|
+
- `LOCAL_SYNTAX_VERSION`: currently the literal `'local-draft-2'`. Use it to record the syntax revision a document uses.
|
|
300
|
+
- `compileExpression(source: string)`: returns an object with `source`, `dependencies`, `evaluate(env)` and `inferType(env)`; throws `LocalExpressionError` on failure.
|
|
301
|
+
- `LocalExpressionError`: contains `code` and `offset`.
|
|
302
|
+
- `compileLatex(source: string)`: returns an object with `source`, `dependencies` and `evaluate(x, env, budget?)`; throws an error with `code` and `offset` on failure.
|
|
303
|
+
- `samplePlot(expression, env, min, max, samples = 200, sharedBudget?)`: returns `{ points: { x: number; y: number | null }[]; endpoint: number | null }`; throws when the range, sample count or budget is invalid.
|
|
304
|
+
- State files: `exportLocalState`, `importLocalState`, `createLocalStateFile`, `parseLocalState`, `resolveLocalState`, `applyLocalState` and `serializeLocalState`; `LOCAL_STATE_FORMAT` is `'reactive-md-state/v1'`.
|
|
305
|
+
- Source revisions: `inspectLocalSourceVersion`, `checkLocalUpgrade` and `migrateLocalSource`; `LocalUpgradeOptions` configures the source revision and semantic-change allowance.
|
|
306
|
+
- Retention: `planLocalStateRetention` and `applyLocalStateRetention`.
|
|
307
|
+
- Background compilation: `LocalCompileScheduler`, `LOCAL_COMPILE_DELAY_MS` and `startLocalCompileWorker`.
|
|
308
|
+
- Type exports: `Diagnostic`, `SourceRange`, `LocalValue`, `LocalValueKind`, `LocalNode`, `LocalBinding`, `LocalComputation`, `LocalValidation`, `LocalDocument`, `LocalCompileLimits`, `LocalCompileOptions`, `LocalCompileResult`, `LocalHostPropKind`, `LocalHostPropSchema`, `LocalHostComponentSchema`, `LocalUpgradeOptions`, `LocalRuntime`, `LocalSnapshot`, `LocalStateFile`, `LocalStateGenerator`, `LocalStateParseResult`, `LocalStateResolution`, `LocalRetainedState`, `LocalStateRetentionReason`, `LocalStateRetentionDrop`, `LocalStateRetentionInput`, `LocalStateRetentionResult`, `LocalCompileWorker`, `LocalCompileWorkerScope`, `LocalCompileRequest`, `LocalCompileResponse`, `LocalCompileOutcome`, `LocalCompileMode`, `LocalCompileSchedulerOptions`.
|
|
309
|
+
|
|
310
|
+
`compileExpression`, `compileLatex` and `samplePlot` are lower-level utilities with the same stability level as the core API; usually only `compileLocal` and `createLocalRuntime` are needed.
|
|
311
|
+
|
|
312
|
+
## Diagnostics
|
|
313
|
+
|
|
314
|
+
The fields and stability levels of `Diagnostic` are described in the diagnostics contract in [Versions and compatibility](compatibility-en.md). Key points: `line`, `column` and `range` are for programmatic location; `code` can be used for coarse classification in the current version, but 0.x does not promise cross-version stability; `message` is display text and should not be parsed.
|
|
315
|
+
|
|
316
|
+
`onDiagnostics` receives compile diagnostics when the compilation result changes, and runtime diagnostics when control writes are rejected. Documents with compile errors do not activate interaction; runtime local errors replace only the corresponding content.
|
|
317
|
+
|
|
318
|
+
## State, instances and cleanup
|
|
319
|
+
|
|
320
|
+
- `LocalReactiveDocument` recompiles and creates a runtime when `source` changes, cleaning up the old instance; React StrictMode is supported.
|
|
321
|
+
- When managing the lifecycle yourself, render with `<LocalDocumentView document={result.document} runtime={runtime} />` and call `runtime.dispose()` on unmount.
|
|
322
|
+
- `subscribe()` returns an unsubscribe function. `dispose()` clears remaining subscriptions; calling other runtime methods afterwards throws.
|
|
323
|
+
- `snapshot()` returns the same object until state changes, which is useful for external store subscriptions. `reset(panelNode)` commits once for the panel subtree, and subscribers receive one notification; hidden controls inside the panel are also within reset scope.
|
|
324
|
+
- Document state lives only in memory; the runtime never writes storage, cookies or the network. Refreshing, remounting or replacing the source starts from initial values. Persistence is an explicit host action through `exportLocalState` and `importLocalState`; the [retention helpers](#keeping-values-when-source-changes) can carry compatible values into a new runtime.
|
|
325
|
+
- Hidden regions keep parameters, tab selection and checklist state; timers in hidden regions pause and stay paused when shown again until the reader starts them. Disposing an instance releases timers and subscriptions.
|
|
326
|
+
|
|
327
|
+
## Image and link policy
|
|
328
|
+
|
|
329
|
+
Images are not loaded by default, including relative-path images, so documents do not automatically request host APIs or external sites. Hosts can explicitly allow image sources through `urlPolicy`; both `LocalReactiveDocument` and `LocalDocumentView` accept this prop. Links keep safe protocol checks by default.
|
|
330
|
+
|
|
331
|
+
```tsx
|
|
332
|
+
import type { LocalUrlPolicy } from 'reactive-md/react';
|
|
333
|
+
|
|
334
|
+
const urlPolicy: LocalUrlPolicy = (raw, kind) => {
|
|
335
|
+
if (kind === 'link') return true;
|
|
336
|
+
try {
|
|
337
|
+
const url = new URL(raw);
|
|
338
|
+
return url.protocol === 'https:' && url.origin === 'https://images.example.com';
|
|
339
|
+
} catch {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
<LocalReactiveDocument source={source} urlPolicy={urlPolicy} />;
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
| Target | Without a policy | With a policy |
|
|
348
|
+
| --- | --- | --- |
|
|
349
|
+
| Images | All rejected, including relative addresses | Protocol-bearing addresses are checked first and only HTTP(S) is allowed; relative addresses are decided by the policy |
|
|
350
|
+
| Links | Relative addresses and `http`, `https`, `mailto`, `tel` allowed | Decided by the policy after protocol checks; external HTTP(S) links get `_blank` and `noopener noreferrer` |
|
|
351
|
+
|
|
352
|
+
The policy receives the raw URL with leading and trailing whitespace removed, and `'image' | 'link'`. If the policy throws, the address is rejected. The renderer always checks the protocol first; even if the policy allows it, `javascript:` or dangerous `data:` addresses cannot be used. Images allowed to load use `referrerPolicy="no-referrer"`; same-origin requests may still carry cookies, so image allowlists should avoid business API paths.
|
|
353
|
+
|
|
354
|
+
`urlPolicy` controls only rendered links and images; it is not server-side authorization or a sandbox. Hosts still need to handle CSP, network egress and isolation policies for untrusted authors.
|
|
355
|
+
|
|
356
|
+
## Theme and style scoping
|
|
357
|
+
|
|
358
|
+
`reactive-md/styles.css` is a global stylesheet, not isolated through Shadow DOM or CSS Modules. Hosts should import it explicitly once; the `reactive-md/react` library build extracts styles into this file and does not inject them automatically when importing JavaScript.
|
|
359
|
+
|
|
360
|
+
- Style selectors are mainly `.md-document`, `.local-document` and `.md-*`, `.local-*` class names. The document root rendered by components is `.md-document.local-document`.
|
|
361
|
+
- Theme variables are declared on `.md-document` and `.reactive-md-theme`, including `--ink`, `--surface`, `--line`, `--blue`, `--teal`, `--danger`, `--radius-*` and font variables. Override them after the library styles with rules such as `.my-article .md-document { --blue: #245c98; }`; the document root carries default values, so setting variables only on an ancestor container will not override same-name values on the root.
|
|
362
|
+
- Documents may start with `<theme name="default">`; omission selects `default`. Register custom themes through `themes`; see the [theme protocol](theme-protocol-en.md).
|
|
363
|
+
- `colorScheme` forces light or dark mode. The default `auto` reads the nearest ancestor's `data-color-scheme` or legacy `data-theme`, then the system preference. Each document exposes independent `data-rmd-theme` and resolved `data-color-scheme` attributes.
|
|
364
|
+
- Documents default to `max-width: 720px` and are horizontally centered. To fill the host container, override the width and margins of `.md-document` within your own scope.
|
|
365
|
+
- Prefer public variables for theme styling. Component outer `.md-*` and `.local-*` classes and semantic state attributes are theme hooks; internal node ordering is not an extension API. See the theme protocol for compatibility requirements.
|
|
366
|
+
- Neither React component accepts `className` or `style`. For local overrides, scope them with the host's own wrapper element.
|
|
367
|
+
|
|
368
|
+
## Resource limits
|
|
369
|
+
|
|
370
|
+
A single string is limited to 100,000 characters, an array to 10,000 items, and the total string length within an array to 100,000 characters. Email validation uses a length-limited linear check. The runtime rejects writes over a limit and keeps the last valid state.
|
|
371
|
+
|
|
372
|
+
A single document source is limited to 1,000,000 characters. There are at most 100 diagnostics, and a single message is at most 2,000 characters.
|
|
373
|
+
|
|
374
|
+
Each plot component has at most 16 curves; the whole document requests at most 20,000 curve sample points, including hidden regions. Plotting computation is also limited by a shared execution budget of 2,000,000 steps. A document has at most 100 validation rules. Generated `data-table` rows, columns and text have per-table and whole-document budgets described in [constraints and collections](constraints-collections-en.md). Documents over a limit receive diagnostics; expression and math rendering also have their own depth and token budgets.
|
|
375
|
+
|
|
376
|
+
These limits bound the work for a single document; they do not replace host control over request size, concurrency and execution time. See the [security policy](../SECURITY.md) for the full threat boundary.
|
|
377
|
+
|
|
378
|
+
## Version pinning and upgrades
|
|
379
|
+
|
|
380
|
+
- During 0.x, pin the exact package version and commit the lockfile. `^0.3.0` allows only patch versions, but production integrations should still pin the version or the tarball SHA256.
|
|
381
|
+
- Use one package version for both the core and React entries; do not mix different versions of `reactive-md` and `reactive-md/react`.
|
|
382
|
+
- Record `LOCAL_SYNTAX_VERSION` in application configuration or document metadata, alongside the persisted `.reactive.md` source. Migrate according to [Versions and compatibility](compatibility-en.md) when the syntax revision changes.
|
|
383
|
+
- After upgrading, recompile your own documents and check `result.diagnostics`, rendered output and browser interactions. Do not depend on the text of diagnostic `message`.
|
|
384
|
+
|
|
385
|
+
## Features not provided
|
|
386
|
+
|
|
387
|
+
The default ReactiveMD path supports P0 HTML. Host options for author CSS, JavaScript and extended HTML use the separate native HTML path described in [HTML compatibility](html-compatibility-en.md). Local mode still provides no automatic state persistence or unrestricted network access, plugins or custom component registration, external data APIs, Vue support, React 18 support or a CommonJS entry. State export and import are explicit host calls. `LocalReactiveDocument` starts from initial values when the source changes; use retention helpers or manage the runtime and document yourself.
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
See [local-draft-2 components and migration](local-components-v2-en.md) for new tags, colors and slot state, and [0.4.0 release and migration](release-0.4.0-en.md) for the upgrade checklist. `0.4.0` is the preview release on the `next` channel.
|
|
391
|
+
|
|
392
|
+
.5.3 adds compile-option-aware authoring and explicit screen/print styles. See [0.5.3 host integration](release-0.5.3-en.md).
|