@drghaliasri/butex 7.4.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +49 -553
  2. package/dist/{document2-cli.js → document-cli.js} +332 -302
  3. package/dist/document-cli.js.map +1 -0
  4. package/dist/document.d.mts +1022 -186
  5. package/dist/document.d.ts +1022 -186
  6. package/dist/document.js +6068 -658
  7. package/dist/document.js.map +1 -1
  8. package/dist/document.mjs +5928 -618
  9. package/dist/document.mjs.map +1 -1
  10. package/dist/react-document-preview.d.mts +338 -0
  11. package/dist/react-document-preview.d.ts +338 -0
  12. package/dist/{react-document2-preview.js → react-document-preview.js} +783 -783
  13. package/dist/react-document-preview.js.map +1 -0
  14. package/dist/{react-document2-preview.mjs → react-document-preview.mjs} +776 -776
  15. package/dist/react-document-preview.mjs.map +1 -0
  16. package/dist/react-document.d.mts +634 -35
  17. package/dist/react-document.d.ts +634 -35
  18. package/dist/react-document.js +13259 -4282
  19. package/dist/react-document.js.map +1 -1
  20. package/dist/react-document.mjs +12617 -3648
  21. package/dist/react-document.mjs.map +1 -1
  22. package/dist/react.js +4 -4
  23. package/dist/react.js.map +1 -1
  24. package/dist/react.mjs +4 -4
  25. package/dist/react.mjs.map +1 -1
  26. package/package.json +7 -17
  27. package/dist/document2-cli.js.map +0 -1
  28. package/dist/document2.d.mts +0 -1156
  29. package/dist/document2.d.ts +0 -1156
  30. package/dist/document2.js +0 -9137
  31. package/dist/document2.js.map +0 -1
  32. package/dist/document2.mjs +0 -8972
  33. package/dist/document2.mjs.map +0 -1
  34. package/dist/react-document2-preview.d.mts +0 -338
  35. package/dist/react-document2-preview.d.ts +0 -338
  36. package/dist/react-document2-preview.js.map +0 -1
  37. package/dist/react-document2-preview.mjs.map +0 -1
  38. package/dist/react-document2.d.mts +0 -754
  39. package/dist/react-document2.d.ts +0 -754
  40. package/dist/react-document2.js +0 -23011
  41. package/dist/react-document2.js.map +0 -1
  42. package/dist/react-document2.mjs +0 -22981
  43. package/dist/react-document2.mjs.map +0 -1
package/README.md CHANGED
@@ -1,596 +1,92 @@
1
1
  # BuTeX
2
2
 
