diff --git a/index.html b/index.html index d7deedf..60fac02 100644 --- a/index.html +++ b/index.html @@ -115,6 +115,7 @@ + diff --git a/src/app.ts b/src/app.ts index f49d796..662ffb8 100644 --- a/src/app.ts +++ b/src/app.ts @@ -31,7 +31,7 @@ import { openDrawing } from "./bim/drawing"; import { ItemsPanel } from "./ui/items"; import { OffsetEdgeOp } from "./tools/offsetEdge"; import { faceFreeformTool } from "./tools/faceFreeform"; -import { AxisOp, ConnectOp, EdgeOp, ExtrudeOp, FillOp, FillToPlaneOp, ThreadOp, ImageOp, LoftOp, MidplaneOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, ScaleRefOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./tools/ops"; +import { bodyCenter, AxisOp, ConnectOp, EdgeOp, ExtrudeOp, FillOp, FillToPlaneOp, ThreadOp, ImageOp, LoftOp, MidplaneOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, ScaleRefOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./tools/ops"; import { add, dist, scale, toWorld, xDirFor } from "./geom"; import { entityPolylines } from "./sketch/curves"; import { FreeformTool } from "./tools/freeform"; @@ -41,13 +41,15 @@ import { BooleanOp } from "./tools/booleanOp"; import { FeatureOp, sketchesUsed } from "./tools/featureOp"; import { SketchTool } from "./tools/sketch"; import { definedCurves } from "./sketch/constraints"; -import { bodiesOf, edgeRefOf, edgesOfFace, faceRefOf, sameSel, sourcesOf, type AppContext, type Sel, type Tool } from "./tools/tool"; +import { bodiesOf, edgeRefOf, edgesOfFace, faceRefOf, sameSel, sourceFrame, sourcesOf, type AppContext, type Sel, type Tool } from "./tools/tool"; import { setupRightColumn } from "./ui/panels"; import type { ToolItem } from "./ui/ui"; import { UI } from "./ui/ui"; import { Wheel } from "./ui/wheel"; +import { Sentence } from "./ui/sentence"; import { evaluate, setUnits, setVariables } from "./units"; import { InputRouter } from "./view/input"; +import { pickTolerance } from "./device"; import { ViewCube } from "./view/viewcube"; import { PivotButton } from "./ui/pivot"; import { HelpPanel } from "./ui/help"; @@ -76,6 +78,10 @@ export class App implements AppContext { readonly wheel = new Wheel({ ui: this.ui, mainTools: () => this.mainTools(), onFold: () => this.tool === this.selectTool && this.selectTool.refresh() }); /** The Settings wheel: always on the screen while the wheel is on (folded to its cog unless opened). */ readonly settingsWheel = new Wheel({ ui: this.ui, mainTools: () => [] }, "settings"); + /** The sentence bar (More: Sentence bar): the pick, then what it offers, on one line - in place of the wheel while it is on. */ + sentence!: Sentence; + /** Where the view was last tapped (the sentence bar starts a sketch tool that acts where it is tapped right there). */ + private lastTapAt: { x: number; y: number; type: "mouse" | "pen" | "touch" } | null = null; /** Pictures to look at while modelling, each in a window over the model (under the buttons). */ readonly refImages = new RefImages((text, kind) => this.ui.toast(text, kind)); readonly web = new WebWindow(); @@ -102,6 +108,27 @@ export class App implements AppContext { this.selectTool = new SelectTool(this); this.tool = this.selectTool; this.input.handler = this.tool; + this.sentence = new Sentence({ + ui: this.ui, + view: this.view, + mainTools: () => this.mainTools(), + selection: () => this.selection, + mode: () => (this.tool === this.selectTool ? "model" : this.tool instanceof SketchTool ? "sketch" : this.tool instanceof FreeformTool ? "freeform" : "tool"), + sketchPicked: () => (this.tool instanceof SketchTool ? this.tool.pickedCount : 0), + anchor: () => this.pickAnchor(), + retap: () => { + const p = this.lastTapAt; + if (p) this.tool.tap?.({ x: p.x, y: p.y, type: p.type, shift: false, tol: pickTolerance(p.type) }, 1); + }, + }); + canvas.addEventListener( + "pointerup", + (e) => { + const r = canvas.getBoundingClientRect(); + this.lastTapAt = { x: e.clientX - r.left, y: e.clientY - r.top, type: (e.pointerType || "mouse") as "mouse" | "pen" | "touch" }; + }, + true, + ); // Headsets: bigger targets everywhere (CSS) - aiming a controller is less precise than a mouse. if (isHeadset) document.body.classList.add("headset"); // A spinner while the geometry engine works on something that takes a moment. @@ -295,6 +322,33 @@ export class App implements AppContext { this.refreshHighlights(); } + /** The sentence bar on or off (More: Sentence bar). Off, the tool wheel is back. */ + setSentence(on: boolean): void { + if (on === settings.value.sentence) return; + settings.set("sentence", on); + // (The guide text and what the pick offers are said for the one that is on.) + if (this.tool === this.selectTool) this.selectTool.refresh(); + } + + /** Where the last thing picked is on the model (the sentence bar's thread runs to it). */ + private pickAnchor(): Vec3 | null { + const sel = this.selection; + const s = sel[sel.length - 1]; + if (!s) return null; + const view = this.view; + if (s.kind === "face") return view.body(s.body)?.faces[s.face]?.center ?? null; + if (s.kind === "edge") return view.body(s.body)?.edges[s.edge]?.mid ?? null; + if (s.kind === "vertex") return view.vertexOf(s.body, s.vertex) ?? null; + if (s.kind === "body") return bodyCenter(this, bodiesOf(sel)); + if (s.kind === "profile") { + const src = sourcesOf(this, [s])[0]; + return src ? sourceFrame(this, src).base : null; + } + if (s.kind === "plane") return view.planeShownAt(s.id) ?? view.planeOf(s.id)?.origin ?? null; + if (s.kind === "axis") return view.axisOf(s.id)?.plane.origin ?? null; + return null; + } + setTool(tool: Tool | null): void { const next = tool ?? this.selectTool; const leavingOp = this.tool !== this.selectTool; @@ -962,10 +1016,15 @@ export class App implements AppContext { } mainTools(): ToolItem[] { - const wait = (label: string, accepts: Sel["kind"][], run: () => void) => () => { - this.selectTool.waitFor(label, accepts, run); - this.selectTool.refresh(); - }; + // (Marked: it asks for a pick after it is tapped. The sentence bar leaves those out - there the pick comes first.) + const wait = (label: string, accepts: Sel["kind"][], run: () => void) => + Object.assign( + () => { + this.selectTool.waitFor(label, accepts, run); + this.selectTool.refresh(); + }, + { needsPick: true }, + ); const bodies = () => bodiesOf(this.selection); const transform = (kind: ConstructorParameters[1], label: string) => wait(label, ["body", "face", "edge"], () => this.setTool(new TransformOp(this, kind, bodies()))); @@ -1440,6 +1499,12 @@ export class App implements AppContext { paintHints(); this.ui.refreshHint(); }); + // The sentence bar: what is picked and what can be done with it, on one line (in place of the tool wheel). + const sentenceState = document.getElementById("m-sentence-state")!; + const paintSentence = () => (sentenceState.textContent = settings.value.sentence ? "On" : "Off"); + paintSentence(); + settings.onChange(paintSentence); + moreItem("m-sentence", () => this.setSentence(!settings.value.sentence)); // Offline mode: the app kept on this device, so it works with no connection. const offlineState = document.getElementById("m-offline-state")!; const offline = new Offline((t, k) => this.ui.toast(t, k), (state) => (offlineState.textContent = state)); diff --git a/src/debug.ts b/src/debug.ts index 93626a3..a597576 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -136,6 +136,11 @@ export function installDebug(app: App): void { /** The tool wheel: where its groups and fanned-out tools are on the page, to point and tap at. */ wheel: () => app.wheel.describe(), + /** The sentence bar: what it says now (its words, where each is), and its switch. */ + sentence: (on?: boolean) => { + if (on !== undefined) app.setSentence(on); + return app.sentence.describe(); + }, /** Every tool the wheel offers now, by where it is ("Tools › Fillet"): the same as sg.actions(), arranged its way. */ wheelTools: () => app.wheel.tools(), diff --git a/src/settings.ts b/src/settings.ts index 739795e..1c205f9 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -56,6 +56,12 @@ export interface Settings { * the tools (kept as a setting for the code that asks). */ wheel: boolean; + /** + * The sentence (More: Sentence bar): a line at the bottom that says what is + * picked and what can be done with it, in place of the tool wheel. Off + * unless switched on. + */ + sentence: boolean; } const DEFAULTS: Settings = { @@ -88,6 +94,7 @@ const DEFAULTS: Settings = { showHints: true, offline: false, wheel: true, + sentence: false, version: 5, }; diff --git a/src/style.css b/src/style.css index 5a6e3b9..0c2e416 100644 --- a/src/style.css +++ b/src/style.css @@ -6423,3 +6423,509 @@ circle.wheel-plate { .web-win.lifted .web-grab { cursor: grabbing; } + +/* ------------------------------------------------------------ sentence bar */ +/* (More: Sentence bar. The app worked by finishing a sentence: the pick, what + it offers, the tool's options as words. Nothing here applies while it is off.) */ + +body.sentence-ui #toolbar, +body.sentence-ui #bottom-left, +body.sentence-ui #flyout, +body.sentence-ui #panel:not(:has(.text-input)) { + display: none !important; +} +#sentence[hidden], +#sentence-thread:not(.on) { + display: none; +} +#sentence { + --sn-h: 48px; + position: fixed; + left: 50%; + bottom: calc(10px + var(--safe-b)); + transform: translateX(-50%); + width: max-content; + min-width: 260px; + max-width: min(980px, calc(100vw - 268px)); + z-index: 12; + display: flex; + flex-direction: column; + align-items: stretch; + gap: 8px; + pointer-events: none; +} +#sentence > * { + pointer-events: auto; +} +.sn-line { + display: flex; + align-items: stretch; + min-height: var(--sn-h); + background: linear-gradient(180deg, rgba(40, 43, 49, 0.96), rgba(26, 28, 32, 0.97)); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + box-shadow: 0 12px 34px rgba(0, 0, 0, 0.45), inset 0 1px 0 rgba(255, 255, 255, 0.06); + backdrop-filter: blur(14px); + -webkit-backdrop-filter: blur(14px); + overflow: hidden; +} +.sn-row { + flex: 1 1 auto; + min-width: 0; + display: flex; + align-items: center; + gap: 4px; + padding: 5px 8px; + overflow-x: auto; + overflow-y: hidden; + scrollbar-width: none; + overscroll-behavior: contain; + touch-action: pan-x; + /* (More to the side: the words fade out at the edge they run under.) */ + -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 26px), transparent); + mask-image: linear-gradient(90deg, #000 calc(100% - 26px), transparent); +} +.sn-row::-webkit-scrollbar { + display: none; +} +.sn-row::after { + content: ""; + flex: 0 0 18px; +} +.sn-word { + flex: 0 0 auto; + position: relative; + display: inline-flex; + flex-direction: column; + justify-content: center; + align-items: flex-start; + min-height: 38px; + padding: 3px 11px; + border: 0; + border-radius: 11px; + background: rgba(255, 255, 255, 0.055); + color: var(--text); + font-size: 13.5px; + line-height: 1.15; + white-space: nowrap; + cursor: pointer; + transition: background 0.12s, transform 0.12s, box-shadow 0.12s, color 0.12s; + touch-action: pan-x; +} +.sn-word:hover { + background: rgba(255, 255, 255, 0.11); +} +.sn-word:active { + transform: scale(0.955); +} +.sn-body { + display: inline-flex; + align-items: center; + gap: 6px; +} +.sn-icon { + display: inline-grid; + width: 18px; + height: 18px; + opacity: 0.85; +} +.sn-icon svg { + width: 18px; + height: 18px; +} +.sn-swatch { + width: 16px; + height: 16px; + border-radius: 50%; + box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.25); +} +.sn-cap { + font-size: 9.5px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--muted); + margin-bottom: 1px; +} +.sn-more { + font-size: 9px; + opacity: 0.6; +} +.sn-kbd { + font: 10px/1 ui-monospace, Menlo, Consolas, monospace; + padding: 2px 4px; + border-radius: 4px; + background: rgba(255, 255, 255, 0.09); + color: var(--muted); +} +/* The subject: what the sentence is about. */ +.sn-word.sn-subject { + background: none; + font-weight: 650; + font-size: 14.5px; + padding-left: 8px; + padding-right: 6px; + color: #fff; +} +.sn-word.sn-subject:not(.quiet) { + background: linear-gradient(180deg, rgba(255, 206, 84, 0.24), rgba(255, 206, 84, 0.13)); + color: #ffe19a; + padding-left: 12px; + padding-right: 9px; +} +.sn-word.sn-subject.quiet { + cursor: default; + color: var(--muted); + font-weight: 600; +} +.sn-word.sn-subject.quiet.on { + color: #9cc4ff; +} +.sn-word.sn-subject.quiet:active { + transform: none; +} +.sn-x { + margin-left: 2px; + font-size: 15px; + line-height: 1; + opacity: 0.6; +} +/* (The subject, then what is said of it.) */ +.sn-row > .sn-subject::after { + content: ""; + position: absolute; + right: -3px; + top: 30%; + bottom: 30%; + width: 1px; + background: rgba(255, 255, 255, 0.14); +} +.sn-row > .sn-subject:not(.quiet)::after { + display: none; +} +/* Lit: the tool in use, a switch that is on, the option chosen. */ +.sn-word.on:not(.sn-subject):not(.sn-slot) { + background: var(--accent-soft); + color: #cfe2ff; + box-shadow: inset 0 0 0 1px rgba(61, 139, 255, 0.55); +} +.sn-word.sn-toggle:not(.on) .sn-text { + opacity: 0.55; + text-decoration: line-through; + text-decoration-color: rgba(255, 255, 255, 0.35); +} +/* A number: typed, or dragged sideways. */ +.sn-word.sn-value .sn-text { + font-variant-numeric: tabular-nums; + font-weight: 600; + border-bottom: 1px dashed rgba(255, 255, 255, 0.35); +} +.sn-word.sn-value { + cursor: ew-resize; +} +.sn-word.sn-value.scrub { + background: var(--accent-soft); + box-shadow: inset 0 0 0 1px rgba(61, 139, 255, 0.7), 0 0 0 4px rgba(61, 139, 255, 0.14); +} +/* A blank: filled by a tap on the model. */ +.sn-word.sn-slot .sn-text { + border-bottom: 2px solid rgba(255, 255, 255, 0.28); + padding: 0 4px 1px; + min-width: 34px; + color: var(--muted); +} +.sn-word.sn-slot.on .sn-text { + color: var(--text); + border-bottom-color: rgba(79, 209, 139, 0.75); +} +.sn-word.sn-slot.blank { + background: rgba(255, 206, 84, 0.1); +} +.sn-word.sn-slot.blank .sn-text { + border-bottom-color: #ffce54; + color: #ffe19a; + animation: sn-blank 1.4s ease-in-out infinite; +} +@keyframes sn-blank { + 50% { + border-bottom-color: rgba(255, 206, 84, 0.25); + } +} +.sn-word.pulse, +.sn-end-btn.pulse { + animation: sn-pulse 1.5s ease-out infinite; +} +@keyframes sn-pulse { + 0% { + box-shadow: 0 0 0 0 rgba(61, 139, 255, 0.65); + } + 100% { + box-shadow: 0 0 0 9px rgba(61, 139, 255, 0); + } +} +/* A word coming in: it rises into the line, one after another. */ +.sn-word.sn-in { + animation: sn-in 0.24s cubic-bezier(0.2, 0.8, 0.2, 1) backwards; +} +.sn-word.sn-in.pulse { + animation: sn-in 0.24s cubic-bezier(0.2, 0.8, 0.2, 1) backwards, sn-pulse 1.5s ease-out 0.3s infinite; +} +@keyframes sn-in { + from { + opacity: 0; + transform: translateY(9px) scale(0.94); + } +} +/* The end of the line: everything, the eraser, the tick. */ +.sn-end { + flex: 0 0 auto; + display: flex; + align-items: center; + gap: 4px; + padding: 5px 6px 5px 2px; +} +.sn-end:empty { + display: none; +} +.sn-end-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 5px; + min-width: 40px; + height: 38px; + padding: 0 9px; + border: 0; + border-radius: 11px; + background: rgba(255, 255, 255, 0.07); + color: var(--text); + cursor: pointer; + transition: background 0.12s, transform 0.12s; +} +.sn-end-btn svg { + width: 20px; + height: 20px; +} +.sn-end-btn:hover { + background: rgba(255, 255, 255, 0.14); +} +.sn-end-btn:active { + transform: scale(0.93); +} +.sn-end-btn.sn-done { + background: var(--accent); + color: #fff; + min-width: 48px; +} +.sn-end-btn.sn-done:hover { + background: #5a9dff; +} +.sn-end-btn.sn-all.on { + background: var(--accent-soft); + color: #cfe2ff; +} +.sn-end-name { + font-size: 13px; +} +/* The sheet over the line: everything for the pick, a word's kinds, a number's box. */ +.sn-sheet { + align-self: center; + max-width: 100%; + max-height: min(52vh, 420px); + overflow-y: auto; + padding: 10px 12px 12px; + background: rgba(28, 30, 34, 0.97); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5); + backdrop-filter: blur(14px); + -webkit-backdrop-filter: blur(14px); + overscroll-behavior: contain; +} +.sn-sheet[hidden] { + display: none; +} +.sn-sheet.sn-all { + align-self: stretch; + columns: 200px; + column-gap: 18px; +} +.sn-sheet.sn-all .sn-group { + break-inside: avoid; + margin-bottom: 12px; +} +body.sn-open .quick-actions, +body.sn-open .copy-toggle { + visibility: hidden; +} +.sn-sheet.sn-kids, +.sn-sheet.sn-typing { + align-self: flex-start; + margin-left: clamp(0px, calc(var(--sn-at, 50%) - 110px), calc(100% - 220px)); + min-width: 160px; + max-width: min(100%, 420px); +} +.sn-group-cap { + font-size: 10px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted); + margin: 0 0 6px 2px; +} +.sn-group-words { + display: flex; + flex-wrap: wrap; + gap: 5px; +} +.sn-sheet .sn-word { + min-height: 36px; +} +.sn-type { + display: flex; + align-items: center; + gap: 8px; +} +.sn-type-label { + color: var(--muted); + font-size: 12px; +} +.sn-type input { + width: 110px; + height: 38px; + padding: 0 10px; + border-radius: 10px; + border: 1px solid rgba(61, 139, 255, 0.7); + background: rgba(0, 0, 0, 0.35); + color: #fff; + font: 600 16px/1 system-ui, sans-serif; + font-variant-numeric: tabular-nums; + outline: none; + -webkit-user-select: text; + user-select: text; +} +.sn-type-unit { + color: var(--muted); +} +/* The sentence said: it lifts away. */ +.sn-ghost { + position: fixed; + z-index: 13; + pointer-events: none; + -webkit-mask-image: none; + mask-image: none; +} +/* The thread: from the subject to the thing it names. */ +#sentence-thread { + position: fixed; + inset: 0; + width: 100%; + height: 100%; + z-index: 8; + pointer-events: none; + overflow: visible; +} +#sentence-thread path { + fill: none; + stroke: #ffce54; + stroke-width: 1.5; + stroke-linecap: round; + opacity: 0.55; + filter: drop-shadow(0 0 3px rgba(255, 206, 84, 0.5)); +} +#sentence-thread circle { + fill: #ffce54; + stroke: rgba(0, 0, 0, 0.45); + stroke-width: 1; +} +/* Phones: the line is the whole width, over the undo row. */ +html[data-screen="phone"] #sentence { + left: calc(6px + var(--safe-l)); + right: calc(6px + var(--safe-r)); + transform: none; + width: auto; + max-width: none; + min-width: 0; + bottom: calc(8px + var(--safe-b)); +} +/* (Upright: the line has the bottom edge, where the tool strip was; undo and the guide text stay over it, whatever tool is open.) */ +@media (max-width: 720px) and (orientation: portrait) { + html[data-screen="phone"] body.sentence-ui #undo-dock { + bottom: calc(var(--sn-line, 48px) + 16px + var(--safe-b)) !important; + } + html[data-screen="phone"] body.sentence-ui #hint { + bottom: calc(var(--sn-line, 48px) + 70px + var(--safe-b)) !important; + } + html[data-screen="phone"] .sn-row.sn-wrap { + max-height: 94px; + } +} +html[data-screen="phone"] .sn-sheet { + max-height: 44vh; +} +html[data-screen="phone"] .sn-sheet.sn-all { + columns: auto; +} +@media (max-height: 480px) { + html[data-screen="phone"] #sentence { + left: calc(128px + var(--safe-l)); + bottom: calc(8px + var(--safe-b)); + } + .sn-sheet { + max-height: 56vh; + } +} +body.items-open #sentence { + margin-left: 120px; +} +@media (prefers-reduced-motion: reduce) { + .sn-word, + .sn-end-btn { + transition: none; + animation: none !important; + } +} + +.sn-others { + column-span: all; + border-top: 1px solid var(--line); + padding-top: 8px; +} +.sn-other { + color: var(--muted); + font-size: 12px; + line-height: 1.5; + padding-left: 2px; +} +.sn-row > .sn-subject.quiet + .sn-subject.quiet { + margin-left: 2px; +} + +.sn-row.sn-wrap { + flex-wrap: wrap; + align-content: flex-start; + row-gap: 4px; + max-height: 138px; + overflow-x: hidden; + overflow-y: auto; + touch-action: pan-y; + -webkit-mask-image: none; + mask-image: none; +} +.sn-row.sn-wrap::after { + display: none; +} +.sn-row.sn-wrap .sn-word { + touch-action: pan-y; +} +.sn-line:has(.sn-wrap) .sn-end { + align-self: flex-end; +} + +.sn-word.sn-slot .sn-text { + max-width: 190px; + overflow: hidden; + text-overflow: ellipsis; + min-height: 1.15em; +} +.sn-word.sn-slot:not(.on) .sn-text { + min-width: 52px; +} diff --git a/src/tools/sketch.ts b/src/tools/sketch.ts index 768898b..cca42db 100644 --- a/src/tools/sketch.ts +++ b/src/tools/sketch.ts @@ -1098,6 +1098,11 @@ export class SketchTool implements Tool { return box; } + /** How many curves and points are picked now (the sentence bar offers what can be done with them). */ + get pickedCount(): number { + return this.selected.size + this.selPts.length; + } + // ---------------------------------------------------------------- menu private updateMenu(): void { diff --git a/src/ui/sentence.ts b/src/ui/sentence.ts new file mode 100644 index 0000000..b999f1a --- /dev/null +++ b/src/ui/sentence.ts @@ -0,0 +1,903 @@ +// The sentence bar: the app worked by finishing a sentence. +// +// One line at the bottom of the screen always says where things stand, and it +// is written by touching the model: the pick is its subject ("1 face"), what +// can be done with that pick are the words offered after it (only those - a +// tool that needs something else picked is not there), the tool chosen is its +// verb, and the tool's options are the rest of the sentence: a blank to fill by +// tapping the model ("Axis ____"), a word to swap ("One side"), a number to +// type or to drag sideways ("12 mm"). The tick ends the sentence (Done), the +// eraser takes the last part back (Cancel, then the pick itself). +// +// With nothing picked the sentence starts with "Make": only what makes +// something new is offered, with the view's own tools. A thread runs from the +// subject to the thing it names on the model, so it is always plain what the +// sentence is about. +// +// It shows the very ToolItems and window parts the other ways of working +// hold (`ui.shown()`, `ui.panelContent()`), so a tool added to the app is in +// the sentence by itself. On only while its switch is (More: Sentence bar); +// off, nothing of it is on the page. + +import { settings } from "../settings"; +import type { Vec3 } from "../doc/types"; +import { QUICK } from "../tools/quickActions"; +import type { Sel } from "../tools/tool"; +import { evaluate, toDisplay, UNIT_LABEL, units } from "../units"; +import type { Viewport } from "../view/viewport"; +import { iconNameFor, icons, type IconName } from "./icons"; +import { numpadInput, openNumpad } from "./numpad"; +import { selectAll } from "./textField"; +import { el, usable, type ToolItem, type UI } from "./ui"; +import { ALIAS, GROUP_OF, RANK } from "./wheel"; + +export interface SentenceHost { + readonly ui: UI; + readonly view: Viewport; + mainTools(): ToolItem[]; + /** What is picked on the model. */ + selection(): Sel[]; + /** Where the work is: the model, a sketch, a freeform shape, or another tool. */ + mode(): "model" | "sketch" | "freeform" | "tool"; + /** In a sketch: how many curves and points are picked. */ + sketchPicked(): number; + /** Where the pick is on the model (for the thread to it). */ + anchor(): Vec3 | null; + /** In a sketch: tap the view again where it was last tapped (a tool that acts where it is tapped, started for the piece picked there). */ + retap(): void; +} + +/** One word of the sentence. */ +interface Word { + /** The same word, drawn again: it stays where it is (a new one comes in). */ + key: string; + kind: "subject" | "verb" | "slot" | "choice" | "toggle" | "value" | "button"; + label: string; + /** A small name over it (what the option is: "Ends", "Distance"). */ + cap?: string; + icon?: IconName; + swatch?: string; + /** Lit: the tool in use, a switch that is on, the option chosen. */ + on?: boolean; + /** A blank waiting for a tap on the model. */ + blank?: boolean; + /** The step to take next. */ + pulse?: boolean; + /** The subject with nothing picked, a group's name: said, not tapped. */ + quiet?: boolean; + kbd?: string; + run?: () => void; + /** What it opens: a tool's kinds, a choice's other options. */ + kids?: Word[]; + /** A number: typed, or dragged sideways. */ + value?: { now: number; text: string; kind: "length" | "angle" | "number" | "int"; put(v: number): void; min?: number; max?: number }; + /** Takes the subject away (the pick let go). */ + lets?: boolean; + /** A tool with kinds that starts as it was used last on a tap (a sketch's Rectangle); its kinds on a second tap or a held press. */ + first?: boolean; +} + +interface Built { + subject: Word; + words: Word[]; + /** Everything there is for this pick, by what it is for (the sheet over the line). */ + groups: { cap: string; words: Word[] }[]; + done?: { label: string; run: () => void; pulse?: boolean }; + cancel?: { label: string; run: () => void }; + /** A sketch's way out (its own tick: the sentence there is the whole drawing). */ + exit?: { label: string; run: () => void; pulse?: boolean }; + /** Whose sentence it is: a new subject brings every word in afresh. */ + about: string; + /** Tools this pick has no use for, each with what it needs instead (said under everything it does offer). */ + others?: string[]; +} + +const calm = () => matchMedia("(prefers-reduced-motion: reduce)").matches; +/** A tick under the finger (phones that have it). */ +const buzz = (ms: number | number[] = 5) => { + try { + navigator.vibrate?.(ms); + } catch { + // (not allowed here: nothing lost) + } +}; +const notSep = (it: ToolItem) => !it.id.startsWith("---"); +const needsPick = (it: ToolItem) => !!(it.run as { needsPick?: boolean } | undefined)?.needsPick; + +/** Started with nothing picked, these change what is there (they are offered once the bodies or the edge are picked). */ +const CHANGES = new Set(["offsetEdge", "subtract", "intersect"]); + +/** Only what makes something new (nothing picked): a tool that asks for a pick after its tap is left out, with any group left empty. */ +function makers(items: ToolItem[]): ToolItem[] { + const out: ToolItem[] = []; + for (const it of items) { + if (CHANGES.has(it.id)) continue; + if (it.children?.length) { + const children = makers(it.children); + const runs = it.run && !needsPick(it); + if (!children.length && !runs) continue; + out.push({ ...it, children, run: runs ? it.run : undefined }); + } else if (it.run && !needsPick(it)) out.push(it); + } + return out; +} + +/** In a sketch: tools for curves that are picked (the rest draw something new). */ +const SK_PICKED = new Set(["move", "rotate", "scale", "mirror", "pattern", "offset", "fillet", "trim", "extend", "split", "align", "delete"]); +/** Of those, the ones that act where the view is tapped: started for the piece picked, at the place it was picked. */ +const SK_RETAP = new Set(["trim", "extend", "split", "offset", "fillet"]); +/** And of those, the ones done at that tap (nothing more to set): picking is on again after it. */ +const SK_ONCE = new Set(["trim", "split"]); +/** The model's groups, in the order they are said. */ +const GROUPS = ["create", "modify", "transform", "combine", "construct", "freeform", "sketch"]; + +export class Sentence { + private readonly root = el("div", ""); + private readonly sheet = el("div", "sn-sheet"); + private readonly line = el("div", "sn-line"); + private readonly row = el("div", "sn-row"); + private readonly end = el("div", "sn-end"); + private readonly thread = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + private readonly threadPath = document.createElementNS("http://www.w3.org/2000/svg", "path"); + private readonly threadDot = document.createElementNS("http://www.w3.org/2000/svg", "circle"); + private queued = false; + private built: Built | null = null; + /** What the sheet shows: every word for the pick, one word's kinds, or a number being typed. */ + private open: { kind: "all" } | { kind: "kids"; key: string } | { kind: "type"; key: string } | null = null; + private typing: { end(keep: boolean): void } | null = null; + private about = ""; + /** The thread's ends as last drawn (drawn again only when one moved). */ + private threadSig = ""; + private anchor: Vec3 | null = null; + /** Where the view is on the page (measured again only when the page is laid out anew). */ + private viewAt: { left: number; top: number } | null = null; + /** What was picked when the tool now running was started: the sentence still starts with it. */ + private lastPick = ""; + + constructor(private readonly host: SentenceHost) { + this.root.id = "sentence"; + this.root.hidden = true; + this.line.append(this.row, this.end); + this.root.append(this.sheet, this.line); + this.sheet.hidden = true; + this.thread.id = "sentence-thread"; + this.thread.setAttribute("aria-hidden", "true"); + this.threadDot.setAttribute("r", "3.5"); + this.thread.append(this.threadPath, this.threadDot); + document.body.append(this.thread, this.root); + // (Never through to the model: a press on the line is the line's.) + for (const type of ["pointerdown", "pointerup", "click", "dblclick", "wheel", "contextmenu"] as const) this.root.addEventListener(type, (e) => e.stopPropagation()); + this.root.addEventListener("contextmenu", (e) => e.preventDefault()); + // A press anywhere else puts the sheet away (and is whatever it is there). + document.addEventListener( + "pointerdown", + (e) => { + if (!this.open || this.root.contains(e.target as Node) || (e.target as HTMLElement).closest?.(".numpad")) return; + this.typing?.end(true); + this.close(); + }, + true, + ); + // Esc puts the sheet away first (then it is the tool's, as ever). + document.addEventListener( + "keydown", + (e) => { + if (e.key !== "Escape" || !this.open || this.typing) return; + e.stopPropagation(); + e.preventDefault(); + this.close(); + }, + true, + ); + // The column, the bar or the tool's window changed: the sentence is said again. + const ui = host.ui; + const tools = ui.onTools; + ui.onTools = () => (tools?.(), this.changed()); + const panel = ui.onPanel; + ui.onPanel = () => (panel?.(), this.changed()); + settings.onChange(() => this.sync()); + // (How tall the line is now - a tool's sentence can run to a second line: undo and the guide text on a phone sit just over it.) + new ResizeObserver(() => document.body.style.setProperty("--sn-line", `${Math.round(this.line.getBoundingClientRect().height)}px`)).observe(this.line); + host.view.frameHooks.add(() => this.drawThread()); + // (The line slid along: the thread still starts at its subject, or at the line's near end once that is out of sight.) + this.row.addEventListener("scroll", () => ((this.threadSig = ""), this.drawThread()), { passive: true }); + addEventListener("resize", () => { + this.viewAt = null; + if (this.on) ((this.threadSig = ""), this.drawThread()); + }); + this.sync(); + } + + get on(): boolean { + return settings.value.sentence; + } + + /** On or off: off, the line and its thread are away and the page is as it was. */ + private sync(): void { + const on = this.on; + document.body.classList.toggle("sentence-ui", on); + if (this.root.hidden === !on) return void (on && this.changed()); + this.root.hidden = !on; + if (!on) { + this.typing?.end(false); + this.open = null; + this.sheet.hidden = true; + this.thread.classList.remove("on"); + this.threadSig = ""; + document.body.classList.remove("sn-open"); + return; + } + this.changed(); + } + + /** Something it shows changed: drawn again once, after whatever else changes with it. */ + changed(): void { + if (!this.on || this.queued) return; + this.queued = true; + queueMicrotask(() => { + this.queued = false; + if (this.on) this.render(); + }); + } + + // ------------------------------------------------------------ what it says + + private build(): Built { + const { ui } = this.host; + const mode = this.host.mode(); + const { column, bar } = ui.shown(); + const panel = ui.panelContent(); + if (mode === "sketch") return this.sketch(column, bar, panel); + if (mode === "model" && !panel) return this.model(column, bar); + return this.tool(column, panel, mode); + } + + /** A tool or action as a word (its kinds, the words it opens). */ + private verb(it: ToolItem, pre = "v"): Word { + const kids = (it.children ?? []).filter(notSep).map((c) => this.verb(c, `${pre}-${it.id}`)); + const v = it.value; + return { + key: `${pre}-${it.id}`, + kind: v ? "value" : "verb", + label: it.short ?? it.label, + icon: it.swatch ? undefined : it.icon, + swatch: it.swatch, + on: it.active, + pulse: it.pulse, + kbd: it.shortcut, + run: it.run ? () => it.run!() : undefined, + kids: kids.length ? kids : undefined, + first: !!it.variantsWhenActive && !!it.run, + value: v ? { now: Number(v.now) || 0, text: v.now, kind: v.int ? "int" : "number", put: (n) => v.put(n), min: v.min, max: v.max } : undefined, + }; + } + + /** The model: what is picked, then what it offers - or, with nothing picked, what makes something new. */ + private model(column: ToolItem[], bar: ToolItem[]): Built { + const sel = this.host.selection(); + const main = this.host.mainTools(); + let items = usable(column).filter(notSep); + const view = usable(bar).filter(notSep); + if (!sel.length) { + items = makers(items); + const groups: Built["groups"] = []; + const first = items.filter((it) => !it.children?.length); + if (first.length) groups.push({ cap: "Start", words: first.map((it) => this.verb(it)) }); + // (Shapes first, then what is brought in, then the helpers.) + const order = ["freeform", "more", "construct"]; + const rankOf = (id: string) => (order.indexOf(id) + 1 || order.length + 1); + for (const g of [...items].sort((a, b) => rankOf(a.id) - rankOf(b.id))) if (g.children?.length) groups.push({ cap: g.label, words: g.children.filter(notSep).map((c) => this.verb(c)) }); + if (view.length) groups.push({ cap: "View", words: view.map((it) => this.verb(it)) }); + return { subject: { key: "s-make", kind: "subject", label: "Make", quiet: true }, words: groups.flatMap((g) => g.words), groups, about: "make" }; + } + const des = items.find((it) => it.id === "deselect"); + items = items.filter((it) => it !== des); + const name = des?.sub ?? `${sel.length} picked`; + // Each of its tools with the main tools of its kind (as the wheel has them); its own (Delete, Color) under its name. + const where = new Map(); + const walk = (its: ToolItem[], g: string) => { + for (const it of its) { + if (!where.has(it.id)) where.set(it.id, g); + walk(it.children ?? [], g); + } + }; + for (const g of main) walk([g], g.id); + const groupOf = (id: string) => GROUP_OF[id] ?? where.get(ALIAS[id] ?? id) ?? "own"; + const by = new Map(); + for (const it of items) { + const g = groupOf(it.id); + by.set(g, [...(by.get(g) ?? []), it]); + } + const rank = (it: ToolItem) => { + const k = RANK.indexOf(ALIAS[it.id] ?? it.id); + return k < 0 ? RANK.length : k; + }; + const groups: Built["groups"] = []; + for (const g of GROUPS) { + const its = by.get(g); + if (its?.length) groups.push({ cap: main.find((m) => m.id === g)?.label ?? g, words: [...its].sort((a, b) => rank(a) - rank(b)).map((it) => this.verb(it)) }); + } + const own = [...(by.get("own") ?? []), ...(by.get("more") ?? [])]; + if (own.length) groups.push({ cap: name, words: own.map((it) => this.verb(it)) }); + if (view.length) groups.push({ cap: "View", words: view.map((it) => this.verb(it)) }); + // On the line: the likeliest next for this kind of pick first, then the rest as grouped. + const kind = sel[sel.length - 1].kind as keyof typeof QUICK; + const quick: readonly string[] = sel.every((s) => s.kind === kind) ? (QUICK[kind] ?? []) : []; + const all = groups.flatMap((g) => g.words); + const front = quick.map((id) => all.find((w) => w.key === `v-${id}`)).filter((w): w is Word => !!w); + const words = [...front, ...all.filter((w) => !front.includes(w))]; + const subject: Word = { key: "s-pick", kind: "subject", label: name, lets: true, run: () => des?.run?.() }; + // What it has no use for, and what those need instead: said, never offered. + const others: string[] = []; + const whys = (its: ToolItem[]) => { + for (const it of its) { + if (it.disabled && it.why && it.label) others.push(`${it.label}: ${it.why.charAt(0).toLowerCase()}${it.why.slice(1)}`); + else if (!it.disabled) whys(it.children ?? []); + } + }; + whys(column); + return { subject, words, groups, others, about: `pick:${sel.map((s) => JSON.stringify(s)).join()}` }; + } + + /** A sketch: what draws something new - and, with curves picked, what can be done with them. */ + private sketch(column: ToolItem[], bar: ToolItem[], panel: ReturnType): Built { + const picked = this.host.sketchPicked(); + const items = usable(column).filter(notSep); + const exit = items.find((it) => it.id === "exit"); + const select = items.find((it) => it.id === "select"); + const tools = items.filter((it) => it !== exit && it !== select); + const drawing = tools.some((it) => it.active); + const forPick = tools.filter((it) => SK_PICKED.has(it.id)); + const draw = tools.filter((it) => !SK_PICKED.has(it.id)); + const retapped = (it: ToolItem): Word => { + const w = this.verb(it); + // (It acts where the view is tapped: on the piece picked, where it was picked. One done at that tap leaves picking on.) + if (SK_RETAP.has(it.id) && it.run) { + const start = (run: () => void) => () => { + run(); + this.host.retap(); + if (SK_ONCE.has(it.id)) select?.run?.(); + }; + w.run = start(w.run!); + for (const k of w.kids ?? []) if (k.run) k.run = start(k.run); + } + return w; + }; + const words: Word[] = []; + const groups: Built["groups"] = []; + // A tool is on: Select puts it down (the way back to picking). + if (drawing && select && !select.active) words.push({ ...this.verb(select), label: "Stop" }); + const mine = panel ? this.said(panel) : []; + if (panel && mine.length) words.push({ key: "t-title", kind: "subject", label: panel.title, quiet: true }, ...mine); + // (Said once: the window's own Delete, not the column's too.) + const said = new Set(mine.map((w) => w.label)); + const busy = forPick.find((it) => it.active); + if (busy) { + // A tool for the picked curves is at work (Extend waiting for the line to reach): it alone, lit, until it is put down. + words.push(this.verb(busy)); + } else if (picked > 0) { + // Curves picked: what can be done with them - nothing else. + const w = forPick.filter((it) => !said.has(it.label)).map(retapped); + words.push(...w); + if (w.length) groups.push({ cap: `${picked} picked`, words: w }); + } else { + // Nothing picked: what draws something new. + const d = draw.map((it) => this.verb(it)); + // (The tool in use first: it is what the sentence is about now.) + words.push(...d.filter((w) => w.on), ...d.filter((w) => !w.on)); + if (d.length) groups.push({ cap: "Draw", words: d }); + } + const view = usable(bar).filter(notSep).map((it) => this.verb(it)); + words.push(...view); + if (view.length) groups.push({ cap: "View", words: view }); + return { + subject: { key: "s-sketch", kind: "subject", label: "Sketch", icon: "sketch", quiet: true }, + words, + groups, + done: panel?.done ? { label: "Done", run: panel.done } : undefined, + cancel: panel?.cancel ? { label: "Cancel", run: panel.cancel } : undefined, + exit: exit?.run ? { label: "Exit Sketch", run: () => exit.run!(), pulse: exit.pulse } : undefined, + about: `sketch:${picked > 0 ? "picked" : drawing ? "draw" : "idle"}`, + }; + } + + /** A tool at work: its name, then its window's parts as the rest of the sentence. */ + private tool(column: ToolItem[], panel: ReturnType, mode: string): Built { + const items = usable(column).filter(notSep); + const out = items.find((it) => it.id === "cancel") ?? items.find((it) => it.id === "exit"); + const rest = items.filter((it) => it !== out && it.id !== "deselect").map((it) => this.verb(it, "c")); + // (Its window says it all; a tool with none - Measure, Section View - has its own buttons.) + const words = panel ? this.said(panel) : mode === "model" ? [] : rest; + const title = panel?.title ?? (out?.label.startsWith("Exit ") ? out.label.slice(5) : (items.find((it) => it.active)?.label ?? out?.label ?? "Tool")); + const cancel = panel?.cancel ?? (out?.run ? () => out.run!() : undefined); + const name = panel?.cancel ? "Cancel" : (out?.label ?? "Cancel"); + return { + subject: { key: "s-tool", kind: "subject", label: title, on: true, quiet: true }, + // (Its own name is said once.) + words: words.filter((w) => !(w.label === title && w.on && !w.kids)), + groups: [], + done: panel?.done ? { label: "Done", run: panel.done } : undefined, + // (A way out named Done beside the tick would be the tick twice.) + cancel: cancel && !(panel?.done && name === "Done") ? { label: name, run: cancel } : undefined, + about: `tool:${title}`, + }; + } + + /** A tool's window as words: blanks, words to swap, switches, numbers, things to tap. */ + private said(p: NonNullable>): Word[] { + const ui = this.host.ui; + const out: Word[] = []; + let k = 0; + for (const it of p.items) { + const key = `p-${it.type}-${"label" in it && it.label ? it.label : k}`; + k++; + // (Not filled: a blank - what to tap for it is the guide text's to say. Filled: what it holds.) + if (it.type === "slot") out.push({ key, kind: "slot", cap: it.label, label: it.filled ? it.value : "", blank: it.active, on: it.filled, run: () => it.onClick() }); + else if (it.type === "choice") { + if (!it.options.length) continue; + const now = it.options.find((o) => o.id === it.value); + const kids = it.options.map((o): Word => ({ key: `${key}-${o.id}`, kind: "verb", label: o.label, on: o.id === it.value, run: () => it.onChange(o.id) })); + // (One thing to do and no name - a slot's Clear: a tap.) + if (it.options.length === 1 && !it.label) out.push({ key, kind: "button", label: it.options[0].label, run: kids[0].run }); + else out.push({ key, kind: "choice", cap: it.label, label: now?.label ?? it.options.map((o) => o.label).slice(0, 3).join(" · "), kids }); + } else if (it.type === "toggle") out.push({ key, kind: "toggle", label: it.label, on: it.value, run: () => it.onChange(!it.value) }); + else if (it.type === "number" || it.type === "slider") { + const kind = it.type === "slider" || it.kind === "number" ? "number" : (it.kind ?? "length"); + const len = kind === "length"; + const text = it.type === "slider" ? (it.show?.(it.value) ?? String(+it.value.toFixed(2))) : len ? `${+toDisplay(it.value).toFixed(3)} ${UNIT_LABEL[units()]}` : kind === "angle" ? `${+it.value.toFixed(2)}°` : String(+it.value.toFixed(3)); + const put = (to: number) => { + let v = to; + if (it.type === "slider") v = Math.min(it.max, Math.max(it.min, v)); + else if (it.min !== undefined) v = Math.max(it.min, v); + if (kind === "int") v = Math.round(v); + it.onInput(v); + // (A tool that does not draw its window again keeps this part: it holds the new value from now on.) + it.value = v; + ui.syncPanelValue(it, v); + this.changed(); + }; + out.push({ key, kind: "value", cap: it.label, label: text, value: { now: it.value, text, kind, put, min: it.type === "slider" ? it.min : it.min, max: it.type === "slider" ? it.max : undefined } }); + } else if (it.type === "button") out.push({ key, kind: "button", label: it.label, icon: it.icon ?? iconNameFor(it.label), pulse: it.primary, run: () => it.onClick() }); + else if (it.type === "chips") { + if (!it.chips.length) continue; + const kids = it.chips.map((c, i): Word => ({ key: `${key}-${i}`, kind: "toggle", label: c.glyph ? `${c.glyph} ${c.label}` : c.label, on: !!c.on, run: () => c.onClick() })); + if (kids.length <= 2) out.push(...kids); + else out.push({ key, kind: "choice", label: it.label ?? "Add", kids }); + } + } + for (const a of usable(p.actions).filter(notSep)) out.push(this.verb(a, "a")); + return out; + } + + // ------------------------------------------------------------------ drawing + + private render(): void { + const b = (this.built = this.build()); + const fresh = b.about !== this.about; + this.about = b.about; + // The pick, then its tool: the sentence goes on from the word it started with. + if (b.about.startsWith("pick:")) this.lastPick = b.subject.label; + else if (!b.about.startsWith("tool:")) this.lastPick = ""; + const lead: Word[] = b.about.startsWith("tool:") && this.lastPick ? [{ key: "s-was", kind: "subject", label: this.lastPick, quiet: true }] : []; + // (Another sentence: whatever was open belonged to the last one.) + if (fresh && this.open) { + this.typing?.end(false); + this.open = null; + } + this.fill(this.row, [...lead, b.subject, ...b.words], fresh); + this.row.classList.toggle("sn-make", b.subject.key === "s-make"); + // (A tool's sentence is read whole: it runs on to the next line, as writing does. What a pick offers is one line to slide along.) + this.row.classList.toggle("sn-wrap", b.about.startsWith("tool:")); + if (fresh) this.row.scrollLeft = 0; + // The end of the line: everything for this pick, the eraser, the tick. + this.end.replaceChildren(); + if (b.groups.length && b.words.length > 3) { + const all = this.endButton("grid", "Everything for this", () => this.toggle({ kind: "all" })); + all.classList.add("sn-all"); + all.classList.toggle("on", this.open?.kind === "all"); + this.end.append(all); + } + if (b.cancel) this.end.append(this.endButton("close", b.cancel.label, () => (buzz(), b.cancel!.run()))); + if (b.done) { + const ok = this.endButton("check", b.done.label, () => this.finish(b.done!.run)); + ok.classList.add("sn-done"); + this.end.append(ok); + } + if (b.exit) { + const x = this.endButton("exit", b.exit.label, () => this.finish(b.exit!.run)); + x.classList.add("sn-exit"); + x.classList.toggle("pulse", !!b.exit.pulse); + x.append(el("span", "sn-end-name", "Exit")); + this.end.append(x); + } + this.drawSheet(); + this.anchor = b.subject.key === "s-pick" ? this.host.anchor() : null; + this.threadSig = ""; + this.viewAt = null; + this.drawThread(fresh); + // (A blank to fill: it is brought into sight.) + const blank = this.row.querySelector(".sn-word.blank"); + if (blank) this.reveal(blank); + } + + private endButton(icon: IconName, title: string, run: () => void): HTMLButtonElement { + const b = el("button", "sn-end-btn"); + b.innerHTML = icons[icon] ?? ""; + b.title = title; + b.setAttribute("aria-label", title); + b.addEventListener("click", run); + return b; + } + + /** The words in `box`, each kept if it was there (only what is new comes in). */ + private fill(box: HTMLElement, words: Word[], fresh: boolean): void { + const old = new Map(); + for (const c of Array.from(box.children) as HTMLElement[]) old.set(c.dataset.key ?? "", c); + let n = 0; + let at: Element | null = box.firstElementChild; + for (const w of words) { + let d = fresh ? undefined : old.get(w.key); + const sig = `${w.kind}|${w.label}|${w.cap ?? ""}|${w.on ? 1 : 0}|${w.blank ? 1 : 0}|${w.pulse ? 1 : 0}|${w.kids?.length ?? 0}|${w.swatch ?? ""}`; + if (!d) { + d = this.wordEl(w); + if (!calm()) { + d.classList.add("sn-in"); + d.style.animationDelay = `${Math.min(n++, 14) * 16}ms`; + } + } else { + old.delete(w.key); + if (d.dataset.sig !== sig) this.paint(d, w); + } + d.dataset.sig = sig; + (d as HTMLElement & { word?: Word }).word = w; + if (d !== at) box.insertBefore(d, at); + else at = at.nextElementSibling; + } + for (const d of fresh ? Array.from(box.children).filter((c) => !words.some((w) => (c as HTMLElement & { word?: Word }).word === w)) : old.values()) d.remove(); + } + + private wordEl(w: Word): HTMLElement { + const d = el("button", "sn-word"); + d.dataset.key = w.key; + this.paint(d, w); + const word = () => (d as HTMLElement & { word?: Word }).word ?? w; + // A tap; a number dragged sideways; a press held on a word with kinds opens them. + let down: { x: number; y: number; t: number; v: number; scrub: boolean; id: number } | null = null; + let held = 0; + d.addEventListener("pointerdown", (e) => { + const now = word(); + down = { x: e.clientX, y: e.clientY, t: performance.now(), v: now.value?.now ?? 0, scrub: false, id: e.pointerId }; + clearTimeout(held); + if (now.kids?.length && now.first) held = window.setTimeout(() => ((down = null), buzz(8), this.toggle({ kind: "kids", key: now.key })), 480); + }); + d.addEventListener("pointermove", (e) => { + const now = word(); + if (!down || e.pointerId !== down.id) return; + const dx = e.clientX - down.x; + if (!down.scrub && now.value && Math.abs(dx) > 9 && Math.abs(dx) > Math.abs(e.clientY - down.y) * 1.5) { + down.scrub = true; + clearTimeout(held); + d.setPointerCapture(e.pointerId); + d.classList.add("scrub"); + this.typing?.end(false); + this.close(); + } + if (down.scrub && now.value) this.scrub(d, now, down.v, dx); + else if (Math.hypot(dx, e.clientY - down.y) > 9) clearTimeout(held); + }); + const up = (e: PointerEvent) => { + clearTimeout(held); + if (down?.scrub) { + d.classList.remove("scrub"); + try { + d.releasePointerCapture(e.pointerId); + } catch { + // (already let go) + } + this.changed(); + } + }; + d.addEventListener("pointerup", up); + d.addEventListener("pointercancel", (e) => (up(e), (down = null))); + d.addEventListener("click", () => { + const was = down; + down = null; + // (A drag ended on it, or the held press already opened its kinds.) + if (!was || was.scrub) return; + this.tap(word(), d); + }); + return d; + } + + private paint(d: HTMLElement, w: Word): void { + d.className = `sn-word sn-${w.kind}${d.classList.contains("sn-in") ? " sn-in" : ""}`; + d.classList.toggle("on", !!w.on); + d.classList.toggle("blank", !!w.blank); + d.classList.toggle("pulse", !!w.pulse); + d.classList.toggle("quiet", !!w.quiet); + d.classList.toggle("capped", !!w.cap); + (d as HTMLButtonElement).disabled = !!w.quiet && !w.run && !w.kids; + d.replaceChildren(); + if (w.cap) d.append(el("span", "sn-cap", w.cap)); + const body = el("span", "sn-body"); + if (w.swatch) { + const sw = el("span", "sn-swatch"); + sw.style.background = w.swatch; + body.append(sw); + } else if (w.icon && icons[w.icon] && w.kind !== "value" && w.kind !== "choice" && w.kind !== "slot") { + const ic = el("span", "sn-icon"); + ic.innerHTML = icons[w.icon]; + body.append(ic); + } + body.append(el("span", "sn-text", w.label)); + if (w.kids?.length && !w.first) body.append(el("span", "sn-more", "▾")); + if (w.lets) body.append(el("span", "sn-x", "×")); + if (w.kbd && matchMedia("(hover: hover) and (pointer: fine)").matches) body.append(el("kbd", "sn-kbd", w.kbd)); + d.append(body); + d.title = w.lets ? "Let go of it" : w.value ? `${w.cap ?? w.label}: tap to type, drag sideways to change` : (w.cap ?? ""); + } + + /** A word tapped: it opens what it holds, takes a number, or does what it says. */ + private tap(w: Word, d: HTMLElement): void { + if (w.value) return void this.toggle({ kind: "type", key: w.key }); + // A tool with kinds starts as it was used last; while it is the one in use, a tap shows its kinds. + if (w.kids?.length && (!w.first || w.on)) return void this.toggle({ kind: "kids", key: w.key }); + if (!w.run) return; + buzz(); + const stays = w.kind === "toggle" || w.kind === "slot" || d.closest(".sn-sheet") === null; + if (!stays || this.open?.kind === "all") this.close(); + w.run(); + this.changed(); + } + + /** A number dragged sideways: so much a step, a tick under the finger at each. */ + private scrub(d: HTMLElement, w: Word, from: number, dx: number): void { + const v = w.value!; + // (A length steps in the unit shown; slower past the first stretch would be finer, but a step a few px wide is felt.) + const unit = v.kind === "length" ? 1 / toDisplay(1) : 1; + const px = v.kind === "int" ? 14 : 7; + const steps = Math.trunc(dx / px); + const size = v.kind === "int" ? 1 : v.kind === "angle" ? 1 : v.kind === "length" ? unit * (Math.abs(toDisplay(from)) >= 100 ? 5 : from !== 0 && Math.abs(toDisplay(from)) < 2 ? 0.1 : 1) : Math.abs(from) >= 20 ? 1 : 0.05; + let to = from + steps * size; + if (v.min !== undefined) to = Math.max(v.min, to); + if (v.max !== undefined) to = Math.min(v.max, to); + if (to === v.now) return; + v.now = to; + buzz(3); + v.put(to); + const t = d.querySelector(".sn-text"); + if (t) t.textContent = v.kind === "length" ? `${+toDisplay(to).toFixed(3)} ${UNIT_LABEL[units()]}` : v.kind === "angle" ? `${+to.toFixed(2)}°` : String(+to.toFixed(3)); + } + + /** The tick: the sentence is said - it lifts away as it is done. */ + private finish(run: () => void): void { + buzz([6, 40, 10]); + this.typing?.end(true); + this.close(); + if (!calm()) { + const r = this.row.getBoundingClientRect(); + const ghost = this.row.cloneNode(true) as HTMLElement; + ghost.className = "sn-row sn-ghost"; + Object.assign(ghost.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` }); + ghost.scrollLeft = this.row.scrollLeft; + document.body.append(ghost); + ghost.animate([{ opacity: 0.9, transform: "none" }, { opacity: 0, transform: "translateY(-46px) scale(0.96)" }], { duration: 380, easing: "cubic-bezier(.2,.7,.2,1)" }).finished.then(() => ghost.remove(), () => ghost.remove()); + setTimeout(() => ghost.remove(), 600); + } + run(); + this.changed(); + } + + // -------------------------------------------------------------- the sheet + + private toggle(to: NonNullable): void { + const same = this.open && this.open.kind === to.kind && (to.kind === "all" || (this.open as { key: string }).key === (to as { key: string }).key); + this.typing?.end(true); + this.open = same ? null : to; + buzz(); + this.drawSheet(true); + this.end.querySelector(".sn-all")?.classList.toggle("on", this.open?.kind === "all"); + } + + private close(): void { + if (!this.open) return; + this.open = null; + this.drawSheet(); + this.end.querySelector(".sn-all")?.classList.remove("on"); + } + + private find(key: string): Word | null { + const b = this.built; + if (!b) return null; + const seek = (ws: Word[]): Word | null => { + for (const w of ws) { + if (w.key === key) return w; + const k = w.kids && seek(w.kids); + if (k) return k; + } + return null; + }; + return seek([b.subject, ...b.words]) ?? seek(b.groups.flatMap((g) => g.words)); + } + + /** Over the line: everything for the pick by what it is for, one word's kinds, or a number's box. */ + private drawSheet(rise = false): void { + const o = this.open; + const b = this.built; + // (Open over the model: the round buttons beside the pick step back for it.) + document.body.classList.toggle("sn-open", !!o && !!b && this.on); + if (!o || !b) { + this.sheet.hidden = true; + this.sheet.replaceChildren(); + return; + } + if (o.kind === "type") { + if (this.typing) return; + const w = this.find(o.key); + if (!w?.value) return void this.close(); + this.sheet.hidden = false; + this.sheet.className = "sn-sheet sn-typing"; + return this.type(w); + } + const blocks: { cap: string; words: Word[] }[] = []; + if (o.kind === "all") blocks.push(...b.groups); + else { + const w = this.find(o.key); + if (!w?.kids?.length) return void this.close(); + blocks.push({ cap: w.cap ?? w.label, words: w.kids }); + } + this.sheet.hidden = false; + this.sheet.className = `sn-sheet sn-${o.kind}`; + const old = Array.from(this.sheet.children) as HTMLElement[]; + const had = old.filter((c) => c.classList.contains("sn-group")); + const same = !rise && had.length === blocks.length && had.every((c, i) => c.dataset.cap === blocks[i].cap); + if (!same) this.sheet.replaceChildren(); + blocks.forEach((g, i) => { + let box = same ? had[i] : null; + if (!box) { + box = el("div", "sn-group"); + box.dataset.cap = g.cap; + box.append(el("div", "sn-group-cap", g.cap), el("div", "sn-group-words")); + this.sheet.append(box); + } + this.fill(box.lastElementChild as HTMLElement, g.words, !same); + }); + this.sheet.querySelector(".sn-others")?.remove(); + if (o.kind === "all" && b.others?.length) { + const note = el("div", "sn-others"); + note.append(el("div", "sn-group-cap", "Needs another pick")); + for (const t of b.others.slice(0, 8)) note.append(el("div", "sn-other", t)); + this.sheet.append(note); + } + if (rise && !calm()) this.sheet.animate([{ opacity: 0, transform: "translateY(10px)" }, { opacity: 1, transform: "none" }], { duration: 140, easing: "ease-out" }); + // (One word's kinds: over that word.) + this.sheet.style.setProperty("--sn-at", "50%"); + if (o.kind === "kids") { + const d = this.row.querySelector(`[data-key="${CSS.escape(o.key)}"]`); + const lr = this.line.getBoundingClientRect(); + if (d) { + const r = d.getBoundingClientRect(); + this.sheet.style.setProperty("--sn-at", `${Math.round(Math.min(lr.width - 20, Math.max(20, r.left + r.width / 2 - lr.left)))}px`); + } + } + } + + /** A number typed right there: Enter (or a tap elsewhere) sets it, Esc leaves it as it was. */ + private type(w: Word): void { + const v = w.value!; + const box = el("div", "sn-type"); + box.append(el("span", "sn-type-label", w.cap ?? w.label)); + const input = document.createElement("input"); + input.type = "text"; + input.inputMode = "decimal"; + input.autocomplete = "off"; + input.spellcheck = false; + input.value = v.kind === "length" ? String(+toDisplay(v.now).toFixed(4)) : String(+v.now.toFixed(4)); + input.dataset.kind = v.kind; + if (v.min !== undefined) input.dataset.min = String(v.min); + if (v.max !== undefined) input.dataset.max = String(v.max); + numpadInput(input); + box.append(input); + const unit = v.kind === "length" ? UNIT_LABEL[units()] : v.kind === "angle" ? "°" : ""; + if (unit) box.append(el("span", "sn-type-unit", unit)); + this.sheet.replaceChildren(box); + let over = false; + const end = (keep: boolean) => { + if (over) return; + over = true; + this.typing = null; + if (keep) { + const n = evaluate(input.value, v.kind === "int" ? "number" : v.kind); + if (n !== null) v.put(Math.min(v.max ?? Infinity, Math.max(v.min ?? -Infinity, v.kind === "int" ? Math.round(n) : n))); + } + if (this.open?.kind === "type") this.open = null; + this.sheet.hidden = true; + this.sheet.replaceChildren(); + this.changed(); + }; + this.typing = { end }; + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") (e.preventDefault(), end(true)); + else if (e.key === "Escape") (e.preventDefault(), end(false)); + e.stopPropagation(); + }); + input.addEventListener("blur", () => setTimeout(() => document.activeElement !== input && end(true), 150)); + input.focus(); + selectAll(input); + openNumpad(input); + } + + /** A word brought into sight on the line (a blank to fill, the tool in use). */ + private reveal(d: HTMLElement): void { + const r = d.getBoundingClientRect(); + const box = this.row.getBoundingClientRect(); + if (r.left < box.left + 8 || r.right > box.right - 8) this.row.scrollTo({ left: this.row.scrollLeft + r.left - box.left - 24, behavior: calm() ? "auto" : "smooth" }); + } + + // ------------------------------------------------------------- the thread + + /** + * From the subject to what it names on the model: one curve, drawn again + * only when one of its ends moved (each frame: one point projected and + * compared). + */ + private drawThread(fresh = false): void { + if (!this.on) return; + const a = this.anchor; + const subject = a && this.row.firstElementChild; + const s = a && this.host.view.toScreen(a); + if (!a || !subject || !s) { + if (this.threadSig !== "off") { + this.threadSig = "off"; + this.thread.classList.remove("on"); + } + return; + } + const c = (this.viewAt ??= this.host.view.canvas.getBoundingClientRect()); + const x1 = Math.round(c.left + s[0]); + const y1 = Math.round(c.top + s[1]); + const sig = `${x1},${y1}`; + if (sig === this.threadSig && !fresh) return; + const r = subject.getBoundingClientRect(); + const lr = this.line.getBoundingClientRect(); + const x0 = Math.round(Math.min(Math.max(r.left + r.width / 2, lr.left + 14), lr.right - 14)); + const y0 = Math.round(r.top); + this.threadSig = sig; + // (Up out of the word, then over to the thing: a hanging curve, never a straight wire.) + const lift = Math.max(30, Math.min(140, (y0 - y1) * 0.55)); + this.threadPath.setAttribute("d", `M${x0} ${y0} C${x0} ${y0 - lift} ${x1} ${y1 + lift * 0.35} ${x1} ${y1}`); + this.threadDot.setAttribute("cx", String(x1)); + this.threadDot.setAttribute("cy", String(y1)); + this.thread.classList.add("on"); + if (fresh && !calm()) { + const len = this.threadPath.getTotalLength(); + this.threadPath.animate([{ strokeDasharray: `${len}`, strokeDashoffset: `${-len}` }, { strokeDasharray: `${len}`, strokeDashoffset: "0" }], { duration: 260, easing: "ease-out" }); + this.threadDot.animate([{ r: "9", opacity: 0 }, { r: "3.5", opacity: 1 }], { duration: 300, easing: "ease-out" }); + } + } + + // ------------------------------------------------------------- for checks + + /** What it says now (for `sg.sentence()`): the line's words, the sheet's, the end buttons. */ + describe() { + const b = this.built; + const at = (d: Element) => { + const r = d.getBoundingClientRect(); + return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2), w: Math.round(r.width), h: Math.round(r.height) }; + }; + const words = (box: Element) => + Array.from(box.querySelectorAll(".sn-word")).map((d) => { + const w = (d as HTMLElement & { word?: Word }).word; + return { key: d.dataset.key, kind: w?.kind, cap: w?.cap, label: w?.label, ...(w?.on ? { on: true } : {}), ...(w?.blank ? { blank: true } : {}), ...(w?.kids ? { opens: w.kids.map((k) => k.label) } : {}), ...(w?.quiet ? { quiet: true } : {}), ...at(d) }; + }); + return { + on: this.on, + about: b?.about, + line: words(this.row), + end: Array.from(this.end.children).map((d) => ({ label: (d as HTMLElement).title, ...at(d) })), + open: this.open?.kind ?? null, + sheet: this.sheet.hidden ? [] : Array.from(this.sheet.querySelectorAll(".sn-group")).map((g) => ({ cap: g.dataset.cap, words: words(g) })), + thread: this.thread.classList.contains("on"), + }; + } +} diff --git a/src/ui/wheel.ts b/src/ui/wheel.ts index fa5a664..787a4ea 100644 --- a/src/ui/wheel.ts +++ b/src/ui/wheel.ts @@ -125,7 +125,7 @@ const OWN = "own"; * Where a picked thing's tool goes when it isn't named like one of the main * tools (those go where the main tool is). Anything not known: the top sector. */ -const GROUP_OF: Record = { +export const GROUP_OF: Record = { text: "sketch", offset: "sketch", projs: "sketch", editFreeform: "freeform", fillHole: "freeform", thicken: "freeform", planePerp: "construct", planeEdge: "construct", proje: "construct", @@ -141,7 +141,7 @@ const GROUP_OF: Record = { * the most used is always the shortest move. (Tools not named here come after, * as they are listed.) */ -const RANK = [ +export const RANK = [ "extrude", "revolve", "sweep", "loft", "fillet", "chamfer", "shell", "offsetFace", "fix", "offsetEdge", "thread", "wrap", "subtract", "union", "intersect", "split", @@ -181,7 +181,7 @@ const SLOTS: Record = { const OWN_PICKED = ["deselect", "delete", "measure", "section", "color", "opacity", "variables", "isolate"]; const OWN_FREE = ["", "", "section", "insert", "measure", "bim", "variables", "isolate"]; /** A picked thing's tool that is one of the places' under another name. */ -const ALIAS: Record = { patl: "linear", patc: "circular", moveBody: "move", deleteBody: "delete", planePerp: "perp", planeEdge: "angle" }; +export const ALIAS: Record = { patl: "linear", patc: "circular", moveBody: "move", deleteBody: "delete", planePerp: "perp", planeEdge: "angle" }; /** The model's first ring, clockwise from the top: eight places, each always the same. */ const MODEL_RING = ["create", "combine", "modify", "construct", "transform", "freeform", "sketch", OWN]; @@ -588,7 +588,8 @@ export class Wheel implements WheelHandle { } get on(): boolean { - return settings.value.wheel; + // (The sentence bar switched on takes its place.) + return settings.value.wheel && !settings.value.sentence; } get isOpen(): boolean {