diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbf2798..68aa56b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,3 +64,27 @@ jobs: - name: Build the app with its page embedded, start it and run the smoke test if: runner.os == 'Linux' run: xvfb-run -a npm run smoke + - name: Kill the app while it writes, and check nothing was lost + if: runner.os != 'Linux' + run: node scripts/crash-test.mjs + - name: Kill the app while it writes, and check nothing was lost + if: runner.os == 'Linux' + run: xvfb-run -a node scripts/crash-test.mjs + - name: Close the window right after typing + if: runner.os != 'Linux' + run: node scripts/close-test.mjs + - name: Close the window right after typing + if: runner.os == 'Linux' + run: xvfb-run -a node scripts/close-test.mjs + - name: Open a second copy of the app + if: runner.os != 'Linux' + run: node scripts/instance-test.mjs + - name: Open a second copy of the app + if: runner.os == 'Linux' + run: dbus-run-session -- xvfb-run -a node scripts/instance-test.mjs + - name: Measure typing with 150,000 words + if: runner.os != 'Linux' + run: node scripts/perf-test.mjs + - name: Measure typing with 150,000 words + if: runner.os == 'Linux' + run: xvfb-run -a node scripts/perf-test.mjs diff --git a/CLAUDE.md b/CLAUDE.md index f5edecd..3ef21a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,11 +57,15 @@ Desde la raíz, con Node 24 y Rust estable: | `npm run check:rust` | `rustfmt` y `clippy` | | `npm test` | Todas las pruebas. Por separado: `npm run test:ts` y `npm run test:rust` | | `npm run smoke` | Construye la app real, la arranca con una base temporal y comprueba que todas las capas encajan | +| `npm run crash-test` | Mata la app real mientras escribe, varias veces, y comprueba que no se pierde nada de lo confirmado (regla 2) | +| `npm run close-test` | Cierra la ventana justo después de escribir y comprueba que se guardó todo | +| `npm run perf-test` | Mide el tecleo en la app real con 150.000 palabras | +| `npm run instance-test` | Comprueba que una segunda copia de la app se cierra sola | | `npm run licenses` | Revisa las licencias de todas las dependencias (regla 8) | | `npm run fixtures` | Valida el material de `fixtures/` | La evaluación del análisis aún no existe: llega en M3. Hasta entonces, `npm run fixtures` solo comprueba que el material es coherente. -CI en `.github/workflows/ci.yml`: compila, prueba y arranca la app en Windows, macOS y Linux. +CI en `.github/workflows/ci.yml`: compila, prueba y arranca la app en Windows, macOS y Linux, y ejecuta las pruebas anteriores en cada uno. Un cambio en guardado, Yjs o sync debe pasar `npm run crash-test`. Al añadir una migración, crea una nueva en `packages/core/src/storage/migrations.ts`. Nunca edites una ya publicada. diff --git a/README.md b/README.md index fb86c0e..b69976a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ App de escritura de novelas, de escritorio y sin conexión. **Tú escribes todo.** La IA construye las fichas de tu historia, vigila la coherencia, te propone pequeños pasos y documenta lo que necesites. -Estado: en desarrollo, todavía sin editor. Nombre provisional. +Estado: en desarrollo. Ya se puede escribir, con guardado continuo, historial y exportación, pero aún sin IA. Nombre provisional. ## Empezar diff --git a/ROADMAP.md b/ROADMAP.md index 87c6275..bf0a51e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -29,6 +29,8 @@ TipTap con Yjs por escena, capítulos y escenas, guardado continuo, historial po **Salida:** ninguna pérdida de texto ante cierre forzado. Tecleo fluido con 150.000 palabras. +**Cerrado.** El CI mata la app real mientras escribe y mide el tecleo en Windows, macOS y Linux. Medidas y límites en `docs/adr/0010-editor-y-guardado-de-la-prosa.md`. + ## M3 · Canal de análisis y evaluación Extracción, resolución de identidades, comparación, cola sin conexión y arnés de evaluación con `fixtures/`. diff --git a/SPEC.md b/SPEC.md index 1b79139..a6e0f51 100644 --- a/SPEC.md +++ b/SPEC.md @@ -135,9 +135,10 @@ SQLite local para estructura. Yjs para la prosa. Esquema orientativo: | Tabla | Campos clave | |---|---| | `projects` | id, title, language, era | -| `chapters` | id, project_id, position, title, era_override | -| `scenes` | id, chapter_id, position, title, status, ydoc, content_hash, analyzed_hash | -| `scene_snapshots` | id, scene_id, created_at, ydoc, label | +| `chapters` | id, project_id, position, title, era_override, deleted_at | +| `scenes` | id, chapter_id, position, title, status, ydoc, ydoc_version, deleted_at, content_hash, analyzed_hash | +| `scene_updates` | id, scene_id, update_data | +| `scene_snapshots` | id, scene_id, created_at, ydoc, label, word_count | | `entities` | id, project_id, type, canonical_name, status, summary | | `entity_aliases` | entity_id, alias, source | | `mentions` | id, scene_id, entity_id, anchor | @@ -151,7 +152,8 @@ SQLite local para estructura. Yjs para la prosa. Esquema orientativo: | `ai_usage` | day, provider, requests, searches | Reglas: -- Una escena es un documento Yjs. Las posiciones de `anchor` son posiciones relativas de Yjs, para sobrevivir a las ediciones. +- Una escena es un documento Yjs: su base compactada (`ydoc`) más las actualizaciones de `scene_updates`, un registro de solo añadir. Ver `docs/adr/0010-editor-y-guardado-de-la-prosa.md`. +- Las posiciones de `anchor` son posiciones relativas de Yjs, para sobrevivir a las ediciones. - El reanálisis de una escena **sustituye** sus `mentions`, `facts` y `relations`. - `user_overrides` nunca se borra por un reanálisis y se aplica después de él. diff --git a/apps/desktop/index.html b/apps/desktop/index.html index f315c48..b43c7cb 100644 --- a/apps/desktop/index.html +++ b/apps/desktop/index.html @@ -4,12 +4,9 @@ Ink Writer - + -
-