3
- **Integrators:** treat [**Integration contract (host apps)**](#integration-contract-host-apps) as the source of truth for wiring MathJax and BuTeX. The **npm package** ships `dist/` and this `README.md` only; design notes and ADRs live in the GitHub repo under `docs/` (they are not included in the published tarball).
3
+ **BuTeX** (`@drghaliasri/butex`) provides **Arabic mathematical typography and structured equation/document editing** on MathJax 4. It ships an AST-first equation editor, canonical **Document** model, React editors/previews and a stateless Node document worker.
4
4
 
5
- BuTeX is a browser-side foundation for Arabic mathematical typography and equation editing on top of [MathJax](https://www.mathjax.org/). It ships thin MathJax extensions such as `\arabsqrt` (Arabic-style mirrored radical; CommonHTML uses CSS mirror/unmirror, SVG uses the MathJax SVG pipeline plus BuTeX SVG helpers where applicable), optional GUI/document layers, and helpers such as `parseBuTeX`. The longer-term direction is a GUI editor driven by structured equation ASTs.
6
-
7
- The vendored **[MathJax-src/](MathJax-src/)** folder in this repo is **reference only** — runtime integration uses the **`mathjax`** npm package.
8
-
9
- ## Project direction
10
-
11
- The intended editor model is **AST-first**:
12
-
13
- - A GUI edits equation nodes rather than raw LaTeX strings.
14
- - BuTeX will maintain local TypeScript ASTs for English and Arabic equation structures so users can switch views.
15
- - A remote service may send equations as JSON compatible with the local ASTs; the browser imports that JSON and renders/edit it locally.
16
- - Arabic/English TeX strings are generated from the AST for MathJax rendering. Remote-rendered strings can be useful for testing/debugging, but should not be the editor state.
17
- - The Python files in **[references/](references/)** are reference material for the emerging JSON shape and conversion behavior.
18
-
19
- ## Rendering outputs and MVP scope
20
-
21
- - **CommonHTML (`chtml`)** and **SVG** are supported. Load the matching MathJax 4 bundle (`tex-chtml.js` vs `tex-svg.js`) and pass the same mode as `output` to `renderBuTeXMathIsland` / `mountBuTeXMathIsland`. `<ButexEditor />` and document math preview follow the loaded bundle when possible (`tex2chtml` vs `tex2svg`).
22
- - `\arsqrt`: canonical serialized Arabic TeX command with an optional index and mandatory radicand (same argument shape as `\sqrt`).
23
- - Compatibility macros: MathJax accepts `\arabsqrt` as an alias of `\arsqrt`; `\unit{...}` and `\idx{...}` are browser-side passthrough wrappers for imported/reference TeX.
24
- - **Arabic surface parser** (`parseBuTeX`) — optional helper that maps a tiny subset of Arabic command names to MathJax-safe TeX before rendering (see below). Long-term editor state is structured AST/JSON, not this string transform alone.
25
-
26
- ## Arabic preprocessor (`parseBuTeX`)
27
-
28
- Convert Arabic-friendly math surface syntax to plain MathJax TeX:
29
-
30
-
31
- | Input | Output |
32
- | ------------------- | -------------------------------- |
33
- | `\جذر[3]{س}` | `\arabsqrt[3]{\text{س}}` |
34
- | `\كسر{1}{2}` | `\frac{1}{2}` |
35
- | `\كسر{\جذر{س}}{10}` | `\frac{\arabsqrt{\text{س}}}{10}` |
36
- | `\جتا` | `\arcos` |
37
-
38
-
39
- Pure string transform — call `parseBuTeX(tex)`, pass the result to MathJax.
40
-
41
- ```ts
42
- import { parseBuTeX } from 'butex';
43
-
44
- const mjTex = parseBuTeX(String.raw`\جذر[3]{س}`);
45
- // await renderBuTeXMathIsland(mjTex, { display: true, output: 'chtml' }) ...
46
- ```
47
-
48
- Run tests with `npm test`. Live parser demo: `demo/parser.html` (after `npm run build`; serve the repo root).
5
+ MathJax is an **external peer dependency**, not bundled as a vendored upstream source tree. See [MathJax's upstream source](https://github.com/mathjax/MathJax-src) for the reference implementation; [package.json](package.json) specifies the runtime peer dependency.
49
6
 
50
7
  ## Install
51
8
 
52
9
  ```bash
53
- npm install butex mathjax
54
- ```
55
-
56
- Peer dependency: `mathjax` ^4.x (aligned with MathJax 4 components). If you use **`butex/react`**, also install **`react`** and **`react-dom`** (^18 or ^19).
57
-
58
- ## Usage (browser)
59
-
60
- 1. Load MathJax (e.g. `tex-chtml.js` or `tex-svg.js`) **after** setting `window.MathJax` config.
61
- 2. Load BuTeX’s IIFE bundle (`dist/index.global.js` exposes global `BuTeX`).
62
- 3. In `MathJax.startup.ready`, call `BuTeX.registerBuTeX(MathJax)` before `MathJax.startup.defaultReady()`.
63
- 4. Inject styles once: `BuTeX.injectBuTeXStyles()` (or embed `BuTeX.BUTEX_CHROME_CSS` yourself).
64
- 5. When using **SVG** (`tex-svg.js`), call `BuTeX.registerBuTeXSvgTextWrapper(MathJax)` **after** `defaultReady()` so Takween/Diwani/Maghribi text, RTL multiword `\unit{وحدة تجريبية}` displays, `\ad`, and Arabic atomic commands (`\arsin`, etc.) render correctly in the preview. SVG units use one upright, RTL-isolated text element; neither the unit identity nor the stored notation is reversed. CommonHTML (`tex-chtml.js`) uses the injected CSS classes instead.
65
- 6. Render math with `renderBuTeXMathIsland(tex, options?)` or mount into a host element via `mountBuTeXMathIsland(host, tex, options?)`. Pass `output: 'svg'` when the host loads `tex-svg.js`, or `output: 'chtml'` with `tex-chtml.js`. For raw Arabic TeX that did not come from the editor AST, pass `mirrorOperators: true` to wrap directional operators according to BuTeX's shared operator table. `ButexEditor` picks SVG vs CHTML automatically from the loaded MathJax bundle (`tex2svg` vs `tex2chtml`).
66
-
67
- Ensure TeX `packages` includes `butex-arabic-math` (use `BUTEX_TEX_PACKAGE` in config when using `{ '[+]': [...] }`). BuTeX registers lightweight browser compatibility macros for toolbar symbols such as `\coloneqq` and `\eqqcolon`; XeLaTeX export still relies on the document preamble's `mathtools`.
68
-
69
- ## Usage (npm / bundler)
70
-
71
- ### MathJax entrypoints (bundlers)
72
-
73
- Exact import strings depend on your bundler and how it resolves the `mathjax` package. Typical ESM imports for MathJax 4 components:
74
-
75
- | Desired output | Typical import |
76
- | -------------- | -------------- |
77
- | CommonHTML | `import MathJax from 'mathjax/tex-chtml.js'` |
78
- | SVG | `import MathJax from 'mathjax/tex-svg.js'` |
79
-
80
- Use the same mode in `renderBuTeXMathIsland` / `mountBuTeXMathIsland` via `output: 'chtml'` or `output: 'svg'`. If resolution fails, point your import at whatever path your build resolves to the same component bundle (see MathJax’s docs for your version).
81
-
82
- ```ts
83
- import MathJax from 'mathjax/tex-chtml.js'; // or tex-svg.js — match `output` in render calls
84
- import {
85
- registerBuTeX,
86
- injectBuTeXStyles,
87
- renderBuTeXMathIsland,
88
- BUTEX_TEX_PACKAGE,
89
- } from 'butex';
90
-
91
- // Before startup resolves — same timing rules as browser:
92
- MathJax.startup.ready = () => {
93
- registerBuTeX(MathJax);
94
- injectBuTeXStyles();
95
- MathJax.startup.defaultReady();
96
- };
97
- MathJax.config.tex = {
98
- packages: { '[+]': ['ams', BUTEX_TEX_PACKAGE] },
99
- };
100
- ```
101
-
102
- Maintainer-facing design notes live in the GitHub repo under `docs/` (not shipped on npm).
103
-
104
- ## Integration contract (host apps)
105
-
106
- BuTeX supports two integration modes. Keep this contract for stable behavior.
107
-
108
- ### 1) Render-only contract (MathJax + BuTeX macros)
109
-
110
- Use this when you only need to render LaTeX strings:
111
-
112
- - Register BuTeX with MathJax via `registerBuTeX(MathJax)`.
113
- - Include `butex-arabic-math` in TeX packages.
114
- - Inject BuTeX MathJax styles once via `injectBuTeXStyles(document)` (or embed `BUTEX_CHROME_CSS`).
115
- - Render expressions with `renderBuTeXMathIsland` / `mountBuTeXMathIsland` (set `output` to match the host bundle: `tex-svg.js` vs `tex-chtml.js`).
116
- - For raw Arabic TeX, set `mirrorOperators: true` or call `mirrorBuTeXOperatorsInTex(tex)` before non-island MathJax typesetting. Leave it off for editor-generated TeX because the editor already emits `\butexmirror{...}`.
117
- - For Arabic-friendly surface strings, optionally preprocess with `parseBuTeX(...)` before rendering.
118
-
119
- This mode does not require the GUI editor runtime.
120
-
121
- ### Host CSS resets (Tailwind Preflight and similar)
122
-
123
- MathJax renders SVG equations as inline `<svg>` elements, and MathJax 4's inline
124
- line-breaking can emit one equation as **several sibling `<svg>` chunks**. Global
125
- CSS resets that declare `svg { display: block }` (e.g. **Tailwind Preflight**)
126
- stack those chunks vertically, so equations render one term per line.
127
-
128
- BuTeX's injected styles guard against this with:
129
-
130
- ```css
131
- mjx-container svg {
132
- display: inline;
133
- }
10
+ npm install @drghaliasri/butex mathjax
11
+ # Add these if using the React editors:
12
+ npm install react react-dom
134
13
  ```
135
14
 
136
- The guard ships in both `injectBuTeXStyles()` (`BUTEX_CHROME_CSS`) and
137
- `injectBuTeXDocument2Styles()` (`DOCUMENT2_WIDGET_CSS`), so make sure the host
138
- calls at least one of them (or embeds the CSS constants). If your app injects
139
- neither and you see stacked/wrapped equations under Tailwind, add the rule above
140
- to your global stylesheet after the reset.
141
-
142
- Also pin the MathJax version the host loads (e.g. `mathjax@4.1`) instead of a
143
- floating major tag, so CDN updates cannot change rendering behavior silently.
15
+ Node.js **20+** is required for tooling/worker usage. MathJax `^4.1.0` is a peer dependency; React and ReactDOM 18/19 are optional peers. [package.json](package.json) defines current versions, supported imports and CLI names.
144
16
 
145
- ### 2) GUI editor contract (shippable editor UX)
17
+ ## Public entrypoints
146
18
 
147
- When exporting a structured delimiter to English LaTeX, BuTeX places an ordinary space after its opening delimiter. In math mode this is a harmless token separator that keeps command-style delimiters such as `\left\lVert x\right\rVert` valid.
19
+ | Import / executable | Implemented purpose |
20
+ | --- | --- |
21
+ | `@drghaliasri/butex` | Core Arabic MathJax macros, `parseBuTeX`, registration, math-island rendering |
22
+ | `@drghaliasri/butex/react` | Standalone `ButexEditor` equation editor |
23
+ | `@drghaliasri/butex/document` | `DocumentJson`, commands, import/export, outline, validation, diff |
24
+ | `@drghaliasri/butex/react-document` | `ButexDocumentEditor` editor |
25
+ | `@drghaliasri/butex/react-document-preview` | Lightweight read-only `ButexDocumentPreview` |
26
+ | `butex-document` | Stateless stdin / authenticated HTTP worker |
148
27
 
149
- Use this when you want the same editor UX as the demo:
28
+ On the unmerged migration branch, the first-generation model and GUI were removed (Round 3), the maintained headless API and worker were promoted to `Document` (Round 4), and the current maintained React GUI was promoted to `react-document` and `react-document-preview` in Round 5. This branch is not a published package.
150
29
 
151
- - Inject editor styles once via `injectBuTeXEditorStyles(document)` (or embed `BUTEX_EDITOR_CSS`).
152
- - Create runtime with `Editor.createEditorRuntime({ ... })`.
153
- - Pass your editor surface element as `surfaceEl`.
154
- - Optionally pass `buttonElements` (undo/redo/copy/cut/split toggle) for auto button state refresh.
155
- - Wire your toolbar/actions to runtime methods (`toggleSide`, `insertDelimiterByKind`, `addSup`, `addSub`, `removeSup`, `removeSub`, `deleteStructure`, `performUndo`, `performRedo`, `performCopy`, `performCut`, `performPaste`).
156
- - Use `onSessionChange(session)` to render external previews (e.g., MathJax pane, status labels).
157
- - **Imported `MathObject` / `CharObject` for the editor:** document LaTeX preview treats `CharObject.expr` as already-rendered Arabic TeX (e.g. `\text{م}`). When opening an imported equation in `<ButexEditor />` via `mathObjectToEditorSession`, BuTeX unwraps supported LaTeX text/font wrappers into plain glyph `expr` plus editor `characterFont`. Supported patterns: `\text{…}`, `\takween{…}`, `\diwani{…}`, `\butextakween{…}`, `\butexdiwani{…}`, `\butexdiwanioutline{…}`, `\butexmaghribi{…}`, and nested forms such as `\text{\takween{…}}`. On save, default-font chars stay plain `CharObject` nodes; non-default fonts are stored as font `CommandObject` wrappers so editor round-trip preserves `characterFont`. Upstream converters may still emit wrapped `expr` on import.
158
- - **Standard math round-trip:** imported structured equations preserve explicit `\top`, the six `\mathbb{N/Z/Q/R/C/H}` number systems, exact differential `\mathrm{d}`, atomic named variables carried by `\mathtt{...}`, and units carried through `\unit{...}` / upstream `\mathsf{...}` source identity. Node-bound `source_latex` is preserved only while that editable occurrence is unchanged and is cleared when its editable name changes.
30
+ ## MathJax setup
159
31
 
160
- Minimal browser example:
32
+ Use MathJax **4** `tex-chtml.js` or `tex-svg.js`, matching the `chtml` / `svg` output mode. Configure the `butex-arabic-math` TeX package and call `registerBuTeX` before MathJax startup completes. Use `registerBuTeXSvgTextWrapper` after startup initialization for SVG-specific Arabic text behavior.
161
33
 
162
34
  ```ts
163
- BuTeX.injectBuTeXEditorStyles(document);
164
- const runtime = BuTeX.Editor.createEditorRuntime({
165
- surfaceEl: document.getElementById('surface'),
166
- onSessionChange: (session) => {
167
- // host-render math preview/status here
168
- },
169
- });
170
- ```
171
-
172
- ### React widget (`butex/react`)
173
-
174
- Shipped as a separate entry so apps that do not use React never pull it in.
35
+ import { registerBuTeX, injectBuTeXStyles } from '@drghaliasri/butex';
175
36
 
176
- - Import: `import { ButexEditor } from 'butex/react'`.
177
- - Peer dependencies when using this entry: `react` and `react-dom` (^18 or ^19).
178
- - The component wraps `Editor.createEditorRuntime` (toolbar, surface, MathJax preview strip, optional dev panels via `debug`).
179
- - Touch devices use a textarea-backed input bridge, so tapping the structured equation surface opens the software keyboard and supports normal text, deletion, and composed/IME input without making TeX strings the editor state. When `window.visualViewport` exposes valid metrics, BuTeX automatically follows its visible bounds and re-reveals the active caret after keyboard or orientation resizing; `100dvh` remains the no-API fallback.
180
- - Load MathJax and register BuTeX **before** relying on the preview (same timing as the GUI contract above). Equation preview in `ButexEditor` uses the same `renderBuTeXMathIsland` path as document math islands (output follows the loaded bundle: SVG when `tex2svg` is available, otherwise CHTML). Optional legacy `mountBuTeXMathTypeset` (`typesetPromise`) remains exported for hosts that still rely on it.
181
- - Next.js App Router: put BuTeX in a **client component** (`'use client'`).
182
-
183
- ```tsx
184
- 'use client';
185
-
186
- import { ButexEditor } from 'butex/react';
187
-
188
- export default function Page() {
189
- return <ButexEditor uiLocale="en" defaultSide="english" showSideSwitcher={false} />;
190
- }
37
+ // Inside your host's MathJax startup.ready integration:
38
+ registerBuTeX(MathJax);
39
+ injectBuTeXStyles();
40
+ // Then complete the chosen MathJax component's startup.
191
41
  ```
192
42
 
193
- `uiLocale` selects Arabic (`"ar"`, the default) or English (`"en"`) GUI labels, tooltips, errors, accessibility text, and chrome direction. `defaultSide` independently selects the initial `"english"` or `"arabic"` equation side. Side controls remain visible by default for standalone compatibility; pass `showSideSwitcher={false}` to hide both the desktop switch and compact-sheet side choices without removing either synchronized equation tree.
194
-
195
- Equation-toolbar responsiveness is automatic and package-owned. At a layout viewport width of 768px or less, the wrapped desktop toolbar is replaced by a compact command hierarchy: Undo, Redo, Fraction, Superscript, Subscript, Delimiters, Delete, and More. Advanced commands remain available in localized Structures, Functions, Operators, Matrices, Typography, Spacing, and Digit forms sheets. The rendered preview stays mounted but starts collapsed in compact mode so the structured surface receives the available height. Above 768px the existing desktop toolbar and preview remain unchanged. Use `responsiveMode="desktop"` or `responsiveMode="compact"` only when the host intentionally needs to override the automatic workflow.
196
-
197
- Compact command sheets trap focus while open. Dismissing a sheet restores its trigger, while running an editing command restores the textarea-backed input bridge. Wide and nested equations pan locally inside the structured surface; edits and caret navigation reveal the active position by the smallest required horizontal movement without scrolling the host page or reacting to panning alone.
43
+ See [math/rendering architecture](docs/architecture/equations.md) for initialization and semantic/visual RTL rules. `parseBuTeX` is a small Arabic-friendly surface preprocessor, **not** a general LaTeX-to-structured-AST parser.
198
44
 
199
- There is no configurable breakpoint or keyboard-aware prop. These behaviors are automatic enhancements and do not change the equation AST or session API. BuTeX never calls `window.scrollTo` or locks the host document body; hosts should leave the editor's fixed overlay outside transformed or unexpectedly clipping ancestors and should test their own nested scrolling shell with the target mobile keyboards.
200
-
201
- ### Document AST (`butex/document`)
202
-
203
- Use this headless entry when a host app or remote service already has `DocumentObject` JSON and needs a structured import/export layer.
45
+ ## Document model basics
204
46
 
205
47
  ```ts
206
48
  import {
207
- fromDocumentJson,
208
49
  createEmptyDocument,
209
- renderDocumentLatex,
210
- buildDocumentPreview,
211
- } from 'butex/document';
212
-
213
- const documentNode = fromDocumentJson({
214
- node_type: 'DocumentObject',
215
- blocks: [{ command: '\\section', value: 'Intro $x$' }],
216
- });
217
-
218
- const emptyDocument = createEmptyDocument();
219
- const latex = renderDocumentLatex(documentNode);
220
- const preview = buildDocumentPreview(documentNode);
221
- ```
222
-
223
- V1 supports simple headings, paragraphs, `itemize` / `enumerate`, `tabular`, `includegraphics`, raw blocks, and math spans detected inside text. The document layer detects math delimiters and can align them with ordered imported `MathObject` JSON; it does not parse arbitrary equation LaTeX into chain nodes in the browser.
224
-
225
- ### Document React widget (`butex/react-document`)
226
-
227
- Use this entry for the first document-editor UI. It edits supported document blocks, shows a live semantic preview, and opens the equation editor for supported imported math islands.
228
-
229
- ```tsx
230
- 'use client';
231
-
232
- import { ButexDocumentEditor } from 'butex/react-document';
233
-
234
- export default function Page() {
235
- return (
236
- <ButexDocumentEditor
237
- debug
238
- onLatexChange={(latex) => console.log(latex)}
239
- />
240
- );
241
- }
242
- ```
243
-
244
- The preview is semantic HTML for document structure. Math is emitted as escaped per-span islands, so host apps still need the normal MathJax + BuTeX registration when they want typeset math preview rather than TeX placeholders.
245
-
246
- ### Document AST v2 (`butex/document2`)
247
-
248
- Use this parallel v2 headless entry for the token-owned document model. Imported delimited math is converted into math tokens between prose tokens; normal editing should mutate text tokens and math tokens separately rather than treating raw delimited TeX as one textarea value.
249
-
250
- ```ts
251
- import {
252
- fromDocumentJson2,
253
- document2Latex,
254
- document2Preview,
255
- } from 'butex/document2';
256
-
257
- const documentNode = fromDocumentJson2({
258
- node_type: 'DocumentObject',
259
- blocks: [{ command: '\\paragraph', value: 'نص $x$' }],
260
- });
261
-
262
- const latex = document2Latex(documentNode);
263
- const preview = document2Preview(documentNode, 'svg');
264
- ```
265
-
266
- `document2Latex(doc)` emits a **complete Arabic XeLaTeX document** by default (preamble + `\begin{document}` + body + `\end{document}`). Structured and editor-authored Arabic roots serialize with the canonical `\arsqrt`; the bundled preamble also accepts raw legacy `\arabsqrt` with the same optional-index signature. It defines BuTeX font wrappers (`\butextakween`, `\butexdiwani`, `\butexdiwanioutline`, `\butexmaghribi`) and the MathJax-compatible `\butexmirror` bridge. The title-path basmala keeps its Maghribi title styling; the fixed closing hamdala is emitted as normal centered `\maghribi` text rather than display math so it participates in ordinary column/page flow. Pass `{ wrapDocument: false }` for body-only blocks. Paragraph blocks export as `\par` followed by the inline content, so prose, citations, and math are not wrapped inside `\paragraph{...}`. Optional `digitsMapping: 'arabicdigits' | 'digits'` controls eastern vs western digit font mapping in the preamble (default `'arabicdigits'`). Pass `{ twocolumn: true }` for `\documentclass[12pt,a4paper,notitlepage,twocolumn]{article}`; title content stays in-column and Document2 figure/table floats use fixed `[H]` placement (with the `float` package) so source block order remains predictable. Figures continue to use `\columnwidth`. See [`examples/example-latex-export.tex`](examples/example-latex-export.tex) for a full sample (regenerated by the wrap vitest). Hosts can also call `getArabicXeLatexPreamble()` alone.
267
-
268
- For XeLaTeX compiler images, install `src/fonts/Almaghribi-Warsh-Quran.otf` as a system font and refresh fontconfig (`fc-cache -f -v`). Verify with `fc-match "Almaghribi Warsh Quran"`; the preamble uses that installed family name.
269
-
270
- To add another character font, add its metadata to `src/editor/characterFonts.ts` and its browser `@font-face` asset to `src/diwani-font.ts`.
271
-
272
- Figures and tables export as centered `figure` / `table` environments. In one-column export they retain normal `[htbp]` float placement; in `twocolumn` export they use fixed `[H]` placement to avoid unexpected reordering/gaps. Simple editor table column specifications made only from `l`, `c`, and `r` (for example `lll`) receive a visible grid by default (`|l|l|l|` plus `\hline`); explicitly structured specifications such as `c|c` are preserved. Optional caption/label fields emit `\caption` / `\label`; a labeled figure/table without a caption uses `\refstepcounter{figure}` / `\refstepcounter{table}` before its label so the reference owns the correct counter. Display math stays `\[…\]` unless an equation label is enabled, then export uses `\begin{equation}…\label{…}\end{equation}`. Internal cross-refs still store `\ref` / `\eqref` tokens separately from bibliography `\cite`, but LaTeX export adds the known Arabic object type (`الشكل`, `الجدول`, or `المعادلة`) when the reference target is known and the prose immediately before the token has not already named that type.
273
-
274
- V2 exports Arabic TeX by default for equations saved from the embedded editor. Imported raw-only math is preserved as raw source and marked non-editable until a structured equation object is attached.
275
-
276
- ### Headless document commands
277
-
278
- Canonical `Document2Json` exports include stable block IDs, list-item IDs, and an `inline_ids` sidecar for every text-bearing field. Table cells use a parallel `cell_inline_ids` matrix. Each sidecar contains a stable `field_id` plus text/math/citation/reference token IDs and their JavaScript string offsets. Legacy input may omit all identities; its next import/export normalization adds them lazily.
279
-
280
- Blocks may also carry creation provenance as `metadata: { source: 'agent' | 'user' }`. The editor and preview expose it as `data-butex-block-source` and intentionally ship no provenance styling.
281
-
282
- Use the pure command and outline helpers for server-side session transforms:
283
-
284
- ```ts
285
- import {
286
- applyDocument2Command,
287
- document2Outline,
288
50
  fromDocumentJson2,
289
51
  toDocumentJson2,
290
- } from '@drghaliasri/butex/document2';
52
+ validateDocument,
53
+ } from '@drghaliasri/butex/document';
291
54
 
292
- const canonical = toDocumentJson2(fromDocumentJson2(legacyDocument));
293
- const outline = document2Outline(canonical);
294
- const updated = applyDocument2Command(canonical, {
295
- op: 'insert_text_block',
296
- kind: 'paragraph',
297
- text: 'New session text',
298
- anchor: { end: true },
299
- });
55
+ const document = createEmptyDocument();
56
+ const validation = validateDocument(document);
57
+ const saved = toDocumentJson2(document);
58
+ const restored = fromDocumentJson2(saved);
300
59
  ```
301
60
 
302
- Block insertions accept `{ end: true }`, `{ before_block_id }`, or `{ after_block_id }`; missing targets fail explicitly. The command union also includes stable-ID inline token operations, list/item operations, and table cell/row/column operations. List and table targets are found recursively, while row and column coordinates are zero-based. Column shape changes require the complete resulting LaTeX `columns` specification.
303
-
304
- Article authoring commands can move top-level blocks, patch `meta`, manage the ordered reference catalog by normalized key, insert the derived bibliography block, revise figure/table captions and labels, and update an existing figure's host asset association or include value. Reference anchors use `{ before_reference_key }`, `{ after_reference_key }`, or `{ end: true }`. Asset upload/storage and session revisions remain host-owned; see [`docs/fastapi-document2-worker-contract.md`](docs/fastapi-document2-worker-contract.md) for the complete command and error contract.
305
-
306
- Whole-field replacement rejects formatted text, citations, references, and math so an agent cannot silently discard structured content. Inline math insertion/replacement requires one complete delimited `source` plus a matching structured `MathObject`; BuTeX does not parse raw LaTeX into an equation AST.
61
+ Use `ButexDocumentEditor` from `@drghaliasri/butex/react-document` for the interactive editor; use `ButexDocumentPreview` from `@drghaliasri/butex/react-document-preview` to show read-only snapshots.
307
62
 
308
- ### Document worker CLI
63
+ **Host responsibility:** authentication, article permissions, immutable revisions, image uploads/storage, compilation and publishing. BuTeX supplies pure Document transformations and editing UI, never an article database or MCP authorization bypass. See [Document](docs/architecture/document.md), [React integration](docs/architecture/react-editor.md), and [the worker](docs/architecture/worker.md).
309
64
 
310
- Node 20+ can run the same transforms through the isolated `butex-document2` executable. One-shot mode reads one request from stdin and writes one response to stdout:
65
+ ## Development and demos
311
66
 
312
67
  ```bash
313
- printf '%s' '{"action":"normalize","document":{"node_type":"DocumentObject","blocks":[]}}' | butex-document2
314
- ```
315
-
316
- Railway HTTP mode is stateless and requires a service token:
317
-
318
- ```bash
319
- BUTEX_WORKER_TOKEN=replace-me PORT=3000 \
320
- butex-document2 --serve --host 0.0.0.0
321
- ```
322
-
323
- It exposes `GET /health` plus authenticated `POST /v1/document2/normalize`, `/v1/document2/outline`, and `/v1/document2/commands`. The worker accepts document JSON and returns transformed JSON only. FastAPI remains responsible for user authentication, article/session lookup, revisions, idempotency, S3 persistence, and MCP policy; browsers and agents must never call the worker directly.
324
-
325
- ### Document JSON contract (`value` + `math_objects`)
326
-
327
- Both document layers import the same shape. A text field holds `value` (the full string, **with math delimiters kept in place**) and an optional parallel `math_objects` array that supplies the structured equation AST for each math span found in that string.
328
-
329
- Rules:
330
-
331
- - **Detect, then align.** The importer scans `value` for delimiters (`$…$`, `\(…\)`, `\[…\]`, `$$…$$`, and math environments) and binds each detected span to `math_objects` **in reading order (left-to-right)**.
332
- - **Count and order must match.** Extra or missing entries produce a diagnostic; the browser never silently remaps. `math_mode`/`closing` on each `MathObject` must match the delimiter in `value`.
333
- - **Per field, not per document.** Each paragraph, heading, and list `item` carries its own `math_objects`.
334
- - **Tables are the exception:** one flat `math_objects` array lives on the `\begin{tabular}` block and is consumed **row-major** across all cells (each cell takes as many entries as it has spans).
335
- - **Missing `math_objects`** → the span renders as a non-editable raw math chip from its delimited source.
336
- - **Mixed raw and structured math** uses `null` placeholders so every detected span still has one positional entry, for example `math_objects: [null, structuredMathObject]`. A labeled raw display span uses a `RawMathObject` positional metadata entry so its label survives without pretending the equation has an editable AST.
337
- - The browser **does not** parse equation LaTeX bodies into `ChainClass`; structured chains come from `math_objects` (import) or the equation editor (GUI).
338
-
339
- Paragraph with one inline span:
340
-
341
- ```json
342
- {
343
- "command": "\\paragraph",
344
- "value": "لدينا $x^2$ ثابت.",
345
- "math_objects": [
346
- { "node_type": "MathObject", "math_mode": "$",
347
- "lines": [{ "node_type": "ChainClass", "chain": [] }], "closing": "$" }
348
- ]
349
- }
350
- ```
351
-
352
- List item with a display span (`math_mode`/`closing` match the delimiter in `value`):
353
-
354
- ```json
355
- {
356
- "value": "الحل \\[a+b\\]",
357
- "math_objects": [
358
- { "node_type": "MathObject", "math_mode": "\\[",
359
- "lines": [{ "node_type": "ChainClass", "chain": [] }], "closing": "\\]" }
360
- ]
361
- }
68
+ npm ci
69
+ npm run build
70
+ npm run typecheck
71
+ npm run lint
72
+ npm test
362
73
  ```
363
74
 
364
- Table: one flat array, consumed row-major (here `$x$`, then `$y$`):
365
-
366
- ```json
367
- {
368
- "command": "\\begin{tabular}",
369
- "columns": "cc",
370
- "rows": [["الرمز $x$", "القيمة"], ["الرمز $y$", "القيمة"]],
371
- "math_objects": [
372
- { "node_type": "MathObject", "math_mode": "$",
373
- "lines": [{ "node_type": "ChainClass", "chain": [] }], "closing": "$" },
374
- { "node_type": "MathObject", "math_mode": "$",
375
- "lines": [{ "node_type": "ChainClass", "chain": [] }], "closing": "$" }
376
- ]
377
- }
378
- ```
379
-
380
- ### Document React widget v2 (`butex/react-document2`)
381
-
382
- Use this entry for the new document editor integration. It opens embedded `<ButexEditor />` sessions in Arabic/RTL mode by default and renders document preview math islands with MathJax **SVG** by default (`mathOutput` defaults to `'svg'`; pass `mathOutput="chtml"` only if the host loads `tex-chtml.js`).
383
-
384
- ```tsx
385
- 'use client';
386
-
387
- import { ButexDocumentEditor2 } from 'butex/react-document2';
388
-
389
- export default function Page() {
390
- return (
391
- <ButexDocumentEditor2
392
- debug
393
- uiLocale="en"
394
- documentDirection="ltr"
395
- equationSide="english"
396
- editableEquations
397
- onLatexChange={(latex) => console.log(latex)}
398
- />
399
- );
400
- }
401
- ```
402
-
403
- #### Persisting Document Editor v2 state
404
-
405
- `Document2Node` is the live editor AST. It contains class-backed equation nodes and must not cross an API, database, local-storage, worker, or `JSON.stringify` boundary. Persist the canonical `Document2Json` wire format instead. The backend may store and return that JSON unchanged.
406
-
407
- Use `onDocumentJsonChange` for a persistence-ready snapshot:
408
-
409
- ```tsx
410
- 'use client';
411
-
412
- import { useRef } from 'react';
413
- import { ButexDocumentEditor2 } from '@drghaliasri/butex/react-document2';
414
- import type { Document2Json } from '@drghaliasri/butex/document2';
415
-
416
- export function ArticleEditor({ loadedDocument }: { loadedDocument: Document2Json }) {
417
- const latestDocument = useRef<Document2Json>(loadedDocument);
418
-
419
- async function saveArticle() {
420
- await fetch('/api/article', {
421
- method: 'PUT',
422
- headers: { 'content-type': 'application/json' },
423
- body: JSON.stringify({ document: latestDocument.current }),
424
- });
425
- }
426
-
427
- return (
428
- <>
429
- <ButexDocumentEditor2
430
- initialDocument={loadedDocument}
431
- editableEquations
432
- onDocumentJsonChange={(json) => {
433
- latestDocument.current = json;
434
- }}
435
- />
436
- <button type="button" onClick={saveArticle}>Save</button>
437
- </>
438
- );
439
- }
440
- ```
441
-
442
- `onDocumentChange` remains available for hosts that need the live AST. Convert it before persistence with `toDocumentJson2`:
443
-
444
- ```ts
445
- import { toDocumentJson2 } from '@drghaliasri/butex/document2';
446
-
447
- onDocumentChange={(node) => {
448
- latestDocument.current = toDocumentJson2(node);
449
- }}
450
- ```
451
-
452
- Do not call `JSON.stringify(documentNode)` directly. JSON serialization removes `CharNode`, `CommandNode`, and other equation prototypes: the saved TeX source can still render in preview, but the structured equation cannot reopen in the editor. Also do not feed every change callback back into `initialDocument`; that prop is for initial or externally loaded data, and changing it resets the editor state and undo history. Keep the current save snapshot in a ref or separate state that is not passed back as `initialDocument`. Change callbacks run during editing, so debounce network autosaves or save explicitly.
453
-
454
- ##### Host-driven figure insert
455
-
456
- After an external upload (for example S3), insert a figure on the **live** editor without remounting or rewriting `initialDocument`:
457
-
458
- ```tsx
459
- 'use client';
460
-
461
- import { useRef } from 'react';
462
- import {
463
- ButexDocumentEditor2,
464
- type ImageAssetRef,
465
- type ButexDocumentEditor2Ref,
466
- } from '@drghaliasri/butex/react-document2';
467
-
468
- export function ArticleEditorWithUpload() {
469
- const editorRef = useRef<ButexDocumentEditor2Ref>(null);
470
-
471
- async function onFileUploaded(uuid: string) {
472
- // Sets asset_id and \\includegraphics{assets/<uuid>.jpg} after the focused block.
473
- // Do not call addDocument2ImageBlock outside the component or remount with key++.
474
- editorRef.current?.insertImageBlock({ assetId: `assets/${uuid}.jpg` } satisfies ImageAssetRef);
475
- }
476
-
477
- return (
478
- <ButexDocumentEditor2
479
- ref={editorRef}
480
- resolveImageUrl={({ assetId, value }) =>
481
- assetId ? `https://cdn.example/${assetId}` : value
482
- }
483
- onRequestImagePick={async ({ current }) => {
484
- /* open host asset picker; return { assetId, value?, label?, thumbUrl? } or null */
485
- return current;
486
- }}
487
- onDocumentJsonChange={(json) => {
488
- /* persist json */
489
- }}
490
- />
491
- );
492
- }
493
- ```
494
-
495
- `insertImageBlock` matches the toolbar figure button (focus-aware insert + undo snapshot). Pass `{ assetId, value?, label?, thumbUrl? }` to set both live `assetId` and wire `asset_id`; passing a non-empty string remains supported and treats that string as both `value` and `asset_id`. New figures are centered by default, and each image block exposes a **Center figure** checkbox backed by the existing JSON `centered` field and LaTeX `\centering` output. Use `updateImageBlockAsset(blockId, ref)` to set a host asset on an existing image block, `updateImageBlockValue(blockId, value)` to change only the path value while preserving any existing asset identity, and `getDocumentJson()` to read the canonical wire JSON without host-side AST mutation. BuTeX never uploads image bytes; hosts provide `resolveImageUrl`, optionally `onRequestImagePick`, `listImageAssets`, or `renderImageBlockEditor` for picker/inventory UI.
496
-
497
- Host apps still register BuTeX with MathJax before preview rendering. `uiLocale` selects Arabic (`"ar"`, the default) or English (`"en"`) document-editor chrome and is passed to the embedded equation editor. `documentDirection` independently controls prose inputs and preview flow without creating a second document tree. `equationSide` independently controls whether structured equations open, render, and save from the `"english"` or `"arabic"` side; the embedded drawer hides side-switching controls so editing remains locked to that host-selected side. Set `editableEquations={false}` to show math islands without equation insertion, deletion, or editor access. Set `previewOnly={true}` to render only the read-only document preview with no toolbar, editor panel, or equation drawer. Optional `\includegraphics` `asset_id` is preserved on import; pass `resolveImageUrl={({ assetId, value }) => …})` so preview can load S3/CDN/local assets while plain `value` URLs keep working without a resolver. Document JSON may include root `meta` (`title`, `authors`, structured Hijri `date` `{ day, month, year }` with Arabic month names such as `"محرم"`, `abstract`) plus a `references` catalog (`key`, `authors`, `title`, `year`, `url`, `venue`) and `\cite{key1,key2}` spans in text values. Pass `documentMeta` to seed missing meta fields from the host; JSON keys win when present. The editor always centers a fixed basmala line before the title block and a closing ḥamdala after the body (preview + LaTeX). Hijri date uses day/month/year dropdowns (no calendar conversion; default year 1448). The editor shows numeric cite chips and a bibliography block. RTL preview/chips render reversed labels such as `[٣،٢،١]` (Arabic comma); LTR stays `[1, 2, 3]`. Pass `digitForm` (`western` / `arabicIndic` / `persianIndic`, defaulting from `documentDirection`) or use the toolbar digit control. LaTeX export keeps logical `\cite{…}` key order for XeLaTeX; digit shaping and bidi display in PDF belong in the host preamble (`bidi`/polyglossia + font `Mapping`, see `references/commands.py`). Range compression (`[3–7]`) is not implemented yet. Raw-only equations keep their original source because the browser does not parse raw LaTeX into equation ASTs. Document editor v2 defaults to **`tex-svg.js`**; use `tex-chtml.js` only if you pass `mathOutput="chtml"`.
498
-
499
- ### Styling/theming contract
500
-
501
- - Core editor classes (`.surface`, `.chain`, `.slot`, `.node`, `.scripts`, `.delim*`, etc.) are shipped from `src/editor/styles.ts`.
502
- - Theme with **one namespace**, `--butex-*`, on `.butex-widget` (or an ancestor of the editor surface). Defaults are set on `ButexEditor`’s root; hosts override accents, borders, **`--butex-surface-bg` / `--butex-surface-fg`**, **`--butex-preview-bg` / `--butex-preview-fg`**, focus/slot/selection, scripts, optional **`--butex-dev-*`** / **`--butex-dev-inset-*`** when using `debug`, etc., without redefining structure classes.
503
- - Document editor theming is scoped under `.butex-document-widget`. Override `--butex-document-*` variables on that root or an ancestor, especially `--butex-document-bg`, `--butex-document-fg`, `--butex-document-panel`, `--butex-document-border`, `--butex-document-accent`, `--butex-document-preview-bg`, `--butex-document-drawer-bg`, `--butex-document-input-bg`, `--butex-document-table-border`, `--butex-document-math-bg`, and `--butex-document-dev-bg`.
504
- - Document editor v2 theming is scoped under `.butex-document2-widget`. Override `--butex-document2-*` variables on that root or an ancestor; defaults inherit from the existing `--butex-*` variables where practical, including accent, panel, border, preview, focus, danger/error, and debug colors. The embedded equation editor opens as a centered modal (backdrop + panel); its BuTeX chrome reads the same `--butex-document2-*` tokens via a scoped bridge, so hosts normally theme once on `.butex-document2-widget` without a second equation theme. The built-in editor uses a **sticky compact icon toolbar** (Arabic `نص` formatting icons, heading glyphs, inline `$…$` vs display `\[…\]` math buttons with tooltips, a labeled references menu, and a table size popover), **focus-aware block insertion** after the active block, **↑/↓ block reorder**, **math delete** (chip × and drawer button), **document undo/redo** (toolbar + Ctrl/⌘Z, Ctrl/⌘Shift+Z, Ctrl+Y) via AST snapshots, and theme-tinted block cards. Preview tables keep black cell borders and scroll inside their preview region when their columns cannot shrink safely; raw `\raw` blocks stay out of preview until dedicated rendering exists.
505
-
506
- Both React editors register shrinkable inline-size containers for local overflow containment, but interaction mode follows the **layout viewport**, not the editor container. At a viewport width of 900px or narrower, Document Editor v2 automatically presents one principal panel at a time with an accessible Edit/Preview control; at 768px or narrower, the equation editor uses its compact toolbar and categorized sheets. This keeps a narrow editor inside a wide desktop page on the refined desktop workflow. Opening a software keyboard does not change modes because `visualViewport` is used only to reposition the equation modal, not to select a toolbar. At 430px or narrower, phone spacing, safe areas, and local scrolling apply. `previewOnly` continues to render Preview alone without either toolbar.
507
-
508
- Both components accept `responsiveMode="auto" | "desktop" | "compact"` (`"auto"` is the default). Hosts normally use one component tree and leave the mode automatic; force a mode only for an intentional desktop or touch-oriented shell:
509
-
510
- ```tsx
511
- <ButexEditor responsiveMode="desktop" />
512
- <ButexDocumentEditor2 responsiveMode="compact" />
513
- ```
514
-
515
- `desktop` and `compact` select the toolbar/panel workflow. Physical phone modal sizing remains viewport-based, so forcing compact mode in a wide kiosk does not turn the equation drawer into an unnecessarily wide full-screen overlay.
516
-
517
- Edit/Preview changes are announced through a localized polite status region. Closing an embedded equation restores the originating math chip or text/block position; saving focuses the updated or newly inserted equation location, and deletion focuses adjacent editable text when possible. Nested equation command sheets remain above the drawer in the focus stack, so Escape closes only the top surface.
518
-
519
- The automatic 900px and 768px breakpoints remain package defaults; `responsiveMode` is the supported override when a host deliberately needs another workflow. BuTeX does not display document-level saved/dirty state: persistence remains owned by the host through `onDocumentJsonChange`, `onDocumentChange`, or the imperative JSON getter. Wide matrices and other unbreakable equations scroll inside the equation surface, preview, or document math island; caret movement reveals the active position without intentionally scrolling the host page.
520
-
521
- #### Keeping the Document Editor v2 toolbar sticky
522
-
523
- `<ButexDocumentEditor2 />` injects `style#butex-document2-widget-styles`; its main toolbar ships with `position: sticky`, `top: var(--butex-document2-sticky-top)`, and a stacking layer. If a strict CSP blocks injected inline styles, embed `DOCUMENT2_WIDGET_CSS` through the host's approved global stylesheet or nonced style path, after Tailwind Preflight or other resets.
524
-
525
- Do not override `.butex-document2-widget__toolbar` with `position: static` or `position: fixed`. Avoid `overflow: auto`, `scroll`, or `hidden` on editor ancestors unless that ancestor is intentionally the constrained vertical scrolling container; sticky positioning follows the nearest such ancestor. Avoid `transform`, `filter`, or `contain` values that turn an ancestor into a containing block for the fixed equation overlay. `overflow-x: clip` by itself does not require an override. For a fixed application header, set the supported sticky-offset variable on the editor root:
526
-
527
- ```css
528
- .article-editor.butex-document2-widget {
529
- --butex-document2-sticky-top: var(--app-header-height, 0px);
530
- }
531
- ```
532
-
533
- The default stacking order is toolbar (`--butex-document2-z-toolbar: 20`), toolbar popovers (`--butex-document2-z-popover: 30`), document overlays (`--butex-document2-z-overlay: 40`), then the equation modal (`--butex-document2-z-equation: 50`). Override those variables on the editor root when coordinating with a host stacking system. Safe-area defaults come from `env(safe-area-inset-*)`; hosts may set `--butex-safe-area-top`, `--butex-safe-area-right`, `--butex-safe-area-bottom`, and `--butex-safe-area-left` on the editor root when they need explicit values.
534
-
535
- When diagnosing host CSS, verify that `#butex-document2-widget-styles` exists and that `getComputedStyle(toolbar).position` is `sticky` before adding overrides.
536
-
537
- The Phase 4 viewport and accessibility hardening adds no prop, entrypoint, AST, or JSON migration. The repository's recommended mobile and keyboard matrix, evidence status, and release limits are recorded in [`docs/responsive-mobile-validation.md`](docs/responsive-mobile-validation.md).
538
-
539
- ### Migrating to 7.0.0
540
-
541
- Version 7 makes the responsive workflows above the package defaults: Document2 switches to its single-panel workflow at a 900px viewport, and the equation editor switches to its compact command hierarchy at a 768px viewport. Existing call sites remain valid; the additive `responsiveMode` prop is available when a host must force either workflow. Equation/document ASTs, JSON formats, runtime methods, and package entrypoints are unchanged. Upgrades from 6.1.1 also include the validated Document2 public entrypoint and LaTeX/export fixes released in 6.1.2–6.1.5.
542
-
543
- ## Demo
544
-
545
- From repo root (after `npm run build`):
546
-
547
- ```bash
548
- npm run demo
549
- ```
550
-
551
- Open:
552
-
553
- - `http://localhost:4173/demo/` (MathJax + `\arabsqrt`)
554
- - `http://localhost:4173/demo/parser.html` (parser-only normalize preview)
555
- - **Equation editor (React):** run `cd demo/editor-app && npm install && npm run dev`, then open the URL Vite prints (see `demo/editor.html` for a short pointer). The equation editor demo loads MathJax SVG from `public/vendor/` and includes portrait/landscape frames, a constrained host scroller, visible-viewport diagnostics, UI-language and equation-side controls, wide equations, and matrices.
556
- - **Document editor (React):** run `cd demo/document-editor-app && npm install && npm run dev`, then open the URL Vite prints (see `demo/document.html` for a short pointer).
557
- - **Document editor v2 (React):** run `cd demo/document-editor-app2 && npm install && npm run dev`, then open the URL Vite prints. The v2 demo loads MathJax SVG, exercises metadata, editable wide math and matrices, lists, tables, figures, citations, and bibliography, and includes 320, 360, 375, 390, 430, 768, 900px, and desktop-width presets. Its realistic host-shell mode adds a sticky application header, constrained vertical scroller, safe-area overrides, surrounding content, locale/side controls, and visible-viewport diagnostics. Optional bottom dev panels (LaTeX + AST) appear only if you append `?debug=1` to the URL or pass the `debug` prop from your host app.
75
+ The equation-editor demo is `demo/editor-app/`; the modern document editor is `demo/document-editor-app/`; the first-generation demo was replaced by the promoted modern demo at the canonical path. Read [local development](docs/development/local.md) and [verification](docs/development/verification.md).
558
76
 
