Merge remote-tracking branch 'origin/master' into worktree-agent-a80b9c17e273a868d
# Conflicts: # TODO.md # src/i18n/de.ts # src/i18n/en.ts
This commit is contained in:
52 files changed
+895
-130
No files matched your search
@@ -14,6 +14,7 @@ Anzeige nur über die zwei Rust-Engines `render2d` und `render3d` (WebGPU/Metal)
|
||||
ansehen") — Zahlen allein reichen nicht.
|
||||
5. **Abschliessen:** kleine Commits, Nachricht deutsch, beginnt mit den IDs (`[63] Baurecht: …`), ohne
|
||||
Co-Authored-By-Zeile. `TODO.md` im selben Commit nachführen (Stand + Datum + was offen bleibt).
|
||||
Gewollte Änderung an Plan/Schnitt/Ansicht/3D: `npx vitest run -u src/plan/golden.test.ts`, Diff in `src/plan/__golden__` im Commit prüfen ([119]).
|
||||
6. **Ehrlich berichten:** was geprüft wurde und was nicht (z. B. „nicht in der Tauri-App getestet").
|
||||
|
||||
```
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
Dossier — Hinweise zu übernommenem und eingebundenem Fremdcode ([51])
|
||||
|
||||
Material Symbols (Icon-Font, npm-Paket material-symbols, https://github.com/marella/material-symbols; Schrift von Google,
|
||||
https://github.com/google/material-design-icons), Apache-2.0
|
||||
Lokal gebündelt (src/main.tsx), statt von fonts.googleapis.com geladen ([117]).
|
||||
|
||||
acadrust (https://github.com/hakanaktt/acadrust), MPL-2.0
|
||||
Abhängigkeit von src-tauri/fileio (DXF/DWG lesen und schreiben), unverändert eingebunden.
|
||||
Der DWG-Code von acadrust ist aus ACadSharp portiert:
|
||||
|
||||
@@ -1041,10 +1041,20 @@ Frage: WebGPU weiterführen oder wie BIMCraft CPU + native GPU?
|
||||
|
||||
Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code gelesen.
|
||||
|
||||
- ○ **[116] Speichern absturzsicher.** `native/saveFile.ts:49` überschreibt direkt; Temp-Datei + Umbenennen
|
||||
(Rust-Befehl), `.obp~`-Sicherung; Autosave erst nach erfolgreichem Umbenennen löschen. · S
|
||||
- ○ **[117] CSP setzen.** `tauri.conf.json` hat `"csp": null`; strikte CSP (`script-src 'self' 'wasm-unsafe-eval'`,
|
||||
`connect-src` = netFetch-Hosts + ipc). Rich-Text-`innerHTML` prüfen. · S
|
||||
- ✅ **[116] Speichern absturzsicher.** 3.11.: Rust-Befehl `save_atomic` (`src-tauri/src/atomic_save.rs`):
|
||||
`<pfad>.tmp` schreiben + fsync, Vorversion als `<pfad>~` kopieren, Umbenennen, Ordner-fsync; Fehler lassen die
|
||||
Datei unberührt. `saveProjectFile` nutzt ihn (`saveTextFile(..., atomic)`); bei Fehler `SaveError` + `notify`
|
||||
(`project.save.failed`), Autosave-Kopie bleibt, sonst Löschen erst nach Erfolg. Offen: nur Projektdatei
|
||||
(Exporte/`saveBinaryFile` schreiben weiter direkt); in der Tauri-App nicht von Hand geprüft; Electron
|
||||
schreibt keine Dateien (Browser-Download), daher keine Änderung; keine Wiederherstellungs-UI für `.obp~`. · S
|
||||
- ✅ **[117] CSP setzen.** (3.11.) Eine Quelle `scripts/csp.cjs` (`script-src 'self' 'wasm-unsafe-eval'`, `worker-src 'self' blob:`,
|
||||
`style-src` mit `'unsafe-inline'` für React-Inline-Styles (Icon-Font seit 3.11. lokal gebündelt: `material-symbols`, kein Google-Fonts-Host mehr), `connect-src` = ipc + netFetch-Hosts +
|
||||
localhost/127.0.0.1 + ws://127.0.0.1 für die KI-Brücke). Tauri: `tauri.conf.json` (`devCsp: null`, Test `src/net/csp.test.ts`
|
||||
gleicht mit `csp.cjs` und `ALLOWED_HOSTS` ab); Electron: Antwort-Header nur gepackt; Browser/e2e: Meta-Tag nur im Vite-Build
|
||||
(Dev-HMR unberührt). `e2e/csp.spec.ts` prüft Plan/Schnitt/Ansicht/3D auf CSP-Verletzungen. Rich-Text: Text war schon
|
||||
escaped; Farbe/Schriftname/Ausrichtung/Zeilenhöhe aus Dateien jetzt per Positivliste (`safeCssColor`, `safeFontFamily`).
|
||||
Offen: nicht in der Tauri-App (macOS) und nicht im gepackten Electron geprüft (`'self'` unter `file://` ungeprüft);
|
||||
`'unsafe-inline'` bei Stilen bleibt; Material-Symbols-Font kommt noch von Google Fonts (lokal bündeln würde zwei Hosts sparen). · S
|
||||
- ◐ **[118] Wiederanlauf nach Kern-Panic.** (3.11.) `core()` (`engine/coreWasm.ts`) hüllt alle Kern-Exporte: ein
|
||||
Trap (`RuntimeError`/`unreachable`) baut sofort eine frische Instanz aus dem übersetzten Modul
|
||||
(`__dossier_reinit`, ergänzt von `scripts/build-core.mjs` = `npm run build:core`), jedes `ProjectDocument`
|
||||
@@ -1056,8 +1066,9 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
|
||||
Offen: Undo-Verlauf geht beim Neustart verloren (Meldung sagt es) — Wiederaufbau per Op-Log wäre der
|
||||
nächste Schritt; nur im Linux-Container (vitest/Node) geprüft, nicht in Tauri/Electron (synchrones
|
||||
`new WebAssembly.Instance` im Haupt-Thread). · M
|
||||
- ○ **[119] Referenz-Ausgaben (golden).** Plan-Puffer/SVG/Schnitt/Ansicht der Musterprojekte als Snapshot;
|
||||
seit TS gelöscht ist, fehlt die Bitgleich-Referenz. · M
|
||||
- ✅ **[119] Referenz-Ausgaben (golden).** 3.11.: `src/plan/golden.test.ts` — beide Musterprojekte: Grundriss je Geschoss
|
||||
(1:100, 1:50), Schnitt, Ansicht, 3D-Zusammenfassung als Digest (Zähler, Rahmen, Hash gerundeter Zahlen) in
|
||||
`src/plan/__golden__/`; Update mit `vitest -u`. Nur Linux geprüft; Hash deckt Detailabweichungen ab, Diff zeigt nur Zähler. · M
|
||||
- ○ **[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
|
||||
@@ -1073,8 +1084,9 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
|
||||
- ○ **[127] 3D-Booleans klären:** BSP in `fileio/csg.rs` stilllegen, Manifold vs. truck dokumentieren. · S
|
||||
- ○ **[128] Restlogik nach Rust:** Griffe (`useGripEditing.ts`), `layoutModel.ts`, Kollisions-Vorprüfung,
|
||||
`exportStep.projectSolidSpecs`. · L
|
||||
- ○ **[129] Grenze schärfen:** React-freies `t()` (Kern importiert `i18n` → React), `net/` in `CORE_DIRS`,
|
||||
transitive Importe prüfen. · S
|
||||
- ✅ **[129] Grenze schärfen.** (3.11.) `i18n/translate.ts` (React-frei: `t`, Sprache, Wörterbücher), `i18n/index.ts` re-exportiert
|
||||
und hält nur `useT`; Kern-Dateien importieren `i18n/translate`. `net/` in `CORE_DIRS`, neuer Test prüft transitive
|
||||
relative Importe (Ausnahmelisten leer). · S
|
||||
- ○ **[130] Kleinkram:** eine generische Fenster-Brücke statt 5 Kopien; Auswahl als ein `Selection`-Objekt statt
|
||||
12 Felder; `primitives.tsx` auf Overlay zurückschneiden; Cargo-Workspace + cargo-deny; NOTICE (OFL-Schriften,
|
||||
wgpu, Tauri, React, pdf.js, lcms). · M
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// [117] Strikte CSP (Meta-Tag im Build, s. vite.config.ts / scripts/csp.cjs): Musterhaus öffnen, Plan, Schnitt,
|
||||
// Ansicht und 3D besuchen — es darf keine CSP-Verletzung geben (Konsole oder securitypolicyviolation).
|
||||
import { discardIfAsked, expect, fileMenu, startNewProject, test } from "./app";
|
||||
|
||||
test("keine CSP-Verletzung bei Plan, Schnitt, Ansicht und 3D", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const violations: string[] = [];
|
||||
page.on("console", (m) => {
|
||||
const t = m.text();
|
||||
if (/Content Security Policy|violates the following|^CSPV /i.test(t)) violations.push(t.slice(0, 300));
|
||||
});
|
||||
await page.addInitScript(() => {
|
||||
document.addEventListener("securitypolicyviolation", (e) => {
|
||||
console.warn(`CSPV ${e.violatedDirective} ${e.blockedURI}`);
|
||||
});
|
||||
});
|
||||
|
||||
await startNewProject(page);
|
||||
expect(await page.locator('meta[http-equiv="Content-Security-Policy"]').count(), "CSP-Meta-Tag im Build").toBe(1);
|
||||
await fileMenu(page, /Musterhaus \(komplex\)/);
|
||||
await discardIfAsked(page);
|
||||
await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 });
|
||||
|
||||
for (const name of ["Schnitt A-A", "Ansicht Süd"]) {
|
||||
await page
|
||||
.getByRole("tablist", { name: "Zeichnungen" })
|
||||
.getByRole("tab", { name: `${name} Ausschnitt-Tab löschen`, exact: true })
|
||||
.click();
|
||||
await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
await page.getByRole("button", { name: "Axonometrie", exact: true }).click();
|
||||
await expect(page.getByText(/^Perspektive · /)).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "Grundriss", exact: true }).click();
|
||||
await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
+1
-8
@@ -3,14 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<!-- Material Symbols (Icon-Font) — DOSSIER-Look; ohne diese Font erschienen
|
||||
die Ligaturnamen (z. B. „content_copy") als roher Text in Menüs/Toolbar. -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200"
|
||||
/>
|
||||
<!-- Material Symbols (Icon-Font) wird lokal über src/main.tsx gebündelt ([117]). -->
|
||||
<link
|
||||
rel="icon"
|
||||
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%232f6df6'/%3E%3Cg fill='white'%3E%3Crect x='3' y='3' width='4' height='4'/%3E%3Crect x='9' y='3' width='4' height='4'/%3E%3Crect x='3' y='9' width='4' height='4'/%3E%3Crect x='9' y='9' width='4' height='4'/%3E%3C/g%3E%3C/svg%3E"
|
||||
|
||||
Generated
+7
@@ -19,6 +19,7 @@
|
||||
"jspdf": "^4.2.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lcms-wasm": "^1.0.5",
|
||||
"material-symbols": "^0.48.2",
|
||||
"pdfjs-dist": "^6.2.108",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -4562,6 +4563,12 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/material-symbols": {
|
||||
"version": "0.48.2",
|
||||
"resolved": "https://registry.npmjs.org/material-symbols/-/material-symbols-0.48.2.tgz",
|
||||
"integrity": "sha512-HepjQnrny9CsxBuTofUJsHS1Il41l3oa9ZiLHTnrKJKZbIyDvXHZJBD1ffLEO/5lSKdb8v2filRW59IPsO65yA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"jspdf": "^4.2.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lcms-wasm": "^1.0.5",
|
||||
"material-symbols": "^0.48.2",
|
||||
"pdfjs-dist": "^6.2.108",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Content-Security-Policy ([117]) — eine Quelle für Electron (Header), Vite-Build (Meta-Tag, damit
|
||||
// `vite preview`/die e2e-Suite sie ausübt) und die Prüfung gegen `src-tauri/tauri.conf.json`
|
||||
// (`src/net/csp.test.ts`; Tauri braucht den Text wörtlich in der JSON-Datei).
|
||||
// Hosts = `ALLOWED_HOSTS` aus `src/net/net.ts` (der Test gleicht ab).
|
||||
|
||||
const NET_HOSTS = [
|
||||
"ambientcg.com",
|
||||
"api.ambientcg.com",
|
||||
"geo.admin.ch",
|
||||
"api3.geo.admin.ch",
|
||||
"wms.geo.admin.ch",
|
||||
"data.geo.admin.ch",
|
||||
"overpass-api.de",
|
||||
"nominatim.openstreetmap.org",
|
||||
];
|
||||
|
||||
const https = NET_HOSTS.map((h) => `https://${h}`);
|
||||
|
||||
const DIRECTIVES = {
|
||||
"default-src": ["'self'"],
|
||||
// 'wasm-unsafe-eval': WASM-Module (Kern, render2d/3d, truck). Kein 'unsafe-eval', kein Inline-Skript.
|
||||
"script-src": ["'self'", "'wasm-unsafe-eval'"],
|
||||
// Import-Worker (DXF/IFC/Mesh/Punktwolke) und pdf.js-Worker: Modul-URLs aus dem eigenen Bundle.
|
||||
"worker-src": ["'self'", "blob:"],
|
||||
// React setzt viele Inline-`style`-Attribute -> 'unsafe-inline' (nur Stile, keine Skripte).
|
||||
"style-src": ["'self'", "'unsafe-inline'"],
|
||||
"font-src": ["'self'", "data:"],
|
||||
"img-src": ["'self'", "data:", "blob:", ...https],
|
||||
"media-src": ["'self'", "blob:"],
|
||||
"connect-src": [
|
||||
"'self'",
|
||||
"ipc:",
|
||||
"http://ipc.localhost",
|
||||
"blob:",
|
||||
"data:",
|
||||
...https,
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
"ws://127.0.0.1:*", // KI-Brücke (net/aiBridge.ts)
|
||||
],
|
||||
"object-src": ["'none'"],
|
||||
"base-uri": ["'self'"],
|
||||
"form-action": ["'none'"],
|
||||
};
|
||||
|
||||
/** Die Richtlinie als Header-/Meta-Text. */
|
||||
function buildCsp() {
|
||||
return Object.entries(DIRECTIVES)
|
||||
.map(([k, v]) => `${k} ${v.join(" ")}`)
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
module.exports = { buildCsp, NET_HOSTS };
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
const { app, BrowserWindow, Menu, ipcMain } = require("electron");
|
||||
const path = require("node:path");
|
||||
const { buildCsp } = require("./csp.cjs");
|
||||
|
||||
// Randloses App-Fenster wie chromium-shell.sh (--app=…): keine native
|
||||
// Menüleiste (File/Edit/View/Window), kein Fensterrahmen. Minimieren/
|
||||
@@ -66,7 +67,16 @@ ipcMain.handle("window:is-maximized", (event) => {
|
||||
return BrowserWindow.fromWebContents(event.sender)?.isMaximized() ?? false;
|
||||
});
|
||||
|
||||
app.whenReady().then(createWindow);
|
||||
app.whenReady().then(() => {
|
||||
// [117] CSP als Antwort-Header — nur gepackt: der Dev-Server (Vite HMR) braucht Inline-Skripte.
|
||||
if (!isDev) {
|
||||
const { session } = require("electron");
|
||||
session.defaultSession.webRequest.onHeadersReceived((details, cb) => {
|
||||
cb({ responseHeaders: { ...details.responseHeaders, "Content-Security-Policy": [buildCsp()] } });
|
||||
});
|
||||
}
|
||||
createWindow();
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") app.quit();
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Absturzsicheres Speichern ([116]): erst `<pfad>.tmp` im selben Ordner schreiben und
|
||||
// auf den Datentraeger zwingen (fsync), dann die bisherige Datei als `<pfad>~`
|
||||
// (eine Generation) sichern und die Temp-Datei per Umbenennen an den Zielpfad setzen.
|
||||
// Bricht irgendein Schritt ab, bleibt die urspruengliche Datei unveraendert.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
|
||||
let mut s = path.as_os_str().to_os_string();
|
||||
s.push(suffix);
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
/// Schreibt `content` atomar nach `path`; die Vorversion landet in `<path>~`.
|
||||
pub fn save_atomic_impl(path: &Path, content: &[u8]) -> Result<(), String> {
|
||||
let tmp = with_suffix(path, ".tmp");
|
||||
let backup = with_suffix(path, "~");
|
||||
let write_tmp = || -> std::io::Result<()> {
|
||||
let mut f = File::create(&tmp)?;
|
||||
f.write_all(content)?;
|
||||
f.sync_all()
|
||||
};
|
||||
if let Err(e) = write_tmp() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(format!("Temp-Datei schreiben: {e}"));
|
||||
}
|
||||
// Vorversion sichern (Kopie statt Umbenennen: der Zielpfad existiert so zu jedem Zeitpunkt).
|
||||
if path.exists() {
|
||||
if let Err(e) = fs::copy(path, &backup) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(format!("Sicherung anlegen: {e}"));
|
||||
}
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, path) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(format!("Umbenennen: {e}"));
|
||||
}
|
||||
// Ordner-Eintrag sichern (unter Windows nicht moeglich, dort best effort).
|
||||
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
if let Ok(d) = File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tmpdir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("dossier-atomic-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neue_datei_ohne_sicherung() {
|
||||
let d = tmpdir("neu");
|
||||
let p = d.join("a.obp");
|
||||
save_atomic_impl(&p, b"eins").unwrap();
|
||||
assert_eq!(fs::read(&p).unwrap(), b"eins");
|
||||
assert!(!with_suffix(&p, "~").exists());
|
||||
assert!(!with_suffix(&p, ".tmp").exists());
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ueberschreiben_legt_sicherung_an() {
|
||||
let d = tmpdir("ueber");
|
||||
let p = d.join("a.obp");
|
||||
save_atomic_impl(&p, b"eins").unwrap();
|
||||
save_atomic_impl(&p, b"zwei").unwrap();
|
||||
assert_eq!(fs::read(&p).unwrap(), b"zwei");
|
||||
assert_eq!(fs::read(with_suffix(&p, "~")).unwrap(), b"eins");
|
||||
save_atomic_impl(&p, b"drei").unwrap();
|
||||
assert_eq!(fs::read(with_suffix(&p, "~")).unwrap(), b"zwei");
|
||||
assert!(!with_suffix(&p, ".tmp").exists());
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fehler_laesst_original_unberuehrt() {
|
||||
let d = tmpdir("fehler");
|
||||
let p = d.join("a.obp");
|
||||
save_atomic_impl(&p, b"original").unwrap();
|
||||
// Ein Ordner an der Stelle der Temp-Datei laesst das Schreiben scheitern.
|
||||
fs::create_dir(with_suffix(&p, ".tmp")).unwrap();
|
||||
assert!(save_atomic_impl(&p, b"neu").is_err());
|
||||
assert_eq!(fs::read(&p).unwrap(), b"original");
|
||||
// Nicht existierender Zielordner: Fehler, nichts angelegt.
|
||||
assert!(save_atomic_impl(&d.join("nope").join("b.obp"), b"x").is_err());
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -16,6 +16,9 @@ mod native_embed;
|
||||
// App-Instanzen (OS-Advisory-Lock via `fs4`, siehe lock.rs).
|
||||
mod lock;
|
||||
|
||||
// Absturzsicheres Speichern ([116]): Temp-Datei + fsync + Umbenennen, `<pfad>~` als Sicherung.
|
||||
mod atomic_save;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use tauri::State;
|
||||
|
||||
@@ -31,6 +34,12 @@ fn acquire_project_lock(
|
||||
lock::acquire(&state, &PathBuf::from(path))
|
||||
}
|
||||
|
||||
/// Schreibt eine Projektdatei atomar ([116]); die Vorversion bleibt als `<pfad>~` erhalten.
|
||||
#[tauri::command]
|
||||
fn save_atomic(path: String, content: String) -> Result<(), String> {
|
||||
atomic_save::save_atomic_impl(&PathBuf::from(path), content.as_bytes())
|
||||
}
|
||||
|
||||
/// Gibt einen von dieser Instanz gehaltenen Lock frei. No-op, wenn der Pfad
|
||||
/// nicht gelockt war.
|
||||
#[tauri::command]
|
||||
@@ -280,7 +289,8 @@ pub fn run() {
|
||||
push_native_scene,
|
||||
push_native_walls,
|
||||
acquire_project_lock,
|
||||
release_project_lock
|
||||
release_project_lock,
|
||||
save_atomic
|
||||
]);
|
||||
#[cfg(not(any(feature = "native2d", feature = "native3d")))]
|
||||
let builder = builder.invoke_handler(tauri::generate_handler![
|
||||
@@ -295,7 +305,8 @@ pub fn run() {
|
||||
native2d_frame,
|
||||
native2d_texts,
|
||||
acquire_project_lock,
|
||||
release_project_lock
|
||||
release_project_lock,
|
||||
save_atomic
|
||||
]);
|
||||
|
||||
builder
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
"csp": "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: https://ambientcg.com https://api.ambientcg.com https://geo.admin.ch https://api3.geo.admin.ch https://wms.geo.admin.ch https://data.geo.admin.ch https://overpass-api.de https://nominatim.openstreetmap.org; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost blob: data: https://ambientcg.com https://api.ambientcg.com https://geo.admin.ch https://api3.geo.admin.ch https://wms.geo.admin.ch https://data.geo.admin.ch https://overpass-api.de https://nominatim.openstreetmap.org http://localhost:* http://127.0.0.1:* ws://127.0.0.1:*; object-src 'none'; base-uri 'self'; form-action 'none'",
|
||||
"devCsp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
// Der Aufruf gehört in EIN `setProject` (ein Undo-Schritt).
|
||||
|
||||
import type { Drawing2D, DrawingLevel, Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { applyOps } from "../core/ops";
|
||||
import type { CoreOp } from "../core/ops";
|
||||
import { addItems } from "../core/opsBuild";
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Wächter für die Kern/Hülle-Grenze (docs/core-ui-split.md, Phase A). Es gibt kein ESLint im
|
||||
// Projekt — die Regeln laufen deshalb als Test über die Importzeilen aller Quelldateien.
|
||||
//
|
||||
// 1. Der KERN (model, geometry, plan, io, export, analysis, materials, text, engine) importiert
|
||||
// 1. Der KERN (core, model, geometry, plan, io, export, analysis, materials, text, engine, net) — auch
|
||||
// transitiv über relative Importe importiert
|
||||
// nie die HÜLLE (ui, panels, views, menus, editors, viewport, native, tools, state, commands,
|
||||
// App) und nie React/Zustand/Tauri statisch.
|
||||
// 2. Die HÜLLE holt Funktionen aus `plan/` und `geometry/` nur über die Fassade `src/core`.
|
||||
@@ -14,7 +15,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { dirname, join, normalize, relative, sep } from "node:path";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
const CORE_DIRS = new Set(["core", "model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine"]);
|
||||
const CORE_DIRS = new Set(["core", "model", "geometry", "plan", "io", "export", "analysis", "materials", "text", "engine", "net"]);
|
||||
const SHELL_DIRS = new Set(["ui", "panels", "views", "menus", "editors", "viewport", "native", "tools", "state", "commands"]);
|
||||
const FACADE_DIRS = new Set(["plan", "geometry"]);
|
||||
const FORBIDDEN_PACKAGES = /^(react|react-dom|zustand|@tauri-apps\/.*)$/;
|
||||
@@ -80,6 +81,43 @@ describe("Kern/Hülle-Grenze", () => {
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("der Kern erreicht transitiv keine Hülle und keine UI-Pakete", () => {
|
||||
const violations: string[] = [];
|
||||
const resolve = (target: string): string | null => {
|
||||
for (const c of [`${target}.ts`, `${target}.tsx`, `${target}/index.ts`, `${target}/index.tsx`, target]) {
|
||||
const abs = join(SRC, c);
|
||||
try {
|
||||
if (statSync(abs).isFile()) return abs;
|
||||
} catch {
|
||||
/* nächster Kandidat */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
for (const root of files) {
|
||||
if (!CORE_DIRS.has(top(root))) continue;
|
||||
const seen = new Set<string>([root]);
|
||||
const queue: Array<{ file: string; path: string[] }> = [{ file: root, path: [] }];
|
||||
while (queue.length) {
|
||||
const { file, path } = queue.shift()!;
|
||||
for (const i of importsOf(file)) {
|
||||
const tt = i.target?.split("/")[0];
|
||||
const chain = () => [relative(SRC, root), ...path, i.target ?? i.spec].join(" → ");
|
||||
if (tt && (SHELL_DIRS.has(tt) || tt === "App" || tt === "main")) violations.push(chain());
|
||||
else if (!i.target && FORBIDDEN_PACKAGES.test(i.spec)) violations.push(chain());
|
||||
else if (i.target) {
|
||||
const next = resolve(i.target);
|
||||
if (next && !seen.has(next) && !/\.test\.tsx?$/.test(next)) {
|
||||
seen.add(next);
|
||||
queue.push({ file: next, path: [...path, i.target] });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect([...new Set(violations)]).toEqual([]);
|
||||
});
|
||||
|
||||
it("die Hülle holt plan/ und geometry/ nur über die Fassade src/core", () => {
|
||||
const violations: string[] = [];
|
||||
for (const f of files) {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
import { jsPDF } from "jspdf";
|
||||
import type { Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import type { AreaRow, IvhbOptions } from "../analysis/areaTable";
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// (wie die Fenster-/Türliste, `openingSchedule.ts`).
|
||||
|
||||
import type { Layer, Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { documentFor } from "../core/document";
|
||||
import type { AreaReport, Cell, ReportRow } from "./areaReport";
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import { jsPDF } from "jspdf";
|
||||
import "svg2pdf.js";
|
||||
import type { Layout, LayoutPaperFormat, MasterLayout, Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { legendPlan, legendPrintSvg } from "./legendSvg";
|
||||
import { categoryLayerGroups, enablePdfLayers, type PdfLayers } from "./pdfLayers";
|
||||
import { generatePlan, type Plan } from "../plan/generatePlan";
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// (`areaReport.ts`: `areaReportToCsv` / `areaReportToSvg` / `buildAreaReportPdf`).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { documentFor } from "../core/document";
|
||||
import type { AreaReport, Cell, ReportRow, ReportSection } from "./areaReport";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Die Zahlen rechnet der Kern (`analysis/roomProgram.ts`); hier nur die Beschriftung mit `t()`.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { compareRoomProgram } from "../analysis/roomProgram";
|
||||
import type { CompareSum, Light } from "../analysis/roomProgram";
|
||||
import type { AreaReport, Cell, ReportRow, ReportSection } from "./areaReport";
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import type { jsPDF } from "jspdf";
|
||||
import type { Layout, LayoutTable, LayoutTableSource, Project } from "../model/types";
|
||||
import { t } from "../i18n";
|
||||
import { t } from "../i18n/translate";
|
||||
import { documentFor } from "../core/document";
|
||||
|
||||
export type { LayoutTable, LayoutTableSource };
|
||||
|
||||
@@ -2384,6 +2384,7 @@ export const de = {
|
||||
"startup.previousCrashed": "Dossier wurde beim letzten Mal nicht sauber beendet. Ungesicherte Arbeit wird beim Öffnen zur Wiederherstellung angeboten.",
|
||||
"project.open.failed": "Projekt konnte nicht geöffnet werden.",
|
||||
"core.restarted": "Interner Fehler im Kern – der Vorgang wurde abgebrochen, das Projekt ist wiederhergestellt. Der Rückgängig-Verlauf wurde dabei geleert.",
|
||||
"project.save.failed": "Projekt konnte nicht gespeichert werden; die Datei und die Wiederherstellungskopie bleiben unverändert.",
|
||||
"menu.native.clashCheck": "Kollisionsprüfung …",
|
||||
"menu.native.kennzahlen": "Kennzahlen und Raumprogramm …",
|
||||
"kennzahlen.summary": "GF {gf} m² · aGF {agf} m² · GV {gv} m³",
|
||||
|
||||
@@ -2334,6 +2334,7 @@ export const en: Record<TranslationKey, string> = {
|
||||
"startup.previousCrashed": "Dossier did not shut down cleanly last time. Unsaved work is offered for recovery when you open it.",
|
||||
"project.open.failed": "Project could not be opened.",
|
||||
"core.restarted": "Internal error in the core – the operation was aborted and the project has been restored. The undo history was cleared.",
|
||||
"project.save.failed": "Project could not be saved; the file and the recovery copy are unchanged.",
|
||||
"menu.native.clashCheck": "Clash detection …",
|
||||
"menu.native.kennzahlen": "Key figures and room programme …",
|
||||
"kennzahlen.summary": "GFA {gf} m² · usable {agf} m² · volume {gv} m³",
|
||||
|
||||
+5
-84
@@ -1,94 +1,15 @@
|
||||
// i18n-Schicht — eine einzige Übersetzungsfunktion `t(key, params?)` plus ein
|
||||
// optionaler React-Hook `useT`. Default-Sprache ist Deutsch; das deutsche
|
||||
// Wörterbuch (de.ts) hält die EXAKTEN bisherigen UI-Texte, sodass die Umstellung
|
||||
// optisch nichts ändert. en.ts beweist die Übersetzbarkeit.
|
||||
//
|
||||
// Bewusst minimal gehalten: ein modulweiter „current language" + Wörterbuch-
|
||||
// Lookup mit {param}-Interpolation. Kein Provider-Zwang — t(...) ist überall
|
||||
// direkt aufrufbar; useT() liefert dieselbe Funktion und re-rendert Komponenten
|
||||
// beim Sprachwechsel (subscribe), falls je ein Umschalter gebaut wird.
|
||||
//
|
||||
// Identifier/Keys bleiben englisch (DOSSIER-Namespacing); nur die Wörterbuch-
|
||||
// Werte sind übersetzbarer Text.
|
||||
// i18n-Fassade: React-freier Kern in ./translate (für Kern-Module), dazu der React-Hook `useT`.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { de } from "./de";
|
||||
import { en } from "./en";
|
||||
import type { TranslationKey } from "./de";
|
||||
import { getLanguage, subscribeLanguage, t } from "./translate";
|
||||
|
||||
export type { TranslationKey } from "./de";
|
||||
|
||||
/** Unterstützte Sprachen. Default ist „de". */
|
||||
export type Language = "de" | "en";
|
||||
|
||||
/** Wörterbücher je Sprache. de ist die Quelle der Keys (Default-Sprache). */
|
||||
const DICTS: Record<Language, Record<TranslationKey, string>> = { de, en };
|
||||
|
||||
/** Werte für die Platzhalter-Interpolation (`{name}` → params.name). */
|
||||
export type TParams = Record<string, string | number>;
|
||||
|
||||
// ── Modulweiter Sprachzustand + Abonnenten (für useT) ──────────────────────
|
||||
|
||||
let currentLanguage: Language = "de";
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
/** Aktuell gewählte Sprache. */
|
||||
export function getLanguage(): Language {
|
||||
return currentLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sprache umschalten. Benachrichtigt abonnierte Komponenten (useT), damit sie
|
||||
* mit den neuen Texten neu rendern. (Noch kein UI-Umschalter — die Naht ist
|
||||
* aber vorhanden und verdrahtet.)
|
||||
*/
|
||||
export function setLanguage(lang: Language): void {
|
||||
if (lang === currentLanguage) return;
|
||||
currentLanguage = lang;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
// ── Kern: Lookup + Interpolation ───────────────────────────────────────────
|
||||
|
||||
/** Ersetzt `{name}`-Platzhalter im Wert durch die übergebenen Parameter. */
|
||||
function interpolate(value: string, params?: TParams): string {
|
||||
if (!params) return value;
|
||||
return value.replace(/\{(\w+)\}/g, (match, name: string) =>
|
||||
name in params ? String(params[name]) : match,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Übersetzt einen Key in der aktuellen Sprache mit optionaler {param}-
|
||||
* Interpolation. Fehlt der Key in der gewählten Sprache, greift Deutsch als
|
||||
* Fallback; fehlt er auch dort, wird der Key selbst zurückgegeben (sichtbar,
|
||||
* damit fehlende Texte auffallen statt leer zu bleiben).
|
||||
*/
|
||||
export function t(key: TranslationKey | string, params?: TParams): string {
|
||||
const dict = DICTS[currentLanguage];
|
||||
const value =
|
||||
(dict as Record<string, string>)[key] ??
|
||||
(de as Record<string, string>)[key] ??
|
||||
key;
|
||||
return interpolate(value, params);
|
||||
}
|
||||
|
||||
// ── React-Hook ─────────────────────────────────────────────────────────────
|
||||
export * from "./translate";
|
||||
|
||||
/**
|
||||
* Hook-Variante: liefert dieselbe `t`-Funktion, abonniert aber den
|
||||
* Sprachzustand, sodass die Komponente beim Sprachwechsel neu rendert. In den
|
||||
* meisten Komponenten reicht der direkte `t`-Import; useT() ist für den Fall
|
||||
* gedacht, dass ein Live-Sprachumschalter existiert.
|
||||
* Sprachzustand, sodass die Komponente beim Sprachwechsel neu rendert.
|
||||
*/
|
||||
export function useT(): typeof t {
|
||||
useSyncExternalStore(
|
||||
(cb) => {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
},
|
||||
getLanguage,
|
||||
getLanguage,
|
||||
);
|
||||
useSyncExternalStore(subscribeLanguage, getLanguage, getLanguage);
|
||||
return t;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// i18n-Kern (React-frei) — von Kern-Modulen importierbar. Der Hook `useT` liegt in index.ts.
|
||||
// i18n-Schicht — eine einzige Übersetzungsfunktion `t(key, params?)` plus ein
|
||||
// optionaler React-Hook `useT`. Default-Sprache ist Deutsch; das deutsche
|
||||
// Wörterbuch (de.ts) hält die EXAKTEN bisherigen UI-Texte, sodass die Umstellung
|
||||
// optisch nichts ändert. en.ts beweist die Übersetzbarkeit.
|
||||
//
|
||||
// Bewusst minimal gehalten: ein modulweiter „current language" + Wörterbuch-
|
||||
// Lookup mit {param}-Interpolation. Kein Provider-Zwang — t(...) ist überall
|
||||
// direkt aufrufbar; useT() liefert dieselbe Funktion und re-rendert Komponenten
|
||||
// beim Sprachwechsel (subscribe), falls je ein Umschalter gebaut wird.
|
||||
//
|
||||
// Identifier/Keys bleiben englisch (DOSSIER-Namespacing); nur die Wörterbuch-
|
||||
// Werte sind übersetzbarer Text.
|
||||
|
||||
import { de } from "./de";
|
||||
import { en } from "./en";
|
||||
import type { TranslationKey } from "./de";
|
||||
|
||||
export type { TranslationKey } from "./de";
|
||||
|
||||
/** Unterstützte Sprachen. Default ist „de". */
|
||||
export type Language = "de" | "en";
|
||||
|
||||
/** Wörterbücher je Sprache. de ist die Quelle der Keys (Default-Sprache). */
|
||||
const DICTS: Record<Language, Record<TranslationKey, string>> = { de, en };
|
||||
|
||||
/** Werte für die Platzhalter-Interpolation (`{name}` → params.name). */
|
||||
export type TParams = Record<string, string | number>;
|
||||
|
||||
// ── Modulweiter Sprachzustand + Abonnenten (für useT) ──────────────────────
|
||||
|
||||
let currentLanguage: Language = "de";
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
/** Aktuell gewählte Sprache. */
|
||||
export function getLanguage(): Language {
|
||||
return currentLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sprache umschalten. Benachrichtigt abonnierte Komponenten (useT), damit sie
|
||||
* mit den neuen Texten neu rendern. (Noch kein UI-Umschalter — die Naht ist
|
||||
* aber vorhanden und verdrahtet.)
|
||||
*/
|
||||
export function setLanguage(lang: Language): void {
|
||||
if (lang === currentLanguage) return;
|
||||
currentLanguage = lang;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
// ── Kern: Lookup + Interpolation ───────────────────────────────────────────
|
||||
|
||||
/** Ersetzt `{name}`-Platzhalter im Wert durch die übergebenen Parameter. */
|
||||
function interpolate(value: string, params?: TParams): string {
|
||||
if (!params) return value;
|
||||
return value.replace(/\{(\w+)\}/g, (match, name: string) =>
|
||||
name in params ? String(params[name]) : match,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Übersetzt einen Key in der aktuellen Sprache mit optionaler {param}-
|
||||
* Interpolation. Fehlt der Key in der gewählten Sprache, greift Deutsch als
|
||||
* Fallback; fehlt er auch dort, wird der Key selbst zurückgegeben (sichtbar,
|
||||
* damit fehlende Texte auffallen statt leer zu bleiben).
|
||||
*/
|
||||
export function t(key: TranslationKey | string, params?: TParams): string {
|
||||
const dict = DICTS[currentLanguage];
|
||||
const value =
|
||||
(dict as Record<string, string>)[key] ??
|
||||
(de as Record<string, string>)[key] ??
|
||||
key;
|
||||
return interpolate(value, params);
|
||||
}
|
||||
|
||||
/** Abo für den Sprachzustand (für `useT`). */
|
||||
export function subscribeLanguage(cb: () => void): () => void {
|
||||
listeners.add(cb);
|
||||
return () => listeners.delete(cb);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { initCore } from "./core";
|
||||
import { getLanguage, setLanguage } from "./i18n";
|
||||
import type { Language } from "./i18n";
|
||||
import { applyThemeMode, getStoredThemeMode } from "./theme/themeMode";
|
||||
import "material-symbols/outlined.css";
|
||||
import "./styles.css";
|
||||
import "./text/fonts.css";
|
||||
|
||||
|
||||
@@ -118,6 +118,7 @@ export async function openProjectFileAtPath(path: string): Promise<OpenedProject
|
||||
* @param projectName `project.name` für den Standard-Dateinamen (Fallback "projekt").
|
||||
* @param onSavedPath Optionaler Callback mit dem gewählten Pfad (Zuletzt-
|
||||
* geöffnet-Liste, s. state/recentProjects.ts).
|
||||
* Schreibt atomar ([116]); wirft `SaveError`, wenn das Schreiben scheitert.
|
||||
*/
|
||||
export async function saveProjectFile(
|
||||
json: string,
|
||||
@@ -125,7 +126,7 @@ export async function saveProjectFile(
|
||||
onSavedPath?: (path: string) => void,
|
||||
): Promise<boolean> {
|
||||
const filename = `${projectName || "projekt"}.${PROJECT_EXT}`;
|
||||
return saveTextFile(json, filename, "application/json", PROJECT_DIALOG_FILTERS, onSavedPath);
|
||||
return saveTextFile(json, filename, "application/json", PROJECT_DIALOG_FILTERS, onSavedPath, true);
|
||||
}
|
||||
|
||||
// ── Lock gegen Doppelöffnung (nur Tauri) ────────────────────────────────────
|
||||
|
||||
@@ -49,3 +49,34 @@ describe("saveTextFile", () => {
|
||||
await expect(saveTextFile("x", "a.bin")).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveTextFile atomar ([116])", () => {
|
||||
async function withTauri(invoke: (cmd: string, args: unknown) => Promise<unknown>) {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal("window", { __TAURI_INTERNALS__: {} });
|
||||
vi.doMock("@tauri-apps/plugin-dialog", () => ({ save: async () => "/tmp/x/a.obp" }));
|
||||
vi.doMock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
return import("./saveFile");
|
||||
}
|
||||
|
||||
it("ruft save_atomic mit Pfad und Inhalt und meldet den Pfad erst danach", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const m = await withTauri(async (cmd, args) => void calls.push([cmd, args]));
|
||||
const saved: string[] = [];
|
||||
const ok = await m.saveTextFile("{}", "a.obp", "application/json", undefined, (p) => saved.push(p), true);
|
||||
expect(ok).toBe(true);
|
||||
expect(calls).toEqual([["save_atomic", { path: "/tmp/x/a.obp", content: "{}" }]]);
|
||||
expect(saved).toEqual(["/tmp/x/a.obp"]);
|
||||
});
|
||||
|
||||
it("wirft SaveError bei Fehler, ohne Download-Fallback und ohne Pfad-Callback", async () => {
|
||||
const m = await withTauri(async () => {
|
||||
throw "Umbenennen: Permission denied";
|
||||
});
|
||||
const saved: string[] = [];
|
||||
await expect(
|
||||
m.saveTextFile("{}", "a.obp", "application/json", undefined, (p) => saved.push(p), true),
|
||||
).rejects.toBeInstanceOf(m.SaveError);
|
||||
expect(saved).toEqual([]);
|
||||
});
|
||||
});
|
||||
+29
-2
@@ -12,6 +12,26 @@ function isTauri(): boolean {
|
||||
|
||||
let warnedFallback = false;
|
||||
|
||||
/** Schreiben in die Zieldatei ist gescheitert ([116]); die bisherige Datei ist unverändert.
|
||||
* Wird NICHT auf den Browser-Download zurückgefallen — der Aufrufer meldet es dem Nutzer. */
|
||||
export class SaveError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "SaveError";
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomar schreiben über den Rust-Befehl `save_atomic` (Temp-Datei + fsync + Umbenennen,
|
||||
* Vorversion als `<pfad>~`). Wirft {@link SaveError}. */
|
||||
export async function writeFileAtomic(path: string, content: string): Promise<void> {
|
||||
try {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
await invoke("save_atomic", { path, content });
|
||||
} catch (err) {
|
||||
throw new SaveError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
/** Datei-Endungsfilter fuer den nativen Speichern-/Oeffnen-Dialog (Tauri). */
|
||||
export interface FileDialogFilter {
|
||||
name: string;
|
||||
@@ -29,6 +49,8 @@ export interface FileDialogFilter {
|
||||
* @param onSavedPath Optionaler Callback mit dem gewaehlten Pfad, NUR bei
|
||||
* erfolgreichem Tauri-Speichern (z. B. fuer die Zuletzt-geoeffnet-Liste,
|
||||
* s. state/recentProjects.ts) — additiv, aendert den Rueckgabewert nicht.
|
||||
* @param atomic Absturzsicher schreiben ([116], `writeFileAtomic`): bei Fehler wird
|
||||
* {@link SaveError} geworfen statt auf den Download zurückzufallen.
|
||||
* @returns `true` wenn geschrieben/geladen wurde, `false` bei Abbruch (Dialog
|
||||
* ohne Pfad). Bei einem Tauri-Fehler wird auf den Browser-Fallback
|
||||
* zurueckgefallen.
|
||||
@@ -39,17 +61,22 @@ export async function saveTextFile(
|
||||
mime = "application/octet-stream",
|
||||
filters?: FileDialogFilter[],
|
||||
onSavedPath?: (path: string) => void,
|
||||
atomic = false,
|
||||
): Promise<boolean> {
|
||||
if (isTauri()) {
|
||||
try {
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const path = await save({ defaultPath: defaultName, filters });
|
||||
if (!path) return false; // Nutzer hat abgebrochen
|
||||
const { writeTextFile } = await import("@tauri-apps/plugin-fs");
|
||||
await writeTextFile(path, content);
|
||||
if (atomic) await writeFileAtomic(path, content);
|
||||
else {
|
||||
const { writeTextFile } = await import("@tauri-apps/plugin-fs");
|
||||
await writeTextFile(path, content);
|
||||
}
|
||||
onSavedPath?.(path);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err instanceof SaveError) throw err;
|
||||
if (!warnedFallback) {
|
||||
warnedFallback = true;
|
||||
console.warn(
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// [117] Die CSP-Quelle (scripts/csp.cjs) deckt die netFetch-Hosts ab und steht wörtlich in tauri.conf.json.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ALLOWED_HOSTS } from "./net";
|
||||
|
||||
const { buildCsp, NET_HOSTS } = createRequire(import.meta.url)("../../scripts/csp.cjs") as {
|
||||
buildCsp: () => string;
|
||||
NET_HOSTS: string[];
|
||||
};
|
||||
|
||||
describe("CSP", () => {
|
||||
it("connect-src enthält genau die Remote-Hosts von ALLOWED_HOSTS", () => {
|
||||
const remote = ALLOWED_HOSTS.filter((h) => h !== "localhost" && h !== "127.0.0.1");
|
||||
expect([...NET_HOSTS].sort()).toEqual([...remote].sort());
|
||||
const connect = buildCsp().split("; ").find((d) => d.startsWith("connect-src "))!;
|
||||
for (const h of remote) expect(connect).toContain(`https://${h}`);
|
||||
});
|
||||
it("tauri.conf.json trägt dieselbe Richtlinie", () => {
|
||||
const conf = JSON.parse(readFileSync("src-tauri/tauri.conf.json", "utf8"));
|
||||
expect(conf.app.security.csp).toBe(buildCsp());
|
||||
});
|
||||
it("kein unsafe-eval, keine Inline-Skripte", () => {
|
||||
const script = buildCsp().split("; ").find((d) => d.startsWith("script-src "))!;
|
||||
expect(script).toBe("script-src 'self' 'wasm-unsafe-eval'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox -4.2 0 37.045 17.778
|
||||
bytes 344306
|
||||
circle 4
|
||||
line 1261
|
||||
polygon 1529
|
||||
rect 1
|
||||
svg 1
|
||||
text 4
|
||||
hash ac47902c2752e848
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 35.22
|
||||
bytes 339680
|
||||
circle 14
|
||||
line 3498
|
||||
path 8
|
||||
polygon 91
|
||||
rect 1
|
||||
svg 1
|
||||
text 36
|
||||
hash 30888ca0d5cb84be
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 35.22
|
||||
bytes 343059
|
||||
circle 14
|
||||
line 3498
|
||||
path 8
|
||||
polygon 91
|
||||
rect 1
|
||||
svg 1
|
||||
text 36
|
||||
hash f96ebde7ba7f7e74
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 148973
|
||||
circle 16
|
||||
line 861
|
||||
path 68
|
||||
polygon 260
|
||||
rect 1
|
||||
svg 1
|
||||
text 123
|
||||
hash aefdd0fe3c4658bd
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -41.5 0 95 63.6
|
||||
bytes 149368
|
||||
circle 16
|
||||
line 861
|
||||
path 68
|
||||
polygon 260
|
||||
rect 1
|
||||
svg 1
|
||||
text 123
|
||||
hash 65c62fa0ef5ee339
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 35.22
|
||||
bytes 425217
|
||||
circle 14
|
||||
line 4040
|
||||
path 40
|
||||
polygon 236
|
||||
rect 1
|
||||
svg 1
|
||||
text 93
|
||||
hash 961473ba9c3e6937
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 35.22
|
||||
bytes 428731
|
||||
circle 14
|
||||
line 4040
|
||||
path 40
|
||||
polygon 236
|
||||
rect 1
|
||||
svg 1
|
||||
text 93
|
||||
hash 6f37dfa59b4e84a0
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 38.11
|
||||
bytes 86366
|
||||
circle 14
|
||||
line 501
|
||||
path 29
|
||||
polygon 113
|
||||
rect 1
|
||||
svg 1
|
||||
text 74
|
||||
hash cd3c20b2431eec2e
|
||||
@@ -0,0 +1,10 @@
|
||||
viewBox -16.5 0 49 38.11
|
||||
bytes 86522
|
||||
circle 14
|
||||
line 501
|
||||
path 29
|
||||
polygon 113
|
||||
rect 1
|
||||
svg 1
|
||||
text 74
|
||||
hash 53435c6a8ca1a431
|
||||
@@ -0,0 +1,53 @@
|
||||
meshes [1849]
|
||||
meshes[].color [3] x1849
|
||||
meshes[].indices [108] x6
|
||||
meshes[].indices [156648]
|
||||
meshes[].indices [348] x6
|
||||
meshes[].indices [36] x1816
|
||||
meshes[].indices [372]
|
||||
meshes[].indices [4032]
|
||||
meshes[].indices [60] x9
|
||||
meshes[].indices [72]
|
||||
meshes[].indices [84] x2
|
||||
meshes[].indices [96] x6
|
||||
meshes[].positions [1044] x6
|
||||
meshes[].positions [108] x30
|
||||
meshes[].positions [180] x9
|
||||
meshes[].positions [192]
|
||||
meshes[].positions [216]
|
||||
meshes[].positions [24] x1781
|
||||
meshes[].positions [252] x2
|
||||
meshes[].positions [2688]
|
||||
meshes[].positions [288] x6
|
||||
meshes[].positions [324] x6
|
||||
meshes[].positions [72] x5
|
||||
meshes[].positions [78840]
|
||||
roofLayers [59]
|
||||
roofLayers[].color [3] x59
|
||||
roofLayers[].normal [3] x59
|
||||
roofLayers[].polygon [4] x53
|
||||
roofLayers[].polygon [5] x6
|
||||
roofLayers[].polygon[] [3] x242
|
||||
slabs [102]
|
||||
slabs[].color [3] x102
|
||||
slabs[].outline [12]
|
||||
slabs[].outline [14] x5
|
||||
slabs[].outline [21] x4
|
||||
slabs[].outline [24]
|
||||
slabs[].outline [33] x5
|
||||
slabs[].outline [4] x81
|
||||
slabs[].outline [51] x5
|
||||
slabs[].outline[] [2] x934
|
||||
walls [1508]
|
||||
walls[].color [3] x1508
|
||||
walls[].end [2] x1508
|
||||
walls[].endCut [4] x1139
|
||||
walls[].holes [1] x84
|
||||
walls[].holes [2] x25
|
||||
walls[].holes [3] x14
|
||||
walls[].layers [0] x1508
|
||||
walls[].start [2] x1508
|
||||
walls[].startCut [4] x1137
|
||||
walls[].topDrop [2] x112
|
||||
walls[].topPlane [3] x268
|
||||
hash cd9596786d4adacb
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox 4.457 0 21.343 17.778
|
||||
bytes 44167
|
||||
circle 3
|
||||
line 148
|
||||
polygon 169
|
||||
rect 1
|
||||
svg 1
|
||||
text 3
|
||||
hash 3310ddbc4a0ea666
|
||||
@@ -0,0 +1,7 @@
|
||||
viewBox 0.1 0 6.8 7.586
|
||||
bytes 8483
|
||||
line 31
|
||||
polygon 42
|
||||
rect 1
|
||||
svg 1
|
||||
hash c9caba6eee20fbd9
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox -0.672 0 6.345 5.345
|
||||
bytes 15919
|
||||
line 67
|
||||
path 8
|
||||
polygon 61
|
||||
rect 1
|
||||
svg 1
|
||||
text 7
|
||||
hash 97bd11bea3bf9d08
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox -0.672 0 6.345 5.345
|
||||
bytes 15939
|
||||
line 67
|
||||
path 8
|
||||
polygon 61
|
||||
rect 1
|
||||
svg 1
|
||||
text 7
|
||||
hash 7dfca568eb0b0d41
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox -0.9 0 6.8 5.8
|
||||
bytes 7180
|
||||
line 35
|
||||
path 4
|
||||
polygon 23
|
||||
rect 1
|
||||
svg 1
|
||||
text 4
|
||||
hash 5b480a1ff81665ec
|
||||
@@ -0,0 +1,9 @@
|
||||
viewBox -0.9 0 6.8 5.8
|
||||
bytes 7202
|
||||
line 35
|
||||
path 4
|
||||
polygon 23
|
||||
rect 1
|
||||
svg 1
|
||||
text 4
|
||||
hash f1c8c391382719b8
|
||||
@@ -0,0 +1,31 @@
|
||||
meshes [44]
|
||||
meshes[].color [3] x44
|
||||
meshes[].indices [36] x42
|
||||
meshes[].indices [540]
|
||||
meshes[].indices [60]
|
||||
meshes[].positions [120]
|
||||
meshes[].positions [24] x42
|
||||
meshes[].positions [360]
|
||||
roofLayers [2]
|
||||
roofLayers[].color [3] x2
|
||||
roofLayers[].normal [3] x2
|
||||
roofLayers[].polygon [4] x2
|
||||
roofLayers[].polygon[] [3] x8
|
||||
slabs [3]
|
||||
slabs[].color [3] x3
|
||||
slabs[].cut.lineColor [3]
|
||||
slabs[].outline [4] x3
|
||||
slabs[].outline[] [2] x12
|
||||
walls [47]
|
||||
walls[].color [3] x47
|
||||
walls[].cut.lineColor [3] x11
|
||||
walls[].end [2] x47
|
||||
walls[].endCut [4] x47
|
||||
walls[].holes [1] x5
|
||||
walls[].holes [2] x5
|
||||
walls[].layers [0] x47
|
||||
walls[].start [2] x47
|
||||
walls[].startCut [4] x47
|
||||
walls[].topDrop [2] x6
|
||||
walls[].topPlane [3] x6
|
||||
hash 43431f51d1e44e8b
|
||||
@@ -0,0 +1,7 @@
|
||||
viewBox 0.1 0 6.8 7.586
|
||||
bytes 7242
|
||||
line 31
|
||||
polygon 31
|
||||
rect 1
|
||||
svg 1
|
||||
hash 64ff798e38d40dd0
|
||||
@@ -0,0 +1,101 @@
|
||||
// [119] Referenz-Ausgaben: Plan (je Geschoss, 1:100 und 1:50), ein Schnitt, eine Ansicht und die
|
||||
// 3D-Zusammenfassung beider Musterprojekte als lesbarer Digest (Zähler, Rahmen, Hash der gerundeten
|
||||
// Zahlen) gegen eingecheckte Dateien in src/plan/__golden__. Gewollte Änderung übernehmen mit
|
||||
// npx vitest run -u src/plan/golden.test.ts
|
||||
// und den Diff der Dateien im Commit ansehen. Zahlen sind gerundet (Plan 1e-3 m, 3D 1e-4 m).
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { computeSection, generateElevationPlan, generatePlan, generateSectionPlan, planToSvgString, projectToModel3d } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
const roundNums = (s: string, dec: number): string =>
|
||||
s.replace(/-?\d+\.\d+(?:e-?\d+)?/g, (m) => {
|
||||
const v = Number(Number(m).toFixed(dec));
|
||||
return String(Object.is(v, -0) ? 0 : v);
|
||||
});
|
||||
const sha = (s: string): string => createHash("sha256").update(s).digest("hex").slice(0, 16);
|
||||
|
||||
function svgDigest(svg: string): string {
|
||||
const s = roundNums(svg, 3);
|
||||
const tags = new Map<string, number>();
|
||||
for (const m of s.matchAll(/<([a-z]+)\b/g)) tags.set(m[1], (tags.get(m[1]) ?? 0) + 1);
|
||||
const viewBox = /viewBox="([^"]*)"/.exec(s)?.[1] ?? "-";
|
||||
const lines = [`viewBox ${viewBox}`, `bytes ${s.length}`];
|
||||
for (const [k, v] of [...tags].sort()) lines.push(`${k} ${v}`);
|
||||
lines.push(`hash ${sha(s)}`);
|
||||
return lines.join("\n") + "\n";
|
||||
}
|
||||
|
||||
// Beliebige Struktur → Zähler je Feld (Länge von Listen/Puffern) + Hash der gerundeten Zahlen.
|
||||
function structDigest(o: unknown): string {
|
||||
const lines: string[] = [];
|
||||
const h = createHash("sha256");
|
||||
const walk = (v: unknown, path: string): void => {
|
||||
if (typeof v === "number") {
|
||||
h.update(path + "=" + Number(v.toFixed(4)) + ";");
|
||||
} else if (ArrayBuffer.isView(v)) {
|
||||
const a = Array.from(v as unknown as ArrayLike<number>);
|
||||
lines.push(`${path} [${a.length}]`);
|
||||
h.update(path + ":" + a.map((x) => Number(x.toFixed(4))).join(",") + ";");
|
||||
} else if (Array.isArray(v)) {
|
||||
lines.push(`${path} [${v.length}]`);
|
||||
v.forEach((x, i) => walk(x, `${path}[${i}]`));
|
||||
} else if (v && typeof v === "object") {
|
||||
for (const k of Object.keys(v).sort()) walk((v as Record<string, unknown>)[k], path ? `${path}.${k}` : k);
|
||||
} else {
|
||||
h.update(path + "=" + String(v) + ";");
|
||||
}
|
||||
};
|
||||
walk(o, "");
|
||||
// Elementweise Pfade (mit Index) nur im Hash, im Text nur die Feldzähler ohne Index
|
||||
const counts = new Map<string, number>();
|
||||
for (const l of lines) {
|
||||
const key = l.replace(/\[\d+\](?=[. ])/g, "[]");
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
}
|
||||
return [...counts].sort().map(([k, n]) => `${k}${n > 1 ? ` x${n}` : ""}`).join("\n") + `\nhash ${h.digest("hex").slice(0, 16)}\n`;
|
||||
}
|
||||
|
||||
const projects: [string, () => Project][] = [
|
||||
["muster", () => sampleProject],
|
||||
["komplex", buildComplexSampleProject],
|
||||
];
|
||||
|
||||
for (const [name, make] of projects) {
|
||||
describe(`Golden ${name}`, () => {
|
||||
const p = make();
|
||||
const codes = new Set(p.layers.map((l) => l.code));
|
||||
|
||||
for (const lvl of p.drawingLevels.filter((l) => l.kind === "floor")) {
|
||||
for (const scale of [100, 50]) {
|
||||
it(`Grundriss ${lvl.id} 1:${scale}`, async () => {
|
||||
const svg = planToSvgString(generatePlan(p, lvl.id, codes, undefined, "mittel", false, false, true, scale), { scaleDenominator: scale });
|
||||
await expect(svgDigest(svg)).toMatchFileSnapshot(`__golden__/${name}-grundriss-${lvl.id}-${scale}.txt`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
it("Schnitt", async () => {
|
||||
const sec = p.drawingLevels.find((l) => l.kind === "section");
|
||||
if (!sec) return;
|
||||
const out = await computeSection(p, sec);
|
||||
expect(out).toBeTruthy();
|
||||
const svg = planToSvgString(generateSectionPlan(out!, false, { visibleCodes: codes, hiddenLines: sec.hiddenLines, openings: true, scaleDenominator: 100 }), { scaleDenominator: 100 });
|
||||
await expect(svgDigest(svg)).toMatchFileSnapshot(`__golden__/${name}-schnitt-${sec.id}.txt`);
|
||||
}, 30_000);
|
||||
|
||||
it("Ansicht", async () => {
|
||||
const el = p.drawingLevels.find((l) => l.kind === "elevation");
|
||||
if (!el) return;
|
||||
const plan = generateElevationPlan(p, el, { scaleDenominator: 100 });
|
||||
expect(plan).toBeTruthy();
|
||||
await expect(svgDigest(planToSvgString(plan!, { scaleDenominator: 100 }))).toMatchFileSnapshot(`__golden__/${name}-ansicht-${el.id}.txt`);
|
||||
});
|
||||
|
||||
it("3D-Modell", async () => {
|
||||
await expect(structDigest(projectToModel3d(p))).toMatchFileSnapshot(`__golden__/${name}-model3d.txt`);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -370,15 +370,22 @@ export function useProjectFileActions(
|
||||
const json = serializeProject(project);
|
||||
return saveProjectFile(json, project.name, (path) =>
|
||||
addRecentProject(path, project.name || "modell"),
|
||||
).then((saved) => {
|
||||
if (saved) {
|
||||
lastSavedProjectRef.current = project;
|
||||
void clearAutosave(openedProjectPathRef.current);
|
||||
void clearAutosave(null);
|
||||
autosaveTracker.cleared();
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
).then(
|
||||
(saved) => {
|
||||
if (saved) {
|
||||
lastSavedProjectRef.current = project;
|
||||
// Erst nach erfolgreichem Umbenennen ([116]) — bei Fehler bleibt die Kopie.
|
||||
void clearAutosave(openedProjectPathRef.current);
|
||||
void clearAutosave(null);
|
||||
autosaveTracker.cleared();
|
||||
}
|
||||
return saved;
|
||||
},
|
||||
(e) => {
|
||||
notify(`${t("project.save.failed")} ${e instanceof Error ? e.message : String(e)}`, "error");
|
||||
return false;
|
||||
},
|
||||
);
|
||||
};
|
||||
// „Neu" (Datei-Menü): leeres Projekt, wie am Startbildschirm — löst dabei
|
||||
// einen evtl. gehaltenen Datei-Lock der bisherigen Projektdatei und vergisst
|
||||
|
||||
@@ -119,3 +119,33 @@ describe("docToHtml — sizeUnit reicht bis in jeden Run-Span durch", () => {
|
||||
expect(html).toContain("font-size:1.5em");
|
||||
});
|
||||
});
|
||||
|
||||
describe("docToHtml: Bereinigung nicht vertrauenswürdiger Dateiinhalte ([117])", () => {
|
||||
const evil = (over: Record<string, unknown>, text = "x"): RichTextDoc =>
|
||||
({
|
||||
version: 1,
|
||||
paragraphs: [{ runs: [{ text, marks: { ...over } }] }],
|
||||
}) as unknown as RichTextDoc;
|
||||
|
||||
it("escapt Tags im Text", () => {
|
||||
const html = docToHtml(evil({}, '<img src=x onerror=alert(1)><script>1</script>'));
|
||||
expect(html).not.toContain("<img");
|
||||
expect(html).not.toContain("<script");
|
||||
expect(html).toContain("<img");
|
||||
});
|
||||
it("verwirft Schrift und Farbe mit CSS-/Attribut-Einschleusung", () => {
|
||||
const html = docToHtml(evil({ font: 'a";onmouseover="alert(1)', color: "red;background:url(https://evil/x)" }));
|
||||
expect(html).not.toContain("onmouseover");
|
||||
expect(html).not.toContain("url(");
|
||||
expect(html).not.toContain("font-family");
|
||||
});
|
||||
it("behält harmlose Werte", () => {
|
||||
const html = docToHtml(evil({ font: "Inter", color: "#aabbcc" }));
|
||||
expect(html).toContain("font-family:Inter");
|
||||
expect(html).toContain("color:#aabbcc");
|
||||
});
|
||||
it("Absatz-Ausrichtung nur aus der Positivliste", () => {
|
||||
const doc = { version: 1, paragraphs: [{ align: 'center;position:fixed', runs: [] }] } as unknown as RichTextDoc;
|
||||
expect(docToHtml(doc)).not.toContain("position");
|
||||
});
|
||||
});
|
||||
+31
-4
@@ -27,6 +27,31 @@ function escapeAttr(s: string): string {
|
||||
|
||||
// ── Gemeinsame Mark→Stil-Zuordnung ──────────────────────────────────────────
|
||||
|
||||
// ── CSS-Werte aus Dateien ([117]) ───────────────────────────────────────────
|
||||
// Rich-Text kommt auch aus importierten Projektdateien und landet per `innerHTML` im Editor. Der Text ist
|
||||
// escaped; die Stil-Werte (Farbe, Schriftname, Ausrichtung, Zeilenhöhe) werden hier auf eine Positivliste
|
||||
// beschränkt, damit keine CSS-Einschleusung (`;`, `url(…)`, `position:fixed` …) möglich ist.
|
||||
|
||||
/** Farbe: `#rgb[a]`/`#rrggbb[aa]`, `rgb()/rgba()/hsl()` mit Zahlen, `var(--name)` oder ein Farbwort. */
|
||||
export function safeCssColor(v: unknown): string | undefined {
|
||||
if (typeof v !== "string") return undefined;
|
||||
const c = v.trim();
|
||||
if (/^#[0-9a-f]{3,8}$/i.test(c)) return c;
|
||||
if (/^(rgb|rgba|hsl|hsla)\(\s*[0-9.%\s,/-]+\)$/i.test(c)) return c;
|
||||
if (/^var\(--[a-z0-9-]+\)$/i.test(c)) return c;
|
||||
if (/^[a-z]{3,20}$/i.test(c)) return c;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Schriftname: Buchstaben, Ziffern, Leerzeichen, `-`, `,`, `_`, `.`, Anführungszeichen (kein `;(){}:/\\`). */
|
||||
export function safeFontFamily(v: unknown): string | undefined {
|
||||
if (typeof v !== "string") return undefined;
|
||||
const f = v.trim();
|
||||
return f.length > 0 && f.length <= 120 && /^[\p{L}\p{N} _.,'"-]+$/u.test(f) ? f : undefined;
|
||||
}
|
||||
|
||||
const SAFE_ALIGN = new Set(["left", "center", "right", "justify"]);
|
||||
|
||||
/** Kombiniert underline + strike zu einem CSS/SVG-text-decoration-Wert. */
|
||||
function textDecoration(marks: Marks): string | undefined {
|
||||
const parts: string[] = [];
|
||||
@@ -67,11 +92,13 @@ export function runCssProps(
|
||||
if (marks.italic) css["font-style"] = "italic";
|
||||
const deco = textDecoration(marks);
|
||||
if (deco) css["text-decoration"] = deco;
|
||||
if (marks.font) css["font-family"] = marks.font;
|
||||
const font = safeFontFamily(marks.font);
|
||||
if (font) css["font-family"] = font;
|
||||
const sizePt = (marks.sizePt ?? basePt) * (marks.super || marks.sub ? SCRIPT_SCALE : 1);
|
||||
css["font-size"] =
|
||||
sizeUnit === "em" ? `${round(sizePt / basePt)}em` : `${round(sizePt)}pt`;
|
||||
if (marks.color) css["color"] = marks.color;
|
||||
const color = safeCssColor(marks.color);
|
||||
if (color) css["color"] = color;
|
||||
if (marks.super) css["vertical-align"] = "super";
|
||||
if (marks.sub) css["vertical-align"] = "sub";
|
||||
return css;
|
||||
@@ -113,8 +140,8 @@ export function docToHtml(doc: RichTextDoc, opts: HtmlOptions = {}): string {
|
||||
|
||||
function paragraphToHtml(p: Paragraph, basePt: number, sizeUnit: "pt" | "em", color?: string): string {
|
||||
const styles: string[] = [];
|
||||
if (p.align && p.align !== "left") styles.push(`text-align:${p.align}`);
|
||||
if (p.lineHeight != null) styles.push(`line-height:${p.lineHeight}`);
|
||||
if (p.align && p.align !== "left" && SAFE_ALIGN.has(p.align)) styles.push(`text-align:${p.align}`);
|
||||
if (typeof p.lineHeight === "number" && Number.isFinite(p.lineHeight)) styles.push(`line-height:${p.lineHeight}`);
|
||||
const style = styles.length ? ` style="${styles.join(";")}"` : "";
|
||||
if (p.runs.length === 0) return `<div${style}><br></div>`;
|
||||
const inner = p.runs.map((r) => runToHtmlSpan(r, basePt, sizeUnit, color)).join("");
|
||||
|
||||
+13
-1
@@ -1,9 +1,21 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const { buildCsp } = createRequire(import.meta.url)("./scripts/csp.cjs") as { buildCsp: () => string };
|
||||
|
||||
// [117] CSP nur im Build (Meta-Tag): der Dev-Server braucht Inline-Skripte für HMR/React-Refresh.
|
||||
const cspPlugin = {
|
||||
name: "dossier-csp",
|
||||
apply: "build" as const,
|
||||
transformIndexHtml: () => [
|
||||
{ tag: "meta", attrs: { "http-equiv": "Content-Security-Policy", content: buildCsp() }, injectTo: "head-prepend" as const },
|
||||
],
|
||||
};
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
plugins: [react(), cspPlugin],
|
||||
// Tauri lädt die App über den Vite-Dev-Server; dessen Logs (cargo/tauri)
|
||||
// sollen nicht vom Bildschirm gewischt werden, und Tauri-eigene Env-Vars
|
||||
// müssen im Client sichtbar sein.
|
||||
|
||||
Reference in new issue
Block a user