[122] Kern: verstecktes zweites Dokument abgeschafft (Fang mit Ausschluss, withDocument für abgewandelte Projekte)

documentFor findet nur offene Dokumente (Store, CLI, withDocument); kein sync/Differenz-Abgleich mehr.
Fang beim Ziehen: excludeIds -> doc_snap_hold(..., skip). Export/Publikation/Legende/Vorschau/Standards/
Stifte/Schnitt auf älterem Stand: kurzlebiges Dokument. Fremdes Projekt neben dem Store wirft in Dev/Tests.
This commit is contained in:
Claude committed 2026-11-03 19:36:01 +00:00
1 parent bc02b30a55
commit 3433d49c24
20 files changed
+277 -135

No files matched your search

+14 -2
View File
@@ -1073,8 +1073,20 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
- ○ **[120] macOS in CI.** `cargo check --features native2d`, Bildvergleich Metal ↔ WebGPU. · M
- ○ **[121] App.tsx zerlegen, Neurendern stoppen.** `App.tsx:365` abonniert ganzes Projekt, 0× `memo`;
Abschnitte in Hooks/Komponenten, Panels lesen den Store selbst; Nebenfenster bekommen Ops statt Projekt. · L
- ○ **[122] Zweites Kern-Dokument (`documentFor` → `shared`, Differenz-Abgleich) abschaffen.** Fang/Griffe/
Export bauen abgewandelte Projekte; stattdessen Ausschluss-Filter an Kern-Abfragen. · M
- ✅ **[122] Zweites Kern-Dokument (`documentFor` → `shared`, Differenz-Abgleich) abschaffen.** (3.11.) `sync`/
Differenz-Abgleich gestrichen; `documentFor` findet nur offene Dokumente über die Leseansicht (Store, CLI,
`withDocument`). Abgewandelte Projekte: Fang beim Ziehen (`App.tsx` 3D-Griff, `useGripEditing`) über
`excludeIds` → `doc_snap_hold(…, skip)` (Kern-Fang ohne die gezogenen Elemente, eigener Cache-Schlüssel);
Export (Auswahl/LV95, Publikation, Legende), Öffnungs-Vorschau, `withStandards`, Stift-Neueinbrennen und
Musterhaus-Bau öffnen ausdrücklich ein kurzlebiges Dokument (`withDocument`, danach geschlossen).
Fremdes Projekt neben dem Store-Dokument: wirft in Entwicklung/Tests, im Produkt `console.error` + volles
Laden; ohne Store (Unit-Tests, Skripte) volles Laden in ein eigenes Dokument (`detachedLoadCount`).
Gemessen (Musterhaus komplex, 200 Fang-Bewegungen, Node/vitest): statisch (3D-Griff, Projekt unverändert)
27–48 → 11–12 ms; Griff-Zug (je Bewegung Commit + Fang) 252–282 → 343–379 ms: der Modell-Teil des Fangs
wird je Stand neu gesammelt (vorher blieb die gefilterte Kopie unverändert und damit veraltet: Schichtgrenzen
der Nachbarwände). Schnitt-Plan auf älterem Stand (asynchron) über `withDocument`.
Offen: Fang-Sammeln je Element zwischenspeichern (Griff-Zug); nicht in Tauri geprüft; andere Pfade, die im Produkt noch fremde Projekte abfragen, zeigt nur
`console.error` (Entwicklung wirft). · M
- ○ **[123] Doppelte Transformation + alte Werkzeugliste streichen** (`activeTransform` in App, `tools/tools.ts`);
alles über `CommandEngine`. `commitTransform` (nur Tests) löschen. · M
- ○ **[124] Kern typisiert.** 152 Funktionen lesen rohes JSON (`grips::field/num_of`); Ops gegen Modell prüfen,
+50 -16
View File
@@ -127,11 +127,12 @@ pub fn wall_layer_segments(p: &Project, w: &crate::model::Wall, out: &mut Vec<Se
}
/// Modell-Teil eines Geschosses (alles ausser den 2D-Zeichnungen).
pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapPart {
let vis = |floor: &str, code: &str| floor == level && codes.contains(code);
/// `skip`: ids der Elemente, die nicht fangen (z. B. die gerade gezogenen, [122]).
pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>, skip: &HashSet<String>) -> SnapPart {
let vis_el = |id: &str, floor: &str, code: &str| floor == level && codes.contains(code) && !skip.contains(id);
let mut segs: Vec<Seg> = Vec::new();
for w in &p.walls {
if vis(&w.floor_id, &w.category_code) {
if vis_el(&w.id, &w.floor_id, &w.category_code) {
if crate::wall_arc::is_arc_bulge(w.bulge) {
let pts = crate::wall_arc::axis_polyline((w.start.x, w.start.y), (w.end.x, w.end.y), w.bulge, 0.0, 0.0);
segs.extend(pts.windows(2).map(|q| [q[0].0, q[0].1, q[1].0, q[1].1]));
@@ -143,12 +144,12 @@ pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapP
}
let mut anchors = Vec::new();
for r in p.rooms.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) {
if vis_el(&r.id, &r.floor_id, &r.category_code) {
closed_poly(&r.boundary, &mut segs);
}
}
for c in p.ceilings.as_deref().unwrap_or(&[]) {
if vis(&c.floor_id, &c.category_code) {
if vis_el(&c.id, &c.floor_id, &c.category_code) {
closed_poly(&c.outline, &mut segs);
for hole in c.openings.as_deref().unwrap_or(&[]) {
closed_poly(hole, &mut segs);
@@ -156,13 +157,13 @@ pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapP
}
}
for r in p.roofs.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) {
if vis_el(&r.id, &r.floor_id, &r.category_code) {
closed_poly(&r.outline, &mut segs);
}
}
let mut stair_arcs = Vec::new();
for s in p.stairs.as_deref().unwrap_or(&[]) {
if !vis(&s.floor_id, &s.category_code) {
if !vis_el(&s.id, &s.floor_id, &s.category_code) {
continue;
}
// `stairOutline`: `[0, n, Punkte…]` Polygon, `[1, 4 Punkte, 2 × (cx, cy, r, a0, a1)]` Wendel.
@@ -185,7 +186,7 @@ pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapP
}
let mut circles = Vec::new();
for col in p.columns.as_deref().unwrap_or(&[]) {
if !vis(&col.floor_id, &col.category_code) {
if !vis_el(&col.id, &col.floor_id, &col.category_code) {
continue;
}
match col.profile {
@@ -195,7 +196,7 @@ pub fn collect_model(p: &Project, level: &str, codes: &HashSet<String>) -> SnapP
}
circles.extend(stair_arcs);
for r in p.rooms.as_deref().unwrap_or(&[]) {
if vis(&r.floor_id, &r.category_code) && r.boundary.len() >= 3 {
if vis_el(&r.id, &r.floor_id, &r.category_code) && r.boundary.len() >= 3 {
anchors.push(match &r.stamp_anchor {
Some(a) => (a.x, a.y),
None => {
@@ -260,14 +261,14 @@ fn drawing_segs(g: &Drawing2DGeom, out: &mut Vec<Seg>) {
}
}
/// Zeichnungs-Teil eines Geschosses.
pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>) -> SnapPart {
/// Zeichnungs-Teil eines Geschosses; `skip` wie bei [`collect_model`].
pub fn collect_drawings(p: &Project, level: &str, codes: &HashSet<String>, skip: &HashSet<String>) -> SnapPart {
let mut segs: Vec<Seg> = Vec::new();
let mut circles = Vec::new();
let mut ellipses = Vec::new();
let mut anchors = Vec::new();
for d in &p.drawings2d {
if !crate::grid::visible_on(d, level) || !codes.contains(&d.category_code) {
if !crate::grid::visible_on(d, level) || !codes.contains(&d.category_code) || skip.contains(&d.id) {
continue;
}
match &d.geom {
@@ -461,6 +462,8 @@ struct PartKey {
revs: Vec<u64>,
level: String,
codes: String,
/// Ausgenommene ids (sortiert, `\n`-getrennt).
skip: String,
}
/// Felder, aus denen der Modell-Teil sammelt (ändert sich eines, wird neu gesammelt).
@@ -505,6 +508,17 @@ impl SnapCache {
/// sammeln bzw. wiederverwenden; Nummer für [`SnapCache::get`]. Dieselbe Nummer, solange sich die
/// betroffenen Felder nicht ändern.
pub fn hold(&mut self, doc_id: u32, doc: &mut crate::document::Document, level: &str, codes: &[String]) -> u32 {
self.hold_except(doc_id, doc, level, codes, &[])
}
/// Wie [`SnapCache::hold`], ohne die Elemente mit den ids `skip` (Fang beim Ziehen: das gezogene
/// Element fängt nicht an sich selbst, [122] — statt eines abgewandelten Projekts).
pub fn hold_except(&mut self, doc_id: u32, doc: &mut crate::document::Document, level: &str, codes: &[String], skip: &[String]) -> u32 {
let mut skip_sorted: Vec<&str> = skip.iter().map(String::as_str).filter(|s| !s.is_empty()).collect();
skip_sorted.sort_unstable();
skip_sorted.dedup();
let skip_key = skip_sorted.join("\n");
let skip_set: HashSet<String> = skip_sorted.iter().map(|s| (*s).to_owned()).collect();
let mut sorted: Vec<&str> = codes.iter().map(String::as_str).collect();
sorted.sort_unstable();
sorted.dedup();
@@ -517,6 +531,7 @@ impl SnapCache {
revs: fields.iter().map(|f| revs.field(f)).collect(),
level: level.to_owned(),
codes: codes_key.clone(),
skip: skip_key.clone(),
};
let (mut mk, dk) = (key(&MODEL_FIELDS, doc.revs()), key(&DRAWING_FIELDS, doc.revs()));
// Blatt-Ebene eines Layouts ([93]): statt des (leeren) Modells die Inhalte der Viewports, auf das
@@ -530,11 +545,11 @@ impl SnapCache {
doc.project()
.map(|p| match crate::sheet_viewports::layout_of_level(p, level).filter(|_| sheet) {
Some(l) => SnapPart { segs: SnapSet::new(crate::sheet_viewports::viewport_snap_segments(p, l)), ..SnapPart::default() },
None => collect_model(p, level, &set),
None => collect_model(p, level, &set, &skip_set),
})
.unwrap_or_default()
});
let drawings = cached(&mut self.drawings, dk, || doc.project().map(|p| collect_drawings(p, level, &set)).unwrap_or_default());
let drawings = cached(&mut self.drawings, dk, || doc.project().map(|p| collect_drawings(p, level, &set, &skip_set)).unwrap_or_default());
if let Some(e) = self.held.iter().find(|e| Rc::ptr_eq(&e.1.model, &model) && Rc::ptr_eq(&e.1.drawings, &drawings) && e.1.near_mode == near_mode) {
return e.0;
}
@@ -678,7 +693,7 @@ mod tests {
let p: Project = serde_json::from_value(v).unwrap();
let codes: HashSet<String> = ["20".to_string()].into_iter().collect();
for level in ["eg", "og"] {
let part = collect_drawings(&p, level, &codes);
let part = collect_drawings(&p, level, &codes, &HashSet::new());
assert_eq!(part.anchors.len(), 4, "{level}");
assert!(part.anchors.contains(&(5.0, 5.0)));
}
@@ -686,12 +701,31 @@ mod tests {
v["drawings2d"] = json!([{"id": "G", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "grid", "origin": {"x": 0, "y": 0}, "angle": 0, "radial": true,
"a": [{"label": "1", "pos": 0}, {"label": "2", "pos": 90}], "b": [{"label": "A", "pos": 3}], "extend": 1}}]);
let p: Project = serde_json::from_value(v).unwrap();
let part = collect_drawings(&p, "eg", &codes);
let part = collect_drawings(&p, "eg", &codes, &HashSet::new());
assert_eq!(part.circles.len(), 1);
assert_eq!(part.circles[0].r, 3.0);
assert_eq!(part.anchors.len(), 2);
}
#[test]
fn ausgenommene_elemente_fangen_nicht_eigene_nummer() {
let mut v = base();
v["walls"] = json!([wall(None)]);
v["drawings2d"] = json!([{"id": "l", "levelId": "eg", "categoryCode": "20", "geom": {"shape": "line", "a": {"x": 0, "y": 5}, "b": {"x": 1, "y": 5}}}]);
let mut d = doc(v);
let mut cache = SnapCache::default();
let all = cache.hold(1, &mut d, "eg", &codes());
let no_wall = cache.hold_except(1, &mut d, "eg", &codes(), &["w".into()]);
let no_line = cache.hold_except(1, &mut d, "eg", &codes(), &["l".into(), String::new()]);
assert!(all != no_wall && all != no_line && no_wall != no_line);
assert!(!cache.get(all).unwrap().model.segs.segs.is_empty());
assert!(cache.get(no_wall).unwrap().model.segs.segs.is_empty());
assert_eq!(cache.get(no_wall).unwrap().drawings.segs.segs.len(), 1);
assert!(cache.get(no_line).unwrap().drawings.segs.segs.is_empty());
// Leere Ausnahme = ohne Ausnahme.
assert_eq!(cache.hold_except(1, &mut d, "eg", &codes(), &[]), all);
}
#[test]
fn gleiche_nummer_solange_nichts_relevantes_aendert_teile_einzeln_neu() {
let mut v = base();
+9 -4
View File
@@ -13,12 +13,17 @@ thread_local! {
static CACHE: RefCell<SnapCache> = RefCell::new(SnapCache::default());
}
fn lines(s: &str) -> Vec<String> {
if s.is_empty() { Vec::new() } else { s.split('\n').map(str::to_owned).collect() }
}
/// Kandidaten des Geschosses `level` mit den sichtbaren Ebenen `codes` (durch `\n` getrennt) im
/// Dokument `h`; Nummer ≥ 1 für [`snap_query`] (0 = Dokument nicht offen).
/// Dokument `h`, ohne die Elemente mit den ids `skip` (durch `\n` getrennt; gezogene Elemente, [122]);
/// Nummer ≥ 1 für [`snap_query`] (0 = Dokument nicht offen).
#[wasm_bindgen]
pub fn doc_snap_hold(h: u32, level: &str, codes: &str) -> u32 {
let codes: Vec<String> = if codes.is_empty() { Vec::new() } else { codes.split('\n').map(str::to_owned).collect() };
with_doc(h, |d| CACHE.with(|c| c.borrow_mut().hold(h, d, level, &codes))).unwrap_or(0)
pub fn doc_snap_hold(h: u32, level: &str, codes: &str, skip: &str) -> u32 {
let (codes, skip) = (lines(codes), lines(skip));
with_doc(h, |d| CACHE.with(|c| c.borrow_mut().hold_except(h, d, level, &codes, &skip))).unwrap_or(0)
}
fn push(out: &mut Vec<f64>, c: Option<Cand>) {
+2 -7
View File
@@ -34,7 +34,6 @@ import type {
LayoutLegend,
LayoutTable,
LayoutViewport,
Project,
Roof,
Vec2,
Wall,
@@ -2005,14 +2004,10 @@ export default function App() {
excludeWallIds: Set<string>,
excludeDrawingIds: Set<string>,
): SnapResult | null => {
const snapProject: Project = {
...project,
walls: project.walls.filter((w) => !excludeWallIds.has(w.id)),
drawings2d: project.drawings2d.filter((d) => !excludeDrawingIds.has(d.id)),
};
return computeSnap({
raw,
project: snapProject,
project,
excludeIds: [...excludeWallIds, ...excludeDrawingIds],
levelId: activeLevel.id,
visibleCodes,
settings: snap,
+39 -18
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { ProjectDocument } from "./document";
import { ProjectDocument, detachedLoadCount, documentFor, setPrimaryDocument, withDocument } from "./document";
import { sampleProject } from "../model/sampleProject";
import type { Project } from "../model/types";
@@ -32,25 +32,46 @@ describe("ProjectDocument (Kern-Spiegel)", () => {
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([]);
it("documentFor: ohne Store ein eigenes, ganz geladenes Dokument je Projekt-Stand (kein Abgleich)", () => {
for (let seed = 1; seed <= 20; seed++) {
const cur = mutate(sampleProject, seed);
const before = detachedLoadCount();
const d = documentFor(cur);
expect(documentFor(cur)).toBe(d);
expect(detachedLoadCount()).toBe(before + 1);
expect(JSON.parse(d.json())).toEqual(plain(cur));
}
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();
it("withDocument: kurzlebiges Dokument, documentFor trifft es, danach geschlossen", async () => {
const p = mutate(sampleProject, 7);
const before = detachedLoadCount();
let held: ProjectDocument | null = null;
const n = withDocument(p, (d) => {
held = d;
expect(documentFor(p)).toBe(d);
return d.current.walls.length;
});
expect(n).toBe(p.walls.length);
expect(held!.id).toBe(0);
await withDocument(p, async (d) => {
await Promise.resolve();
expect(documentFor(p)).toBe(d);
});
expect(detachedLoadCount()).toBe(before);
});
it("mit Store-Dokument wirft ein fremdes Projekt (Entwicklung/Tests)", () => {
const store = new ProjectDocument(sampleProject);
setPrimaryDocument(store);
try {
expect(documentFor(sampleProject)).toBe(store);
expect(() => documentFor({ ...sampleProject, name: "anders" })).toThrow(/withDocument/);
const other = { ...sampleProject, name: "anders" };
expect(withDocument(other, (d) => documentFor(other) === d)).toBe(true);
} finally {
setPrimaryDocument(null);
store.close();
}
});
});
+80 -44
View File
@@ -1,15 +1,14 @@
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`;
// S4: Laden/Speichern der Projektdatei, s. `loadFile`/`serialize`). Änderungen kommen als Ops
// (`commit`), ein anderes Projekt als Ganzes (`load`, `loadFile` — leert den Verlauf). TS hält die
// Leseansicht (`current`). Das gemeinsame Abfrage-Dokument (`documentFor`) folgt fremden Projekten
// feldweise (`sync`); bei jedem Widerspruch wird es aus dem vollen Projekt neu geöffnet.
// Leseansicht (`current`). Abfragen finden ihr Dokument über die Leseansicht (`documentFor`); ein
// abgewandeltes Projekt wird ausdrücklich geöffnet (`withDocument`) statt abgeglichen ([122]).
import type { Project } from "../model/types";
import { core, registerCoreRestore } from "../engine/coreWasm";
import { applyOps, opsToJson } from "./ops";
import { fromMarkedJson, toMarkedJson } from "./ops";
import type { CoreOp } from "./ops";
import { fieldOps } from "./opsBuild";
import { opsMutation } from "./opsBuild";
import { StepStates } from "./stepStates";
import type { ProjectMutation } from "./opsBuild";
@@ -110,9 +109,6 @@ export type QueryName =
| "selectionHighlight"
| "modelJson";
/** Ab so vielen Ops öffnet `sync` das Dokument neu, statt sie einzeln anzuwenden. */
const SYNC_REOPEN_OPS = 2000;
export class ProjectDocument {
private handle = 0;
private mirror: Project;
@@ -152,34 +148,6 @@ export class ProjectDocument {
else if (this.limits) core().doc_history_limits(this.handle, this.limits[0], this.limits[1]);
}
/**
* Bringt das Abfrage-Dokument auf den Stand `next` (ohne Verlauf): nur die Felder, deren Referenz
* sich geändert hat, je über {@link fieldOps} (Listen elementweise) — unveränderte Teile kosten
* nichts. Kein Weg für Benutzer-Änderungen (die gehen als Ops über {@link commit}).
*/
sync(next: Project): void {
if (next === this.mirror) return;
const a = this.mirror as unknown as Record<string, unknown>;
const b = next as unknown as Record<string, unknown>;
const ops: CoreOp[] = [];
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
if (a[key] !== b[key]) ops.push(...fieldOps(this.mirror, key as keyof Project, b[key] as never));
}
this.mirror = next;
if (ops.length === 0) return;
// Ganz anderes Projekt (Tests, Laden): neu öffnen statt Tausender Einzel-Ops — das Entfernen
// vieler Elemente einzeln wäre quadratisch (Kataster-Importe mit 10⁵ Zeichnungen).
if (!this.handle || ops.length > SYNC_REOPEN_OPS) {
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);
}
}
/**
* Abfrage auf dem typisierten Projekt im Kern (`queries.rs`); `args` Zahlen, `text` ein Text
* (z. B. eine id). Das Ergebnis ist JSON; Fehler im Kern (Projekt passt nicht zum Modell,
@@ -595,7 +563,7 @@ registerCoreRestore(() => {
try {
doc.restoreAfterRestart();
} catch (e) {
// Bleibt zu (Handle 0) und öffnet sich beim nächsten Gebrauch neu (`ensure`/`sync`).
// Bleibt zu (Handle 0) und öffnet sich beim nächsten Gebrauch neu (`ensure`/`load`).
console.error("Kern-Dokument nach Neustart nicht wieder geöffnet.", e);
}
}
@@ -613,8 +581,8 @@ function gripJson(req: object): string {
let shared: ProjectDocument | null = null;
/**
* Das gemeinsame Abfrage-Dokument (ohne Verlauf), z. B. für das CLI: eine dort geladene Datei
* ({@link ProjectDocument.loadFile}) ist sofort das Dokument der Abfragen auf ihrem Projekt.
* Das Dokument des CLI (ohne Verlauf): eine dort geladene Datei ({@link ProjectDocument.loadFile})
* ist sofort das Dokument der Abfragen auf ihrem Projekt (s. {@link documentFor}).
*/
export function sharedDocument(): ProjectDocument {
if (!shared) shared = new ProjectDocument({} as Project);
@@ -628,16 +596,84 @@ export function setPrimaryDocument(doc: ProjectDocument | null): void {
primary = doc;
}
/** Ausdrücklich geöffnete, kurzlebige Dokumente ({@link withDocument}), innerste zuletzt. */
const scoped: ProjectDocument[] = [];
/** Offenes Dokument, dessen Leseansicht `project` ist (Store, CLI, {@link withDocument}). */
function lookup(project: Project): ProjectDocument | null {
if (primary && primary.current === project && primary.id) return primary;
for (let i = scoped.length - 1; i >= 0; i--) if (scoped[i].current === project && scoped[i].id) return scoped[i];
if (shared && shared.current === project && shared.id) return shared;
return null;
}
/**
* Das gemeinsame Kern-Dokument, auf den Stand von `project` gebracht. Der Abgleich läuft über die
* Differenz zum zuletzt gesehenen Projekt (Referenzvergleich, unveränderte Teile kosten nichts);
* wechselt ein Aufrufer zwischen sehr verschiedenen Projekten, ist es nur langsamer, nie falsch.
* Rechnet `run` auf einem eigenen, kurzlebigen Dokument von `project` (z. B. Export einer gefilterten
* Kopie): voll geöffnet, ohne Abgleich; Abfragen auf `project` (`documentFor`) treffen es, solange
* `run` läuft (auch über `await`), danach wird es geschlossen. Ist `project` schon offen (Store),
* läuft `run` direkt auf jenem Dokument.
*/
export function withDocument<T>(project: Project, run: (doc: ProjectDocument) => T): T {
const known = lookup(project);
if (known) return run(known);
const doc = new ProjectDocument(project);
if (!doc.id) throw new Error("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
scoped.push(doc);
const done = () => {
scoped.splice(scoped.indexOf(doc), 1);
doc.close();
};
let out: T;
try {
out = run(doc);
} catch (e) {
done();
throw e;
}
if (out instanceof Promise) return out.finally(done) as T;
done();
return out;
}
/** Ohne Store (Tests, Skripte): Dokument des zuletzt gefragten fremden Projekts, als Ganzes geladen. */
let detached: ProjectDocument | null = null;
/** Zähler der Ganz-Ladungen ausserhalb der offenen Dokumente (Messung, Tests: heisser Pfad = 0). */
let detachedLoads = 0;
export function detachedLoadCount(): number {
return detachedLoads;
}
const ENV = (import.meta as unknown as { env?: Record<string, unknown> }).env;
/** Entwicklung und Tests: ein Projekt ohne offenes Dokument neben dem Store ist ein Fehler. */
const STRICT = !!ENV?.DEV || ENV?.MODE === "test";
/**
* Das Kern-Dokument, dessen Leseansicht `project` ist: das des Stores (aktueller Stand), des CLI
* oder eines {@link withDocument}. Es gibt keinen versteckten Abgleich mehr ([122]): wer ein
* abgewandeltes Projekt abfragen will, öffnet es ausdrücklich ({@link withDocument}) oder gibt der
* Kern-Abfrage einen Filter mit (z. B. Fang ohne gezogene Elemente, `holdModelSnap`).
*
* Ohne Store-Dokument (Unit-Tests, Skripte, Musterhaus-Bau) wird ein fremdes Projekt als Ganzes in
* ein eigenes Dokument geladen (kein Abgleich, jede neue Identität = volles Laden). Mit Store-Dokument
* ist ein fremdes Projekt ein Fehler: in Entwicklung/Tests wirft es, im Produkt meldet es und lädt.
*/
export function documentFor(project: Project): ProjectDocument {
if (primary && primary.current === project && primary.id) return primary;
if (!shared) shared = new ProjectDocument(project);
else shared.sync(project);
return shared;
const known = lookup(project);
if (known) return known;
if (primary && primary.id) {
const msg = "documentFor: Projekt ist weder der Stand des Store-Dokuments noch ausdrücklich geöffnet (withDocument).";
if (STRICT) throw new Error(msg);
console.error(msg);
}
if (!detached) {
detached = new ProjectDocument(project);
detachedLoads++;
} else if (detached.current !== project || !detached.id) {
detached.load(project);
detachedLoads++;
}
if (!detached.id) throw new Error("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
return detached;
}
/**
+1
View File
@@ -49,6 +49,7 @@ export type { SiteCheck } from "../analysis/siteRules";
export { sampleProject } from "../model/sampleProject";
export { parseDxf } from "../io/dxfParser";
export { ProjectDocument, sharedDocument } from "./document";
export { withDocument } from "./document";
export { emptyProject } from "../model/sampleProject";
export { buildComplexSampleProject } from "../model/sampleProjectComplex";
export { readPointCloud, readPointCloudFlat, isPointCloudFile, DEFAULT_MAX_POINTS } from "../io/pointCloud";
+3 -2
View File
@@ -6,7 +6,7 @@ import { describe, it, expect } from "vitest";
import { cutSegmentOps, splitOps } from "./splitJoin";
import { getState } from "../state/appStore";
import type { Drawing2D, Project } from "../model/types";
import { documentFor } from "../core/document";
import { documentFor, withDocument } from "../core/document";
import { applyOps } from "../core/ops";
import { sampleProject } from "../model/sampleProject";
@@ -129,7 +129,8 @@ describe("Split (Kern `cmd_split.rs`)", () => {
const b: Drawing2D = { id: "b", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "line", a: { x: 4, y: -1 }, b: { x: 4, y: 1 } } };
const z: Drawing2D = { id: "z", type: "drawing2d", levelId: "eg", categoryCode: "20", geom: { shape: "circle", center: { x: 0, y: 0 }, r: 1 } };
const p = { ...sampleProject, drawings2d: [a, b, z] } as Project;
const { ops, selectIds } = splitOps(p, ["a", "z"]);
// Eigenes Projekt neben dem Store: ausdrücklich geöffnet ([122]).
const { ops, selectIds } = withDocument(p, () => splitOps(p, ["a", "z"]));
const next = applyOps(p, ops).drawings2d;
expect(next.map((d) => d.geom)).toEqual([
{ shape: "line", a: { x: 0, y: 0 }, b: { x: 4, y: 0 } },
+3 -1
View File
@@ -6,6 +6,7 @@
import type { Layout, LayoutLegend, Project } from "../model/types";
import { collectVisibleCodes } from "../model/types";
import { generatePlan, type Plan } from "../plan/generatePlan";
import { withDocument } from "../core/document";
import { legendDrawings, legendEntries } from "../analysis/legend";
import { SHEET_SCALE_DENOMINATOR, sheetMmToModel } from "../model/layoutModel";
import { planToPrintSvg } from "./planToPrintSvg";
@@ -45,7 +46,8 @@ export function legendPlan(project: Project, layout: Layout, legend: LayoutLegen
const levelId = `legend-${legend.id}`;
const { drawings, widthMm, heightMm } = legendDrawings(project, legend, entries, levelId);
const tmp = legendProject(project, layout, drawings, levelId);
const plan = generatePlan(tmp, levelId, collectVisibleCodes(tmp.layers), undefined, "fein", false, false, false, SHEET_SCALE_DENOMINATOR, true);
// Hilfsprojekt = eigenes, kurzlebiges Dokument ([122]); `forPrint` braucht danach nichts mehr davon.
const plan = withDocument(tmp, () => generatePlan(tmp, levelId, collectVisibleCodes(tmp.layers), undefined, "fein", false, false, false, SHEET_SCALE_DENOMINATOR, true));
return { plan, xMm: legend.xMm, yMm: legend.yMm, widthMm, heightMm };
}
+11 -2
View File
@@ -11,6 +11,7 @@ import { legendDrawings, legendEntries } from "../analysis/legend";
import { buildPagesPdf, layoutPages } from "./layoutPdf";
import { buildPlanDwg, buildPlanDxfBinary } from "./exportDxf";
import { loadFileio } from "../engine/fileioWasm";
import { withDocument } from "../core/document";
import type { PublishPlan } from "./publishSet";
import type { FolderPdfPage } from "../model/layoutModel";
@@ -63,15 +64,23 @@ async function cadFile(project: Project, set: PublishSet, plan: PublishPlan, fil
.find(Boolean);
const levelId = firstSnap?.activeLevelId ?? scoped.drawingLevels.find((l) => !l.layoutId)?.id ?? scoped.drawingLevels[0]?.id ?? "";
const scale = set.scaleOverride ?? 100;
const p = generatePlan(scoped, levelId, collectVisibleCodes(scoped.layers), undefined, "fein", false, false, true, scale, true);
const opts = { scaleDenominator: scale, paperLayout: true, levelId, title: set.name };
const bytes = format === "dwg" ? buildPlanDwg(p, scoped, opts) : buildPlanDxfBinary(p, scoped, opts);
// Gefilterte Kopie mit Legenden = eigenes, kurzlebiges Dokument ([122]).
const bytes = withDocument(scoped, () => {
const p = generatePlan(scoped, levelId, collectVisibleCodes(scoped.layers), undefined, "fein", false, false, true, scale, true);
return format === "dwg" ? buildPlanDwg(p, scoped, opts) : buildPlanDxfBinary(p, scoped, opts);
});
return { fileName, bytes, mime: format === "dwg" ? "image/vnd.dwg" : "application/dxf" };
}
/** Erzeugt alle Dateien des Plans. */
export async function runPublish(project: Project, set: PublishSet, plan: PublishPlan): Promise<PublishedFile[]> {
const shown = projectForPublish(project, plan);
// Das veröffentlichte Projekt (Revisionen hochgezählt) = eigenes Dokument, solange der Lauf dauert ([122]).
return withDocument(shown, () => publishFiles(shown, set, plan));
}
async function publishFiles(shown: Project, set: PublishSet, plan: PublishPlan): Promise<PublishedFile[]> {
const out: PublishedFile[] = [];
for (const f of plan.files) {
if (f.format === "dxf" || f.format === "dwg") {
+3 -2
View File
@@ -69,10 +69,11 @@ function flat(segs: readonly SnapSeg[]): Float64Array {
/**
* Kandidaten des Geschosses `levelId` (sichtbare Ebenen `codes`) im Kern sammeln bzw. wiederfinden:
* dieselbe Nummer, solange sich die betroffenen Felder des Dokuments nicht ändern. 0 = kein Dokument.
* `skip`: ids der Elemente, die nicht fangen (die gerade gezogenen, [122]) — statt eines abgewandelten Projekts.
*/
export function holdModelSnap(project: Project, levelId: string, codes: ReadonlySet<string>): number {
export function holdModelSnap(project: Project, levelId: string, codes: ReadonlySet<string>, skip: Iterable<string> = []): number {
const doc = documentFor(project);
return doc.id ? core().doc_snap_hold(doc.id, levelId, [...codes].join("\n")) : 0;
return doc.id ? core().doc_snap_hold(doc.id, levelId, [...codes].join("\n"), [...skip].join("\n")) : 0;
}
const cand = (f: Float64Array, k: number): ModelSnapCand | null =>
+6 -3
View File
@@ -17,7 +17,7 @@
// Projekt laufen danach ohne erneute Übergabe.
import type { Project } from "../model/types";
import { documentFor, sharedDocument } from "../core/document";
import { sharedDocument, withDocument } from "../core/document";
import type { LoadFileResult } from "../core/document";
/** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */
@@ -30,7 +30,10 @@ export function parseProjectFile(text: string): ParseProjectResult {
return sharedDocument().loadFile(text);
}
/** Serialisiert ein Projekt für die Datei (mit aktueller Formatversion vorne). */
/**
* Serialisiert ein Projekt für die Datei (mit aktueller Formatversion vorne): über das Dokument des
* Stores bzw. CLI, sonst ein eigenes, kurzlebiges Dokument (z. B. ältere Autosave-Stände, [122]).
*/
export function serializeProject(project: Project): string {
return documentFor(project).serialize();
return withDocument(project, (d) => d.serialize());
}
+4 -4
View File
@@ -36,7 +36,7 @@ import type {
import { sampleProject } from "./sampleProject";
import { withStandards } from "./standards";
import { applyOps, type CoreOp } from "../core/ops";
import { documentFor } from "../core/document";
import { withDocument } from "../core/document";
// ═════════════════════════════════════════════════════════════════════════════
// Hilfen
@@ -74,12 +74,12 @@ let stampSeq = 0;
/** Kern-Befehl auf dem Projekt rechnen und anwenden (wie die Zeichenbefehle der App, fester Stempel). */
function runCmd(p: Project, level: string, cmd: string, req: Record<string, unknown>, cat = "20"): { project: Project; ops: CoreOp[] } {
const lvl = p.drawingLevels.find((l) => l.id === level);
const ops = documentFor(p).cmdOps({
const ops = withDocument(p, (d) => d.cmdOps({
cmd,
...req,
ctx: { level, floorHeight: lvl?.floorHeight ?? null, cat, wallType: "std-wt-iw-backstein" },
stamp: `mk${++stampSeq}`,
});
}));
return { project: ops.length ? applyOps(p, ops) : p, ops };
}
@@ -653,7 +653,7 @@ const ROOMS: RoomDef[] = [
function addRooms(p: Project): Project {
for (const [level, at, nr, name, sia] of ROOMS) {
const lvl = p.drawingLevels.find((l) => l.id === level);
const ops = documentFor(p).cmdOps({ cmd: "room", at: [at.x, at.y], ctx: { level, floorHeight: lvl?.floorHeight ?? null, cat: "60", wallType: "" }, stamp: `raum${nr}` });
const ops = withDocument(p, (d) => d.cmdOps({ cmd: "room", at: [at.x, at.y], ctx: { level, floorHeight: lvl?.floorHeight ?? null, cat: "60", wallType: "" }, stamp: `raum${nr}` }));
const made = ops.find((o) => o.kind === "add" && o.collection === "rooms");
if (!made || made.kind !== "add") throw new Error(`Musterhaus komplex: Raum ${nr} nicht erkannt`);
const stamp: RoomStamp = { number: nr, name, showFloorArea: true, showUsage: true, roundingStep: 0.1 };
+3 -3
View File
@@ -6,16 +6,16 @@
import type { Project } from "./types";
import type { CoreOp } from "../core/ops";
import { applyOps } from "../core/ops";
import { documentFor } from "../core/document";
import { documentFor, withDocument } from "../core/document";
/** Ops, die die fehlenden Standard-Ressourcen anhängen („Standards laden"); leer, wenn alles da ist. */
export function standardsMergeOps(project: Project): CoreOp[] {
return documentFor(project).queryRoot<CoreOp[]>("standardsMergeOps");
}
/** Projekt mit allen Standard-Ressourcen (für neue Projekte). */
/** Projekt mit allen Standard-Ressourcen (für neue Projekte; eigenes, kurzlebiges Dokument, [122]). */
export function withStandards(project: Project): Project {
return applyOps(project, standardsMergeOps(project));
return applyOps(project, withDocument(project, () => standardsMergeOps(project)));
}
/** Was „Standards laden" anhängt: Anzahl neuer Einträge je Projekt-Liste (für die Rückmeldung). */
+6 -1
View File
@@ -4,7 +4,7 @@
// gewöhnlichen Kern-Fassaden, als SVG-Text (`planToSvgString`).
import type { DetailLevel, Project } from "../model/types";
import { documentFor } from "../core/document";
import { documentFor, withDocument } from "../core/document";
import { generatePlan } from "./generatePlan";
import { computeSection, generateSectionPlan } from "./toSection";
import { generateElevationPlan } from "./toElevation";
@@ -25,6 +25,11 @@ export function openingPreviewProject(project: Project, openingId: string): Proj
export async function openingPreviewSvgs(project: Project, openingId: string, detail: DetailLevel = "fein", scale = 20): Promise<OpeningPreviewSvgs | null> {
const mini = openingPreviewProject(project, openingId);
if (!mini) return null;
// Das Vorschau-Projekt ist ein eigenes Projekt: eigenes, kurzlebiges Dokument ([122]).
return withDocument(mini, () => previewSvgs(mini, detail, scale));
}
async function previewSvgs(mini: Project, detail: DetailLevel, scale: number): Promise<OpeningPreviewSvgs> {
const codes = new Set<string>(["", ...collectCodes(mini)]);
const opts = { scaleDenominator: scale, marginM: 0.15 };
const plan = planToSvgString(generatePlan(mini, "preview-floor", codes, undefined, detail, false, false, false, scale), opts);
+4 -2
View File
@@ -7,7 +7,7 @@
import type { DrawingLevel, Project, Vec2 } from "../model/types";
import { flattenCategories, getFloor } from "../model/types";
import { documentFor } from "../core/document";
import { withDocument } from "../core/document";
import { buildSolidMesh } from "../engine/truckSolid";
import { extrudedSolidSpec } from "./extrudedSolidSpec";
import { decodePlanBuf } from "./planBuf";
@@ -132,7 +132,9 @@ export function generateSectionPlan(
const args = output.bodies.slice();
args[0] = mono ? 1 : 0;
args[1] = opts.openings ? 1 : 0;
const buf = decodePlanBuf(documentFor(project).queryBin("sectionPlan", args, text));
// `output` kann von einem älteren Stand stammen (Schnitt-Körper asynchron gerechnet, inzwischen
// geändert): dann rechnet ein eigenes, kurzlebiges Dokument dieses Stands ([122]).
const buf = decodePlanBuf(withDocument(project, (d) => d.queryBin("sectionPlan", args, text)));
if (buf.groups.length === 0) return { primitives: [], bounds: { minX: 0, minY: 0, maxX: 1, maxY: 1 } };
const b = buf.bounds ?? [0, 0, 1, 1];
return lazyPlan(
+13 -3
View File
@@ -11,6 +11,7 @@
import { applyOps } from "../core/ops";
import type { CoreOp } from "../core/ops";
import type { ProjectMutation } from "../core";
import { withDocument } from "../core";
import type { LoadFileResult, ProjectDocument } from "../core/document";
import {
addItems,
@@ -1002,7 +1003,7 @@ export function createProjectSlice(
setActivePenSet: (id) =>
applyChange((p) => {
const stateOps = [setField("activePenSetId", id)];
return [...stateOps, ...rebakePenOps(applyOps(p, stateOps))];
return [...stateOps, ...rebakeAfter(p, stateOps)];
}),
patchPenSetColor: (setId, penId, color) =>
@@ -1014,7 +1015,7 @@ export function createProjectSlice(
[penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), color },
},
}));
return setId === p.activePenSetId ? [...stateOps, ...rebakePenOps(applyOps(p, stateOps))] : stateOps;
return setId === p.activePenSetId ? [...stateOps, ...rebakeAfter(p, stateOps)] : stateOps;
}),
patchPenSetWeight: (setId, penId, weight) =>
@@ -1026,7 +1027,7 @@ export function createProjectSlice(
[penId]: { ...(s.pens[penId] ?? { color: PEN_FALLBACK_COLOR, weight: PEN_FALLBACK_WEIGHT }), weight },
},
}));
return setId === p.activePenSetId ? [...stateOps, ...rebakePenOps(applyOps(p, stateOps))] : stateOps;
return setId === p.activePenSetId ? [...stateOps, ...rebakeAfter(p, stateOps)] : stateOps;
}),
seedStandardPenSet: () => applyChange((p) => seedStandardPenSetOps(p)),
@@ -1260,6 +1261,15 @@ export function createProjectSlice(
}
/** Immutabler Map über einen Raum (per ID); No-op ohne Treffer. */
/**
* Ops, die die Stifte nach `stateOps` neu einbrennen: gerechnet auf dem Stand danach, in einem eigenen,
* kurzlebigen Dokument (der Stand ist noch nicht übernommen, [122]).
*/
function rebakeAfter(p: Project, stateOps: CoreOp[]): CoreOp[] {
const next = applyOps(p, stateOps);
return withDocument(next, () => rebakePenOps(next));
}
function mapRoom(
project: Project,
roomId: string,
+15 -8
View File
@@ -5,7 +5,7 @@
//
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { generatePlan } from "../core";
import { generatePlan, withDocument } from "../core";
import type { CategoryDisplayResolver } from "../core";
import type { DetailLevel } from "../model/viewTypes";
import type { DisplayResolver } from "../viewport/Viewport3D";
@@ -56,9 +56,12 @@ export function useExportHandlers(opts: {
const scopedProject = (selectionOnly: boolean): Project =>
selectionOnly ? filterProjectToSelection(project, selectionMembers) : project;
// Gefilterte/verschobene Kopie = eigenes, kurzlebiges Kern-Dokument ([122]); das ganze Projekt läuft
// direkt über das Dokument des Stores.
const onExportPdf = async (decision: ExportPdfDecision) => {
const plan = generatePlan(
scopedProject(decision.selectionOnly),
const scoped = scopedProject(decision.selectionOnly);
const plan = withDocument(scoped, () => generatePlan(
scoped,
activeLevelId,
visibleCodes,
categoryDisplay,
@@ -68,7 +71,7 @@ export function useExportHandlers(opts: {
true, // includeGlobal (Default, explizit weil forPrint danach folgt)
decision.scaleDenominator, // Export-Massstab: Bemassung in Papier-mm, Strichstärken nach Massstab
true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen
);
));
await savePlanPdf(plan, {
scaleDenominator: decision.scaleDenominator,
paper: decision.paper,
@@ -84,8 +87,9 @@ export function useExportHandlers(opts: {
// Ausrichtung wie der PDF-Export (Nutzer-Wunsch „Kein SVG-Export"), nur
// ohne den jsPDF/svg2pdf-Umweg — reiner Download des Druck-SVG.
const onExportSvg = (decision: ExportPdfDecision) => {
const plan = generatePlan(
scopedProject(decision.selectionOnly),
const scoped = scopedProject(decision.selectionOnly);
const plan = withDocument(scoped, () => generatePlan(
scoped,
activeLevelId,
visibleCodes,
categoryDisplay,
@@ -95,7 +99,7 @@ export function useExportHandlers(opts: {
true, // includeGlobal (Default)
decision.scaleDenominator, // wie PDF
true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen
);
));
savePlanSvg(plan, {
scaleDenominator: decision.scaleDenominator,
paper: decision.paper,
@@ -115,7 +119,9 @@ export function useExportHandlers(opts: {
// damit die Datei in anderer CAD-Software lagerichtig ankommt — auch wenn
// lokal nahe (0,0) gezeichnet wurde. Ohne Bezug bleibt alles lokal.
// (Der Papier-/Layout-Export bleibt bewusst in lokalen Koordinaten.)
const exportProject = projectToWorldCoords(scopedProject(decision.selectionOnly));
const scoped = scopedProject(decision.selectionOnly);
const exportProject = withDocument(scoped, () => projectToWorldCoords(scoped));
await withDocument(exportProject, async () => {
const plan = generatePlan(
exportProject,
activeLevelId,
@@ -142,6 +148,7 @@ export function useExportHandlers(opts: {
} catch (err) {
getState().notify(`${t("exportDxf.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error");
}
});
setExportDxfOpen(false);
};
+4 -10
View File
@@ -1317,15 +1317,8 @@ export function useGripEditing(opts: {
// das singuläre selectedDrawingId/selectedWallId) — von den eigenen
// Snap-Kandidaten ausschließen (sonst fängt der Punkt an sich selbst).
const owner = gripOwners[index];
const snapProject: Project = selectedRoomId
? { ...project, rooms: (project.rooms ?? []).filter((r) => r.id !== selectedRoomId) }
: selectedCeilingId
? { ...project, ceilings: (project.ceilings ?? []).filter((c) => c.id !== selectedCeilingId) }
: owner?.drawingId
? { ...project, drawings2d: project.drawings2d.filter((d) => d.id !== owner.drawingId) }
: owner?.wallId
? { ...project, walls: project.walls.filter((w) => w.id !== owner.wallId) }
: project;
const snapSkip = selectedRoomId || selectedCeilingId || owner?.drawingId || owner?.wallId;
const excludeIds = snapSkip ? [snapSkip] : [];
// Bezugspunkt für Shift-Ortho: ein Nachbar-Griff DESSELBEN Elements
// (festes Ende), relativ zu dem die Bewegung auf H/V eingerastet wird.
const refIndex = neighborGripIndex(index);
@@ -1361,7 +1354,8 @@ export function useGripEditing(opts: {
// laufende Werkzeug-Zustand (kein aktives Zeichenwerkzeug während des Drags).
const snapResult = computeSnap({
raw,
project: snapProject,
project,
excludeIds,
levelId,
visibleCodes,
settings: snap,
+7 -3
View File
@@ -43,6 +43,8 @@ export interface SnapInput {
pxPerMeter: number;
shift: boolean;
ctrl: boolean;
/** ids der Elemente, die nicht fangen (gerade gezogen; sonst fängt der Punkt an sich selbst). */
excludeIds?: readonly string[];
}
/** Eine Strecke als Snap-Quelle (Entwurf, Blatt-Geometrie, Verweil-Referenz). */
@@ -66,16 +68,18 @@ interface LevelHold {
project: Project;
levelId: string;
codes: Set<string>;
skip: string;
held: number;
}
const levelHolds: LevelHold[] = [];
const MAX_LEVEL_HOLDS = 4;
function levelHold(input: SnapInput, fresh: boolean): number {
let e = levelHolds.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes);
const skip = input.excludeIds?.length ? input.excludeIds.join("\n") : "";
let e = levelHolds.find((h) => h.project === input.project && h.levelId === input.levelId && h.codes === input.visibleCodes && h.skip === skip);
if (e && !fresh) return e.held;
const held = holdModelSnap(input.project, input.levelId, input.visibleCodes);
const held = holdModelSnap(input.project, input.levelId, input.visibleCodes, input.excludeIds ?? []);
if (!e) {
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, held };
e = { project: input.project, levelId: input.levelId, codes: input.visibleCodes, skip, held };
levelHolds.push(e);
if (levelHolds.length > MAX_LEVEL_HOLDS) levelHolds.shift();
}