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
@@ -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("");
|
||||
|
||||
Reference in new issue
Block a user