release: improve rendering architecture and dark mode

This commit is contained in:
Formsmith
2026-07-28 14:52:59 +03:00
parent 33671c1aae
commit edbb11c97d
32 changed files with 3944 additions and 310 deletions
+51
View File
@@ -0,0 +1,51 @@
export const APP_THEME_STORAGE_KEY = "sketchForge.theme";
export const APP_THEME_OPTIONS = [
{ value: "system", label: "System" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
] as const;
export type AppThemePreference = (typeof APP_THEME_OPTIONS)[number]["value"];
export type ResolvedAppTheme = Exclude<AppThemePreference, "system">;
export function normalizeAppThemePreference(value: unknown): AppThemePreference {
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function resolveAppTheme(preference: AppThemePreference, prefersDark: boolean): ResolvedAppTheme {
return preference === "system" ? (prefersDark ? "dark" : "light") : preference;
}
export function readStoredAppTheme(storage: Pick<Storage, "getItem"> | null | undefined): AppThemePreference {
if (!storage) return "system";
try {
return normalizeAppThemePreference(storage.getItem(APP_THEME_STORAGE_KEY));
} catch {
return "system";
}
}
export function storeAppTheme(
storage: Pick<Storage, "setItem"> | null | undefined,
preference: AppThemePreference,
) {
if (!storage) return;
try {
storage.setItem(APP_THEME_STORAGE_KEY, preference);
} catch {
// The selected theme still applies for this session when storage is unavailable.
}
}
export function applyAppTheme(preference: AppThemePreference, prefersDark?: boolean) {
if (typeof document === "undefined") return;
const systemPrefersDark = prefersDark ?? (
typeof window !== "undefined" && typeof window.matchMedia === "function"
? window.matchMedia("(prefers-color-scheme: dark)").matches
: false
);
const resolved = resolveAppTheme(preference, systemPrefersDark);
document.documentElement.dataset.theme = resolved;
document.documentElement.style.colorScheme = resolved;
}
+33
View File
@@ -133,6 +133,39 @@ export function cadModifierPrimitiveForBakedShape(shape: WorkplaneShape): CadMod
};
}
export function bakedBoxSelectionFrame(shape: WorkplaneShape) {
const primitive = cadModifierPrimitiveForBakedShape(shape);
if (!primitive || primitive.kind !== "box") {
return null;
}
const matrix = cadTransformToMatrix(primitive.transform);
const xVector = new THREE.Vector3(primitive.width, 0, 0).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const yVector = new THREE.Vector3(0, primitive.height, 0).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const zVector = new THREE.Vector3(0, 0, primitive.depth).applyMatrix3(new THREE.Matrix3().setFromMatrix4(matrix));
const width = xVector.length();
const height = yVector.length();
const depth = zVector.length();
if (![width, height, depth].every((value) => Number.isFinite(value) && value > 0.001)) {
return null;
}
const xAxis = xVector.normalize();
const yAxis = yVector.normalize();
const zAxis = zVector.normalize();
const center = new THREE.Vector3(0, primitive.height / 2, 0).applyMatrix4(matrix);
const basis = new THREE.Matrix4().makeBasis(xAxis, yAxis, zAxis);
return {
center,
quaternion: new THREE.Quaternion().setFromRotationMatrix(basis),
xAxis,
yAxis,
zAxis,
width,
height,
depth,
};
}
export function cadBrepTransformForShape(shape: WorkplaneShape) {
const frame = shape.cadBrepFrame;
if (!frame) return undefined;
+48 -1
View File
@@ -1,16 +1,63 @@
import type { CadModifierEdge } from "@/lib/cadModifierTypes";
export const CAD_MODIFIER_RUNTIME_BASE = "/occt";
export const CAD_MODIFIER_REQUEST_TIMEOUT_MS = 30_000;
export const CAD_MODIFIER_MAX_SHARP_ANGLE = 90;
export type CadModifierRequestPhase = "prepare" | "preview";
export function cadTransformRequiresGeneralTransform(transform: number[]) {
if (transform.length !== 12 || !transform.every(Number.isFinite)) {
return false;
}
const x = [transform[0], transform[4], transform[8]];
const y = [transform[1], transform[5], transform[9]];
const z = [transform[2], transform[6], transform[10]];
const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const xLengthSquared = dot(x, x);
const yLengthSquared = dot(y, y);
const zLengthSquared = dot(z, z);
const scaleSquared = Math.max(xLengthSquared, yLengthSquared, zLengthSquared);
if (scaleSquared <= 1e-18) {
return true;
}
const tolerance = scaleSquared * 1e-9;
return (
Math.abs(dot(x, y)) > tolerance ||
Math.abs(dot(x, z)) > tolerance ||
Math.abs(dot(y, z)) > tolerance ||
Math.abs(xLengthSquared - yLengthSquared) > tolerance ||
Math.abs(xLengthSquared - zLengthSquared) > tolerance ||
Math.abs(yLengthSquared - zLengthSquared) > tolerance
);
}
export function isCadModifierWasmMemoryFault(message: string, errorName = "") {
return (
/memory access out of bounds|out of bounds memory access|\bwasm\b|\babort(?:ed)?\b/i.test(message) ||
/memory access out of bounds|out of bounds memory access|\babort(?:ed)?\b/i.test(message) ||
/^(?:WebAssembly\.)?RuntimeError$/i.test(errorName)
);
}
export function defaultCadModifierTangentChain(appliedFeatureCount: number) {
return appliedFeatureCount === 0;
}
export function cadModifierTopologyEdgeIsSelectable(
edge: Pick<CadModifierEdge, "manifold" | "boundary" | "points">,
) {
return edge.manifold && !edge.boundary && edge.points.length >= 6;
}
export function selectableCadModifierEdge(
edge: Pick<CadModifierEdge, "display" | "selectable" | "manifold" | "boundary" | "angle">,
sharpAngle: number,
) {
return edge.selectable && edge.manifold && !edge.boundary && edge.angle + 1e-3 >= sharpAngle;
}
export function edgeModifierSelectionStatus(prepared: boolean, selectedCount: number, availableCount: number) {
return prepared ? `${selectedCount} of ${availableCount} sharp edges selected` : "Preparing edges\u2026";
}
+109 -21
View File
@@ -1,9 +1,8 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { canonicalizeShape, serializeShapesForSync } from "@/lib/workplaneShapes";
import { canonicalizeShape } from "@/lib/workplaneShapes";
export const MAX_EDITOR_HISTORY_ENTRIES = 5000;
export const MAX_EDITOR_HISTORY_BYTES = 64 * 1024 * 1024;
export type EditorHistoryExportLimit = "unlimited" | 100 | 50 | 30;
export type EditorHistoryExportLimit = "unlimited" | number;
export type EditorHistoryEntry = {
shapes: WorkplaneShape[];
@@ -17,8 +16,24 @@ export type EditorHistoryState = {
index: number;
};
export function serializedSceneSignature(shapes: WorkplaneShape[]) {
const serialized = serializeShapesForSync(shapes);
type ResourceSignature = {
fingerprint: string;
estimatedBytes: number;
};
const resourceSignatureCache = new WeakMap<object, ResourceSignature>();
const stringSignatureCache = new Map<string, ResourceSignature>();
const MAX_CACHED_STRING_SIGNATURES = 64;
const COMPACT_RESOURCE_KEYS = new Set([
"cadDisplayEdges",
"edgeTreatmentHistory",
"imagePlate",
"importedMesh",
"sketchProfile",
]);
const COMPACT_STRING_KEYS = new Set(["cadBrep"]);
function signatureFromSerialized(serialized: string): ResourceSignature {
let hashA = 2166136261;
let hashB = 5381;
for (let index = 0; index < serialized.length; index += 1) {
@@ -32,6 +47,65 @@ export function serializedSceneSignature(shapes: WorkplaneShape[]) {
};
}
function objectResourceSignature(resource: object) {
const cached = resourceSignatureCache.get(resource);
if (cached) return cached;
const signature = signatureFromSerialized(JSON.stringify(resource));
resourceSignatureCache.set(resource, signature);
return signature;
}
export function immutableResourceFingerprint(resource: object) {
return objectResourceSignature(resource).fingerprint;
}
function stringResourceSignature(resource: string) {
const cached = stringSignatureCache.get(resource);
if (cached) {
stringSignatureCache.delete(resource);
stringSignatureCache.set(resource, cached);
return cached;
}
const signature = signatureFromSerialized(resource);
stringSignatureCache.set(resource, signature);
while (stringSignatureCache.size > MAX_CACHED_STRING_SIGNATURES) {
const oldest = stringSignatureCache.keys().next().value;
if (oldest === undefined) break;
stringSignatureCache.delete(oldest);
}
return signature;
}
export function serializedSceneSignature(shapes: WorkplaneShape[]) {
const countedObjects = new Set<object>();
const countedStrings = new Set<string>();
let resourceBytes = 0;
const serialized = JSON.stringify(shapes.map(canonicalizeShape), (key, value: unknown) => {
if (COMPACT_RESOURCE_KEYS.has(key) && value !== null && typeof value === "object") {
const signature = objectResourceSignature(value);
if (!countedObjects.has(value)) {
countedObjects.add(value);
resourceBytes += signature.estimatedBytes;
}
return { $resource: key, fingerprint: signature.fingerprint };
}
if (COMPACT_STRING_KEYS.has(key) && typeof value === "string" && value.length > 0) {
const signature = stringResourceSignature(value);
if (!countedStrings.has(value)) {
countedStrings.add(value);
resourceBytes += signature.estimatedBytes;
}
return { $resource: key, fingerprint: signature.fingerprint };
}
return value;
});
const signature = signatureFromSerialized(serialized);
return {
fingerprint: signature.fingerprint,
estimatedBytes: signature.estimatedBytes + resourceBytes,
};
}
export function projectShapesFingerprint(shapes: WorkplaneShape[]) {
return serializedSceneSignature(shapes).fingerprint;
}
@@ -46,17 +120,35 @@ export function editorHistoryEntry(shapes: WorkplaneShape[], selectedIds: string
};
}
export function boundedEditorHistory(entries: EditorHistoryEntry[]) {
const bounded = entries.slice(-MAX_EDITOR_HISTORY_ENTRIES);
let totalBytes = bounded.reduce((total, entry) => total + entry.estimatedBytes, 0);
while (bounded.length > 2 && totalBytes > MAX_EDITOR_HISTORY_BYTES) {
const removed = bounded.shift();
totalBytes -= removed?.estimatedBytes ?? 0;
}
return bounded;
export function boundedEditorHistory(entries: EditorHistoryEntry[], limit: EditorHistoryExportLimit = "unlimited") {
return boundedEditorHistoryState(entries, entries.length - 1, limit).entries;
}
export function appendEditorHistorySnapshot(entries: EditorHistoryEntry[], requestedIndex: number, entry: EditorHistoryEntry) {
export function boundedEditorHistoryState(
entries: EditorHistoryEntry[],
requestedIndex: number,
limit: EditorHistoryExportLimit = "unlimited",
): EditorHistoryState {
if (entries.length === 0) return { entries: [], index: 0 };
const index = Math.min(Math.max(0, requestedIndex), entries.length - 1);
const retainedActions = limit === "unlimited"
? MAX_EDITOR_HISTORY_ENTRIES - 1
: Math.min(MAX_EDITOR_HISTORY_ENTRIES - 1, Math.max(1, Math.round(limit)));
const maxEntries = retainedActions + 1;
if (entries.length <= maxEntries) return { entries, index };
let start = Math.max(0, index - retainedActions);
const end = Math.min(entries.length, start + maxEntries);
if (end - start < maxEntries) start = Math.max(0, end - maxEntries);
const bounded = entries.slice(start, end);
return { entries: bounded, index: index - start };
}
export function appendEditorHistorySnapshot(
entries: EditorHistoryEntry[],
requestedIndex: number,
entry: EditorHistoryEntry,
limit: EditorHistoryExportLimit = "unlimited",
) {
const index = Math.min(Math.max(0, requestedIndex), Math.max(0, entries.length - 1));
const current = entries[index];
if (current?.fingerprint === entry.fingerprint) {
@@ -68,7 +160,7 @@ export function appendEditorHistorySnapshot(entries: EditorHistoryEntry[], reque
};
}
const nextEntries = boundedEditorHistory([...entries.slice(0, index + 1), entry]);
const nextEntries = boundedEditorHistory([...entries.slice(0, index + 1), entry], limit);
return { entries: nextEntries, index: nextEntries.length - 1, changed: true };
}
@@ -76,6 +168,7 @@ export function hydrateEditorHistoryState(
currentShapes: WorkplaneShape[],
storedEntries: EditorHistoryEntry[] | undefined,
requestedIndex: number | undefined,
limit: EditorHistoryExportLimit = "unlimited",
): EditorHistoryState {
const fallback = editorHistoryEntry(currentShapes, []);
if (!Array.isArray(storedEntries) || storedEntries.length === 0) {
@@ -96,12 +189,7 @@ export function hydrateEditorHistoryState(
return { entries: [fallback], index: 0 };
}
const entries = boundedEditorHistory(normalized);
const boundedIndex = index - (normalized.length - entries.length);
if (boundedIndex < 0 || boundedIndex >= entries.length) {
return { entries: [fallback], index: 0 };
}
return { entries, index: boundedIndex };
return boundedEditorHistoryState(normalized, index, limit);
} catch {
return { entries: [fallback], index: 0 };
}
+13 -9
View File
@@ -3,11 +3,6 @@ import type { WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchf
const MIN_VISIBLE_GRID_STEP = 1;
const MAX_VISIBLE_GRID_STEP = 200;
export type GridFootprintBounds = {
minX: number;
minZ: number;
};
function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
@@ -21,6 +16,13 @@ export function visibleGridStep(workspace: WorkplaneWorkspaceSettings) {
return clamp(workspace.gridBlockSize, MIN_VISIBLE_GRID_STEP, MAX_VISIBLE_GRID_STEP);
}
export type GridFootprintBounds = {
minX: number;
maxX: number;
minZ: number;
maxZ: number;
};
function nearestVisibleGridLine(value: number, workspaceSize: number, step: number) {
const gridOrigin = -workspaceSize / 2;
return gridOrigin + Math.round((value - gridOrigin) / step) * step;
@@ -32,11 +34,13 @@ export function snapShapeFootprintToVisibleGrid(
workspace: WorkplaneWorkspaceSettings,
) {
const step = visibleGridStep(workspace);
const snappedMinX = nearestVisibleGridLine(bounds.minX, workspace.width, step);
const snappedMinZ = nearestVisibleGridLine(bounds.minZ, workspace.depth, step);
const xOffsets = [bounds.minX, bounds.maxX].map((value) => nearestVisibleGridLine(value, workspace.width, step) - value);
const zOffsets = [bounds.minZ, bounds.maxZ].map((value) => nearestVisibleGridLine(value, workspace.depth, step) - value);
const deltaX = xOffsets.reduce((best, value) => Math.abs(value) < Math.abs(best) ? value : best);
const deltaZ = zOffsets.reduce((best, value) => Math.abs(value) < Math.abs(best) ? value : best);
return {
...shape,
x: cleanCoordinate(shape.x + snappedMinX - bounds.minX),
z: cleanCoordinate(shape.z + snappedMinZ - bounds.minZ),
x: cleanCoordinate(shape.x + deltaX),
z: cleanCoordinate(shape.z + deltaZ),
};
}
@@ -0,0 +1,92 @@
import { immutableResourceFingerprint, type EditorHistoryEntry } from "@/lib/editorHistory";
import type { WorkplaneShape } from "@/types/sketchforge";
export type ImportedMeshResource = NonNullable<WorkplaneShape["importedMesh"]>;
type CompactProjectShapeState = {
shapes: WorkplaneShape[];
history: EditorHistoryEntry[];
resources: Map<string, ImportedMeshResource>;
};
function compactImportedMesh(resource: ImportedMeshResource, resources: Map<string, ImportedMeshResource>): ImportedMeshResource {
const resourceId = immutableResourceFingerprint(resource);
if (!resources.has(resourceId)) {
resources.set(resourceId, {
...resource,
storageResourceId: undefined,
});
}
return {
positions: [],
baseWidth: resource.baseWidth,
baseDepth: resource.baseDepth,
baseHeight: resource.baseHeight,
triangleCount: resource.triangleCount,
sourceFormat: resource.sourceFormat,
assetId: resource.assetId,
storageResourceId: resourceId,
};
}
function compactShape(shape: WorkplaneShape, resources: Map<string, ImportedMeshResource>): WorkplaneShape {
const next: WorkplaneShape = {
...shape,
importedMesh: shape.importedMesh ? compactImportedMesh(shape.importedMesh, resources) : undefined,
};
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map((child) => compactShape(child, resources));
}
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: compactShape(entry.before, resources),
}));
}
return next;
}
function hydrateShape(shape: WorkplaneShape, resources: ReadonlyMap<string, ImportedMeshResource>): WorkplaneShape {
const resourceId = shape.importedMesh?.storageResourceId;
const resource = resourceId ? resources.get(resourceId) : undefined;
const next: WorkplaneShape = {
...shape,
importedMesh: resource ?? shape.importedMesh,
};
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map((child) => hydrateShape(child, resources));
}
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
before: hydrateShape(entry.before, resources),
}));
}
return next;
}
export function compactProjectShapeState(shapes: WorkplaneShape[], history: EditorHistoryEntry[]): CompactProjectShapeState {
const resources = new Map<string, ImportedMeshResource>();
return {
shapes: shapes.map((shape) => compactShape(shape, resources)),
history: history.map((entry) => ({
...entry,
shapes: entry.shapes.map((shape) => compactShape(shape, resources)),
})),
resources,
};
}
export function hydrateProjectShapeState(
shapes: WorkplaneShape[],
history: EditorHistoryEntry[] | undefined,
resources: ReadonlyMap<string, ImportedMeshResource>,
) {
return {
shapes: shapes.map((shape) => hydrateShape(shape, resources)),
history: history?.map((entry) => ({
...entry,
shapes: entry.shapes.map((shape) => hydrateShape(shape, resources)),
})),
};
}
+14 -4
View File
@@ -135,6 +135,7 @@ export type SkfProjectExportInput = {
workspace: WorkplaneWorkspaceSettings;
snapGrid: GridSize;
placementElevation: number;
compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
};
export type SkfRestoredProject = {
@@ -292,6 +293,7 @@ class SkfArchiveBuilder {
readonly assets: SkfAssetRecordV1[] = [];
readonly sourceIdMap = new Map<string, string>();
private readonly recordByKindAndHash = new Map<string, SkfAssetRecordV1>();
private readonly derivedMeshByResource = new WeakMap<object, Promise<SkfAssetRecordV1>>();
async addAsset(
kind: SkfAssetKind,
@@ -336,6 +338,14 @@ class SkfArchiveBuilder {
this.sourceIdMap.set(asset.id, record.id);
}
}
addDerivedMesh(mesh: NonNullable<WorkplaneShape["importedMesh"]>) {
const cached = this.derivedMeshByResource.get(mesh);
if (cached) return cached;
const pending = this.addAsset("derived-mesh", encodeMeshCache(mesh), "application/vnd.sketchforge.mesh");
this.derivedMeshByResource.set(mesh, pending);
return pending;
}
}
function assertUniqueRuntimeObjectIds(shapes: WorkplaneShape[], stateLabel: string) {
@@ -410,7 +420,7 @@ async function serializeShapeNode(
let meshAssetId: string | undefined;
let brepStepAssetId: string | undefined;
if (!canRegenerate) {
meshAssetId = (await builder.addAsset("derived-mesh", encodeMeshCache(importedMesh), "application/vnd.sketchforge.mesh")).id;
meshAssetId = (await builder.addDerivedMesh(importedMesh)).id;
if (importedMesh.brepStep) {
brepStepAssetId = (await builder.addAsset("brep", strToU8(importedMesh.brepStep), "application/step")).id;
}
@@ -600,9 +610,9 @@ function activeProjectIndexes(state: SkfStateV1) {
return { features, groups, sketches, exactCad };
}
function zipAsync(files: AsyncZippable) {
function zipAsync(files: AsyncZippable, level: NonNullable<SkfProjectExportInput["compressionLevel"]> = 6) {
return new Promise<Uint8Array>((resolve, reject) => {
zip(files, { level: 6, mtime: new Date("1980-01-01T00:00:00.000Z") }, (error, data) => {
zip(files, { level, mtime: new Date("1980-01-01T00:00:00.000Z") }, (error, data) => {
if (error) reject(error);
else resolve(data);
});
@@ -678,7 +688,7 @@ export async function exportSkfProject(input: SkfProjectExportInput) {
},
};
builder.files["project.json"] = strToU8(`${JSON.stringify(document, null, 2)}\n`);
return zipAsync(Object.fromEntries(Object.entries(builder.files).sort(([a], [b]) => a.localeCompare(b))));
return zipAsync(Object.fromEntries(Object.entries(builder.files).sort(([a], [b]) => a.localeCompare(b))), input.compressionLevel);
}
function inspectZipBeforeExpansion(bytes: Uint8Array) {
+47 -1
View File
@@ -1,7 +1,10 @@
import type { ResolvedAppTheme } from "@/lib/appTheme";
const WORKPLANE_BOUNDARY_EPSILON = 0.0001;
export const WORKPLANE_LINE_ELEVATION = 0;
export const WORKPLANE_MAJOR_GRID_INTERVAL = 5;
export const DEFAULT_WORKPLANE_GRID_COLOR = "#28b4de";
export type WorkplaneGridCoordinate = {
coordinate: number;
@@ -15,7 +18,32 @@ export type WorkplaneGridPalette = {
border: { color: string; opacity: number };
};
export function workplaneGridPalette(): WorkplaneGridPalette {
export type WorkplaneThemePalette = {
sceneBackground: string;
surface: { color: string; opacity: number };
grid: WorkplaneGridPalette;
};
export function workplaneGridPalette(
theme: ResolvedAppTheme = "light",
configuredColor: string = DEFAULT_WORKPLANE_GRID_COLOR,
): WorkplaneGridPalette {
if (configuredColor.toLowerCase() !== DEFAULT_WORKPLANE_GRID_COLOR) {
return {
minor: { color: configuredColor, opacity: theme === "dark" ? 0.42 : 0.38 },
major: { color: configuredColor, opacity: theme === "dark" ? 0.7 : 0.68 },
axis: { color: configuredColor, opacity: 0.94 },
border: { color: configuredColor, opacity: 0.9 },
};
}
if (theme === "dark") {
return {
minor: { color: "#397080", opacity: 0.5 },
major: { color: "#4d9caf", opacity: 0.72 },
axis: { color: "#65c9df", opacity: 0.92 },
border: { color: "#59b8cc", opacity: 0.88 },
};
}
return {
minor: { color: "#91dff0", opacity: 0.55 },
major: { color: "#4bbddf", opacity: 0.7 },
@@ -24,6 +52,24 @@ export function workplaneGridPalette(): WorkplaneGridPalette {
};
}
export function workplaneThemePalette(
theme: ResolvedAppTheme,
configuredBackground: string,
configuredGridColor: string = DEFAULT_WORKPLANE_GRID_COLOR,
): WorkplaneThemePalette {
return theme === "dark"
? {
sceneBackground: "#101820",
surface: { color: "#183640", opacity: 0.9 },
grid: workplaneGridPalette("dark", configuredGridColor),
}
: {
sceneBackground: configuredBackground,
surface: { color: "#ddf8ff", opacity: 0.68 },
grid: workplaneGridPalette("light", configuredGridColor),
};
}
export function interiorWorkplaneGridCoordinates(span: number, step: number): WorkplaneGridCoordinate[] {
if (!Number.isFinite(span) || !Number.isFinite(step) || span <= 0 || step <= 0) {
return [];
+16 -1
View File
@@ -1,5 +1,6 @@
import type { GridSize, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
@@ -9,6 +10,7 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
sizePreset: "200 x 200 mm",
gridBlockSize: 5,
gridBlockPreset: "5 mm",
gridColor: DEFAULT_WORKPLANE_GRID_COLOR,
background: "#f8fbfc",
showShadows: true,
showGrid: true,
@@ -17,6 +19,7 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
units: "Metric (Default)",
scale: "1:1 (millimeters)",
accuracy: 2,
historyLimit: "unlimited",
};
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
@@ -29,6 +32,10 @@ function stringOrDefault(value: unknown, fallback: string) {
return typeof value === "string" && value.trim() ? value : fallback;
}
function colorOrDefault(value: unknown, fallback: string) {
return typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value.trim()) ? value : fallback;
}
function booleanOrDefault(value: unknown, fallback: boolean) {
return typeof value === "boolean" ? value : fallback;
}
@@ -37,6 +44,12 @@ function accuracyOrDefault(value: unknown, fallback: MeasurementAccuracy) {
return value === 1 || value === 2 || value === 3 ? value : fallback;
}
function historyLimitOrDefault(value: unknown, fallback: HistoryRetentionLimit): HistoryRetentionLimit {
if (value === "unlimited") return value;
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
return Math.min(5000, Math.max(1, Math.round(value)));
}
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
}
@@ -50,6 +63,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
sizePreset: stringOrDefault(candidate.sizePreset, fallback.sizePreset),
gridBlockSize: numberOrDefault(candidate.gridBlockSize, fallback.gridBlockSize),
gridBlockPreset: stringOrDefault(candidate.gridBlockPreset, fallback.gridBlockPreset),
gridColor: colorOrDefault(candidate.gridColor, fallback.gridColor),
background: stringOrDefault(candidate.background, fallback.background),
showShadows: booleanOrDefault(candidate.showShadows, fallback.showShadows),
showGrid: booleanOrDefault(candidate.showGrid, fallback.showGrid),
@@ -58,6 +72,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
units,
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
};
}