From a06df4100d0d8c4d11f8ae06fa444bd5e921dce0 Mon Sep 17 00:00:00 2001 From: joshmarinacci Date: Fri, 20 Nov 2026 13:19:04 -0800 Subject: [PATCH 1/3] Make wall thickness and lid tolerance apply per side Each side wall was half the Wall thickness setting (the cavity was `width - thick` wide), while the floor got the full value. Lid tolerance was likewise the total gap, split between the two sides, and the lid's insert ring had half-thickness walls too. Now the floor, every side wall and the lid ring are all Wall thickness thick, and Lid tolerance is the clearance on each side. The default tolerance drops from 2 to 0.4 mm, since 2 mm per side would be very loose. Saved links keep their numbers but now produce thicker walls and a smaller interior. Co-Authored-By: Claude Opus 5.5 --- src/box.test.ts | 36 ++++++++++++++++++++++++++++++++++++ src/box.ts | 47 ++++++++++++++++++++++------------------------- 2 files changed, 58 insertions(+), 25 deletions(-) diff --git a/src/box.test.ts b/src/box.test.ts index a329471..05a7d47 100644 --- a/src/box.test.ts +++ b/src/box.test.ts @@ -32,6 +32,42 @@ describe('boxToSolids', () => { }) }) +describe('wall thickness and lid tolerance', () => { + // Exact area of a rounded rectangle; the meshes approximate the arcs with 16 segments per corner. + const area = (w: number, d: number, r: number) => w * d - (4 - Math.PI) * Math.max(0, r) ** 2 + const box = { + width: 40, + depth: 30, + height: 20, + wallThickness: 1.5, + lidThickness: 2, + lidTolerance: 0.4, + cornerRadius: 5, + } + const t = box.wallThickness + const tol = box.lidTolerance + + // Regression: each side wall used to be half the wall thickness. + it('makes every side wall and the floor wallThickness thick', () => { + const outer = area(box.width, box.depth, box.cornerRadius) * box.height + const cavity = area(box.width - 2 * t, box.depth - 2 * t, box.cornerRadius - t) * (box.height - t) + expect(measureVolume(boxToSolids(box)[0]) / (outer - cavity)).toBeCloseTo(1, 2) + }) + + // Regression: lid tolerance used to be the total gap, split between the two sides. + it('leaves lidTolerance of clearance on each side of the lid insert, whose ring is wallThickness thick', () => { + const capVolume = area(box.width, box.depth, box.cornerRadius) * (box.lidThickness / 2) + const plug = area(box.width - 2 * t - 2 * tol, box.depth - 2 * t - 2 * tol, box.cornerRadius - t - tol) + const hole = area(box.width - 4 * t - 2 * tol, box.depth - 4 * t - 2 * tol, box.cornerRadius - 2 * t - tol) + const ringAboveCap = (plug - hole) * (box.lidThickness / 2) + expect(measureVolume(boxToSolids(box)[1]) / (capVolume + ringAboveCap)).toBeCloseTo(1, 2) + }) + + it('defaults to a snug 0.4mm lid tolerance', () => { + expect(DEFAULT_BOX.lidTolerance).toBe(0.4) + }) +}) + describe('corner radius', () => { const big = { ...DEFAULT_BOX, width: 30, depth: 20, height: 15 } diff --git a/src/box.ts b/src/box.ts index e179dfa..f0bcbe2 100644 --- a/src/box.ts +++ b/src/box.ts @@ -23,7 +23,7 @@ export const DEFAULT_BOX: Box = { depth: 10, wallThickness: 2, lidThickness: 2, - lidTolerance: 2, + lidTolerance: 0.4, cornerRadius: 2, } @@ -50,42 +50,39 @@ export function boxToSolids(box: Box): Geom3[] { // gap between the two shapes const gap = 3 const lidThick = box.lidThickness - // thickness must be less than box dimensions - const thick = Math.min(box.wallThickness, box.width - 0.1, box.depth - 0.1) + // Wall thickness and lid tolerance are per side. Clamp walls so the cavity always has some room. + const thick = Math.min(box.wallThickness, (Math.min(box.width, box.depth) - 0.1) / 2) const lidTol = box.lidTolerance - // Each inner outline is the outer one inset by half its size reduction, and insetting a - // rounded rectangle by d shrinks its corner radius by d. That keeps walls an even thickness - // around the corners and keeps the lid insert the same shape as the opening it drops into. + + // How much narrower than the outside each part is, counting both sides. + const cavityShrink = 2 * thick // the box's inside + const plugShrink = cavityShrink + 2 * lidTol // the lid's insert, a tolerance gap inside the cavity + const holeShrink = plugShrink + 2 * thick // the hole that turns the insert into a ring + + // Each inner outline is the outer one inset by half its shrink, and insetting a rounded + // rectangle by d shrinks its corner radius by d. That keeps walls an even thickness around the + // corners and keeps the lid insert the same shape as the opening it drops into. const r = box.cornerRadius - const insetRadius = (sizeReduction: number) => Math.max(0, r - sizeReduction / 2) - const fits = (sizeReduction: number) => Math.min(box.width, box.depth) - sizeReduction > EPS + const insetRadius = (shrink: number) => Math.max(0, r - shrink / 2) + const fits = (shrink: number) => Math.min(box.width, box.depth) - shrink > EPS + const inset = (shrink: number, height: number, centerZ = 0) => + roundedBlock(box.width - shrink, box.depth - shrink, height, insetRadius(shrink), centerZ) // The lid is a flat cap plus a ring that drops into the box opening. On small boxes with thick // walls there may be no room for the ring's hole (the ring becomes a solid plug), or for the // ring at all (the lid is just the cap). const lidCap = () => roundedBlock(box.width, box.depth, lidThick / 2, r, -lidThick / 2 / 2) - const lidPlug = () => - roundedBlock(box.width - thick - lidTol, box.depth - thick - lidTol, lidThick, insetRadius(thick + lidTol)) - const lidHole = () => - roundedBlock( - box.width - thick - lidTol - thick, - box.depth - thick - lidTol - thick, - 20, - insetRadius(2 * thick + lidTol), - -lidThick / 2 / 2 + lidThick / 2, - ) - const lidRing = () => (fits(2 * thick + lidTol) ? subtract(lidPlug(), lidHole()) : lidPlug()) - const lid = () => (fits(thick + lidTol) ? union(lidRing(), lidCap()) : lidCap()) + const lidPlug = () => inset(plugShrink, lidThick) + const lidHole = () => inset(holeShrink, 20, -lidThick / 2 / 2 + lidThick / 2) + const lidRing = () => (fits(holeShrink) ? subtract(lidPlug(), lidHole()) : lidPlug()) + const lid = () => (fits(plugShrink) ? union(lidRing(), lidCap()) : lidCap()) try { return [ - // the box + // the box: full-height cavity raised by `thick`, leaving a floor of that thickness translate( [-box.width / 2 - gap, 0, box.height / 2], - subtract( - roundedBlock(box.width, box.depth, box.height, r), - roundedBlock(box.width - thick, box.depth - thick, box.height, insetRadius(thick), thick), - ), + subtract(roundedBlock(box.width, box.depth, box.height, r), inset(cavityShrink, box.height, thick)), ), // the lid translate([box.width / 2 + gap, 0, lidThick / 2], lid()), From 53431fe3cb2d417384acdfdcf318b821eaf89c16 Mon Sep 17 00:00:00 2001 From: joshmarinacci Date: Fri, 20 Nov 2026 13:19:04 -0800 Subject: [PATCH 2/3] Fix Back/Forward through box edits - Restoring a history entry no longer pushes a new one, which had wiped out Forward and kept Back from stepping through edits. - The entry the page loads on now gets a state via replaceState, so Back can return to the starting box (it used to fail to parse and do nothing). - Going back cancels an edit still waiting on the 1 s save debounce. - An entry without valid state falls back to the ?data= in its URL. Co-Authored-By: Claude Opus 5.5 --- src/history.test.tsx | 88 ++++++++++++++++++++++++++++++++++++++++++++ src/schema.ts | 57 +++++++++++++++++----------- 2 files changed, 123 insertions(+), 22 deletions(-) create mode 100644 src/history.test.tsx diff --git a/src/history.test.tsx b/src/history.test.tsx new file mode 100644 index 0000000..ff9df2a --- /dev/null +++ b/src/history.test.tsx @@ -0,0 +1,88 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { SAVE_DELAY_MS, useHistoryDoc } from './schema' +import { BoxSchema, DEFAULT_BOX } from './box' +import type { Box } from './box' + +// Drives real jsdom history (pushState / back / forward) to check the URL-backed document. + +const box = (width: number): Box => ({ ...DEFAULT_BOX, width }) + +/** Wait for jsdom to finish a history traversal and fire popstate. */ +async function traverse(go: () => void) { + const popped = new Promise((resolve) => window.addEventListener('popstate', resolve, { once: true })) + await act(async () => { + go() + await popped + }) +} + +describe('useHistoryDoc', () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + window.history.replaceState(null, '', '/') + }) + afterEach(() => { + vi.useRealTimers() + }) + + const setup = () => renderHook(() => useHistoryDoc(BoxSchema, DEFAULT_BOX)) + + const edit = (result: ReturnType['result'], next: Box) => { + act(() => result.current[1](next)) + act(() => vi.advanceTimersByTime(SAVE_DELAY_MS)) + } + + it('saves edits to the URL after a pause', () => { + const { result } = setup() + const before = window.history.length + edit(result, box(20)) + expect(window.history.length).toBe(before + 1) + expect(decodeURIComponent(window.location.search)).toContain('"width":20') + }) + + // Regression: Back pushed a new entry, which broke Forward and trapped the user. + it('steps back and forward through edits without adding entries', async () => { + const { result } = setup() + edit(result, box(20)) + edit(result, box(30)) + const length = window.history.length + + await traverse(() => window.history.back()) + expect(result.current[0].width).toBe(20) + act(() => vi.advanceTimersByTime(SAVE_DELAY_MS * 2)) + expect(window.history.length).toBe(length) + + await traverse(() => window.history.forward()) + expect(result.current[0].width).toBe(30) + }) + + // Regression: the first entry had no state, so going back to it did nothing. + it('returns to the box the page loaded with', async () => { + const { result } = setup() + edit(result, box(20)) + await traverse(() => window.history.back()) + expect(result.current[0]).toEqual(DEFAULT_BOX) + }) + + it('restores a box from a shared link when going back to it', async () => { + const shared = box(55) + window.history.replaceState(null, '', '/?data=' + encodeURIComponent(JSON.stringify(shared))) + const { result } = setup() + expect(result.current[0]).toEqual(shared) + edit(result, box(60)) + await traverse(() => window.history.back()) + expect(result.current[0]).toEqual(shared) + }) + + it('drops an unsaved edit when the user goes back', async () => { + const { result } = setup() + edit(result, box(20)) + act(() => result.current[1](box(99))) // not saved yet + const length = window.history.length + await traverse(() => window.history.back()) + act(() => vi.advanceTimersByTime(SAVE_DELAY_MS * 2)) + expect(window.history.length).toBe(length) + expect(result.current[0]).toEqual(DEFAULT_BOX) + }) +}) diff --git a/src/schema.ts b/src/schema.ts index 0f294f2..8b3f7e6 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,6 +1,11 @@ import type { ZodType } from 'zod' import { useEffect, useState } from 'react' +// The document lives in the URL (`?data=`) and in browser history, so links restore a box +// and Back/Forward step through edits. Edits are pushed as history entries after a short pause. + +export const SAVE_DELAY_MS = 1000 + /** Read the starting document from `?data=` in the URL, falling back to `backup`. */ export function startDoc(schema: ZodType, backup: T): T { const startBox = schema.parse(backup) @@ -8,27 +13,30 @@ export function startDoc(schema: ZodType, backup: T): T { const q = window.location.search if (q && q.startsWith('?data=')) { const json = decodeURIComponent(q.substring(6)) - const data = schema.parse(JSON.parse(json)) - console.log('got data from url', data) - return data + return schema.parse(JSON.parse(json)) } } catch (e) { - console.log('error happened', e) + console.log('ignoring invalid ?data= in the URL', e) } return startBox } -let debounceTimer: ReturnType | undefined -function debounce(callback: () => void, time: number) { - clearTimeout(debounceTimer) - debounceTimer = setTimeout(callback, time) -} +const docUrl = (doc: unknown) => '?data=' + encodeURIComponent(JSON.stringify(doc)) + +let saveTimer: ReturnType | undefined +/** Push `doc` as a new history entry once edits pause, replacing any save still waiting. */ export function saveDoc(doc: T) { - debounce(() => { - const str = encodeURIComponent(JSON.stringify(doc)) - window.history.pushState(doc, 'box-state', '?data=' + str) - }, 1000) + clearTimeout(saveTimer) + saveTimer = setTimeout(() => { + saveTimer = undefined + window.history.pushState(doc, '', docUrl(doc)) + }, SAVE_DELAY_MS) +} + +export function cancelPendingSave() { + clearTimeout(saveTimer) + saveTimer = undefined } export function useHistoryDoc(schema: ZodType, defaultDoc: A): [A, (a: A) => void] { @@ -38,17 +46,22 @@ export function useHistoryDoc(schema: ZodType, defaultDoc: A): [A, (a: A) saveDoc(next) } useEffect(() => { + // The entry the page loaded on has no state yet; give it one so Back can return to it. + if (window.history.state === null) { + window.history.replaceState(startDoc(schema, defaultDoc), '', window.location.href) + } const historyChanged = (event: PopStateEvent) => { - try { - const restored = schema.parse(event.state) - setDoc(restored) - saveDoc(restored) - } catch { - console.log('error restoring from history') - } + // Navigating away wins over an edit that hasn't been saved yet. + cancelPendingSave() + // Restore only: pushing here would add an entry and break Forward. + const parsed = schema.safeParse(event.state) + setDoc(parsed.success ? parsed.data : startDoc(schema, defaultDoc)) } window.addEventListener('popstate', historyChanged) - return () => window.removeEventListener('popstate', historyChanged) - }, [schema]) + return () => { + window.removeEventListener('popstate', historyChanged) + cancelPendingSave() + } + }, [schema, defaultDoc]) return [doc, update] } From 44cab0807fa3a9eaccdf548c950670544beaa01c Mon Sep 17 00:00:00 2001 From: joshmarinacci Date: Fri, 20 Nov 2026 13:19:05 -0800 Subject: [PATCH 3/3] Document per-side wall thickness, lid tolerance and history Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 248b17f..91de910 100644 --- a/README.md +++ b/README.md @@ -11,15 +11,16 @@ See [the live app here](https://apps.josh.earth/boxbuilder/) Drag the sliders (or type into the number boxes) and the preview updates live. All sizes are in mm. When it looks right, press **Download STL** to save `box.stl`. -| Setting | What it does | -| ---------------------- | ----------------------------------------------------------------------------------------------- | -| Width / Depth / Height | Outside size of the box. | -| Wall thickness | Floor thickness. Each side wall is half of this (the cavity is `width − wall thickness` wide). | -| Lid thickness | Total thickness of the lid: a flat cap plus a ring that drops into the box. | -| Lid tolerance | Gap between the lid's ring and the box walls. Increase it if the lid is too tight. | -| Corner radius | Rounds the four vertical corners of the box and lid. The rim stays flat so the lid seats flush. | - -The current settings are saved in the page URL, so you can bookmark or share a box. +| Setting | What it does | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Width / Depth / Height | Outside size of the box. | +| Wall thickness | Thickness of the floor, each side wall, and the lid's insert ring. | +| Lid thickness | Total thickness of the lid: a flat cap plus a ring that drops into the box. | +| Lid tolerance | Gap on each side between the lid's ring and the box walls. 0.4 is a common starting point; increase it if the lid is too tight, decrease it if it's loose. | +| Corner radius | Rounds the four vertical corners of the box and lid. The rim stays flat so the lid seats flush. | + +The current settings are saved in the page URL, so you can bookmark or share a box. Each edit becomes a +browser history entry, so Back and Forward step through your changes. **Moving the preview:** drag to rotate, shift-drag to pan, scroll to zoom. On touch screens, drag with one finger and pinch with two. With the preview focused (click it or Tab to it), arrow keys