Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions src/box.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
47 changes: 22 additions & 25 deletions src/box.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const DEFAULT_BOX: Box = {
depth: 10,
wallThickness: 2,
lidThickness: 2,
lidTolerance: 2,
lidTolerance: 0.4,
cornerRadius: 2,
}

Expand All @@ -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()),
Expand Down
88 changes: 88 additions & 0 deletions src/history.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof setup>['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)
})
})
57 changes: 35 additions & 22 deletions src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,42 @@
import type { ZodType } from 'zod'
import { useEffect, useState } from 'react'

// The document lives in the URL (`?data=<json>`) 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=<json>` in the URL, falling back to `backup`. */
export function startDoc<T>(schema: ZodType<T>, backup: T): T {
const startBox = schema.parse(backup)
try {
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<typeof setTimeout> | 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<typeof setTimeout> | undefined

/** Push `doc` as a new history entry once edits pause, replacing any save still waiting. */
export function saveDoc<T>(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<A>(schema: ZodType<A>, defaultDoc: A): [A, (a: A) => void] {
Expand All @@ -38,17 +46,22 @@ export function useHistoryDoc<A>(schema: ZodType<A>, 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]
}
Loading