release: add sketch revolve and configurable gears

This commit is contained in:
Formsmith
2026-07-24 11:55:44 +03:00
parent 5dde9faceb
commit fe161f8d75
32 changed files with 1913 additions and 115 deletions
@@ -2,7 +2,7 @@
import { useEffect, useState, type CSSProperties } from "react";
import { Check, LoaderCircle, Minus, Plus, RotateCcw, X } from "lucide-react";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import type { CadModifierKind, CadModifierQuality } from "@/lib/cadModifierTypes";
import { CAD_MODIFIER_MAX_SHARP_ANGLE, edgeModifierSelectionStatus } from "@/lib/cadModifierRuntime";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -71,7 +71,7 @@ function EdgeModifierSlider({
const toModelValue = (nextValue: number) => length ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
onChange(clamp(toModelValue(finiteNext), safeMin, safeMax));
setEditing(false);
@@ -89,10 +89,7 @@ function EdgeModifierSlider({
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={controlMax}
step={controlStep}
type="text"
value={editing ? draft : formatSliderValue(controlValue, workspace.accuracy, controlStep)}
inputMode="decimal"
disabled={disabled}
@@ -1,11 +1,30 @@
"use client";
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen, Split } from "lucide-react";
import { useEffect, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
import { ToolbarHideSelectedIcon } from "@/components/icons";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay } from "@/lib/measurementUnits";
import {
DEFAULT_GEAR_HELIX_ANGLE,
DEFAULT_GEAR_HELIX_QUALITY,
DEFAULT_GEAR_TEETH,
DEFAULT_GEAR_TOOTH_SIZE,
MAX_GEAR_HELIX_ANGLE,
MAX_GEAR_HELIX_QUALITY,
MIN_GEAR_HELIX_ANGLE,
MIN_GEAR_HELIX_QUALITY,
gearCenterHoleLimits,
normalizeGearHelixAngle,
normalizeGearHelixQuality,
normalizeGearCenterHoleSize,
normalizeGearToothSize,
normalizeGearToothWidth,
normalizeGearType,
gearToothPitch,
} from "@/lib/gearGeometry";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import type { GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
const MIN_SHAPE_SIZE = 0.01;
@@ -40,6 +59,11 @@ const SOLID_COLORS = [
"#111111",
];
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
const GEAR_TYPE_OPTIONS: Array<{ value: GearType; label: string }> = [
{ value: "spur", label: "Spur gear" },
{ value: "helical", label: "Helical gear" },
{ value: "bevel", label: "Bevel gear" },
];
type RangePropertyConfig = {
type?: "range";
@@ -80,7 +104,7 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step
}
function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness"].includes(label);
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
@@ -95,6 +119,20 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
};
const setHeight = (height: number) => onUpdate({ height }, { resizeAxis: "height" });
if (shape.sketchOperation === "revolve" || shape.sketchRevolve) {
const settings = normalizeSketchRevolveSettings(shape.sketchRevolve);
const updateRevolve = (patch: Partial<typeof settings>) => onUpdate({ sketchRevolve: normalizeSketchRevolveSettings({ ...settings, ...patch }) });
return [
{ label: "Start Angle", value: settings.startAngle, min: 0, max: 359, step: 1, onChange: (startAngle) => updateRevolve({ startAngle }) },
{ label: "Sweep", value: settings.sweepAngle, min: -360, max: 360, step: 1, onChange: (sweepAngle) => updateRevolve({ sweepAngle }) },
{ label: "Sides", value: settings.sides, min: 3, max: 128, step: 1, onChange: (sides) => updateRevolve({ sides }) },
{ label: "Thickness", value: settings.thickness, min: 0.1, max: 20, step: 0.1, onChange: (thickness) => updateRevolve({ thickness }) },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
];
}
if (shape.kind === "box") {
return [
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
@@ -168,6 +206,92 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
];
}
if (shape.kind === "gear") {
const setGearWidth = (value: number) => {
const toothSize = normalizeGearToothSize(shape.toothSize, value, depth);
const toothWidth = normalizeGearToothWidth(shape.toothWidth, value, depth, shape.teeth);
const centerHoleSize = normalizeGearCenterHoleSize(shape.centerHoleSize, value, depth, toothSize);
onUpdate({ width: value, size: resizedShapeSize(value, depth), toothSize, toothWidth, centerHoleSize }, { resizeAxis: "width" });
};
const setGearDepth = (value: number) => {
const toothSize = normalizeGearToothSize(shape.toothSize, width, value);
const toothWidth = normalizeGearToothWidth(shape.toothWidth, width, value, shape.teeth);
const centerHoleSize = normalizeGearCenterHoleSize(shape.centerHoleSize, width, value, toothSize);
onUpdate({ depth: value, size: resizedShapeSize(width, value), toothSize, toothWidth, centerHoleSize }, { resizeAxis: "depth" });
};
const teeth = shape.teeth ?? DEFAULT_GEAR_TEETH;
const toothPitch = gearToothPitch(width, depth, teeth);
const toothSize = normalizeGearToothSize(shape.toothSize ?? DEFAULT_GEAR_TOOTH_SIZE, width, depth);
const centerHoleLimits = gearCenterHoleLimits(width, depth, toothSize);
const properties: ShapePropertyConfig[] = [
{
label: "Teeth",
value: teeth,
min: 6,
max: 64,
step: 1,
onChange: (value) => {
const nextTeeth = Math.round(value);
onUpdate({
teeth: nextTeeth,
toothWidth: normalizeGearToothWidth(shape.toothWidth, width, depth, nextTeeth),
});
},
},
{
label: "Tooth Size",
value: toothSize,
min: 0.2,
max: Math.max(0.2, Math.min(width, depth) * 0.22),
step: 0.1,
onChange: (nextToothSize) => onUpdate({
toothSize: nextToothSize,
centerHoleSize: normalizeGearCenterHoleSize(shape.centerHoleSize, width, depth, nextToothSize),
}),
},
{
label: "Tooth Width",
value: normalizeGearToothWidth(shape.toothWidth, width, depth, teeth),
min: toothPitch * 0.12,
max: toothPitch * 0.82,
step: 0.1,
onChange: (toothWidth) => onUpdate({ toothWidth }),
},
];
if (normalizeGearType(shape.gearType) === "helical") {
properties.push({
label: "Helix Angle",
value: normalizeGearHelixAngle(shape.helixAngle ?? DEFAULT_GEAR_HELIX_ANGLE),
min: MIN_GEAR_HELIX_ANGLE,
max: MAX_GEAR_HELIX_ANGLE,
step: 1,
onChange: (helixAngle) => onUpdate({ helixAngle }),
});
properties.push({
label: "Quality",
value: normalizeGearHelixQuality(shape.helixQuality ?? DEFAULT_GEAR_HELIX_QUALITY),
min: MIN_GEAR_HELIX_QUALITY,
max: MAX_GEAR_HELIX_QUALITY,
step: 1,
onChange: (helixQuality) => onUpdate({ helixQuality: Math.round(helixQuality) }),
});
}
properties.push(
{
label: "Center Hole",
value: normalizeGearCenterHoleSize(shape.centerHoleSize, width, depth, toothSize),
min: centerHoleLimits.min,
max: centerHoleLimits.max,
step: 0.1,
onChange: (centerHoleSize) => onUpdate({ centerHoleSize }),
},
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setGearDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setGearWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
);
return properties;
}
if (shape.kind === "text") {
return [
{
@@ -222,14 +346,31 @@ export function ShapeInspector({
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
const locked = Boolean(shape.locked);
const properties = getShapeProperties(shape, onUpdate);
const gearType = shape.kind === "gear" ? normalizeGearType(shape.gearType) : null;
const primaryProperties = shape.kind === "gear"
? properties.filter((property) => ["Center Hole", "Length", "Width", "Height"].includes(property.label))
: properties;
const gearTeethProperties = shape.kind === "gear"
? properties.filter((property) => ["Teeth", "Tooth Size", "Tooth Width"].includes(property.label))
: [];
const gearHelixProperties = shape.kind === "gear"
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
: [];
const isSketchRevolve = shape.sketchOperation === "revolve" || Boolean(shape.sketchRevolve);
const inspectorRef = useRef<HTMLElement>(null);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [gearTeethOpen, setGearTeethOpen] = useState(true);
const [gearHelixOpen, setGearHelixOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
const [minimized, setMinimized] = useState(false);
useEffect(() => () => onInteractionActiveChange?.(false), [onInteractionActiveChange]);
useLayoutEffect(() => {
inspectorRef.current?.scrollTo({ top: 0, left: 0 });
}, [isSketchRevolve, shape.id]);
return (
<aside className={`shape-inspector ${minimized ? "minimized" : ""}`} aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<aside ref={inspectorRef} className={`shape-inspector ${isSketchRevolve ? "sketch-revolve-inspector" : ""} ${shape.kind === "gear" ? "gear-inspector" : ""} ${minimized ? "minimized" : ""}`} aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
<div className="shape-inspector-header">
<button
className="inspector-header-icon"
@@ -334,7 +475,7 @@ export function ShapeInspector({
</button>
) : null}
<div className="property-card">
<div className={`property-card ${propertiesOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
@@ -347,18 +488,55 @@ export function ShapeInspector({
</button>
{propertiesOpen ? (
<div className="property-list" id={`properties-${shape.id}`}>
{properties.map((property) => {
if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />;
}
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={locked} />;
}
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />;
})}
{gearType ? (
<GearTypeSelector
value={gearType}
disabled={locked}
onChange={(gearType) => onUpdate({ gearType })}
/>
) : null}
<ShapePropertyRows properties={primaryProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
{shape.kind === "gear" ? (
<div className={`property-card ${gearTeethOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
aria-expanded={gearTeethOpen}
aria-controls={`gear-teeth-${shape.id}`}
onClick={() => setGearTeethOpen((open) => !open)}
>
<span>Teeth</span>
<ChevronUp className={gearTeethOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{gearTeethOpen ? (
<div className="property-list" id={`gear-teeth-${shape.id}`}>
<ShapePropertyRows properties={gearTeethProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
) : null}
{gearType === "helical" ? (
<div className={`property-card ${gearHelixOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
aria-expanded={gearHelixOpen}
aria-controls={`gear-helix-${shape.id}`}
onClick={() => setGearHelixOpen((open) => !open)}
>
<span>Helix</span>
<ChevronUp className={gearHelixOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{gearHelixOpen ? (
<div className="property-list" id={`gear-helix-${shape.id}`}>
<ShapePropertyRows properties={gearHelixProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
) : null}
<div className="inspector-snap-dock">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
</div>
@@ -368,6 +546,28 @@ export function ShapeInspector({
);
}
function ShapePropertyRows({
properties,
workspace,
disabled,
onInteractionActiveChange,
}: {
properties: ShapePropertyConfig[];
workspace: WorkplaneWorkspaceSettings;
disabled?: boolean;
onInteractionActiveChange?: (active: boolean) => void;
}) {
return properties.map((property) => {
if (property.type === "text") {
return <TextProperty key={property.label} {...property} disabled={disabled} onInteractionActiveChange={onInteractionActiveChange} />;
}
if (property.type === "select") {
return <SelectProperty key={property.label} {...property} disabled={disabled} />;
}
return <RangeProperty key={property.label} {...property} workspace={workspace} disabled={disabled} onInteractionActiveChange={onInteractionActiveChange} />;
});
}
export function SnapGridControl({
snap,
snapOpen,
@@ -437,7 +637,7 @@ function RangeProperty({
}, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = Number(draft);
const next = parseMeasurementInput(draft);
const finiteNext = Number.isFinite(next) ? next : controlValue;
const nextModelValue = toModelValue(finiteNext);
onChange(allowsAboveSliderMax ? Math.max(min, nextModelValue) : clamp(nextModelValue, min, max));
@@ -455,10 +655,7 @@ function RangeProperty({
<span className="range-property-name">{label}</span>
<span className="range-value-control">
<input
type="number"
min={controlMin}
max={allowsAboveSliderMax ? undefined : controlMax}
step={controlStep}
type="text"
value={editing ? draft : formatPropertyNumber(controlValue, accuracy, controlStep)}
disabled={disabled}
inputMode="decimal"
@@ -533,3 +730,30 @@ function SelectProperty({ label, value, options, disabled, onChange }: SelectPro
</label>
);
}
function GearTypePreview({ type }: { type: GearType }) {
return <img src={`assets/sketchforge/gear-types/${type}.png`} alt="" aria-hidden="true" />;
}
function GearTypeSelector({ value, disabled, onChange }: { value: GearType; disabled?: boolean; onChange: (value: GearType) => void }) {
return (
<div className="gear-type-property" role="group" aria-label="Gear type">
<span>Gear Type</span>
<div className="gear-type-options">
{GEAR_TYPE_OPTIONS.map((option) => (
<button
key={option.value}
className={value === option.value ? "selected" : ""}
type="button"
disabled={disabled}
aria-pressed={value === option.value}
onClick={() => onChange(option.value)}
>
<GearTypePreview type={option.value} />
<span>{option.label}</span>
</button>
))}
</div>
</div>
);
}
@@ -155,6 +155,7 @@ export function TransformOverlay({
style={{ "--overlay-x": `${editingDimension.x}px`, "--overlay-y": `${editingDimension.y}px` } as CSSProperties}
value={editingDimension.value}
autoFocus
inputMode="decimal"
onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onEditingDimensionChange(event.target.value)}
onBlur={onCommitDimensionEdit}
@@ -2,7 +2,7 @@
import { Grid3X3, Palette, Ruler, X } from "lucide-react";
import { useEffect, useState } from "react";
import { normalizeScaleForUnits, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits, WORKSPACE_UNIT_OPTIONS } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -56,6 +56,7 @@ export function WorkspaceSettingsModal({
width: workspace.width.toFixed(workspace.accuracy),
depth: workspace.depth.toFixed(workspace.accuracy),
}));
const [gridBlockSizeDraft, setGridBlockSizeDraft] = useState(() => workspace.gridBlockSize.toFixed(workspace.accuracy));
const scaleOptions = scaleOptionsForUnits(workspace.units);
const scaleValue = normalizeScaleForUnits(workspace.units, workspace.scale);
useEffect(() => {
@@ -64,13 +65,16 @@ export function WorkspaceSettingsModal({
depth: workspace.depth.toFixed(workspace.accuracy),
});
}, [workspace.accuracy, workspace.depth, workspace.width]);
useEffect(() => {
setGridBlockSizeDraft(workspace.gridBlockSize.toFixed(workspace.accuracy));
}, [workspace.accuracy, workspace.gridBlockSize]);
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => {
setDefaultSaved(false);
const next = { ...workspace, ...patch };
onWorkspaceChange({ ...next, scale: normalizeScaleForUnits(next.units, next.scale) });
};
const setDimension = (key: "width" | "depth", value: string) => {
const parsed = Number.parseFloat(value);
const parsed = parseMeasurementInput(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
setDimensionDrafts((current) => ({ ...current, [key]: next.toFixed(workspace.accuracy) }));
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
@@ -87,7 +91,9 @@ export function WorkspaceSettingsModal({
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
};
const setGridBlockSize = (value: string) => {
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
const parsed = parseMeasurementInput(value);
const next = clamp(Number.isFinite(parsed) ? parsed : workspace.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
setGridBlockSizeDraft(next.toFixed(workspace.accuracy));
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
};
@@ -201,11 +207,9 @@ export function WorkspaceSettingsModal({
<label>
<span>Width</span>
<input
type="number"
type="text"
inputMode="decimal"
value={dimensionDrafts.width}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, width: value }));
@@ -219,11 +223,9 @@ export function WorkspaceSettingsModal({
<label>
<span>Length</span>
<input
type="number"
type="text"
inputMode="decimal"
value={dimensionDrafts.depth}
min={MIN_WORKSPACE_SIZE}
max={MAX_WORKSPACE_SIZE}
step={1}
onChange={(event) => {
const value = event.currentTarget.value;
setDimensionDrafts((current) => ({ ...current, depth: value }));
@@ -241,12 +243,14 @@ export function WorkspaceSettingsModal({
<label>
<span>Block size</span>
<input
type="number"
value={workspace.gridBlockSize.toFixed(workspace.accuracy)}
min={MIN_GRID_BLOCK_SIZE}
max={MAX_GRID_BLOCK_SIZE}
step={0.5}
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
type="text"
inputMode="decimal"
value={gridBlockSizeDraft}
onChange={(event) => setGridBlockSizeDraft(event.currentTarget.value)}
onBlur={(event) => setGridBlockSize(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
</div>