Ink Writer

-

-
+
diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 782e1a5..894ebfa 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -11,11 +11,34 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@fontsource-variable/instrument-sans": "5.3.0", + "@fontsource-variable/literata": "5.3.0", "@ink-writer/core": "*", - "@tauri-apps/api": "2.12.4" + "@tauri-apps/api": "2.12.4", + "@tiptap/core": "3.33.0", + "@tiptap/extension-bold": "3.33.0", + "@tiptap/extension-collaboration": "3.33.0", + "@tiptap/extension-document": "3.33.0", + "@tiptap/extension-hard-break": "3.33.0", + "@tiptap/extension-italic": "3.33.0", + "@tiptap/extension-paragraph": "3.33.0", + "@tiptap/extension-text": "3.33.0", + "@tiptap/pm": "3.33.0", + "@tiptap/react": "3.33.0", + "@tiptap/y-tiptap": "3.2.0", + "react": "19.3.1", + "react-dom": "19.3.1", + "y-protocols": "1.0.7", + "yjs": "13.6.33" }, "devDependencies": { "@tauri-apps/cli": "2.12.4", + "@testing-library/dom": "10.4.2", + "@testing-library/react": "16.3.3", + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.2.1", + "fflate": "0.8.3", "vite": "8.3.6" } } diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index f9a5a53..2aa1eba 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -47,6 +47,137 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "atk" version = "0.18.2" @@ -142,6 +273,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "9.1.1" @@ -332,6 +476,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "cookie" version = "0.18.2" @@ -677,6 +830,33 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -704,6 +884,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -838,6 +1038,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.34" @@ -1193,6 +1406,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -1477,6 +1696,8 @@ dependencies = [ "serde_json", "tauri", "tauri-build", + "tauri-plugin-dialog", + "tauri-plugin-single-instance", "tempfile", ] @@ -2031,6 +2252,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2", + "libc", "objc2", "objc2-core-foundation", ] @@ -2115,6 +2337,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "pango" version = "0.18.3" @@ -2140,6 +2372,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2228,6 +2466,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2260,6 +2509,20 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2496,6 +2759,32 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rsqlite-vfs" version = "0.2.0" @@ -2825,6 +3114,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3207,6 +3506,80 @@ dependencies = [ "tauri-utils", ] +[[package]] +name = "tauri-plugin" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d58eb1d4984e535f47a642ffec09a2da6f5c18a12b5902d12126cb7626d628b" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.2.1+spec-1.1.0", + "url", +] + +[[package]] +name = "tauri-plugin-single-instance" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f" +dependencies = [ + "serde", + "serde_json", + "tauri", + "thiserror 2.0.21", + "tokio", + "tracing", + "windows-sys 0.61.2", + "zbus", +] + [[package]] name = "tauri-runtime" version = "2.12.2" @@ -3589,9 +3962,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -3641,6 +4026,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -4323,6 +4719,76 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.5", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -4388,3 +4854,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow 1.0.5", +] diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 342ab69..00eca9e 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -26,6 +26,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" base64 = "0.23" rusqlite = { version = "0.41", features = ["bundled", "limits"] } +tauri-plugin-single-instance = "2.5" +tauri-plugin-dialog = "2.8" [dev-dependencies] tempfile = "3" diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index c6ddb0b..275e851 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -1,7 +1,7 @@ { "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", - "description": "Only the app's own commands. No file, shell or HTTP plugin reaches the WebView.", + "description": "Only the app's own commands. No file, shell or HTTP plugin reaches the WebView. Closing the window is allowed so that the page can finish saving first.", "windows": ["main"], - "permissions": ["core:default"] + "permissions": ["core:default", "core:window:allow-destroy"] } diff --git a/apps/desktop/src-tauri/src/db.rs b/apps/desktop/src-tauri/src/db.rs index 36c7603..72d9b81 100644 --- a/apps/desktop/src-tauri/src/db.rs +++ b/apps/desktop/src-tauri/src/db.rs @@ -14,7 +14,7 @@ use base64::engine::general_purpose::STANDARD; use rusqlite::config::DbConfig; use rusqlite::limits::Limit; use rusqlite::types::{Value as Sql, ValueRef}; -use rusqlite::{Connection, TransactionBehavior, params_from_iter}; +use rusqlite::{Connection, ErrorCode, TransactionBehavior, params_from_iter}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Number, Value as Json, json}; @@ -40,6 +40,9 @@ pub struct Database { conn: Mutex, } +/// What `Database::open` reports when another process holds the database. +pub const ALREADY_OPEN: &str = "already_open"; + fn check_safe(value: i64) -> Result { if value.abs() > MAX_SAFE_INTEGER { return Err(format!( @@ -120,14 +123,21 @@ impl Database { std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; } let conn = Connection::open(path).map_err(text_error)?; - Self::configure(&conn).map_err(text_error)?; + Self::configure(&conn).map_err(|error| match error.sqlite_error_code() { + Some(ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked) => ALREADY_OPEN.to_string(), + _ => error.to_string(), + })?; Ok(Self { conn: Mutex::new(conn), }) } fn configure(conn: &Connection) -> rusqlite::Result<()> { - conn.busy_timeout(Duration::from_secs(5))?; + conn.busy_timeout(Duration::from_secs(1))?; + // Only this process may touch the database while it runs, so that two copies of the app + // can never edit the same scene. The system releases the lock when a process dies, however + // it dies. Must come before WAL, so that WAL needs no shared memory between processes. + conn.pragma_update(None, "locking_mode", "EXCLUSIVE")?; conn.pragma_update(None, "journal_mode", "WAL")?; // FULL syncs the log on every commit, so that a commit survives a power cut too. The cost // is small next to losing text, and M2 measures it with real typing. @@ -136,6 +146,8 @@ impl Database { conn.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)?; conn.set_db_config(DbConfig::SQLITE_DBCONFIG_TRUSTED_SCHEMA, false)?; conn.set_limit(Limit::SQLITE_LIMIT_ATTACHED, 0)?; + // The lock is taken on first use. Doing it here makes a second copy fail right away. + conn.execute_batch("BEGIN IMMEDIATE; COMMIT;")?; Ok(()) } @@ -423,6 +435,36 @@ mod tests { assert_eq!(count(&db), 0, "the table is still there"); } + #[test] + fn a_second_copy_is_refused_while_the_first_is_open() { + let dir = tempdir().unwrap(); + let path = dir.path().join("test.db"); + let first = Database::open(&path).unwrap(); + table(&first); + + assert_eq!(Database::open(&path).err().as_deref(), Some(ALREADY_OPEN)); + + // The refusal didn't disturb the first copy. + first.execute("INSERT INTO t VALUES (1)", &[]).unwrap(); + assert_eq!(count(&first), 1); + } + + #[test] + fn opens_again_once_the_first_copy_closes() { + let dir = tempdir().unwrap(); + let path = dir.path().join("test.db"); + drop(Database::open(&path).unwrap()); + assert!(Database::open(&path).is_ok()); + } + + #[test] + fn reports_other_problems_as_they_are() { + let dir = tempdir().unwrap(); + // A folder where the database file should be. + let error = Database::open(dir.path()).err().unwrap(); + assert_ne!(error, ALREADY_OPEN); + } + #[test] fn data_survives_reopening() { let dir = tempdir().unwrap(); diff --git a/apps/desktop/src-tauri/src/files.rs b/apps/desktop/src-tauri/src/files.rs new file mode 100644 index 0000000..3303779 --- /dev/null +++ b/apps/desktop/src-tauri/src/files.rs @@ -0,0 +1,88 @@ +//! Writing files the author asked for, without ever leaving a partial one behind. + +use std::io::Write; +use std::path::Path; + +/// Writes to a temporary file beside the target, syncs it, then renames it over the target. If +/// anything fails or the process dies, the target is either the old file or the new one, whole. +pub fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + let dir = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let name = path + .file_name() + .ok_or_else(|| std::io::Error::other("the path has no file name"))? + .to_string_lossy(); + let temporary = dir.join(format!(".{name}.{}.tmp", std::process::id())); + let result = (|| { + let mut file = std::fs::File::create(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&temporary, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn writes_a_new_file() { + let dir = tempdir().unwrap(); + let path = dir.path().join("novela.docx"); + write_atomically(&path, b"datos").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"datos"); + } + + #[test] + fn replaces_an_existing_file_whole() { + let dir = tempdir().unwrap(); + let path = dir.path().join("novela.docx"); + std::fs::write(&path, b"un texto anterior mucho mas largo").unwrap(); + write_atomically(&path, b"nuevo").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"nuevo"); + } + + #[test] + fn leaves_no_temporary_file_behind() { + let dir = tempdir().unwrap(); + write_atomically(&dir.path().join("a.md"), b"x").unwrap(); + let names: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, ["a.md"]); + } + + #[test] + fn keeps_the_old_file_when_the_write_fails() { + let dir = tempdir().unwrap(); + // A directory in the way makes the final rename fail, after the data was written. + let blocked = dir.path().join("novela.docx"); + std::fs::create_dir(&blocked).unwrap(); + std::fs::write(blocked.join("dentro"), b"intacto").unwrap(); + + assert!(write_atomically(&blocked, b"nuevo").is_err()); + + assert_eq!(std::fs::read(blocked.join("dentro")).unwrap(), b"intacto"); + let names: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, ["novela.docx"], "no temporary file left"); + } + + #[test] + fn fails_clearly_when_the_folder_does_not_exist() { + let dir = tempdir().unwrap(); + let path = dir.path().join("no-existe").join("a.md"); + assert!(write_atomically(&path, b"x").is_err()); + } +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 2b5bcd0..ceffee8 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -1,3 +1,5 @@ //! Native logic of the shell, kept free of Tauri so it can be tested directly. pub mod db; +pub mod files; +pub mod test_mode; diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 70e1e1d..7d741cf 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -3,25 +3,27 @@ //! The shell stays thin: domain logic lives in the TypeScript core. These commands are the whole //! surface the WebView can reach, and none of them hands out a credential (rule 9). -use std::path::{Path, PathBuf}; -use std::time::Duration; +use std::path::PathBuf; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; use ink_writer::db::{Database, ExecResult, Statement}; +use ink_writer::files::write_atomically; +use ink_writer::test_mode::TestMode; use serde::Serialize; use serde_json::{Map, Value}; use tauri::{AppHandle, Manager, State}; +use tauri_plugin_dialog::DialogExt; const DB_FILE: &str = "ink-writer.db"; - -/// Starts the app on a throwaway database, runs the checks in the page, and exits with the result. -/// It's how CI proves that the app really starts on each operating system. -const SMOKE_FLAG: &str = "--smoke-test"; -const SMOKE_TIMEOUT: Duration = Duration::from_secs(120); +const SINGLE_INSTANCE_TEST: &str = "single-instance"; struct Shell { /// Kept as a `Result` so that the page can explain the problem instead of the app vanishing. db: Result, - smoke: bool, + test: Option, + /// In a test, where exports go. A test can't answer a dialog. + test_dir: Option, } impl Shell { @@ -30,14 +32,25 @@ impl Shell { } } +#[derive(Serialize)] +struct TestInfo { + mode: String, + arg: Option, +} + #[derive(Serialize)] struct AppInfo { - smoke: bool, + test: Option, } #[tauri::command] fn app_info(shell: State<'_, Shell>) -> AppInfo { - AppInfo { smoke: shell.smoke } + AppInfo { + test: shell.test.as_ref().map(|test| TestInfo { + mode: test.name.clone(), + arg: test.arg.clone(), + }), + } } // `async` runs them off the main thread: a slow disk must not freeze the window. @@ -67,60 +80,124 @@ fn db_transaction( shell.db()?.transaction(&statements) } +/// Saves an exported book where the author chooses. The dialog opens here rather than taking a path +/// from the page, so the page can't write anywhere by itself. Returns false if the author cancels. +#[tauri::command(async)] +fn export_file( + app: AppHandle, + shell: State<'_, Shell>, + suggested_name: String, + extension: String, + data_base64: String, +) -> Result { + let label = match extension.as_str() { + "docx" => "Word", + "md" => "Markdown", + _ => return Err(format!("can't export as {extension}")), + }; + let bytes = STANDARD + .decode(data_base64) + .map_err(|error| error.to_string())?; + let target: Option = match &shell.test_dir { + Some(dir) => Some(dir.join(format!("export.{extension}"))), + None => app + .dialog() + .file() + .set_file_name(format!("{suggested_name}.{extension}")) + .add_filter(label, &[extension.as_str()]) + .blocking_save_file() + .map(|path| path.into_path().map_err(|error| error.to_string())) + .transpose()?, + }; + match target { + Some(path) => write_atomically(&path, &bytes) + .map(|()| true) + .map_err(|error| error.to_string()), + None => Ok(false), + } +} + +/// One line to whoever started the test. Sent only after what it reports has really happened. #[tauri::command] -fn smoke_report( +fn test_log(shell: State<'_, Shell>, line: String) -> Result<(), String> { + if shell.test.is_none() { + return Err("only available in a test mode".into()); + } + println!("{line}"); + Ok(()) +} + +/// Closes the window the way the system's close button does, so that a test can go through what +/// happens then. +#[tauri::command] +fn test_close_window(window: tauri::Window, shell: State<'_, Shell>) -> Result<(), String> { + if shell.test.is_none() { + return Err("only available in a test mode".into()); + } + window.close().map_err(|error| error.to_string()) +} + +#[tauri::command] +fn test_finish( app: AppHandle, shell: State<'_, Shell>, ok: bool, detail: String, ) -> Result<(), String> { - if !shell.smoke { - return Err(format!("only available with {SMOKE_FLAG}")); - } + let Some(test) = shell.test.as_ref() else { + return Err("only available in a test mode".into()); + }; let verdict = if ok { "passed" } else { "FAILED" }; - println!("smoke test {verdict}: {detail}"); + println!("{} test {verdict}: {detail}", test.name); app.exit(if ok { 0 } else { 1 }); Ok(()) } -/// A fixed folder recreated on each run, so that it can never touch the user's data, and repeated -/// runs leave at most one behind. -fn smoke_db_path() -> PathBuf { - let dir = std::env::temp_dir().join("ink-writer-smoke"); - let _ = std::fs::remove_dir_all(&dir); - dir.join(DB_FILE) -} - -fn real_db_path(data_dir: &Path) -> PathBuf { - data_dir.join(DB_FILE) -} - fn main() { - let smoke = std::env::args().any(|arg| arg == SMOKE_FLAG); - if smoke { + let test = TestMode::from_args(std::env::args()); + if let Some(test) = &test { // A plain `cargo build` or `cargo test` leaves a binary that loads the page from the dev // server. With none running, the page never appears and the test would only time out. if tauri::is_dev() { - eprintln!("smoke test FAILED: this binary needs the dev server. Use: npm run smoke"); + eprintln!( + "{} test FAILED: this binary needs the dev server. Use the npm script.", + test.name + ); std::process::exit(3); } - std::thread::spawn(|| { - std::thread::sleep(SMOKE_TIMEOUT); - eprintln!("smoke test FAILED: the page didn't report within {SMOKE_TIMEOUT:?}"); + let (name, timeout) = (test.name.clone(), test.timeout); + std::thread::spawn(move || { + std::thread::sleep(timeout); + eprintln!("{name} test FAILED: the page didn't report within {timeout:?}"); std::process::exit(2); }); } - tauri::Builder::default() + let mut builder = tauri::Builder::default(); + // First, as the plugin asks. Not in other tests, which may run alongside copies on purpose. + if test + .as_ref() + .is_none_or(|test| test.name == SINGLE_INSTANCE_TEST) + { + builder = builder.plugin(tauri_plugin_single_instance::init(|app, _, _| { + if let Some(window) = app.get_webview_window("main") { + let _ = window.unminimize(); + let _ = window.set_focus(); + } + })); + } + + builder + .plugin(tauri_plugin_dialog::init()) .setup(move |app| { - let path = if smoke { - smoke_db_path() - } else { - real_db_path(&app.path().app_data_dir()?) + let dir = match &test { + Some(test) => test.data_dir(), + None => app.path().app_data_dir()?, }; app.manage(Shell { - db: Database::open(&path), - smoke, + db: Database::open(&dir.join(DB_FILE)), + test_dir: test.is_some().then(|| dir.clone()), + test, }); Ok(()) }) @@ -129,7 +206,10 @@ fn main() { db_query, db_execute, db_transaction, - smoke_report, + export_file, + test_log, + test_close_window, + test_finish, ]) .run(tauri::generate_context!()) .expect("can't start the application"); diff --git a/apps/desktop/src-tauri/src/test_mode.rs b/apps/desktop/src-tauri/src/test_mode.rs new file mode 100644 index 0000000..55021f4 --- /dev/null +++ b/apps/desktop/src-tauri/src/test_mode.rs @@ -0,0 +1,103 @@ +//! Test modes run the real app, with a database that isn't the user's, to check things only the +//! whole app can show: that it starts on each system, and that a forced close loses nothing. + +use std::path::PathBuf; +use std::time::Duration; + +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120); + +#[derive(Debug, PartialEq, Eq)] +pub struct TestMode { + /// Which check the page runs. + pub name: String, + /// Where the database goes. Without one, a fixed temporary folder that's emptied first. + pub dir: Option, + /// A value for the check. + pub arg: Option, + pub timeout: Duration, +} + +impl TestMode { + /// `None` unless the app was started with `--test-mode=`. + pub fn from_args(args: impl IntoIterator) -> Option { + let mut mode = None; + let mut dir = None; + let mut arg = None; + let mut timeout = DEFAULT_TIMEOUT; + for value in args { + if let Some(name) = value.strip_prefix("--test-mode=") { + mode = Some(name.to_string()); + } else if let Some(path) = value.strip_prefix("--test-dir=") { + dir = Some(PathBuf::from(path)); + } else if let Some(text) = value.strip_prefix("--test-arg=") { + arg = Some(text.to_string()); + } else if let Some(seconds) = value.strip_prefix("--test-timeout=") + && let Ok(seconds) = seconds.parse() + { + timeout = Duration::from_secs(seconds); + } + } + mode.map(|name| Self { + name, + dir, + arg, + timeout, + }) + } + + /// Where this run's database folder is. It can never be the user's own data folder. + pub fn data_dir(&self) -> PathBuf { + match &self.dir { + Some(dir) => dir.clone(), + None => { + let dir = std::env::temp_dir().join("ink-writer-test"); + let _ = std::fs::remove_dir_all(&dir); + dir + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Option { + TestMode::from_args(args.iter().map(|arg| arg.to_string())) + } + + #[test] + fn a_normal_start_has_no_test_mode() { + assert_eq!(parse(&["ink-writer"]), None); + // Other flags alone don't turn it on. + assert_eq!(parse(&["ink-writer", "--test-dir=/tmp/x"]), None); + } + + #[test] + fn reads_every_option() { + let mode = parse(&[ + "ink-writer", + "--test-mode=crash-writer", + "--test-dir=/tmp/x", + "--test-arg=42", + "--test-timeout=600", + ]) + .unwrap(); + assert_eq!(mode.name, "crash-writer"); + assert_eq!(mode.dir, Some(PathBuf::from("/tmp/x"))); + assert_eq!(mode.arg.as_deref(), Some("42")); + assert_eq!(mode.timeout, Duration::from_secs(600)); + } + + #[test] + fn has_a_default_timeout_even_when_given_nonsense() { + let mode = parse(&["--test-mode=smoke", "--test-timeout=soon"]).unwrap(); + assert_eq!(mode.timeout, DEFAULT_TIMEOUT); + } + + #[test] + fn without_a_folder_it_uses_a_temporary_one() { + let mode = parse(&["--test-mode=smoke"]).unwrap(); + assert!(mode.data_dir().starts_with(std::env::temp_dir())); + } +} diff --git a/apps/desktop/src-tauri/tests/forced_close.rs b/apps/desktop/src-tauri/tests/forced_close.rs index 7c45dd2..db45e9a 100644 --- a/apps/desktop/src-tauri/tests/forced_close.rs +++ b/apps/desktop/src-tauri/tests/forced_close.rs @@ -48,6 +48,7 @@ fn committed_writes_survive_a_forced_close() { run_child("child_commits_then_dies", &path); + // Opening at all shows that the child's exclusive lock died with it. assert_eq!(rows(&path), ["single", "batch-1", "batch-2"]); } diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx new file mode 100644 index 0000000..9b143d0 --- /dev/null +++ b/apps/desktop/src/App.tsx @@ -0,0 +1,74 @@ +import { openSqlStorage, type Project, type Storage } from "@ink-writer/core"; +import { useEffect, useMemo, useState } from "react"; +import { LanguageContext } from "./i18n"; +import { describeStartupError, MESSAGES, pickLocale } from "./messages"; +import { ProjectScreen } from "./project/ProjectScreen"; +import { ProjectsScreen } from "./projects/ProjectsScreen"; +import type { Shell } from "./shell"; + +type Boot = + | { readonly status: "opening" } + | { readonly status: "ready"; readonly storage: Storage } + | { readonly status: "failed"; readonly error: unknown }; + +export interface AppProps { + readonly shell: Shell; + readonly language?: string; +} + +export function App({ shell, language = navigator.language }: AppProps) { + const locale = pickLocale(language); + const value = useMemo(() => ({ locale, messages: MESSAGES[locale] }), [locale]); + const messages = value.messages; + const [boot, setBoot] = useState({ status: "opening" }); + const [project, setProject] = useState(null); + + useEffect(() => { + document.documentElement.lang = locale; + }, [locale]); + + useEffect(() => { + let active = true; + openSqlStorage(shell.driver).then( + ({ storage }) => { + if (active) setBoot({ status: "ready", storage }); + }, + (error: unknown) => { + if (active) setBoot({ status: "failed", error }); + }, + ); + return () => { + active = false; + }; + }, [shell]); + + return ( + + {boot.status === "opening" && ( +
+

