[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:
1 parent
1c3f38e9ab
commit
8a120329ee
10 files changed
+546
-1
No files matched your search
Generated
+62
@@ -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"
|
||||
@@ -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 }
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user