559
- ### Editor MVP notes (`demo/editor-app`)
77
+ ## Book authoring — proposed only
560
78
 
561
- - Editing is AST-first (not raw LaTeX text editing).
562
- - End-user UI is Arabic-first.
563
- - Supported structures in this MVP: chars, numbers, operators, delimiter pairs `()`, `[]`, `{}`, fractions (`\frac`), and sup/sub chains.
564
- - Caret: **Left/Right** walk every insertion gap in a fixed depth-first order (baseline and nested chains). **Up/Down** move between superscript and subscript where applicable (from the baseline, Up prefers superscript and Down prefers subscript when both exist). On the Arabic surface, arrow keys follow RTL progression.
565
- - Char/number typing: by default keystrokes **merge into the same leaf** along the caret gap (digits only extend `number`, letters only extend `char`). Use the **Split leaf typing** toolbar control to toggle **split mode** (one new leaf per keystroke). **Delete/Backspace** trim inside the merged string when split mode is off.
566
- - Structural edits are mirrored across Arabic/English trees; text edits apply to the active side.
567
- - **Undo/redo:** full-session snapshots (`createUndoRedoStacks`, `pushUndoRedoSnapshot`, `restoreUndo`, `restoreRedo`). The demo exposes toolbar buttons plus **Ctrl+Z** / **⌘Z** for undo and **Ctrl+Shift+Z** / **⌘⇧Z** / **Ctrl+Y** for redo while the editing surface is focused. Caret moves and language switching are not recorded so undo targets content edits only. History caps at ~100 steps by default (`DEFAULT_UNDO_HISTORY_MAX_DEPTH`).
568
- - **Selection + copy/cut/paste:** range selection lives at the slot level inside a single chain (no cross-chain selection in the MVP). Whole nodes are the copy unit, so superscripts/subscripts/inner subtrees always travel with their owner.
569
- - **Keyboard:** **Shift+ArrowLeft/ArrowRight** extend selection (RTL-aware), **Ctrl/⌘+C/X/V** copy/cut/paste, **Backspace/Delete** and typing **replace** an active selection.
570
- - **Mouse:** click-drag from one slot to another inside the same chain. Cross-chain mouse moves are ignored.
571
- - **Clipboard format:** `application/x-butex-fragment+json` with both EN and AR mirrored nodes (`EditorFragment` v1) plus a **plain-text LaTeX fallback** for cross-app pasting. External plain text re-enters through the typing path so split/merge mode applies.
572
- - **Future node types:** the single helper `nodeChildChains(node)` enumerates a node's nested chains. Adding command, env, or math-object kinds (see `[references/nodes.py](references/nodes.py)`) only requires extending this helper; selection, copy, paste, and id-remap stay unchanged.
573
- - Debug panels are dev-only (`debug` prop on `<ButexEditor />`, or `?debug=1` in the Vite demo URL).
574
- - Includes LaTeX dump, passive chain preview, and copyable command/render log.
79
+ The [BuTeX book design](docs/proposals/book-editor.md) and [Al-Bayan integration plan](https://github.com/Pontmousse/albayan/blob/develop/docs/proposals/book-authoring.md) describe future multi-chapter editing, scoped references and whole-book export. Book/editor/worker APIs in those plans **do not ship today**.
575
80
 
576
- ### Editor theming (CSS variables)
81
+ ## Documentation
577
82
 
578
- Override these on `:root` (or a host container) to customize colors:
83
+ - [Architecture](docs/architecture/README.md) — implemented package and host contracts
84
+ - [Development](docs/development/README.md) — building, browser testing and releases
85
+ - [Proposals](docs/proposals/README.md) — book authoring and the Document-to-Document migration
86
+ - [Archive](docs/archive/README.md) — historical design records
579
87
 
580
- - `--butex-bg`
581
- - `--butex-fg`
582
- - `--butex-muted`
583
- - `--butex-accent`
584
- - `--butex-border`
585
- - `--butex-panel`
586
- - `--butex-caret`
587
- - `--butex-selected`
588
- - `--butex-error`
589
- - `--butex-error-bg`
590
- - `--butex-accent-hover` (optional, demo toolbar)
591
- - `--butex-shadow-sm` / `--butex-shadow-md` (optional, panels)
592
- - `--butex-dev-bg` / `--butex-dev-border` / `--butex-dev-badge` / `--butex-dev-muted` (optional, developer-only strips when `debug` is on)
88
+ The npm tarball includes `dist/` and this README; `docs/` live in the [GitLab repository](https://gitlab.com/drghaliasri/butex).
593
89
 
594
90
  ## License
595
91
 
596
- ISC (BuTeX package). MathJax is Apache-2.0 — see upstream.
92
+ See the license field in [package.json](package.json).