{messages.loading}

+
+ )} + {boot.status === "failed" && ( +
+

Ink Writer

+

+ {describeStartupError(boot.error, messages)} +

+
+ )} + {boot.status === "ready" && + (project === null ? ( + + ) : ( + setProject(null)} + /> + ))} +
+ ); +} diff --git a/apps/desktop/src/editor/SceneEditor.tsx b/apps/desktop/src/editor/SceneEditor.tsx new file mode 100644 index 0000000..97852a4 --- /dev/null +++ b/apps/desktop/src/editor/SceneEditor.tsx @@ -0,0 +1,64 @@ +import type { SceneSession } from "@ink-writer/core"; +import type { Editor } from "@tiptap/core"; +import { EditorContent, useEditor } from "@tiptap/react"; +import { useEffect } from "react"; +import { proseExtensions } from "./extensions"; + +export interface SceneEditorProps { + readonly session: SceneSession; + readonly label: string; + readonly language: string; + /** False in the reading mode. */ + readonly editable?: boolean; + readonly autofocus?: boolean; + /** For whoever needs the editor itself: to restore a version, or to measure typing. */ + readonly onEditor?: (editor: Editor | null) => void; + /** Called on every change the author makes, without re-rendering anything. */ + readonly onInput?: () => void; +} + +/** + * The text itself. `shouldRerenderOnTransaction: false` keeps it out of React's rendering, so that + * typing costs the same however much of the app is on screen. The parent gives this a `key` per + * session: a scene never shares an editor with another one. + */ +export function SceneEditor({ + session, + label, + language, + editable = true, + autofocus = true, + onEditor, + onInput, +}: SceneEditorProps) { + const editor = useEditor({ + extensions: proseExtensions(session.doc), + autofocus: autofocus ? "end" : false, + editable, + shouldRerenderOnTransaction: false, + // It would add a