diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ece75ea..f5e7cdb 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,6 +1,6 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2026-10-10 00:10:32 UTC using RuboCop version 1.91.0. +# on 2026-12-02 05:27:22 UTC using RuboCop version 1.91.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -43,7 +43,7 @@ RSpec/ExampleLength: RSpec/MessageSpies: EnforcedStyle: receive -# Offense count: 42 +# Offense count: 47 RSpec/MultipleExpectations: Max: 4 diff --git a/app/assets/stylesheets/generator.css b/app/assets/stylesheets/generator.css index 7f52439..7945dad 100644 --- a/app/assets/stylesheets/generator.css +++ b/app/assets/stylesheets/generator.css @@ -29,6 +29,7 @@ .stage .top { fill: var(--birch-light); } .stage .left { fill: var(--birch); } .stage .right { fill: var(--birch-dark); } +.stage .tilted { fill: color-mix(in oklab, var(--birch-light) 55%, var(--birch)); } .stage .inside { stroke: #2a1a0c; stroke-width: 1; } .stage .floor { fill: #6b5231; } .stage .far { fill: #a98a57; } @@ -44,12 +45,19 @@ .panel { position: relative; margin: 0; background: var(--panel); border-top: 3px solid var(--amber); border-bottom: 1px solid var(--rule); - display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)) minmax(0, 1.35fr) minmax(0, 1.2fr) minmax(0, 1.3fr) minmax(140px, 1.1fr); + /* The choices, the three sides, thickness, notch, Generate. */ + display: grid; grid-template-columns: minmax(max-content, 1.3fr) repeat(3, minmax(0, 1fr)) minmax(0, 1.35fr) minmax(0, 1.2fr) minmax(140px, 1.1fr); } -.hint { position: absolute; left: var(--gutter); bottom: calc(100% + 10px); margin: 0; font-size: 14px; color: var(--alarm); } +/* Why the box cannot be made: a bright red pill above the strip. */ +.hint { + position: absolute; left: var(--gutter); bottom: calc(100% + 10px); margin: 0; max-width: calc(100% - 2 * var(--gutter)); + padding: 6px 16px; border-radius: 99px; background: var(--error); color: #fff; font-size: 14px; font-weight: 700; line-height: 1.35; + box-shadow: 0 2px 10px rgb(0 0 0 / 0.35); +} +.hint:empty { display: none; } .field { position: relative; padding: 16px clamp(12px, 1.5vw, 22px) 14px; border-right: 1px solid var(--rule); display: grid; gap: 10px; align-content: start; } -.field > label { font-size: 13px; color: var(--mute); font-stretch: 110%; cursor: ew-resize; user-select: none; touch-action: none; display: flex; justify-content: space-between; gap: 8px; white-space: nowrap; overflow: hidden; } +.field > label { font-size: 13px; color: var(--mute); font-stretch: 110%; cursor: move; user-select: none; touch-action: none; display: flex; justify-content: space-between; gap: 8px; white-space: nowrap; overflow: hidden; } .field > label i { font-style: normal; opacity: 0; transition: opacity 0.15s; white-space: nowrap; } .field:hover > label i, .field:focus-within > label i { opacity: 0.7; } .num { display: flex; align-items: baseline; gap: 6px; } @@ -73,7 +81,24 @@ font-size: 13px; color: var(--soft); cursor: pointer; } .chips button:hover, .more:hover, .pick select:hover { border-color: var(--soft); } -.field .restart { justify-self: start; white-space: nowrap; } +/* Wraps to "Reset to / defaults" when the Width cell is too narrow for one line. */ +.field .restart { text-align: left; border-radius: 14px; } +.reset { position: relative; justify-self: start; } +/* Reset, and the Yes that carries it out, warn in red. */ +.field .restart:hover, .field .restart[aria-expanded="true"], .reset .yes:hover { color: var(--error); border-color: var(--error); } +/* The popup sits to the right of Reset, over the next cell, with a point towards the button. */ +.reset .confirm { + position: absolute; z-index: 5; left: calc(100% + 10px); top: 50%; transform: translateY(-50%); + display: flex; align-items: center; gap: 6px; white-space: nowrap; + padding: 6px 8px 6px 12px; border: 1px solid var(--edge); border-radius: 12px; + background: var(--sheet); box-shadow: 0 4px 16px rgb(0 0 0 / 0.45); font-size: 13px; color: var(--soft); +} +.reset .confirm[hidden] { display: none; } +.reset .confirm::before { + content: ""; position: absolute; left: -6px; top: 50%; width: 10px; height: 10px; + background: var(--sheet); border-left: 1px solid var(--edge); border-bottom: 1px solid var(--edge); + transform: translateY(-50%) rotate(45deg); +} .chips button[aria-pressed="true"] { background: var(--ink); color: var(--panel); border-color: var(--ink); } .side { padding: 14px clamp(12px, 1.5vw, 22px); border-right: 1px solid var(--rule); display: grid; gap: 8px; align-content: center; justify-items: start; } @@ -83,8 +108,17 @@ .seg input:checked + span { background: var(--ink); color: var(--panel); } .seg input:focus-visible + span { outline: 2px solid var(--amber); outline-offset: 2px; } .pick select { padding: 4px 10px; max-width: 100%; } +/* The column is as wide as its longest option; both dropdowns fill it, so they line up. */ +.side .pick { justify-self: stretch; } +.side .pick select { width: 100%; } .pick select option { background: var(--panel); color: var(--ink); } -.soon { color: var(--mute); font-size: 12.5px; line-height: 1.3; } + +/* The slope and front height of a sloped box: a row of its own under the strip, after Generate. */ +.sloped { grid-column: 1 / -1; order: 1; display: grid; grid-template-columns: subgrid; border-top: 1px solid var(--rule); } +.sloped[hidden] { display: none; } +/* A text input is twenty characters wide unless told otherwise; without this the Slope input would widen the choices column. */ +.sloped > .field { contain: inline-size; } +.sloped .note { grid-column: 3 / -1; margin: 0; padding: 16px clamp(12px, 1.5vw, 22px); align-self: center; max-width: 72ch; font-size: 13px; line-height: 1.4; color: var(--mute); } .go { background: var(--beam); color: #160a04; border: 0; cursor: pointer; @@ -101,14 +135,28 @@ /* As tall as the drawing needs and no taller, so no empty band above and below it. */ .stage { height: auto; min-height: 0; margin-top: 8px; } .stage svg { height: auto; max-height: 50vh; } - .panel { grid-template-columns: repeat(3, 1fr); } - .field.thickness { grid-column: span 2; } - .side, .go { grid-column: span 3; } - .field.thickness, .field.notch, .side, .go { border-top: 1px solid var(--rule); } - .side { grid-auto-flow: column; justify-content: start; align-items: center; gap: 10px 14px; grid-auto-flow: row; } + /* Twelve columns: three sides in fourths, then thickness and notch, with slope and front height between them. */ + .panel { grid-template-columns: repeat(12, minmax(0, 1fr)); } + .panel > .field { grid-column: span 4; } + .field.thickness { grid-column: span 8; } + .side, .go, .sloped .note { grid-column: 1 / -1; } + .sloped { display: contents; } + .sloped[hidden] { display: none; } + .sloped:not([hidden]) > .field, + .panel:has(.sloped:not([hidden])) .field.thickness, + .panel:has(.sloped:not([hidden])) .field.notch { grid-column: span 3; } + /* Every control comes before Generate. */ + .field.notch { order: 1; } + .sloped .note { order: 2; } + .go { order: 3; } + /* The choices come first, so every row under them gets a rule. */ + .panel > .field, .sloped > .field, .go { border-top: 1px solid var(--rule); } + /* Above the measurements, the choices sit in one line beside the units pill, wrapping only when there is no room. */ + .side { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 12px; } + .side .pick select { width: auto; } .go { padding: 18px; } - .hint { position: static; grid-column: span 3; padding: 8px var(--gutter) 0; } - .hint:empty { display: none; } + .hint { position: static; grid-column: 1 / -1; justify-self: start; margin: 10px var(--gutter) 0; max-width: none; border-radius: 18px; } + .sloped .note { grid-column: 1 / -1; padding-top: 0; } } /* A phone-width Width cell only has room for "Reset". */ @@ -116,8 +164,8 @@ .field .restart .wide { display: none; } } -/* On a phone, a slim Generate bar sits above the controls instead of below them. */ +/* On a phone, Generate is a slim bar under the controls. */ @media (max-width: 640px) { - .go { order: -1; padding: 9px 14px; font-size: 18px; border-top: 0; } + .go { padding: 9px 14px; font-size: 18px; } .go small { display: none; } } diff --git a/app/assets/stylesheets/tokens.css b/app/assets/stylesheets/tokens.css index 7e6c9bc..a519fb7 100644 --- a/app/assets/stylesheets/tokens.css +++ b/app/assets/stylesheets/tokens.css @@ -37,7 +37,7 @@ --beam: #ff5a2b; /* the laser */ --amber: #ffb53d; /* the accent: headings, edges, whatever is being edited */ --alarm: #ff7a6b; - --error: #ff2020; + --error: #ff2020; /* the error pill */ --birch: #e2c48f; /* plywood */ --birch-light: #efd9aa; --birch-dark: #c4a269; diff --git a/app/controllers/boxes_controller.rb b/app/controllers/boxes_controller.rb index 96cf90d..be8d450 100644 --- a/app/controllers/boxes_controller.rb +++ b/app/controllers/boxes_controller.rb @@ -12,7 +12,7 @@ class BoxesController < ApplicationController # ActionController::Live's own thread, which Rack::Timeout never interrupts. RENDER_SECONDS = 20 - PERMITTED = (BoxRequest::DIMENSIONS + BoxRequest::OPTIONAL + %i[units page_size page_layout metadata lid]).freeze + PERMITTED = (BoxRequest::DIMENSIONS + BoxRequest::OPTIONAL + BoxRequest::SLOPED + %i[units page_size page_layout metadata lid]).freeze # Draws the SVG, reporting progress as it goes and sending the drawing last. def stream diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index 6885f0d..ebea567 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -3,9 +3,8 @@ class HomeController < ApplicationController def index @settings = { - defaults: BoxRequest.defaults, - pageSizes: BoxRequest.page_sizes, - lidsSupported: BoxRequest.lids_supported? + defaults: BoxRequest.defaults, + pageSizes: BoxRequest.page_sizes } end end diff --git a/app/javascript/controllers/generator_controller.js b/app/javascript/controllers/generator_controller.js index 6e2133c..6056d03 100644 --- a/app/javascript/controllers/generator_controller.js +++ b/app/javascript/controllers/generator_controller.js @@ -1,5 +1,7 @@ import { Controller } from "@hotwired/stimulus" import { isoBox, tabCount } from "lib/iso_box" +import { isoSlopedBox } from "lib/iso_sloped_box" +import { slopedProfile, slopeProblem } from "lib/sloped_profile" import { load, trace } from "lib/laser_trace" const STORAGE_KEY = "makeabox:settings:v1" @@ -10,7 +12,10 @@ const STOCK = { in: [["1/8″", 0.125], ["3/16″", 0.1875], ["1/4″", 0.25]], mm: [["3 mm", 3], ["4.5 mm", 4.5], ["6 mm", 6]] } -const STEP = { in: { side: 0.25, thickness: 0.005, notch: 0.05 }, mm: { side: 5, thickness: 0.1, notch: 1 } } +const STEP = { in: { side: 0.25, thickness: 0.005, notch: 0.05, slope: 1 }, mm: { side: 5, thickness: 0.1, notch: 1, slope: 1 } } +// A sloped box starts at 45° from a front this share of the height. A sloped +// box has no lid with tabs along the back (BoxRequest::SLOPED_LIDS). +const SLOPE_START = { slope: 45, front: 0.4 } // The narrowest notch worth cutting. The widest is a third of the shortest // side; on a box too small for both, the narrowest is half the widest. Both // ends are rounded down to NOTCH_SCALE, exactly as BoxRequest does. @@ -27,8 +32,8 @@ const KERF_FIT = { green: ["About just right", "About just right"] } const KERF_STEP = { in: 0.0005, mm: 0.01 } -// What "Reset to defaults" under Width puts back, in inches. -const STARTING_BOX = { width: 5, height: 4, depth: 3, thickness: 0.125, kerf: 0.026 } +// What "Reset to defaults" under Width puts back, in inches, with a closed upright box. +const STARTING_BOX = { width: 5, height: 4, depth: 3, thickness: 0.25, kerf: 0.026 } const TRACE_MS = 1500 const clean = (number) => Number(number.toFixed(4)) @@ -49,7 +54,8 @@ const label = (key) => (key === "thickness" ? "Thickness" : key[0].toUpperCase() export default class extends Controller { static targets = ["preview", "form", "hint", "number", "unit", "chips", "range", "units", "lid", "settings", "optional", "pageSize", "go", "cut", "cutTitle", "cutMaterial", "drawing", "specs", "phase", "count", "bar", "download", - "kerfSlider", "kerfFit", "metadata"] + "kerfSlider", "kerfFit", "metadata", "shape", "sloped", "slope", "frontHeight", + "restart", "confirm"] static values = { settings: Object, streamUrl: String, downloadUrl: String, countUrl: String } connect() { @@ -88,15 +94,32 @@ export default class extends Controller { return query.toString() } + get sloped() { + return this.shapeTarget.value === "sloped" + } + problem() { for (const key of [...SIDES, "thickness"]) if (!(this.number(key) > 0)) return `${label(key)} needs a number above zero.` if (this.number("thickness") >= Math.min(...SIDES.map((key) => this.number(key)))) return "Thickness has to be smaller than the shortest side of the box." + const slope = this.slopeProblem() + if (slope) return slope if (this.notchProblem()) return `Notch length has to be between ${this.notchRange().join(" and ")} ${this.unit}, or blank to let makeabox choose.` const notches = tabCount(Math.max(...SIDES.map((key) => this.number(key))), this.number("notch") || 3 * this.number("thickness")) if (notches > MAX_NOTCHES) return `That is ${notches} notches along the longest side, and ${MAX_NOTCHES} is the most we draw. Use thicker material or a longer notch.` return "" } + slopeProblem() { + if (!this.sloped) return "" + return slopeProblem({ height: this.number("height"), depth: this.number("depth"), thickness: this.number("thickness"), slope: parse(this.fields.slope), + frontHeight: parse(this.fields.front_height), lid: this.lidTarget.value, unit: this.unit }) + } + + get profile() { + return slopedProfile({ depth: this.number("depth"), height: this.number("height"), frontHeight: parse(this.fields.front_height), + slope: parse(this.fields.slope), thickness: this.number("thickness") }) + } + // [narrowest, widest] notch, the same numbers as BoxRequest#notch_range. notchRange() { const scale = NOTCH_SCALE[this.unit], down = (value) => Math.floor(value * scale + 1e-6) / scale @@ -116,7 +139,8 @@ export default class extends Controller { } clamp(key, value) { - const [low, high] = key === "notch" ? this.notchRange() : [this.step(key), Infinity] + const bounds = { notch: () => this.notchRange(), slope: () => [1, 89], front_height: () => [0, Math.max(0, this.number("height") - this.step(key))] } + const [low, high] = bounds[key]?.() ?? [this.step(key), Infinity] return clean(Math.min(high, Math.max(low, value))) } @@ -126,6 +150,17 @@ export default class extends Controller { this.refresh() } + // Upright or sloped. A sloped box starts from SLOPE_START, and swaps the + // lid with tabs along the back, which it cannot have, for the closed box. + reshape() { + if (this.sloped) { + if (this.slopeTarget.value === "") this.slopeTarget.value = SLOPE_START.slope + if (this.frontHeightTarget.value === "") this.frontHeightTarget.value = clean(this.number("height") * SLOPE_START.front) + if (this.lidTarget.value === "back") this.lidTarget.value = "full" + } + this.refresh() + } + focus(event) { this.hot = event.target.closest("[data-key]").dataset.key event.target.select() @@ -146,15 +181,17 @@ export default class extends Controller { this.refresh() } - // Dragging a label left or right changes its number. + // Dragging a label changes its number: right or up for more, left or down + // for less, by whichever way the pointer has moved further. scrub(event) { const label = event.currentTarget, key = label.closest("[data-key]").dataset.key, input = this.input(key) - const from = event.clientX, base = this.start(key) + const [fromX, fromY] = [event.clientX, event.clientY], base = this.start(key) event.preventDefault() label.setPointerCapture(event.pointerId) this.hot = key const move = (drag) => { - input.value = this.clamp(key, base + Math.round((drag.clientX - from) / 6) * this.step(key)) + const [dx, dy] = [drag.clientX - fromX, fromY - drag.clientY] + input.value = this.clamp(key, base + Math.round((Math.abs(dy) > Math.abs(dx) ? dy : dx) / 6) * this.step(key)) this.refresh() } label.addEventListener("pointermove", move) @@ -171,12 +208,41 @@ export default class extends Controller { this.refresh() } - // Back to a 5 × 4 × 3 in box of 1/8″ material with the default kerf. - // Everything else on the form is left as it is. + // Reset opens a popup that asks before the box is thrown away; a second click closes it. + ask() { + this.confirming(this.confirmTarget.hidden) + } + + // No, or Escape: close the popup and go back to Reset. + keep() { + if (this.confirmTarget.hidden) return + this.confirming(false) + this.restartTarget.focus() + } + + // A click anywhere outside Reset and its popup closes the popup. + dismiss(event) { + if (!this.confirmTarget.hidden && !event.target.closest(".reset")) this.confirming(false) + } + + // Opens or closes the popup. Open, No has the focus, so a stray Enter keeps the box. + confirming(open) { + this.confirmTarget.hidden = !open + this.restartTarget.setAttribute("aria-expanded", String(open)) + if (open) this.confirmTarget.querySelector(".no").focus() + } + + // Back to a closed, upright 5 × 4 × 3 in box of 1/4″ material with the default kerf. + // The slope fields are emptied, so a sloped front starts afresh. Everything + // else on the form is left as it is. restart() { + this.confirming(false) if (this.unit !== "in") this.pageSizeTarget.value = "" // a page size in mm has no match in inches this.unitsTargets.forEach((radio) => { radio.checked = radio.value === "in" }) for (const [key, value] of Object.entries(STARTING_BOX)) this.input(key).value = value + this.lidTarget.value = "full" + this.shapeTarget.value = "upright" + this.slopeTarget.value = this.frontHeightTarget.value = "" this.refresh() } @@ -191,7 +257,7 @@ export default class extends Controller { const to = event.target.value if (to === this.unit) return const factor = to === "mm" ? MM_PER_INCH : 1 / MM_PER_INCH, digits = to === "mm" ? 2 : 4 - for (const input of [...this.numberTargets, ...this.optionalTargets]) { + for (const input of [...this.numberTargets, ...this.optionalTargets, this.frontHeightTarget]) { const value = parse(input.value) if (Number.isFinite(value)) input.value = Number((value * factor).toFixed(digits)) } @@ -222,6 +288,7 @@ export default class extends Controller { reset() { try { localStorage.removeItem(STORAGE_KEY) } catch (error) { /* storage is optional */ } this.formTarget.reset() + this.slopeTarget.value = this.frontHeightTarget.value = "" this.unit = "in" this.refresh() } @@ -245,6 +312,7 @@ export default class extends Controller { }) this.pageSizes(unit) this.kerf(unit) + this.shapeFields() this.numberTargets.forEach((input) => input.closest(".field").classList.toggle("bad", !(parse(input.value) > 0))) this.rangeTarget.textContent = this.notchRange()[1] > 0 ? `${this.notchRange().join(" to ")} ${unit}` : "" this.rangeTarget.closest(".field").classList.toggle("bad", this.notchProblem()) @@ -290,6 +358,17 @@ export default class extends Controller { this.kerfFitTarget.dataset.zone = zone } + // Disabled fields are left out of the form, so an upright box sends no slope. + shapeFields() { + const sloped = this.sloped + this.slopedTarget.hidden = !sloped + this.slopeTarget.disabled = this.frontHeightTarget.disabled = !sloped + this.lidTarget.querySelector('option[value="back"]').disabled = sloped + const bad = (input) => input.closest(".field").classList.toggle("bad", sloped && !(parse(input.value) >= 0)) + bad(this.slopeTarget) + bad(this.frontHeightTarget) + } + pageSizes(unit) { const select = this.pageSizeTarget if (select.dataset.unit === unit) return @@ -303,10 +382,14 @@ export default class extends Controller { // so many notches that building the preview stalls the page. draw() { if (this.problem()) return - const { viewBox, markup } = isoBox({ + const box = { width: this.number("width"), height: this.number("height"), depth: this.number("depth"), thickness: this.number("thickness"), - notch: this.number("notch"), units: this.unit, lid: this.lidTarget.value, hot: this.hot - }) + notch: this.number("notch"), units: this.unit, lid: this.lidTarget.value, hot: this.hot === "front_height" ? "frontHeight" : this.hot + } + const profile = this.sloped && this.profile + const { viewBox, markup } = profile + ? isoSlopedBox({ ...box, frontHeight: parse(this.fields.front_height), slope: parse(this.fields.slope) }, profile, tabCount) + : isoBox(box) this.previewTarget.setAttribute("viewBox", viewBox) this.previewTarget.classList.toggle("hot-thickness", this.hot === "thickness" || this.hot === "notch") this.previewTarget.innerHTML = markup // numbers and fixed class names only, see iso_box.js @@ -323,6 +406,11 @@ export default class extends Controller { const unit = saved.units === "mm" ? "mm" : "in" this.unitsTargets.forEach((radio) => { radio.checked = radio.value === unit }) this.pageSizes(unit) // the saved page size needs its option to exist first + // Only a sloped box saves a slope: an upright one leaves the fields disabled. + if (saved.slope !== undefined) { + this.shapeTarget.value = "sloped" + this.shapeFields() + } for (const [key, value] of Object.entries(saved)) { if (key === "metadata") { this.metadataTarget.checked = value !== "0"; continue } const field = this.input(key) @@ -383,6 +471,7 @@ export default class extends Controller { this.cutMaterialTarget.textContent = `${this.number("thickness")} ${unit} material` const rows = [["Inside", `${sides} ${unit}`], ["Material", `${this.number("thickness")} ${unit}`], ["Notch length", tab], ["Top", this.lidTarget.selectedOptions[0].textContent], ["Page", this.pageSizeTarget.value || "fits the box"]] + if (this.sloped) rows.splice(1, 0, ["Front", `${parse(this.fields.front_height)} ${unit}, sloping back at ${parse(this.fields.slope)}°`]) this.specsTarget.replaceChildren(...rows.flatMap(([term, detail]) => { const dt = document.createElement("dt"), dd = document.createElement("dd") dt.textContent = term diff --git a/app/javascript/lib/iso_sloped_box.js b/app/javascript/lib/iso_sloped_box.js new file mode 100644 index 0000000..292f02a --- /dev/null +++ b/app/javascript/lib/iso_sloped_box.js @@ -0,0 +1,125 @@ +// Draws the isometric preview of a box whose front slopes back: the right +// side wall, the front strip, the tilted panel and the top strip, with finger +// joints and the dimensions. For a lid that lifts off, the tilted panel floats +// up off the box. Pure geometry, no state. +// +// Library modules here import nothing (importmap pins them by bare name, which +// the test bundler cannot resolve), so the caller passes in the profile from +// slopedProfile() and tabCount from iso_box.js. The projection matches +// iso_box.js, so both boxes draw at the same scale. + +const COS30 = Math.cos(Math.PI / 6) +const SCALE = 100 + +const project = (x, y, z) => [(x - y) * COS30 * SCALE, ((x + y) * 0.5 - z) * SCALE] +const pair = (point) => point.map((n) => n.toFixed(1)).join(",") + +// box: { width, height, depth, frontHeight, slope, thickness, notch, units, lid, hot } +// profile: slopedProfile() of the same box, in the same units +// Returns { viewBox, markup } for an . Every interpolated value is a number +// or one of a fixed set of words, so the markup is safe to assign as innerHTML. +export function isoSlopedBox(box, profile, tabCount) { + // Drawn in inches whatever the units, as iso_box.js does. + const inch = box.units === "mm" ? 25.4 : 1 + const [W, H, D, Hf, t] = [box.width, box.height, box.depth, box.frontHeight, box.thickness].map((value) => value / inch) + const notch = (box.notch || 3 * box.thickness) / inch + const [Dt, S] = [profile.topDepth / inch, profile.slopeLength / inch] + const tilted = profile.lengths.tilted / inch + const start = Math.hypot(...profile.span[0].map((c, i) => c - [0, box.frontHeight][i])) / inch // where the tilted panel begins on the slope + const [cos, sin] = [Math.cos(profile.angle), Math.sin(profile.angle)] + const open = box.lid === "plain" + const unit = Math.max(W, H, D) + const points = [] + let markup = "" + + // A face maps its own (p, q) onto the box: o + u·p + v·q. + const face = (o, u, v) => ({ o, u, v }) + const at = (f, p, q) => { + const point = project(...[0, 1, 2].map((i) => f.o[i] + f.u[i] * p + f.v[i] * q)) + points.push(point) + return point + } + const shape = (cls, f, corners) => { markup += `` } + const rect = (cls, f, a, b) => shape(cls, f, [[0, 0], [a, 0], [a, b], [0, b]]) + + // A finger is the end grain of the neighbouring panel showing through an + // edge: every other notch along it, one thickness deep. + const fingers = (f, from, dir, inward, length, phase) => { + if (length <= 0) return + const count = tabCount(length, notch) + const point = (s, d) => [from[0] + dir[0] * s + inward[0] * d, from[1] + dir[1] * s + inward[1] * d] + for (let i = phase; i < count; i += 2) { + const a = (i * length) / count, b = ((i + 1) * length) / count + shape("finger", f, [point(a, 0), point(b, 0), point(b, t), point(a, t)]) + } + } + + // Seen from the right, the side's own p runs from the front to the back. + const side = face([W, D, 0], [0, -1, 0], [0, 0, 1]) + const front = face([0, D, 0], [1, 0, 0], [0, 0, 1]) + const slope = face([0, D, Hf], [1, 0, 0], [0, -cos, sin]) + const top = face([0, Dt, H], [1, 0, 0], [0, -1, 0]) + const outline = profile.outline.map(([p, q]) => [p / inch, q / inch]) + + const shadow = [project(-0.04 * unit, D, 0), project(W, D + 0.1 * unit, 0), project(W + 0.22 * unit, D * 0.4, 0), project(W + 0.16 * unit, -0.1 * unit, 0)] + markup += `` + + shape("face right", side, outline) + fingers(side, [0, 0], [1, 0], [0, 1], D, 1) + fingers(side, [D, 0], [0, 1], [-1, 0], H, 1) + fingers(side, [0, 0], [0, 1], [1, 0], Hf, 1) + fingers(side, [D - Dt, H], [1, 0], [0, -1], Dt, 1) + + if (Hf > 0) { + rect("face left", front, W, Hf) + fingers(front, [0, 0], [1, 0], [0, 1], W, 1) + fingers(front, [W, 0], [0, 1], [-1, 0], Hf, 0) + } + if (Dt > 0) { + rect("face top", top, W, Dt) + fingers(top, [0, Dt], [1, 0], [0, -1], W, 0) + fingers(top, [W, 0], [0, 1], [-1, 0], Dt, 0) + } + + if (open) { + // The opening the tilted panel leaves, then the panel, lifted along its + // own normal, a slab one thickness deep. A plain lid lies on the side + // walls, so it has no tabs, and neither has the sloped edge under it. + shape("inside floor", slope, [[0, 0], [W, 0], [W, S], [0, S]]) + const lift = Math.max(0.35 * H, 0.18 * unit) + const up = [0, sin * lift, cos * lift] + const lifted = face(slope.o.map((c, i) => c + up[i]), slope.u, slope.v) + const edge = lifted.o.map((c, i) => c + slope.v[i] * start) // the low edge of the lifted panel + rect("face left", face(edge, [1, 0, 0], [0, -sin, -cos]), W, t) + shape("face tilted", lifted, [[0, start], [W, start], [W, start + tilted], [0, start + tilted]]) + } else { + rect("face tilted", slope, W, S) + fingers(slope, [W, start], [0, 1], [-1, 0], tilted, 0) + // The side's sloped edge, under the tilted panel's fingers. + const [low] = profile.span + fingers(side, [low[0] / inch, low[1] / inch], [cos, sin], [sin, -cos], tilted, 1) + } + + const offset = 0.1 * unit, size = unit * SCALE * 0.052 + const label = (key, at, text) => { + points.push([at[0] - size * 2.4, at[1] - size], [at[0] + size * 2.4, at[1] + size]) + markup += `${text}` + } + const dimension = (key, a, b, away, value) => { + const a1 = project(a[0] + away[0] * offset, a[1] + away[1] * offset, a[2]) + const b1 = project(b[0] + away[0] * offset, b[1] + away[1] * offset, b[2]) + points.push(a1, b1) + markup += `` + label(key, [(a1[0] + b1[0]) / 2, (a1[1] + b1[1]) / 2], `${Number(value)} ${box.units === "mm" ? "mm" : "in"}`) + } + dimension("width", [0, D, 0], [W, D, 0], [0, 1.6], box.width) + dimension("depth", [W, 0, 0], [W, D, 0], [1.6, 0], box.depth) + dimension("height", [W, 0, 0], [W, 0, H], [1.6, -1.2], box.height) + if (Hf > 0) dimension("frontHeight", [0, D, 0], [0, D, Hf], [-1.2, 0], box.frontHeight) + label("slope", project(W + offset, D - (S / 2) * cos, Hf + (S / 2) * sin + offset), `${Number(Number(box.slope).toFixed(1))}°`) + + const xs = points.map((p) => p[0]), ys = points.map((p) => p[1]), pad = unit * 6 + const x0 = Math.min(...xs) - pad, y0 = Math.min(...ys) - pad + const viewBox = [x0, y0, Math.max(...xs) + pad - x0, Math.max(...ys) + pad - y0].map((n) => n.toFixed(1)).join(" ") + return { viewBox, markup } +} diff --git a/app/javascript/lib/sloped_profile.js b/app/javascript/lib/sloped_profile.js new file mode 100644 index 0000000..6bc3203 --- /dev/null +++ b/app/javascript/lib/sloped_profile.js @@ -0,0 +1,67 @@ +// The side view of a box whose front slopes back, the same numbers +// laser-cutter's Sloped::Profile computes. Pure geometry, no state. +// +// Seen from the left, front to the left: a front strip Hf high, a tilted +// panel rising at the slope, a top strip Dt deep, the back H high, and the +// bottom D deep. Every length is of the inside outline. +// +// Where the tilted panel meets a strip the corner is obtuse: the strip runs +// past the corner over the end of the tilted panel, which stops short, so the +// outside faces meet. A strip of zero size is dropped. + +const PRECISION = 1e-6 + +// { depth, height, frontHeight, slope (degrees), thickness } +// Returns null when the numbers do not make this shape, otherwise +// { angle, topDepth, slopeLength, outline, span, lengths }. +export function slopedProfile({ depth: D, height: H, frontHeight: Hf, slope, thickness: t }) { + if (!(D > 0 && H > 0 && t > 0 && slope > 0 && slope < 90 && Hf >= 0 && Hf < H)) return null + const angle = (slope * Math.PI) / 180 + const run = (H - Hf) / Math.tan(angle) + if (run > D + PRECISION) return null + + const topDepth = D - run < PRECISION ? 0 : D - run + const top = topDepth > 0, front = Hf > 0 + const topCut = top ? t / Math.tan(angle) : 0 + const frontCut = front ? t * Math.tan(angle) : 0 + const slopeLength = Math.hypot(run, H - Hf) + const [cos, sin] = [Math.cos(angle), Math.sin(angle)] + + // [depth from the front, height], counter-clockwise from the front of the bottom. + const outline = [[0, 0], [D, 0], [D, H]] + if (top) outline.push([D - topDepth, H]) + if (front) outline.push([0, Hf]) + + return { + angle, + topDepth, + slopeLength, + outline, + // The stretch of the slope the tilted panel covers, low end first. + span: [[frontCut * cos, Hf + frontCut * sin], [run - topCut * cos, H - topCut * sin]], + lengths: { + tilted: slopeLength - frontCut - topCut, + top: top ? topDepth + t / sin : 0, + front: front ? Hf + t / cos : 0 + } + } +} + +// Why a sloped box cannot be drawn, in the words BoxRequest#check_slope uses; +// "" when it can. slope and frontHeight may be NaN for a blank or bad field. +// { height, depth, thickness, slope, frontHeight, lid, unit } +export function slopeProblem({ height, depth, thickness, slope, frontHeight, lid, unit }) { + if (!(slope > 0 && slope < 90)) return "Slope needs an angle above 0 and below 90 degrees." + if (!(frontHeight >= 0)) return "Front height needs a number, zero or more." + if (frontHeight >= height) return "Front height has to be lower than the height of the box." + if (lid === "back") return "A sloped box cannot have the lid with tabs along the back." + const round = (value) => Number(value.toFixed(2)) + const run = (height - frontHeight) / Math.tan((slope * Math.PI) / 180) + if (run > depth + PRECISION) { + return `At ${round(slope)}° the slope runs ${round(run)} ${unit} back, deeper than the box. Make the slope steeper, the front taller, or the box deeper.` + } + // The strips cut the sloped panel short at both ends; laser-cutter refuses one with nothing left. + const profile = slopedProfile({ depth, height, frontHeight, slope, thickness }) + if (profile && profile.lengths.tilted > PRECISION) return "" + return `At ${round(slope)}° from a front of ${round(frontHeight)} ${unit}, nothing is left of the sloped panel in this material. Make the front lower.` +} diff --git a/app/models/box_request.rb b/app/models/box_request.rb index 2970fa7..af1c169 100644 --- a/app/models/box_request.rb +++ b/app/models/box_request.rb @@ -16,7 +16,13 @@ class BoxRequest # 'plain' is a rectangle that lies on top. The last two lift off.log LIDS = %w[full back plain].freeze - LABELS = { notch: 'Notch length' }.freeze + # A front that slopes back: the angle above horizontal, in degrees, and the + # inside height of the front where the slope begins. Both blank is the + # upright box. A sloped box cannot have the lid with tabs along the back. + SLOPED = %i[slope front_height].freeze + SLOPED_LIDS = %w[full plain].freeze + + LABELS = { notch: 'Notch length', front_height: 'Front height' }.freeze # The narrowest notch worth cutting, per unit. The widest is a third of the # shortest side. On a box too small for both, the narrowest drops to half @@ -34,12 +40,6 @@ class BoxRequest KERF_DEFAULT = { 'in' => 0.026, 'mm' => 0.66 }.freeze class << self - # laser-cutter 2.0.0 draws only the full lid. Releases that draw the - # others say so with Laser::Cutter::Box::LIDS. - def lids_supported? - Laser::Cutter::Box.const_defined?(:LIDS) - end - # @return [Hash] what the gem fills in when a field is left blank, per unit def defaults gem_defaults = Laser::Cutter::Configuration.defaults @@ -70,6 +70,7 @@ def valid? check_notch if errors.empty? check_notch_count if errors.empty? check_choices + check_slope if errors.empty? errors.empty? end @@ -81,10 +82,16 @@ def lid LIDS.include?(@params[:lid]) ? @params[:lid] : LIDS.first end + # @return [Boolean] whether the form asks for a front that slopes back + def sloped? + SLOPED.any? { |key| @params[key].present? } + end + # @return [String] a file name that says which box is inside def filename(format) size = DIMENSIONS.first(3).map { |key| trim(number(key)) }.join('x') - "makeabox-#{size}#{units}-#{trim(number(:thickness))}t.#{format}" + slope = sloped? ? "-#{trim(number(:slope))}deg" : '' + "makeabox-#{size}#{units}-#{trim(number(:thickness))}t#{slope}.#{format}" end # Draws the box and returns the file's bytes. Yields the number of lines @@ -109,7 +116,8 @@ def configuration(file) (DIMENSIONS + OPTIONAL).each { |key| options[key] = number(key) if number(key) } options[:kerf] ||= KERF_DEFAULT.fetch(units) options[:page_size] = @params[:page_size] if @params[:page_size].present? - options[:lid] = lid if self.class.lids_supported? && lid != LIDS.first + options[:lid] = lid if lid != LIDS.first + SLOPED.each { |key| options[key] = number(key) } if sloped? Laser::Cutter::Configuration.new(options).tap(&:validate!) end @@ -202,6 +210,37 @@ def check_choices end size = @params[:page_size] errors << "#{size} is not a page size we know." if size.present? && !Laser::Cutter::PageManager::SIZES.key?(size) - errors << 'This lid needs laser-cutter 2.0.1 or newer.' if lid != LIDS.first && !self.class.lids_supported? + end + + # The same rules laser-cutter's Sloped::Request applies, said in the form's words. + def check_slope + return unless sloped? + + slope, front = SLOPED.map { |key| number(key) } + return errors << 'Slope needs an angle above 0 and below 90 degrees.' unless slope&.positive? && slope < 90 + return errors << 'Front height needs a number, zero or more.' unless front&.finite? && !front.negative? + return errors << 'Front height has to be lower than the height of the box.' if front >= number(:height) + return errors << 'A sloped box cannot have the lid with tabs along the back.' if SLOPED_LIDS.exclude?(lid) + + angle = slope * Math::PI / 180 + run = (number(:height) - front) / Math.tan(angle) + if run > number(:depth) + 1e-6 + return errors << "At #{trim(slope.round(2))}° the slope runs #{trim(run.round(2))} #{units} back, deeper than the box. " \ + 'Make the slope steeper, the front taller, or the box deeper.' + end + return if tilted_length(angle, run, front) > 1e-6 + + errors << "At #{trim(slope.round(2))}° from a front of #{trim(front.round(2))} #{units}, " \ + 'nothing is left of the sloped panel in this material. Make the front lower.' + end + + # The sloped panel's length once the strips at its ends have cut it short, + # as laser-cutter's Sloped::Profile#tilted_length works it out. + def tilted_length(angle, run, front) + thickness = number(:thickness) + top_depth = number(:depth) - run + front_cut = front.positive? ? thickness * Math.tan(angle) : 0.0 + top_cut = top_depth > 1e-6 ? thickness / Math.tan(angle) : 0.0 + Math.hypot(run, number(:height) - front) - front_cut - top_cut end end diff --git a/app/views/home/_generator.html.haml b/app/views/home/_generator.html.haml index c616546..abdcce8 100644 --- a/app/views/home/_generator.html.haml +++ b/app/views/home/_generator.html.haml @@ -18,25 +18,53 @@ data: {generator_target: 'form', action: 'submit->generator#generate'}} %p.hint{role: 'status', data: {generator_target: 'hint'}} + -# The first choices: the units, the lid and the shape of the front. + .side + .seg{role: 'group', 'aria-label': 'Units'} + - { 'in' => 'inches', 'mm' => 'mm' }.each do |unit, text| + %label + %input{type: 'radio', name: 'box[units]', value: unit, checked: unit == 'in', data: {generator_target: 'units', action: 'change->generator#convert'}} + %span= text + %label.pick + %span.sr Top of the box + %select{name: 'box[lid]', data: {generator_target: 'lid', action: 'change->generator#edit'}} + %option{value: 'full'} Closed box + %option{value: 'back'} Lid, tabs along the back + %option{value: 'plain'} Lid, no tabs + -# Not sent: an upright box leaves the slope fields disabled, so the form leaves them out. + %label.pick + %span.sr Front of the box + %select{data: {generator_target: 'shape', action: 'change->generator#reshape'}} + %option{value: 'upright'} Upright front + %option{value: 'sloped'} Front slopes back + %button.more{type: 'button', data: {action: 'generator#openSettings'}} Kerf, page, margins… + - { width: 5, height: 3, depth: 4 }.each do |name, value| .field{data: {key: name}} %label{for: "box_#{name}", data: {action: 'pointerdown->generator#scrub'}} = name.to_s.capitalize - %i drag or ↑↓ + %i drag, or ↑↓ keys .num %input{id: "box_#{name}", name: "box[#{name}]", value: value, inputmode: 'decimal', required: true, data: {generator_target: 'number', action: 'input->generator#edit focus->generator#focus blur->generator#blur keydown->generator#nudge'}} %span{data: {generator_target: 'unit'}} in - if name == :width -# On a phone the cell is too narrow for the whole label, so it says just "Reset". - %button.more.restart{type: 'button', 'aria-label': 'Reset to defaults', data: {action: 'generator#restart'}} - Reset - %span.wide to defaults + -# Reset asks first, in a small popup beside it. No, Escape or a click elsewhere puts it away. + .reset{data: {action: 'keydown.esc->generator#keep click@window->generator#dismiss'}} + %button.more.restart{type: 'button', 'aria-label': 'Reset to defaults', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', + data: {generator_target: 'restart', action: 'generator#ask'}} + Reset + %span.wide to defaults + .confirm{role: 'dialog', 'aria-label': 'Reset to defaults?', hidden: true, data: {generator_target: 'confirm'}} + %span Reset to defaults? + %button.more.yes{type: 'button', data: {action: 'generator#restart'}} Yes + %button.more.no{type: 'button', data: {action: 'generator#keep'}} No .field.thickness{data: {key: 'thickness'}} %label{for: 'box_thickness', data: {action: 'pointerdown->generator#scrub'}} Material thickness - %i drag or ↑↓ + %i drag, or ↑↓ keys .num %input#box_thickness{name: 'box[thickness]', value: 0.245, inputmode: 'decimal', required: true, data: {generator_target: 'number', action: 'input->generator#edit focus->generator#focus blur->generator#blur keydown->generator#nudge'}} @@ -46,28 +74,33 @@ .field.notch{data: {key: 'notch'}} %label{for: 'box_notch', data: {action: 'pointerdown->generator#scrub'}} Notch length - %i drag or ↑↓ + %i drag, or ↑↓ keys .num %input#box_notch{name: 'box[notch]', inputmode: 'decimal', placeholder: 'auto', data: {generator_target: 'optional', action: 'input->generator#edit focus->generator#focus blur->generator#blur keydown->generator#nudge'}} %span{data: {generator_target: 'unit'}} in %small.range{data: {generator_target: 'range'}} - .side - .seg{role: 'group', 'aria-label': 'Units'} - - { 'in' => 'inches', 'mm' => 'mm' }.each do |unit, text| - %label - %input{type: 'radio', name: 'box[units]', value: unit, checked: unit == 'in', data: {generator_target: 'units', action: 'change->generator#convert'}} - %span= text - %label.pick - %span.sr Top of the box - %select{name: 'box[lid]', data: {generator_target: 'lid', action: 'change->generator#edit'}} - %option{value: 'full'} Closed box - %option{value: 'back', disabled: !@settings[:lidsSupported]} Lid, tabs along the back - %option{value: 'plain', disabled: !@settings[:lidsSupported]} Lid, no tabs - - unless @settings[:lidsSupported] - %small.soon Lids need laser-cutter 2.0.1 or newer. - %button.more{type: 'button', data: {action: 'generator#openSettings'}} Kerf, page, margins… + .sloped{hidden: true, data: {generator_target: 'sloped'}} + .field{data: {key: 'slope'}} + %label{for: 'box_slope', data: {action: 'pointerdown->generator#scrub'}} + Slope + %i drag, or ↑↓ keys + .num + %input#box_slope{name: 'box[slope]', inputmode: 'decimal', disabled: true, + data: {generator_target: 'slope', action: 'input->generator#edit focus->generator#focus blur->generator#blur keydown->generator#nudge'}} + %span ° + .field{data: {key: 'front_height'}} + %label{for: 'box_front_height', data: {action: 'pointerdown->generator#scrub'}} + Front height + %i drag, or ↑↓ keys + .num + %input#box_front_height{name: 'box[front_height]', inputmode: 'decimal', disabled: true, + data: {generator_target: 'frontHeight', action: 'input->generator#edit focus->generator#focus blur->generator#blur keydown->generator#nudge'}} + %span{data: {generator_target: 'unit'}} in + %p.note + The front rises to the front height, then slopes back at this angle above horizontal until it meets the top. + Zero starts the slope at the bottom. Seven panels; the lid can be notched in or lie on top. %button.go{type: 'submit', data: {generator_target: 'go'}} Generate diff --git a/config/puma.rb b/config/puma.rb index 82c58d6..cfbb0b3 100644 --- a/config/puma.rb +++ b/config/puma.rb @@ -9,7 +9,7 @@ tag 'puma-makeabox' log_requests true -on_restart { puts 'restarting' } +before_restart { puts 'restarting' } worker_timeout 30 pidfile 'tmp/pids/puma.pid' diff --git a/cypress/e2e/generator.cy.js b/cypress/e2e/generator.cy.js index 640f5d1..9fc7a38 100644 --- a/cypress/e2e/generator.cy.js +++ b/cypress/e2e/generator.cy.js @@ -75,17 +75,38 @@ describe("making a box", () => { }) }) - it("resets the box to 5 × 4 × 3 in of 1/8 in material with the default kerf", () => { + it("resets to a closed, upright 5 × 4 × 3 in box of 1/4 in material with the default kerf", () => { cy.contains(".seg span", "mm").click() field("width").clear().type("300") field("thickness").clear().type("6") + field("lid").select("plain") + cy.get('[data-generator-target="shape"]').select("sloped") + cy.get(".sloped").should("be.visible") cy.contains(".field button", "Reset to defaults").click() + cy.contains(".reset .confirm button", "Yes").click() + cy.get(".reset .confirm").should("not.be.visible") cy.get('[name="box[units]"][value="in"]').should("be.checked") - for (const [name, value] of [["width", "5"], ["height", "4"], ["depth", "3"], ["thickness", "0.125"], ["kerf", "0.026"]]) field(name).should("have.value", value) + for (const [name, value] of [["width", "5"], ["height", "4"], ["depth", "3"], ["thickness", "0.25"], ["kerf", "0.026"]]) field(name).should("have.value", value) + field("lid").should("have.value", "full") + cy.get('[data-generator-target="shape"]').should("have.value", "upright") + cy.get(".sloped").should("not.be.visible") + cy.get(".stage svg polygon.tilted").should("not.exist") cy.get(".stage svg text").should("contain", "5 in").and("contain", "4 in").and("contain", "3 in") }) + it("keeps the box when the reset is answered No, or with Escape", () => { + field("width").clear().type("7") + cy.contains(".field button", "Reset to defaults").click() + cy.get(".reset .confirm").should("be.visible").and("contain", "Reset to defaults?") + cy.contains(".reset .confirm button", "No").should("be.focused").click() + cy.get(".reset .confirm").should("not.be.visible") + cy.contains(".field button", "Reset to defaults").should("be.focused").click() + cy.focused().type("{esc}") + cy.get(".reset .confirm").should("not.be.visible") + field("width").should("have.value", "7") + }) + it("reads a decimal comma, and converts it", () => { field("thickness").clear().type("0,25") cy.get(".hint").should("be.empty") @@ -337,6 +358,128 @@ describe("making a box", () => { }) }) + it("puts the units, the lid and the front first, wide enough for every option", () => { + // The widest option's text, in the select's own font, plus its padding and arrow. + // Measured in the app's document: the spec's own document has not loaded the + // app's web font, so it measures a fallback that is wider on Linux. + const fits = ($select) => { + const select = $select[0], page = select.ownerDocument, style = page.defaultView.getComputedStyle(select) + const probe = page.createElement("span") + Object.assign(probe.style, { position: "absolute", visibility: "hidden", whiteSpace: "pre", font: style.font, fontStretch: style.fontStretch }) + page.body.append(probe) + const widest = Math.max(...[...select.options].map((option) => { + probe.textContent = option.textContent + return probe.getBoundingClientRect().width + })) + probe.remove() + expect(select.getBoundingClientRect().width, select.options[0].textContent).to.be.at.least(widest + parseFloat(style.paddingLeft) + 16) + } + for (const width of [1440, 1000]) { + cy.viewport(width, 900) + cy.get(".side").then(($side) => cy.get(".field[data-key='width']").should(($width) => { + expect($side[0].getBoundingClientRect().right).to.be.at.most($width[0].getBoundingClientRect().left + 1) + })) + cy.get(".side select").each(($select) => cy.wrap($select).should(fits)) + cy.get("body").should(($body) => expect($body[0].scrollWidth).to.be.at.most(width)) + } + cy.viewport(1440, 900) + cy.screenshot("choices-first", { capture: "viewport" }) + }) + + it("lines the choices up beside the units pill when they sit above the measurements", () => { + const middle = (el) => { const box = el.getBoundingClientRect(); return Math.round(box.top + box.height / 2) } + cy.viewport(800, 900) + cy.get(".side .seg").then(($seg) => { + cy.get(".side select").each(($select) => expect(Math.abs(middle($select[0]) - middle($seg[0]))).to.be.at.most(4)) + }) + cy.get(".side").then(($side) => cy.get("#box_width").should(($width) => { + expect($side[0].getBoundingClientRect().bottom).to.be.at.most($width[0].getBoundingClientRect().top) + })) + cy.get(".side").scrollIntoView() + cy.screenshot("choices-tablet", { capture: "viewport" }) + + cy.viewport(390, 844) + cy.get("body").should(($body) => expect($body[0].scrollWidth).to.be.at.most(390)) + cy.get(".side").scrollIntoView() + cy.screenshot("choices-phone", { capture: "viewport" }) + }) + + it("changes a number by dragging its label right or up, and back left or down", () => { + const drag = (moves) => { + cy.get('label[for="box_width"]').then(($label) => { + const { left, top } = $label[0].getBoundingClientRect(), start = { clientX: left + 10, clientY: top + 5, pointerId: 1 } + cy.wrap($label).trigger("pointerdown", { ...start, button: 0 }) + for (const [dx, dy] of moves) cy.wrap($label).trigger("pointermove", { clientX: start.clientX + dx, clientY: start.clientY + dy, pointerId: 1 }) + cy.wrap($label).trigger("pointerup", { pointerId: 1 }) + }) + } + cy.get('label[for="box_width"] i').should("have.text", "drag, or ↑↓ keys") + drag([[24, 0]]) // four steps of 0.25 in to the right + field("width").should("have.value", "6") + drag([[0, -24]]) // and four more up + field("width").should("have.value", "7") + drag([[0, 48]]) // eight down + field("width").should("have.value", "5") + }) + + it("previews and cuts a box whose front slopes back", () => { + const shape = () => cy.get('[data-generator-target="shape"]') + field("lid").select("back") + cy.get(".sloped").should("not.be.visible") + field("slope").should("be.disabled") + + shape().select("sloped") + cy.get(".sloped").should("be.visible") + field("slope").should("have.value", "45") + field("front_height").should("have.value", "1.2") + field("lid").should("have.value", "full").find('option[value="back"]').should("be.disabled") + cy.get(".stage svg polygon.tilted").should("have.length", 1) + cy.get(".stage svg .dim text").should("contain", "45°") + + field("slope").clear().type("20") + cy.get(".hint").should("contain", "deeper than the box") + .and("have.css", "background-color", "rgb(255, 32, 32)") + .and("have.css", "color", "rgb(255, 255, 255)") + .and("have.css", "font-weight", "700") + cy.screenshot("hint", { capture: "viewport" }) + cy.get(".go").should("be.disabled") + field("slope").clear().type("60") + cy.get(".hint").should("be.empty") + + cy.get(".go").click() + cy.contains("dialog.cut dd", "1.2 in, sloping back at 60°") + cy.contains("dialog.cut .progress", "Ready", { timeout: 10000 }) + cy.screenshot("sloped", { capture: "viewport" }) + cy.get("dialog.cut button.x").click() + + // An upright box sends no slope at all. + shape().select("upright") + cy.get(".stage svg polygon.tilted").should("not.exist") + cy.request(`/box/download.svg?box[width]=5&box[height]=3&box[depth]=4&box[thickness]=0.245&box[slope]=60&box[front_height]=1.2`) + .its("headers.content-disposition").should("contain", "makeabox-5x3x4in-0.245t-60deg.svg") + }) + + it("lays the slope fields out on a phone", () => { + cy.viewport(390, 844) + cy.get('[data-generator-target="shape"]').select("sloped") + const top = (name) => field(name).then(($input) => Math.round($input[0].getBoundingClientRect().top)) + // Thickness, slope, front height and notch share a row, and Generate comes after them. + top("slope").then((row) => { + for (const name of ["thickness", "front_height", "notch"]) top(name).should("eq", row) + cy.get(".go").should(($go) => expect($go[0].getBoundingClientRect().top).to.be.greaterThan(row)) + }) + cy.get(".stage svg polygon.tilted").should("have.length", 1) + cy.get("body").should(($body) => expect($body[0].scrollWidth).to.be.at.most(390)) + field("front_height").clear().type("3") + cy.get(".hint").should("have.text", "Front height has to be lower than the height of the box.").and("be.visible") + cy.get("body").should(($body) => expect($body[0].scrollWidth).to.be.at.most(390)) + cy.get(".hint").scrollIntoView() + cy.screenshot("phone-hint", { capture: "viewport" }) + field("front_height").clear().type("1.2") + cy.get(".sloped").scrollIntoView() + cy.screenshot("phone-sloped", { capture: "viewport" }) + }) + it("shortens the heading on a phone", () => { cy.get(".hero h1").should("contain.text", "Fully symmetric enclosure boxes") cy.get(".hero h1 .short").should("not.be.visible") @@ -356,8 +499,8 @@ describe("making a box", () => { top("notch").should("be.greaterThan", first) }) cy.get("body").should(($body) => expect($body[0].scrollWidth).to.be.at.most(390)) - // A slim Generate bar sits above the controls. - cy.get(".go").then(($go) => cy.get("#box_width").should(($width) => expect($go[0].getBoundingClientRect().bottom).to.be.lessThan($width[0].getBoundingClientRect().top))) + // A slim Generate bar sits under the controls. + cy.get(".go").then(($go) => cy.get("#box_notch").should(($notch) => expect($go[0].getBoundingClientRect().top).to.be.greaterThan($notch[0].getBoundingClientRect().bottom))) cy.get(".go small").should("not.be.visible") cy.screenshot("phone", { capture: "viewport" }) }) diff --git a/cypress/e2e/lib.cy.js b/cypress/e2e/lib.cy.js index 44b91d6..e786367 100644 --- a/cypress/e2e/lib.cy.js +++ b/cypress/e2e/lib.cy.js @@ -1,6 +1,8 @@ // The pure modules behind the preview and the trace, tested without a page. import { tabCount, isoBox } from "../../app/javascript/lib/iso_box" import { chain } from "../../app/javascript/lib/laser_trace" +import { slopedProfile, slopeProblem } from "../../app/javascript/lib/sloped_profile" +import { isoSlopedBox } from "../../app/javascript/lib/iso_sloped_box" describe("tabCount", () => { it("is odd and at least three, counted the way laser-cutter counts", () => { @@ -66,3 +68,106 @@ describe("chain", () => { expect(chain(lines, 2)).to.eq(lines) }) }) + +describe("slopedProfile", () => { + const box = { depth: 6, height: 4, frontHeight: 1, slope: 45, thickness: 0.25 } + const close = (a, b) => expect(a).to.be.closeTo(b, 1e-9) + + it("computes the numbers laser-cutter's Sloped::Profile computes", () => { + const p = slopedProfile(box) + close(p.topDepth, 3) + close(p.slopeLength, 3 * Math.SQRT2) + expect(p.outline.map((point) => point.map((c) => Number(c.toFixed(9))))).to.deep.eq([[0, 0], [6, 0], [6, 4], [3, 4], [0, 1]]) + close(p.lengths.top, 3 + 0.25 * Math.SQRT2) + close(p.lengths.front, 1 + 0.25 * Math.SQRT2) + close(p.lengths.tilted, 3 * Math.SQRT2 - 0.5) + }) + + it("meets each strip on the outside, with no gap and no overlap", () => { + const p = slopedProfile(box) + const out = ([x, y]) => [x - 0.25 * Math.sin(p.angle), y + 0.25 * Math.cos(p.angle)] + const [low, high] = p.span.map(out) + close(high[0], 6 - p.lengths.top); close(high[1], 4) + close(low[0], 0); close(low[1], p.lengths.front) + }) + + it("drops a strip of zero size", () => { + const wedge = slopedProfile({ ...box, frontHeight: 0, slope: (Math.atan(4 / 6) * 180) / Math.PI }) + expect(wedge.outline).to.have.length(3) + expect([wedge.lengths.top, wedge.lengths.front]).to.deep.eq([0, 0]) + }) + + it("refuses what cannot be built", () => { + for (const bad of [{ slope: 0 }, { slope: 90 }, { slope: 20 }, { frontHeight: 4 }, { frontHeight: -1 }, { thickness: 0 }]) { + expect(slopedProfile({ ...box, ...bad }), JSON.stringify(bad)).to.eq(null) + } + }) +}) + +describe("isoSlopedBox", () => { + const box = { width: 5, height: 4, depth: 6, frontHeight: 1, slope: 45, thickness: 0.25, notch: 0, units: "in", hot: null } + const draw = (extra = {}) => { const b = { ...box, ...extra }; return isoSlopedBox(b, slopedProfile(b), tabCount) } + const count = (markup, cls) => markup.split(`class="${cls}"`).length - 1 + + it("draws the side, the front strip, the tilted panel and the top strip, with fingers", () => { + const { viewBox, markup } = draw({ lid: "full" }) + expect(count(markup, "face right") + count(markup, "face left") + count(markup, "face tilted") + count(markup, "face top")).to.eq(4) + expect(count(markup, "finger")).to.be.greaterThan(20) + expect(markup).to.contain(">5 in<").and.contain(">4 in<").and.contain(">6 in<").and.contain(">1 in<").and.contain(">45°<") + expect(viewBox.split(" ").map(Number).every(Number.isFinite)).to.eq(true) + }) + + it("lifts the tilted panel off for a plain lid", () => { + expect(draw({ lid: "plain" }).markup).to.contain('class="inside floor"') + expect(draw({ lid: "full" }).markup).not.to.contain('class="inside floor"') + }) + + // A plain lid lies on the side walls: a rectangle with no tabs, and none drawn after it. + it("draws the lifted plain lid without tabs", () => { + const afterTilted = (markup) => markup.slice(markup.indexOf('class="face tilted"')) + expect(count(afterTilted(draw({ lid: "plain" }).markup), "finger")).to.eq(0) + expect(count(afterTilted(draw({ lid: "full" }).markup), "finger")).to.be.greaterThan(0) + }) + + it("leaves out a strip of zero size", () => { + const { markup } = draw({ lid: "full", frontHeight: 0, slope: (Math.atan(4 / 6) * 180) / Math.PI }) + expect(count(markup, "face left") + count(markup, "face top")).to.eq(0) + expect(markup).to.contain(">33.7°<") + }) + + it("draws a box in millimetres at the same size as in inches", () => { + const mm = { width: 127, height: 101.6, depth: 152.4, frontHeight: 25.4, thickness: 6.35, units: "mm" } + expect(draw({ ...mm, lid: "full" }).viewBox).to.eq(draw({ lid: "full" }).viewBox) + }) + + it("marks the dimension being edited", () => { + expect(count(draw({ lid: "full", hot: "slope" }).markup, "dim hot")).to.eq(1) + }) +}) + +describe("slopeProblem", () => { + const box = { height: 3, depth: 5, thickness: 0.125, slope: 45, frontHeight: 1, lid: "full", unit: "in" } + + it("passes a box that can be drawn, from a front of zero too", () => { + expect(slopeProblem(box)).to.eq("") + expect(slopeProblem({ ...box, frontHeight: 0, slope: 60, lid: "plain" })).to.eq("") + }) + + it("says what is wrong in the words BoxRequest uses", () => { + expect(slopeProblem({ ...box, slope: 90 })).to.eq("Slope needs an angle above 0 and below 90 degrees.") + expect(slopeProblem({ ...box, slope: NaN })).to.eq("Slope needs an angle above 0 and below 90 degrees.") + expect(slopeProblem({ ...box, frontHeight: NaN })).to.eq("Front height needs a number, zero or more.") + expect(slopeProblem({ ...box, frontHeight: 3 })).to.eq("Front height has to be lower than the height of the box.") + expect(slopeProblem({ ...box, lid: "back" })).to.eq("A sloped box cannot have the lid with tabs along the back.") + expect(slopeProblem({ ...box, slope: 20 })).to.eq( + "At 20° the slope runs 5.49 in back, deeper than the box. Make the slope steeper, the front taller, or the box deeper." + ) + }) + + // The same box BoxRequest refuses: the strips cut the sloped panel short until nothing is left. + it("refuses a slope that leaves nothing of the sloped panel", () => { + const tight = { ...box, depth: 4, thickness: 0.245, frontHeight: 2.75 } + expect(slopeProblem(tight)).to.eq("At 45° from a front of 2.75 in, nothing is left of the sloped panel in this material. Make the front lower.") + expect(slopeProblem({ ...tight, frontHeight: 2 })).to.eq("") + }) +}) diff --git a/docs/badges/coverage_badge.svg b/docs/badges/coverage_badge.svg index f8bd31b..c311ec5 100644 --- a/docs/badges/coverage_badge.svg +++ b/docs/badges/coverage_badge.svg @@ -15,7 +15,7 @@ coverage coverage - 52% - 52% + 53% + 53% diff --git a/lib/makeabox/svg_renderer.rb b/lib/makeabox/svg_renderer.rb index 1ff63ee..c73dc71 100644 --- a/lib/makeabox/svg_renderer.rb +++ b/lib/makeabox/svg_renderer.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Makeabox - # laser-cutter (2.0.0 and 2.0.1) works out the size of the page again for every line it + # laser-cutter (2.x and 3.0) works out the size of the page again for every line it # writes to an SVG, which makes a 10 inch box take eight seconds instead of # a twentieth of one. The size cannot change while rendering, so it is kept. # diff --git a/spec/models/box_request_sloped_spec.rb b/spec/models/box_request_sloped_spec.rb new file mode 100644 index 0000000..57d7ec2 --- /dev/null +++ b/spec/models/box_request_sloped_spec.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +require 'rails_helper' + +# A front that slopes back: BoxRequest's slope and front_height. +RSpec.describe BoxRequest do + subject(:box) { described_class.new(params) } + + let(:params) do + { 'width' => '4', 'height' => '3', 'depth' => '5', 'thickness' => '0.125', 'units' => 'in', 'slope' => '45', 'front_height' => '1' } + end + + def errors_for(changes) + described_class.new(params.merge(changes)).tap(&:valid?).errors + end + + it { is_expected.to be_valid } + it { is_expected.to be_sloped } + + it 'is upright when both slope fields are blank' do + expect(described_class.new(params.merge('slope' => '', 'front_height' => ''))).not_to be_sloped + end + + it 'starts the slope at the bottom with a front height of zero' do + expect(errors_for('front_height' => '0', 'slope' => '60')).to be_empty + end + + it 'refuses an angle that is flat, upright or not a number' do + %w[0 90 steep].each do |slope| + expect(errors_for('slope' => slope)).to eq ['Slope needs an angle above 0 and below 90 degrees.'] + end + end + + it 'refuses a front height that is missing, negative or reaches the top' do + expect(errors_for('front_height' => '')).to eq ['Front height needs a number, zero or more.'] + expect(errors_for('front_height' => '-1')).to eq ['Front height needs a number, zero or more.'] + expect(errors_for('front_height' => '3')).to eq ['Front height has to be lower than the height of the box.'] + end + + it 'refuses the lid with tabs along the back' do + expect(errors_for('lid' => 'back')).to eq ['A sloped box cannot have the lid with tabs along the back.'] + expect(errors_for('lid' => 'plain')).to be_empty + end + + it 'refuses a slope that runs deeper than the box' do + expect(errors_for('slope' => '20')).to eq [ + 'At 20° the slope runs 5.49 in back, deeper than the box. Make the slope steeper, the front taller, or the box deeper.' + ] + end + + it 'rounds the angle it names to two places' do + expect(errors_for('slope' => '20.12345').first).to start_with 'At 20.12° the slope runs' + end + + # The strips cut the sloped panel short at both ends; laser-cutter refuses a panel with nothing left. + describe 'a slope that leaves nothing of the sloped panel' do + let(:tight) { { 'height' => '3', 'depth' => '4', 'thickness' => '0.245', 'slope' => '45', 'front_height' => '2.75' } } + + it 'is refused, and a lower front is not' do + expect(errors_for(tight)).to eq [ + 'At 45° from a front of 2.75 in, nothing is left of the sloped panel in this material. Make the front lower.' + ] + expect(errors_for(tight.merge('front_height' => '2'))).to be_empty + end + + it 'is what laser-cutter refuses too' do + expect { Laser::Cutter::Sloped::Profile.new(depth: 4, height: 3, front_height: 2.75, slope: 45, thickness: 0.245) } + .to raise_error(Laser::Cutter::InvalidOption, /no tilted panel/) + end + end + + it 'names the angle in the file name' do + expect(box.filename('svg')).to eq 'makeabox-4x3x5in-0.125t-45deg.svg' + end + + it 'hands laser-cutter the slope and the front height' do + config = box.configuration(File::NULL) + expect([config[:slope], config[:front_height]]).to eq [45.0, 1.0] + end + + it 'draws the box in both formats' do + expect(box.render('svg')).to include(' 'plain') } - it 'is refused while the installed laser-cutter cannot draw lids' do - allow(described_class).to receive(:lids_supported?).and_return(false) - expect(box).not_to be_valid - expect(box.errors).to eq ['This lid needs laser-cutter 2.0.1 or newer.'] - end - - it 'is accepted once it can' do - allow(described_class).to receive(:lids_supported?).and_return(true) - expect(box).to be_valid - end + it { is_expected.to be_valid } end end @@ -173,18 +164,6 @@ end end - describe '.lids_supported?' do - it 'is off for a laser-cutter that only draws the full lid' do - hide_const('Laser::Cutter::Box::LIDS') - expect(described_class.lids_supported?).to be false - end - - it 'is on once laser-cutter lists its lids' do - stub_const('Laser::Cutter::Box::LIDS', %i[full back plain]) - expect(described_class.lids_supported?).to be true - end - end - describe '#units and #lid' do it 'fall back to inches and the full lid for anything unknown' do box = described_class.new(params.merge('units' => 'furlongs', 'lid' => 'dome')) @@ -219,11 +198,6 @@ expect(box.configuration('/tmp/box.pdf')).to include(notch: 0.5, page_size: 'A4', page_layout: 'landscape', metadata: false) end - it 'falls back to the full lid when laser-cutter cannot draw another' do - allow(described_class).to receive(:lids_supported?).and_return(false) - expect(described_class.new(params.merge('lid' => 'plain')).configuration('/tmp/box.pdf')).to include(lid: 'full') - end - it 'passes the lid on' do expect(described_class.new(params.merge('lid' => 'plain')).configuration('/tmp/box.pdf')).to include(lid: 'plain') end diff --git a/spec/requests/boxes_spec.rb b/spec/requests/boxes_spec.rb index a34509f..621cfd7 100644 --- a/spec/requests/boxes_spec.rb +++ b/spec/requests/boxes_spec.rb @@ -140,6 +140,20 @@ def events expect(response.body).to include(']*disabled/) - expect(response.body).not_to include('Lids need laser-cutter 2.0.1 or newer.') end it 'embeds the discussion' do @@ -70,16 +69,4 @@ it 'leaves analytics out outside production' do expect(response.body).not_to include('googletagmanager') end - - context 'when the installed laser-cutter cannot draw lids' do - before do - allow(BoxRequest).to receive(:lids_supported?).and_return(false) - get '/' - end - - it 'shows them disabled, with a note' do - expect(response.body).to match(/]*disabled[^>]*value="plain"|]*value="plain"[^>]*disabled/) - expect(response.body).to include('Lids need laser-cutter 2.0.1 or newer.') - end - end end