[K4] S1: Projekt-Dokument im Rust-Kern (document.rs), TS-Spiegel ueber Ops (core/document.ts), Store haelt es aktuell

This commit is contained in:
karim committed 2026-10-28 01:41:02 +01:00
1 parent 1c3f38e9ab
commit 8a120329ee
10 files changed
+546 -1

No files matched your search

+15 -1
View File
@@ -119,7 +119,21 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
(Text, Schraffur-Optionen, Zickzack/Motiv); die Verbraucher von `Primitive[]` (SVG/PDF/DXF, Auswahl, Overlay) lesen dann den Puffer.
Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben
(Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS.
- ○ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
- ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL
Ziel (Entscheid 28.10., Maintainer): nur die UI bleibt TS, alles andere Rust. Vorgehen in Stufen, jede verdrahtet und mit
Gleichheitstest gegen die TS-Fassung, die im selben Schritt verschwindet:
- ✅ **S1 Dokument im Kern** (28.10.): `document.rs` hält das Projekt als JSON-Baum, `core/document.ts` spiegelt jede
Änderung von `store.project` (setProject, Laden, Undo/Redo) als Ops (`diffToOps` → `doc_apply`); Selbstheilung durch Neuöffnen.
Test: 300 Zufallsänderungen, Kern-JSON == TS-Projekt. (Spiegel, TS ist noch Quelle der Änderungen.)
- ○ **S2 Ableitungen lesen das Dokument**: typisierte Sicht (serde) je Domäne; Plan/Schnitt/Ansicht, 3D, Kennzahlen, Export
rechnen mit `doc`-Handle statt mit flach gesammelten Arrays; TS-Sammler/-Adapter werden gelöscht ([K3d] hängt hier dran:
Plan-Puffer v2 mit Pick-IDs und vollem Primitive-Umfang).
- ○ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
(`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht.
- ○ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
STEP-Ex- und -Import) im Kern.
Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im
React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`).
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
## Was die Analyse übersieht (Ergänzungen zum Vergleich)
+62
View File
@@ -31,9 +31,28 @@ dependencies = [
"console_error_panic_hook",
"i_overlay",
"kernel2d",
"serde_json",
"wasm-bindgen",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "i_float"
version = "5.0.0"
@@ -76,6 +95,22 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "kernel2d"
version = "0.1.0"
@@ -89,6 +124,12 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -149,6 +190,21 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash",
"indexmap",
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
@@ -210,3 +266,9 @@ checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+1
View File
@@ -19,6 +19,7 @@ web = ["dep:wasm-bindgen", "dep:console_error_panic_hook"]
[dependencies]
i_overlay = { version = "9.1", default-features = false }
serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] }
kernel2d = { path = "../kernel2d" }
wasm-bindgen = { version = "0.2", optional = true }
console_error_panic_hook = { version = "0.1", optional = true }
+267
View File
@@ -0,0 +1,267 @@
//! Projekt-Dokument und Ops ([K4], Stufe S1): Rust hält das Projekt als JSON-Baum und wendet die
//! Op-Folgen an, die TS aus `core/ops.ts` erzeugt (`setField`/`add`/`replace`/`remove`/`reorder`).
//! Die Ops werden atomar angewendet und geprüft (doppelte ids); bei Verstoss bleibt das Dokument
//! unverändert. Später lesen die Ableitungen (Plan, Schnitt, 3D, Kennzahlen, Export) direkt dieses
//! Dokument statt flacher TS-Sammler.
//!
//! JSON kennt weder `undefined` noch NaN: fehlende Felder fehlen, nicht endliche Zahlen prüft TS
//! vor dem Senden (`validateOps`).
use serde_json::{Map, Value};
use std::collections::HashSet;
/// Eine Änderung am Projekt (Spiegel von `CoreOp` in `core/ops.ts`).
#[derive(Clone, Debug, PartialEq)]
pub enum Op {
Add { collection: String, items: Vec<Value>, at: Option<usize> },
Replace { collection: String, entity: Value },
Remove { collection: String, ids: Vec<String> },
Reorder { collection: String, ids: Vec<String> },
SetField { key: String, value: Option<Value> },
}
fn id_of(v: &Value) -> Option<&str> {
v.get("id").and_then(Value::as_str)
}
impl Op {
pub fn from_json(v: &Value) -> Result<Op, String> {
let kind = v.get("kind").and_then(Value::as_str).ok_or("Op ohne kind")?;
let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned).ok_or(format!("Op {kind}: {k} fehlt"));
let ids = |k: &str| -> Result<Vec<String>, String> {
v.get(k)
.and_then(Value::as_array)
.ok_or(format!("Op {kind}: {k} fehlt"))?
.iter()
.map(|x| x.as_str().map(str::to_owned).ok_or(format!("Op {kind}: {k} enthält Nicht-Text")))
.collect()
};
Ok(match kind {
"add" => {
let items = v.get("items").and_then(Value::as_array).ok_or("Op add: items fehlt")?.clone();
if items.iter().any(|e| id_of(e).is_none()) {
return Err("Op add: Element ohne id".into());
}
let at = match v.get("at") {
None | Some(Value::Null) => None,
Some(a) => Some(a.as_f64().filter(|x| x.is_finite()).map(|x| x.max(0.0) as usize).ok_or("Op add: at ungültig")?),
};
Op::Add { collection: s("collection")?, items, at }
}
"replace" => {
let entity = v.get("entity").cloned().ok_or("Op replace: entity fehlt")?;
if id_of(&entity).is_none() {
return Err("Op replace: Element ohne id".into());
}
Op::Replace { collection: s("collection")?, entity }
}
"remove" => Op::Remove { collection: s("collection")?, ids: ids("ids")? },
"reorder" => Op::Reorder { collection: s("collection")?, ids: ids("ids")? },
"setField" => Op::SetField { key: s("key")?, value: v.get("value").filter(|x| !x.is_null()).cloned() },
other => return Err(format!("Unbekannte Op: {other}")),
})
}
fn key(&self) -> &str {
match self {
Op::Add { collection, .. } | Op::Replace { collection, .. } | Op::Remove { collection, .. } | Op::Reorder { collection, .. } => collection,
Op::SetField { key, .. } => key,
}
}
}
/// Liste mit lauter `id`-tragenden Elementen (leer zählt mit).
fn is_id_list(v: &Value) -> bool {
v.as_array().is_some_and(|a| a.iter().all(|e| id_of(e).is_some()))
}
fn unique_ids(list: &[Value]) -> bool {
let mut seen = HashSet::new();
list.iter().all(|e| seen.insert(id_of(e).unwrap_or("")))
}
fn has_dup(v: Option<&Value>) -> bool {
match v {
Some(v) if is_id_list(v) => !unique_ids(v.as_array().unwrap()),
_ => false,
}
}
#[derive(Clone, Debug, Default)]
pub struct Document {
root: Map<String, Value>,
}
impl Document {
pub fn from_json(text: &str) -> Result<Document, String> {
match serde_json::from_str::<Value>(text) {
Ok(Value::Object(root)) => Ok(Document { root }),
Ok(_) => Err("Projekt ist kein JSON-Objekt".into()),
Err(e) => Err(e.to_string()),
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self.root).unwrap_or_default()
}
pub fn field(&self, key: &str) -> Option<&Value> {
self.root.get(key)
}
fn list_mut(&mut self, collection: &str) -> &mut Vec<Value> {
let slot = self.root.entry(collection.to_owned()).or_insert_with(|| Value::Array(vec![]));
if !slot.is_array() {
*slot = Value::Array(vec![]);
}
slot.as_array_mut().unwrap()
}
fn apply_one(&mut self, op: &Op) {
match op {
Op::SetField { key, value } => match value {
Some(v) => {
self.root.insert(key.clone(), v.clone());
}
None => {
self.root.shift_remove(key);
}
},
Op::Add { collection, items, at } => {
let list = self.list_mut(collection);
let at = at.map_or(list.len(), |a| a.min(list.len()));
list.splice(at..at, items.iter().cloned());
}
Op::Replace { collection, entity } => {
let list = self.list_mut(collection);
let id = id_of(entity);
match list.iter().position(|e| id_of(e) == id) {
Some(i) => list[i] = entity.clone(),
None => list.push(entity.clone()),
}
}
Op::Remove { collection, ids } => {
let drop: HashSet<&str> = ids.iter().map(String::as_str).collect();
self.list_mut(collection).retain(|e| !id_of(e).is_some_and(|i| drop.contains(i)));
}
Op::Reorder { collection, ids } => {
let list = std::mem::take(self.list_mut(collection));
let mut ordered = Vec::with_capacity(list.len());
let mut rest = Vec::new();
let listed: HashSet<&str> = ids.iter().map(String::as_str).collect();
for id in ids {
if let Some(e) = list.iter().find(|e| id_of(e) == Some(id.as_str())) {
ordered.push(e.clone());
}
}
for e in &list {
if !id_of(e).is_some_and(|i| listed.contains(i)) {
rest.push(e.clone());
}
}
ordered.extend(rest);
*self.list_mut(collection) = ordered;
}
}
}
/// Wendet `ops` atomar an. Verstösse (neue doppelte ids) → `Err(Meldungen)`, Dokument unverändert.
pub fn apply(&mut self, ops: &[Op]) -> Result<(), Vec<String>> {
// Zustand der berührten Felder sichern (Rücknahme) und Alt-Doppelungen merken.
let mut saved: Vec<(String, Option<Value>)> = Vec::new();
let mut had_dup: HashSet<String> = HashSet::new();
for op in ops {
let k = op.key().to_owned();
if !saved.iter().any(|(s, _)| *s == k) {
if has_dup(self.root.get(&k)) {
had_dup.insert(k.clone());
}
saved.push((k.clone(), self.root.get(&k).cloned()));
}
}
for op in ops {
self.apply_one(op);
}
let mut problems = Vec::new();
let mut checked: HashSet<&str> = HashSet::new();
for op in ops {
let (key, is_add, is_set) = match op {
Op::Add { collection, .. } => (collection.as_str(), true, false),
Op::SetField { key, .. } => (key.as_str(), false, true),
_ => continue,
};
if (is_add || is_set) && checked.insert(key) && !had_dup.contains(key) {
if let Some(v) = self.root.get(key) {
let relevant = is_add || v.as_array().is_some_and(|a| !a.is_empty()) && is_id_list(v);
if relevant && is_id_list(v) && !unique_ids(v.as_array().unwrap()) {
problems.push(format!("Doppelte ids in „{key}\"."));
}
}
}
}
if problems.is_empty() {
return Ok(());
}
for (k, old) in saved {
match old {
Some(v) => {
self.root.insert(k, v);
}
None => {
self.root.shift_remove(&k);
}
}
}
Err(problems)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn doc() -> Document {
Document::from_json(r#"{"id":"p","walls":[{"id":"a","x":1},{"id":"b","x":2}],"name":"N"}"#).unwrap()
}
fn ops(v: Value) -> Vec<Op> {
v.as_array().unwrap().iter().map(|o| Op::from_json(o).unwrap()).collect()
}
#[test]
fn ops_wirken_wie_in_ts() {
let mut d = doc();
d.apply(&ops(json!([
{"kind":"replace","collection":"walls","entity":{"id":"b","x":9}},
{"kind":"add","collection":"walls","items":[{"id":"c"}],"at":0},
{"kind":"remove","collection":"walls","ids":["a"]},
{"kind":"setField","key":"name","value":"M"},
{"kind":"setField","key":"id"},
])))
.unwrap();
assert_eq!(d.to_json(), r#"{"name":"M","walls":[{"id":"c"},{"id":"b","x":9}]}"#.replace(r#"{"name":"M","walls""#, r#"{"walls""#).replace("}]}", r#"}],"name":"M"}"#));
d.apply(&ops(json!([{"kind":"reorder","collection":"walls","ids":["b"]}]))).unwrap();
assert_eq!(d.field("walls").unwrap()[0]["id"], "b");
}
#[test]
fn doppelte_ids_werden_zurueckgenommen() {
let mut d = doc();
let before = d.to_json();
let e = d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"a"}]}]))).unwrap_err();
assert_eq!(e, vec!["Doppelte ids in „walls\".".to_string()]);
assert_eq!(d.to_json(), before);
}
#[test]
fn alt_doppelungen_bleiben_aenderbar() {
let mut d = Document::from_json(r#"{"walls":[{"id":"a"},{"id":"a"}]}"#).unwrap();
d.apply(&ops(json!([{"kind":"add","collection":"walls","items":[{"id":"z"}]}]))).unwrap();
}
#[test]
fn kaputte_ops_sind_fehler() {
assert!(Op::from_json(&json!({"kind":"add","collection":"w","items":[{"x":1}]})).is_err());
assert!(Op::from_json(&json!({"kind":"nope"})).is_err());
}
}
+1
View File
@@ -38,6 +38,7 @@ pub mod plan_walls;
pub mod opening_geom;
pub mod plan_openings;
pub mod delaunay;
pub mod document;
pub mod mesh_section;
pub mod plan_elevation;
pub mod plan_misc;
+63
View File
@@ -0,0 +1,63 @@
//! Bindungen des Projekt-Dokuments (`crate::document`): Handles in einer Tabelle, damit TS das
//! Projekt nicht bei jedem Aufruf neu übergeben muss.
use crate::document::{Document, Op};
use serde_json::Value;
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
thread_local! {
static DOCS: RefCell<Vec<Option<Document>>> = const { RefCell::new(Vec::new()) };
}
fn with_doc<R>(h: u32, f: impl FnOnce(&mut Document) -> R) -> Option<R> {
DOCS.with(|d| d.borrow_mut().get_mut((h as usize).checked_sub(1)?)?.as_mut().map(f))
}
/// Öffnet ein Dokument aus Projekt-JSON; Handle ≥ 1, 0 bei Fehler.
#[wasm_bindgen]
pub fn doc_open(json: &str) -> u32 {
let Ok(doc) = Document::from_json(json) else { return 0 };
DOCS.with(|d| {
let mut d = d.borrow_mut();
if let Some(i) = d.iter().position(Option::is_none) {
d[i] = Some(doc);
i as u32 + 1
} else {
d.push(Some(doc));
d.len() as u32
}
})
}
#[wasm_bindgen]
pub fn doc_close(h: u32) {
DOCS.with(|d| {
if let Some(slot) = (h as usize).checked_sub(1).and_then(|i| d.borrow_mut().get_mut(i).map(|s| s.take())) {
drop(slot);
}
});
}
/// Wendet eine Op-Folge (JSON-Array) an. Leerer Text = ok, sonst JSON-Array der Meldungen.
#[wasm_bindgen]
pub fn doc_apply(h: u32, ops_json: &str) -> String {
let parsed: Result<Vec<Op>, String> = serde_json::from_str::<Value>(ops_json)
.map_err(|e| e.to_string())
.and_then(|v| v.as_array().ok_or("Ops sind kein Array".to_string()).and_then(|a| a.iter().map(Op::from_json).collect()));
let problems = match parsed {
Err(e) => vec![e],
Ok(ops) => match with_doc(h, |d| d.apply(&ops)) {
None => vec!["Dokument nicht offen".to_string()],
Some(Ok(())) => return String::new(),
Some(Err(p)) => p,
},
};
Value::from(problems).to_string()
}
/// Das ganze Dokument als JSON (leer, wenn nicht offen).
#[wasm_bindgen]
pub fn doc_json(h: u32) -> String {
with_doc(h, |d| d.to_json()).unwrap_or_default()
}
+1
View File
@@ -29,6 +29,7 @@ mod plan_stairs;
mod plan_walls;
mod plan_openings;
mod delaunay;
mod document;
mod mesh_section;
mod plan_elevation;
mod plan_misc;
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { ProjectDocument } from "./document";
import { sampleProject } from "../model/sampleProject";
import type { Project } from "../model/types";
const plain = (p: Project): unknown => JSON.parse(JSON.stringify(p));
function mutate(p: Project, seed: number): Project {
let x = seed;
const rnd = () => ((x = (x * 1664525 + 1013904223) % 4294967296) / 4294967296);
let out = { ...p };
const walls = [...out.walls];
if (rnd() < 0.5 && walls.length) walls.splice(Math.floor(rnd() * walls.length), 1);
if (rnd() < 0.7 && walls.length) {
const i = Math.floor(rnd() * walls.length);
walls[i] = { ...walls[i], height: (walls[i].height ?? 2.6) + rnd() };
}
if (rnd() < 0.6) walls.splice(Math.floor(rnd() * (walls.length + 1)), 0, { ...p.walls[0], id: `new-${seed}-a` }, { ...p.walls[0], id: `new-${seed}-b` });
if (rnd() < 0.4) walls.reverse();
out = { ...out, walls };
if (rnd() < 0.5) out = { ...out, name: `n${seed}` };
if (rnd() < 0.3) out = { ...out, referenceElevationMasl: rnd() * 500 };
if (rnd() < 0.3) out = { ...out, geoAnchor: undefined };
if (rnd() < 0.5) out = { ...out, drawings2d: [] };
return out;
}
describe("ProjectDocument (Kern-Spiegel)", () => {
it("öffnet das Projekt unverändert", () => {
const d = new ProjectDocument(sampleProject);
expect(JSON.parse(d.json())).toEqual(plain(sampleProject));
d.close();
});
it("folgt beliebigen Änderungen über Ops", () => {
const d = new ProjectDocument(sampleProject);
let cur = sampleProject;
for (let seed = 1; seed <= 300; seed++) {
cur = mutate(cur, seed);
d.sync(cur);
const got = JSON.parse(d.json()) as Record<string, unknown>;
const want = plain(cur) as Record<string, unknown>;
const bad = [...new Set([...Object.keys(got), ...Object.keys(want)])].filter((k) => JSON.stringify(got[k]) !== JSON.stringify(want[k]));
expect(bad, `seed ${seed}`).toEqual([]);
}
d.close();
});
it("heilt sich bei doppelten ids (Neuöffnen)", () => {
const d = new ProjectDocument(sampleProject);
const dup = { ...sampleProject, walls: [...sampleProject.walls, sampleProject.walls[0]] };
d.sync(dup);
expect(JSON.parse(d.json())).toEqual(plain(dup));
d.close();
});
});
+57
View File
@@ -0,0 +1,57 @@
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1): spiegelt das TS-Projekt über Ops nach Rust
// (`document.rs`). TS bleibt vorerst Quelle der Änderungen (`setProject` → `diffToOps`); Rust hält
// den Stand, auf dem die Ableitungen später direkt rechnen, ohne dass TS das Projekt je Aufruf
// flach neu sammeln muss. Bei jedem Widerspruch (abgelehnte Ops, Fehler) wird das Dokument aus dem
// vollen Projekt neu geöffnet — der Spiegel heilt sich selbst.
import type { Project } from "../model/types";
import { core } from "../engine/coreWasm";
import { diffToOps } from "./ops";
export class ProjectDocument {
private handle = 0;
private mirror: Project;
constructor(project: Project) {
this.mirror = project;
this.reopen(project);
}
/** Handle im Kern (0 = nicht offen). */
get id(): number {
return this.handle;
}
private reopen(project: Project): void {
if (this.handle) core().doc_close(this.handle);
this.handle = core().doc_open(JSON.stringify(project));
if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
}
/** Bringt das Dokument auf den Stand `next` (über die Differenz als Ops). */
sync(next: Project): void {
if (next === this.mirror) return;
const ops = diffToOps(this.mirror, next);
this.mirror = next;
if (ops.length === 0) return;
if (!this.handle) {
this.reopen(next);
return;
}
const problems = core().doc_apply(this.handle, JSON.stringify(ops));
if (problems) {
console.warn("Kern-Dokument weicht ab, wird neu geöffnet:", problems);
this.reopen(next);
}
}
/** Das Dokument als JSON-Text (Test, Export). */
json(): string {
return this.handle ? core().doc_json(this.handle) : "";
}
close(): void {
if (this.handle) core().doc_close(this.handle);
this.handle = 0;
}
}
+23
View File
@@ -7,6 +7,7 @@
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { createStore } from "./store";
import { ProjectDocument } from "../core/document";
import type { StoreApi } from "./store";
import { createProjectSlice } from "./projectSlice";
import type { ProjectSlice } from "./projectSlice";
@@ -63,3 +64,25 @@ const store = createStore<RootState>((api) => ({
export const useStore = store.useStore;
export const getState = store.getState;
export const setState = store.setState;
// Kern-Dokument ([K4] S1): spiegelt jede Änderung von `project` (Setzen, Laden, Undo/Redo) als Ops
// in den Rust-Kern. Ohne geladenen Kern (Start, manche Tests) bleibt es aus und holt sich beim
// nächsten Zugriff den vollen Stand.
let coreDoc: ProjectDocument | null = null;
/** Das Rust-Dokument zum aktuellen Projekt (synchron nachgezogen); `null`, solange der Kern fehlt. */
export function projectDocument(): ProjectDocument | null {
try {
const p = store.getState().project;
if (!coreDoc) coreDoc = new ProjectDocument(p);
else coreDoc.sync(p);
return coreDoc;
} catch {
coreDoc = null;
return null;
}
}
store.subscribe(() => {
void projectDocument();
});