Skip to content

armgit / bygga

Public Imported from GitHub
0

IKEA assembly, step by step: animated, manual-style 3D guides. Scan any paper manual with Together AI.

TypeScript

Keep finished builds, honest times, new end screen

Youssef30c984b6fe2b
diff --git a/src/app/guide.css b/src/app/guide.css
index 32a9c58..2a5e857 100644
--- a/src/app/guide.css
+++ b/src/app/guide.css
@@ -845,6 +845,17 @@
right: 24px;
transform: none;
}
+.built-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ margin: 12px 0 0;
+ padding: 5px 12px 5px 9px;
+ border-radius: 999px;
+ background: var(--accent-soft);
+ font-size: 14px;
+ font-weight: 500;
+}
.voice-offer {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto auto;
@@ -1636,6 +1647,233 @@ input[type="range"] {
background: var(--accent);
color: var(--ink);
}
+/* share card: the picture people post */
+.share-card {
+ display: grid;
+ grid-template-columns: 92px minmax(0, 1fr);
+ gap: 16px;
+ align-items: center;
+ margin-top: 16px;
+ padding: 14px 16px 14px 14px;
+ border-radius: 20px;
+ background: var(--sunk);
+}
+.share-pic {
+ width: 92px;
+ aspect-ratio: 4 / 5;
+ border-radius: 12px;
+ background: #fff;
+ box-shadow:
+ 0 0 0 1px var(--line),
+ 0 10px 22px -12px rgba(18, 18, 18, 0.35);
+ overflow: hidden;
+ transform: rotate(-4deg);
+ transition: transform 0.5s var(--spring);
+}
+.share-pic::before {
+ content: "";
+ display: block;
+ height: 100%;
+ background: linear-gradient(100deg, transparent 20%, rgba(18, 18, 18, 0.05) 50%, transparent 80%) -100% 0 / 200% 100%;
+ animation: shimmer 1.2s linear infinite;
+}
+.share-pic.ready::before {
+ display: none;
+}
+.share-pic img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.share-card:hover .share-pic {
+ transform: rotate(-1deg) scale(1.04);
+}
+@keyframes shimmer {
+ to {
+ background-position: 100% 0;
+ }
+}
+.share-text {
+ display: grid;
+ gap: 2px;
+ min-width: 0;
+}
+.share-text b {
+ font-size: 16px;
+ font-weight: 600;
+}
+.share-text > span {
+ font-size: 14px;
+ color: var(--ink-2);
+}
+.share-actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 4px 12px;
+ margin-top: 8px;
+}
+.btn.share-go {
+ height: 40px;
+ padding: 0 16px 0 14px;
+ background: var(--ink);
+ color: #fff;
+ font-size: 15px;
+ font-weight: 500;
+}
+.btn.share-go:hover {
+ background: #2a2a2a;
+}
+.btn.link.small {
+ font-size: 14px;
+ padding: 4px 2px;
+}
+
+/* next up */
+.next-up {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+}
+.next-card {
+ display: grid;
+ gap: 2px;
+ padding: 6px 6px 10px;
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: inset 0 0 0 1px var(--line);
+ color: var(--ink);
+ text-decoration: none;
+ transition:
+ box-shadow 0.2s,
+ transform 0.2s var(--ease);
+}
+.next-card:hover {
+ box-shadow: inset 0 0 0 1.5px var(--ink);
+ transform: translateY(-1px);
+}
+.next-card:active {
+ transform: scale(0.98);
+}
+.next-thumb {
+ display: block;
+ width: 100%;
+ border-radius: 10px;
+ background: var(--sunk);
+}
+.next-card > span {
+ display: grid;
+ padding: 0 6px;
+ line-height: 1.25;
+ min-width: 0;
+}
+.next-card b {
+ font-family: var(--display);
+ font-weight: 800;
+ font-size: 15px;
+}
+.next-card span span {
+ font-size: 13px;
+ color: var(--ink-2);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* did it match the box */
+.match {
+ margin-top: 22px;
+ padding: 12px 12px 12px 16px;
+ border-radius: 18px;
+ box-shadow: inset 0 0 0 1px var(--line);
+}
+.match-q {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ flex-wrap: wrap;
+}
+.match-q b {
+ font-size: 15px;
+ font-weight: 600;
+}
+.match-btns {
+ display: flex;
+ gap: 6px;
+}
+.match-btns .pill-btn {
+ height: 36px;
+}
+.match-more {
+ display: grid;
+ gap: 10px;
+ margin-top: 12px;
+ overflow: hidden;
+ font-size: 14px;
+}
+.match-steps {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+.step-chip {
+ width: 36px;
+ height: 36px;
+ border: 0;
+ border-radius: 999px;
+ background: var(--sunk);
+ color: var(--ink);
+ font: inherit;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s,
+ transform 0.15s var(--ease);
+}
+.step-chip:active {
+ transform: scale(0.94);
+}
+.step-chip.on {
+ background: var(--ink);
+ color: #fff;
+}
+.match textarea {
+ width: 100%;
+ resize: none;
+ border: 0;
+ border-radius: 12px;
+ padding: 10px 12px;
+ background: var(--sunk);
+ font: inherit;
+ font-size: 15px;
+ color: var(--ink);
+ outline: none;
+}
+.match textarea:focus {
+ box-shadow: inset 0 0 0 1.5px var(--ink);
+}
+.match .btn.primary.small {
+ justify-self: end;
+ height: 40px;
+ padding: 0 18px;
+ font-size: 15px;
+}
+.match-thanks {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 22px 0 0;
+ font-size: 14.5px;
+ color: var(--ink-2);
+}
+.match-thanks svg {
+ color: var(--ok);
+}
+
.after {
list-style: none;
margin: 0;
@@ -2114,6 +2352,10 @@ input[type="range"] {
.guide[data-phase="tools"] {
grid-template-rows: 58px minmax(140px, 22dvh) minmax(0, 1fr);
}
+ /* loading, not found and error screens have no drawing row */
+ .guide.shell {
+ grid-template-rows: 58px minmax(0, 1fr);
+ }
.guide-main {
display: contents;
}
@@ -2241,6 +2483,69 @@ input[type="range"] {
}
}
+/* phones held sideways: drawing and steps side by side, like on a tablet */
+@media (max-width: 900px) and (max-height: 520px) and (orientation: landscape) {
+ .guide,
+ .guide[data-phase="tools"] {
+ grid-template-rows: 52px minmax(0, 1fr);
+ }
+ .guide-main {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(290px, 44vw);
+ gap: 8px;
+ padding: 0 8px 8px;
+ }
+ .sheet,
+ .panel {
+ margin: 0;
+ border-radius: 20px;
+ }
+ .pane-scroll {
+ padding: 16px 16px 12px;
+ }
+ .pane-foot {
+ padding: 8px 10px calc(8px + env(safe-area-inset-bottom));
+ }
+ .guide[data-voice] .step-title {
+ font-size: 24px !important;
+ }
+}
+
+/* the voice invite stays one short row on phones so the step text is still in view */
+@media (max-width: 900px) {
+ .voice-offer {
+ gap: 8px;
+ margin: 0 0 16px;
+ padding: 6px 6px 6px 12px;
+ border-radius: 999px;
+ }
+ .voice-offer-ico {
+ width: 30px;
+ height: 30px;
+ box-shadow: none;
+ background: transparent;
+ }
+ .voice-offer-text span {
+ display: none;
+ }
+ .voice-offer-text b {
+ font-size: 14.5px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .btn.voice-offer-go {
+ height: 34px;
+ padding: 0 14px;
+ font-size: 14px;
+ }
+ /* 16px stops iOS zooming into the field */
+ .guide input,
+ .guide textarea {
+ font-size: 16px;
+ }
+}
+
@media (max-width: 420px) {
.stepper {
gap: 12px;
@@ -2290,6 +2595,24 @@ input[type="range"] {
}
}
+/* the smallest phones: Done is never tappable, so it gives up its room */
+@media (max-width: 360px) {
+ .stepper {
+ gap: 10px;
+ margin-right: 0;
+ }
+ .stp {
+ font-size: 13px;
+ }
+ .stp.next:last-child {
+ display: none;
+ }
+ .guide .topbar {
+ gap: 6px;
+ padding: 0 6px 0 8px;
+ }
+}
+
@media (max-width: 640px) {
.guide:not(.shell) .tb-title {
display: none;
diff --git a/src/components/guide/CoverPanel.tsx b/src/components/guide/CoverPanel.tsx
index c275f51..9de2674 100644
--- a/src/components/guide/CoverPanel.tsx
+++ b/src/components/guide/CoverPanel.tsx
@@ -4,7 +4,7 @@ import Link from "next/link";
import type { Plan } from "@/lib/types";
import type { Progress } from "@/lib/store";
import { floorSpace, totals } from "@/lib/plan/contents";
-import { IArrowRight, IBox, IClock, IExternal, IPeople, IPerson, IRuler, ISparkle, IWrench } from "../art/Icons";
+import { IArrowRight, IBox, ICheck, IClock, IExternal, IPeople, IPerson, IRuler, ISparkle, IWrench } from "../art/Icons";
import { Dots } from "./ui";
import { TOOL_INFO } from "../art/Tools";
import { SCAN_ENABLED } from "@/lib/site";
@@ -13,14 +13,19 @@ export default function CoverPanel({
plan,
via,
resume,
+ built,
onStart,
onResume,
+ onReview,
}: {
plan: Plan;
via: "catalog" | "ai" | "guess" | "scan";
resume: Progress | null;
+ /** Finished at least once on this device. */
+ built?: { at: number; ms?: number; full?: boolean } | null;
onStart: () => void;
onResume: () => void;
+ onReview: () => void;
}) {
const s = plan.spec;
const t = totals(plan);
@@ -34,6 +39,13 @@ export default function CoverPanel({
<p className="eyebrow">{s.brand ? `${s.brand}, ${s.category.toLowerCase()}` : s.category}</p>
<h1 className="product-name">{s.name}</h1>
<p className="product-variant">{s.variant}</p>
+ {built && (
+ <p className="built-pill">
+ <ICheck size={15} strokeWidth={2.6} />
+ Built {new Date(built.at).toLocaleDateString(undefined, { day: "numeric", month: "short" })}
+ {built.full && built.ms ? `, in ${fmtMin(Math.max(1, Math.round(built.ms / 60000)))}` : ""}
+ </p>
+ )}
</header>
{s.variants && s.variants.length > 1 && (
@@ -175,6 +187,18 @@ export default function CoverPanel({
</button>
</div>
</>
+ ) : built ? (
+ <>
+ <button className="btn primary big" onClick={onStart} autoFocus>
+ <span>Build another one</span>
+ <IArrowRight />
+ </button>
+ <div className="foot-row center">
+ <button className="btn link" onClick={onReview}>
+ Look through the steps
+ </button>
+ </div>
+ </>
) : (
<button className="btn primary big" onClick={onStart} autoFocus>
<span>Start building</span>
diff --git a/src/components/guide/DonePanel.tsx b/src/components/guide/DonePanel.tsx
index 4ab3828..c20d561 100644
--- a/src/components/guide/DonePanel.tsx
+++ b/src/components/guide/DonePanel.tsx
@@ -1,56 +1,49 @@
"use client";
-import { useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { motion } from "motion/react";
import type { Plan } from "@/lib/types";
import { totals } from "@/lib/plan/contents";
+import { buildPlan } from "@/lib/plan";
+import { catalogSpec } from "@/lib/catalog";
+import { POPULAR } from "@/lib/search";
+import { getPref, setPref } from "@/lib/store";
import { Figure } from "../art/Figure";
import { IArrowLeft, IArrowRight, ICheck, ILibrary, IShare } from "../art/Icons";
+import Thumb from "../Thumb";
import { fmtMin } from "./CoverPanel";
+import { buildCard } from "./shareCard";
import { encodeSpec } from "@/lib/scan/share";
-export default function DonePanel({ plan, slug, startedAt, doneAt, onReview }: { plan: Plan; slug: string; startedAt?: number; doneAt?: number; onReview: () => void }) {
+export default function DonePanel({ plan, slug, finish, onReview }: { plan: Plan; slug: string; finish: { ms: number; full: boolean } | null; onReview: () => void }) {
const t = totals(plan);
- const spent = startedAt && doneAt ? Math.max(1, Math.round((doneAt - startedAt) / 60000)) : null;
- const a = plan.spec.archetype;
+ const s = plan.spec;
+ // a time only counts when the steps were followed, not tapped through in a minute
+ const mins = finish?.full ? Math.max(1, Math.round(finish.ms / 60000)) : 0;
+ const spent = mins >= s.minutes * 0.2 ? mins : null;
+ const faster = spent !== null && spent < s.minutes * 0.95;
+ const a = s.archetype;
const recheck = a === "table" || a === "bed" || a === "seat" || a === "sofa";
- const tall = plan.steps.some((s) => s.kind === "anchor");
- const faster = spent !== null && spent < plan.spec.minutes;
- const [copied, setCopied] = useState(false);
-
- const share = async () => {
- // scanned guides only exist in this browser, so the link carries the guide itself
- const url = `${location.origin}/build/${slug}` + (plan.spec.source === "scan" ? `#g=${await encodeSpec(plan.spec)}` : "");
- const text = `I just built ${plan.spec.name} with Bygga.`;
- try {
- if (navigator.share) await navigator.share({ title: "Bygga", text, url });
- else {
- await navigator.clipboard.writeText(`${text} ${url}`);
- setCopied(true);
- setTimeout(() => setCopied(false), 1800);
- }
- } catch {
- /* cancelled */
- }
- };
+ const tall = plan.steps.some((x) => x.kind === "anchor");
+ const stat = [spent ? fmtMin(spent) : null, `${plan.steps.length} steps`, `${t.fittings} fittings`].filter(Boolean).join(" \u00b7 ");
return (
<div className="pane done">
<div className="pane-scroll">
<motion.div className="done-hero" initial={{ scale: 0.6, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ type: "spring", stiffness: 260, damping: 16, delay: 0.1 }}>
- <Figure pose="cheer" size={104} bubble="check" className="bounce" />
+ <Figure pose="cheer" size={112} bubble="check" className="bounce" />
</motion.div>
<motion.h2 className="done-title" initial={{ y: 16, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0.25, duration: 0.5, ease: [0.22, 1, 0.36, 1] }}>
- You built {plan.spec.name}.
+ You built {s.name}.
</motion.h2>
<motion.p className="sub center" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.4 }}>
- {faster ? `${plan.spec.minutes - spent!} minutes faster than most people.` : "Every step done. Nice work."}
+ {faster ? `${s.minutes - spent!} minutes faster than most people.` : spent ? "Built at your own pace. That's the right pace." : "Every step done. Nice work."}
</motion.p>
- <dl className="stats">
+ <motion.dl className="stats" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.5 }}>
<div>
<dt>{spent ? "Your time" : "Typical time"}</dt>
- <dd>{fmtMin(spent ?? t.minutes)}</dd>
+ <dd>{fmtMin(spent ?? s.minutes)}</dd>
</div>
<div>
<dt>Steps</dt>
@@ -60,17 +53,24 @@ export default function DonePanel({ plan, slug, startedAt, doneAt, onReview }: {
<dt>Fittings</dt>
<dd>{t.fittings}</dd>
</div>
- </dl>
+ </motion.dl>
+
+ <ShareCard plan={plan} slug={slug} stat={stat} spent={spent} />
+
<Link href="/builds" className="workshop-link">
<span className="wl-ico">
<ILibrary size={18} />
</span>
<span>
<b>Saved to your workshop</b>
- <span>See everything you&apos;ve built, side by side.</span>
+ <span>See everything you&apos;ve built, side by side and to scale.</span>
</span>
<IArrowRight size={18} />
</Link>
+
+ <NextUp plan={plan} />
+ <Match plan={plan} slug={slug} />
+
<h3 className="section-title">Before you load it up</h3>
<ul className="after">
{tall && (
@@ -92,12 +92,9 @@ export default function DonePanel({ plan, slug, startedAt, doneAt, onReview }: {
</ul>
</div>
<div className="pane-foot">
- <button className="btn round" onClick={onReview} aria-label="Back to the last step">
+ <button className="btn round" onClick={onReview} aria-label="Back to the last step" data-tip="Last step">
<IArrowLeft />
</button>
- <button className="btn round" onClick={share} aria-label="Share" data-tip={copied ? "Link copied" : "Share"}>
- {copied ? <ICheck /> : <IShare />}
- </button>
<Link className="btn primary big" href="/">
<span>Build something else</span>
<IArrowRight />
@@ -107,6 +104,164 @@ export default function DonePanel({ plan, slug, startedAt, doneAt, onReview }: {
);
}
+/** The picture people post: the finished piece, its name and their time. */
+function ShareCard({ plan, slug, stat, spent }: { plan: Plan; slug: string; stat: string; spent: number | null }) {
+ const [card, setCard] = useState<{ blob: Blob; url: string } | null>(null);
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ let alive = true;
+ let url = "";
+ const t = setTimeout(() => {
+ buildCard(plan, slug, stat).then((blob) => {
+ if (!alive || !blob) return;
+ url = URL.createObjectURL(blob);
+ setCard({ blob, url });
+ });
+ }, 500);
+ return () => {
+ alive = false;
+ clearTimeout(t);
+ if (url) URL.revokeObjectURL(url);
+ };
+ }, [plan, slug, stat]);
+
+ const share = async () => {
+ // scanned guides only exist in this browser, so the link carries the guide itself
+ const url = `${location.origin}/build/${slug}` + (plan.spec.source === "scan" ? `#g=${await encodeSpec(plan.spec)}` : "");
+ const text = spent ? `I just built ${plan.spec.name} in ${fmtMin(spent)}, one step at a time.` : `I just built ${plan.spec.name}, one step at a time.`;
+ const file = card ? new File([card.blob], `${plan.spec.name.toLowerCase()}-built.png`, { type: "image/png" }) : null;
+ try {
+ if (file && navigator.canShare?.({ files: [file] })) await navigator.share({ files: [file], text: `${text} ${url}` });
+ else if (navigator.share) await navigator.share({ title: "Bygga", text, url });
+ else {
+ await navigator.clipboard.writeText(`${text} ${url}`);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1800);
+ }
+ } catch {
+ /* cancelled */
+ }
+ };
+
+ return (
+ <motion.div className="share-card" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.6 }}>
+ <div className={"share-pic" + (card ? " ready" : "")}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {card && <img src={card.url} alt={`${plan.spec.name}, built`} />}
+ </div>
+ <div className="share-text">
+ <b>Show it off</b>
+ <span>A picture of your build, ready to post.</span>
+ <div className="share-actions">
+ <button className="btn share-go" onClick={share}>
+ {copied ? <ICheck size={17} /> : <IShare size={17} />}
+ {copied ? "Link copied" : "Share"}
+ </button>
+ {card && (
+ <a className="btn link small" href={card.url} download={`${plan.spec.name.toLowerCase()}-built.png`}>
+ Save image
+ </a>
+ )}
+ </div>
+ </div>
+ </motion.div>
+ );
+}
+
+/** Other pieces from the same family, or popular builds when there are none. */
+function NextUp({ plan }: { plan: Plan }) {
+ const s = plan.spec;
+ const picks = useMemo(() => {
+ const own = (s.siblings ?? []).map((x) => ({ slug: x.slug, name: s.name, label: x.label }));
+ const more = POPULAR.filter((p) => p.name !== s.name).map((p) => ({ slug: p.slug, name: p.name, label: p.category }));
+ return [...own, ...more].slice(0, own.length ? Math.min(3, own.length) : 3);
+ }, [s]);
+ if (!picks.length) return null;
+ return (
+ <>
+ <h3 className="section-title">{s.siblings?.length ? `Finish the ${s.name} set` : "Up next"}</h3>
+ <div className="next-up">
+ {picks.map((p) => (
+ <Link key={p.slug} href={`/build/${p.slug}`} className="next-card">
+ <Thumb
+ id={"next-" + p.slug}
+ plan={() => {
+ const sp = catalogSpec(p.slug);
+ return buildPlan(sp!);
+ }}
+ mode={{ kind: "assembled" }}
+ w={200}
+ h={150}
+ lazy
+ className="next-thumb"
+ />
+ <span>
+ <b>{p.name}</b>
+ <span>{p.label}</span>
+ </span>
+ </Link>
+ ))}
+ </div>
+ </>
+ );
+}
+
+/** "Did this match your box?" Wrong guides get found and fixed this way. */
+function Match({ plan, slug }: { plan: Plan; slug: string }) {
+ const key = "match:" + slug;
+ const [state, setState] = useState<"ask" | "no" | "sent">(() => (getPref(key, false) ? "sent" : "ask"));
+ const [step, setStep] = useState<number | null>(null);
+ const [note, setNote] = useState("");
+ const send = (match: boolean) => {
+ setState("sent");
+ setPref(key, true);
+ fetch("/api/feedback", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ slug, name: plan.spec.name, variant: plan.spec.variant, match, step: step ?? undefined, note: note || undefined, via: plan.spec.source }),
+ }).catch(() => {});
+ };
+ if (state === "sent")
+ return (
+ <p className="match-thanks">
+ <ICheck size={16} strokeWidth={2.6} /> Thanks, that helps us fix guides.
+ </p>
+ );
+ return (
+ <div className="match">
+ <div className="match-q">
+ <b>Did the steps match your box?</b>
+ {state === "ask" && (
+ <div className="match-btns">
+ <button className="pill-btn" onClick={() => send(true)}>
+ Yes
+ </button>
+ <button className="pill-btn" onClick={() => setState("no")}>
+ Not quite
+ </button>
+ </div>
+ )}
+ </div>
+ {state === "no" && (
+ <motion.div className="match-more" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }}>
+ <span className="muted">Which step looked different?</span>
+ <div className="match-steps">
+ {plan.steps.map((_, i) => (
+ <button key={i} className={"step-chip" + (step === i + 1 ? " on" : "")} onClick={() => setStep(step === i + 1 ? null : i + 1)} aria-pressed={step === i + 1}>
+ {i + 1}
+ </button>
+ ))}
+ </div>
+ <textarea value={note} onChange={(e) => setNote(e.target.value.slice(0, 400))} placeholder="What was different? (optional)" rows={2} />
+ <button className="btn primary small" onClick={() => send(false)}>
+ Send
+ </button>
+ </motion.div>
+ )}
+ </div>
+ );
+}
+
const PIECES = ["dowel", "screw", "cam", "pin", "nail", "dowel", "screw"];
export function Confetti() {
diff --git a/src/components/guide/GuideApp.tsx b/src/components/guide/GuideApp.tsx
index ffb1de5..d0be072 100644
--- a/src/components/guide/GuideApp.tsx
+++ b/src/components/guide/GuideApp.tsx
@@ -10,7 +10,7 @@ import { buildPlan } from "@/lib/plan";
import { stepContents } from "@/lib/plan/contents";
import { matchCatalog, specForKind } from "@/lib/search";
import { KIND_LABELS, type Kind } from "@/lib/products";
-import { cacheSpec, cachedSpec, getPref, loadProgress, saveProgress, setPref, type Phase, type Progress } from "@/lib/store";
+import { BREAK_MS, cacheSpec, cachedSpec, getPref, isBuilt, loadProgress, saveProgress, setPref, type Phase, type Progress } from "@/lib/store";
import StageView, { type StageHandle } from "../StageView";
import type { StageMode } from "@/engine/stage";
import { LogoMark } from "../Logo";
@@ -26,7 +26,7 @@ import HelpSheet from "./HelpSheet";
import Overview from "./Overview";
import Loader from "./Loader";
import Thumb from "../Thumb";
-import { haptic, speechSupported, useListener, useWakeLock } from "./hooks";
+import { haptic, speechSupported, useListener, useWakeLock, type Mic } from "./hooks";
import { playDone, playStep, playTick, setSound, soundOn } from "./sound";
import { mediaSession, voice } from "./voice";
import { LINES, builtLine, needsLine, spokenAnswer, stepLines, toolsLine, whereLine } from "@/lib/voice/script";
@@ -45,9 +45,11 @@ export default function GuideApp({ slug, query, step, kind }: { slug: string; qu
const isScan = slug.startsWith("scan-");
const q = query || slug.replace(/-/g, " ");
const initial = useMemo(() => (isScan ? null : (catalogSpec(slug) ?? (picked ? { ...specForKind(picked, q.split(" ")[0] || q), slug } : null))), [isScan, slug, picked, q]);
- const local = useMemo(() => (initial || isScan ? null : matchCatalog(q)), [initial, isScan, q]);
+ // a build saved under this name (an AI draft, a picked shape) wins over a near-miss in the catalog
+ const stored = useMemo(() => (mounted && !initial ? (cachedSpec(slug) ?? loadProgress(slug)?.spec ?? null) : null), [mounted, initial, slug]);
+ const match = useMemo(() => (initial || isScan ? null : matchCatalog(q)), [initial, isScan, q]);
+ const local = stored ? null : match;
const [imported, setImported] = useState<{ slug: string; spec: ProductSpec | null } | null>(null);
- const stored = useMemo(() => (mounted && !initial && !local ? cachedSpec(slug) : null), [mounted, initial, local, slug]);
const cached = stored ?? (imported?.slug === slug ? imported.spec : null);
const hash = useMemo(() => (mounted && isScan && location.hash.startsWith("#g=") ? location.hash.slice(3) : ""), [mounted, isScan]);
@@ -66,8 +68,8 @@ export default function GuideApp({ slug, query, step, kind }: { slug: string; qu
};
}, [hash, slug]);
useEffect(() => {
- if (local?.slug && local.slug !== slug) router.replace(`/build/${local.slug}`);
- }, [local, slug, router]);
+ if (mounted && local?.slug && local.slug !== slug) router.replace(`/build/${local.slug}` + (step ? `?step=${step}` : ""));
+ }, [mounted, local, slug, step, router]);
const [fetched, setFetched] = useState<{ slug: string; spec?: ProductSpec; via?: Via; suggestions?: string[]; error?: boolean } | null>(null);
const [ai, setAi] = useState(false);
const result = fetched?.slug === slug ? fetched : null;
@@ -98,7 +100,7 @@ export default function GuideApp({ slug, query, step, kind }: { slug: string; qu
if (j.spec) {
const sp = j.spec as ProductSpec;
if (j.via === "catalog" && sp.slug && sp.slug !== slug) {
- router.replace(`/build/${sp.slug}`);
+ router.replace(`/build/${sp.slug}` + (step ? `?step=${step}` : ""));
return;
}
sp.slug = slug;
@@ -110,7 +112,7 @@ export default function GuideApp({ slug, query, step, kind }: { slug: string; qu
return () => {
alive = false;
};
- }, [mounted, initial, cached, local, isScan, slug, q, router]);
+ }, [mounted, initial, cached, local, isScan, slug, q, step, router]);
const plan = useMemo(() => {
if (!spec) return null;
@@ -236,7 +238,7 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
const [resume, setResume] = useState<Progress | null>(null);
const [maxStep, setMaxStep] = useState(0);
const [reached, setReached] = useState(deep !== null ? 3 : 0);
- const [help, setHelp] = useState<null | { missing?: boolean; ask?: string }>(null);
+ const [help, setHelp] = useState<null | { missing?: boolean; ask?: string; at?: number }>(null);
const [overview, setOverview] = useState(false);
const [voiceOn, setVoiceOn] = useState(false);
const [speaking, setSpeaking] = useState(false);
@@ -251,6 +253,11 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
const [stamp, setStamp] = useState(0);
const [toast, setToast] = useState<{ id: number; text: string } | null>(null);
const [sound, setSoundState] = useState(true);
+ const [seen, setSeen] = useState<number[]>(deep !== null ? [deep] : []);
+ const [built, setBuilt] = useState<{ at: number; ms?: number; full?: boolean } | null>(null);
+ const [finish, setFinish] = useState<{ ms: number; full: boolean } | null>(null);
+ // building time: gaps longer than a break are left out, and so is time on the cover or the done screen
+ const clock = useRef({ at: 0, ms: 0, live: false });
const stage = useRef<StageHandle | null>(null);
const mounted = useMounted();
const canListen = mounted && speechSupported();
@@ -262,16 +269,25 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
setSoundState(soundOn());
setUsedVoice(getPref("voice", false));
const p = loadProgress(slug);
- if (p) {
+ // a save made with another shape picked under the same name doesn't fit this plan
+ const fits = p && (!p.spec || (p.spec.archetype === plan.spec.archetype && p.spec.variant === plan.spec.variant));
+ if (p && fits) {
setResume(p);
setTools(p.tools);
setMissing(new Set(p.missing ?? []));
setStartedAt(p.startedAt);
setMaxStep(Math.min(p.step, steps.length - 1));
- setReached(PHASES.indexOf(p.phase));
+ setReached(Math.max(deep !== null ? 3 : 0, PHASES.indexOf(p.phase)));
+ setSeen((x) => [...new Set([...(p.seen ?? []), ...x])]);
if (p.doneAt) setDoneAt(p.doneAt);
+ if (isBuilt(p)) setBuilt({ at: p.builtAt ?? p.doneAt ?? p.updatedAt, ms: p.builtMs, full: p.builtFull });
}
}
+ useEffect(() => {
+ if (restored) clock.current = { at: Date.now(), ms: resume?.activeMs ?? 0, live: deep !== null };
+ // only once, when the save has been read
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [restored]);
// persist
useEffect(() => {
@@ -293,23 +309,35 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
doneAt,
updatedAt: Date.now(),
spec: plan.spec.source === "catalog" ? undefined : plan.spec,
+ activeMs: clock.current.ms,
+ seen,
+ builtAt: built?.at,
+ builtMs: built?.ms,
+ builtFull: built?.full,
});
- }, [restored, slug, plan, phase, step, tools, missing, startedAt, doneAt, steps.length]);
+ }, [restored, slug, plan, phase, step, tools, missing, startedAt, doneAt, steps.length, seen, built]);
useWakeLock(phase === "steps" || phase === "parts");
const go = useCallback((p: Phase, s?: number, d = 1) => {
+ const c = clock.current, now = Date.now();
+ if (c.live && c.at) c.ms += Math.min(now - c.at, BREAK_MS);
+ c.at = now;
+ c.live = p !== "cover" && p !== "done";
setDir(d);
setPhase(p);
setReached((r) => Math.max(r, PHASES.indexOf(p)));
if (s !== undefined) {
setStep(s);
setMaxStep((m) => Math.max(m, s));
+ if (p === "steps") setSeen((x) => (x.includes(s) ? x : [...x, s]));
}
setHl(null);
setMoved(false);
if (p === "done") setDoneAt((x) => x ?? Date.now());
- }, []);
+ // back on the cover, "Continue at step N" should name where you just were
+ if (p === "cover") setResume(loadProgress(slug));
+ }, [slug]);
const showToast = useCallback((text: string) => {
const id = Date.now();
@@ -336,9 +364,14 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
} else {
playDone();
go("done");
+ const ms = clock.current.ms;
+ // skipping through doesn't earn a time: most of the steps have to have been on screen
+ const full = new Set([...seen, step]).size >= Math.ceil(steps.length * 0.8);
+ setFinish({ ms, full });
+ setBuilt((b) => (!b ? { at: Date.now(), ms, full } : full && (!b.full || !b.ms || ms < b.ms) ? { ...b, ms, full } : b));
}
}
- }, [phase, step, steps.length, go, showToast]);
+ }, [phase, step, steps.length, go, showToast, seen]);
const back = useCallback(() => {
if (phase === "tools") go("cover", undefined, -1);
@@ -355,14 +388,16 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
if (help || overview) return;
const t = e.target as HTMLElement;
if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA")) return;
- if (phase !== "steps") return;
+ if (phase !== "steps" || e.metaKey || e.ctrlKey || e.altKey) return;
if (e.key === "ArrowRight" || e.key === " " || e.key === "Enter") {
- if (t?.tagName === "BUTTON" && (e.key === " " || e.key === "Enter")) return;
+ // a focused button or link answers its own Enter; holding a key shouldn't race through steps
+ if ((t?.tagName === "BUTTON" || t?.tagName === "A") && (e.key === " " || e.key === "Enter")) return;
+ if (e.repeat) return;
e.preventDefault();
next();
} else if (e.key === "ArrowLeft") {
e.preventDefault();
- back();
+ if (!e.repeat) back();
} else if (e.key.toLowerCase() === "r") stage.current?.replay();
else if (e.key === "?") setHelp({});
else if (e.key.toLowerCase() === "o") setOverview(true);
@@ -371,9 +406,34 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
return () => window.removeEventListener("keydown", onKey);
}, [phase, next, back, help, overview]);
+ // the phone's back gesture steps back through the guide instead of leaving it
+ const nav = useRef({ phase, back });
+ useEffect(() => {
+ nav.current = { phase, back };
+ });
+ const guard = useRef(false);
+ const [pops, setPops] = useState(0);
+ useEffect(() => {
+ if (phase === "cover" || guard.current) return;
+ history.pushState({ bygga: "step" }, "");
+ guard.current = true;
+ }, [phase, pops]);
+ useEffect(() => {
+ const onPop = () => {
+ if (!guard.current) return;
+ guard.current = false;
+ if (nav.current.phase === "cover") return;
+ nav.current.back();
+ setPops((n) => n + 1);
+ };
+ window.addEventListener("popstate", onPop);
+ return () => window.removeEventListener("popstate", onPop);
+ }, []);
+
/* ---------- voice ---------- */
const said = useRef("");
+ const micRef = useRef<Mic>("off");
const live = useRef({ next, back, step, voiceOn });
useEffect(() => {
live.current = { next, back, step, voiceOn };
@@ -391,7 +451,12 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
setOffer(false);
setPref("voice", true);
said.current = String(step);
- voice.say([canListen ? LINES.on : LINES.onNoMic, ...stepLines(plan, step)]);
+ voice.say([LINES.on, ...stepLines(plan, step)]).then((ok) => {
+ if (!ok) return;
+ // by now the mic has either started or been refused, so the tip matches what works
+ const m = micRef.current;
+ voice.say([canListen && m !== "denied" && m !== "unsupported" ? LINES.sayNext : LINES.tapNext]);
+ });
}, [canListen, plan, step]);
const stopVoice = useCallback((confirm = false) => {
@@ -481,7 +546,7 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
if (!ai) voice.say([LINES.noAnswer]);
else {
voice.say([LINES.checking]);
- setHelp({ ask: intent.text });
+ setHelp((h) => ({ ...h, ask: intent.text, at: Date.now() }));
}
break;
}
@@ -490,14 +555,19 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
const { mic, heard } = useListener(voiceOn && phase === "steps", (text, final) => {
const intent = parse(text);
if (!intent) return false;
- // the mic can hear the voice itself: ignore anything she is saying
+ // the mic can hear the voice itself: ignore anything she is saying, and questions while she talks
if (voice.echo(heardWords(text))) return false;
+ if (intent.kind === "ask" && voice.speaking) return false;
// "stop" can't wait; everything else waits for the whole phrase
if (!final && intent.kind !== "stop") return false;
run(intent);
return true;
});
+ useEffect(() => {
+ micRef.current = mic;
+ }, [mic]);
+
const speakAnswer = useCallback((text: string) => {
if (live.current.voiceOn) voice.say(spokenAnswer(text));
}, []);
@@ -505,13 +575,13 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const t = e.target as HTMLElement;
- if (e.key.toLowerCase() !== "v" || e.metaKey || e.ctrlKey || phase !== "steps" || help || t?.tagName === "INPUT" || t?.tagName === "TEXTAREA") return;
+ if (e.key.toLowerCase() !== "v" || e.metaKey || e.ctrlKey || e.repeat || phase !== "steps" || help || overview || t?.tagName === "INPUT" || t?.tagName === "TEXTAREA") return;
if (voiceOn) stopVoice();
else startVoice();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [phase, help, voiceOn, startVoice, stopVoice]);
+ }, [phase, help, overview, voiceOn, startVoice, stopVoice]);
// headphone buttons and the lock screen: next track, previous track
useEffect(() => {
@@ -719,14 +789,19 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
plan={plan}
via={via}
resume={resume}
+ built={built}
onStart={() => {
setMissing(new Set());
setStartedAt(Date.now());
setDoneAt(undefined);
setMaxStep(0);
setReached(0);
+ setSeen([]);
+ setFinish(null);
+ clock.current = { at: Date.now(), ms: 0, live: true };
go("tools");
}}
+ onReview={() => go("steps", 0)}
onResume={() => {
if (!resume) return;
if (resume.phase === "steps") go("steps", Math.min(resume.step, steps.length - 1));
@@ -767,7 +842,7 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
offer={!voiceOn && offer && (step === 0 || usedVoice) ? { again: usedVoice, listen: canListen, onStart: startVoice, onDismiss: () => setOffer(false) } : null}
/>
)}
- {phase === "done" && <DonePanel plan={plan} slug={slug} startedAt={startedAt} doneAt={doneAt} onReview={back} />}
+ {phase === "done" && <DonePanel plan={plan} slug={slug} finish={finish} onReview={back} />}
</motion.div>
</AnimatePresence>
</aside>
@@ -786,6 +861,7 @@ function Guide({ plan, slug, via, ai, startStep }: { plan: Plan; slug: string; v
ai={ai}
focusMissing={help.missing}
ask={help.ask}
+ askId={help.at}
onAnswer={voiceOn ? speakAnswer : undefined}
onClose={() => setHelp(null)}
/>
diff --git a/src/components/guide/shareCard.ts b/src/components/guide/shareCard.ts
new file mode 100644
index 0000000..8989268
--- /dev/null
+++ b/src/components/guide/shareCard.ts
@@ -0,0 +1,142 @@
+"use client";
+
+import type { Plan } from "@/lib/types";
+import { shot } from "@/engine/thumbs";
+
+const W = 1080;
+const H = 1350;
+
+function font(name: string, fallback: string) {
+ const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return v || fallback;
+}
+
+function round(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+function load(src: string) {
+ return new Promise<HTMLImageElement>((res, rej) => {
+ const i = new Image();
+ i.onload = () => res(i);
+ i.onerror = rej;
+ i.src = src;
+ });
+}
+
+/** Shrinks text until it fits the width. */
+function fit(ctx: CanvasRenderingContext2D, text: string, max: number, size: number, family: string, weight: number) {
+ let s = size;
+ do {
+ ctx.font = `${weight} ${s}px ${family}`;
+ s -= 4;
+ } while (ctx.measureText(text).width > max && s > 40);
+}
+
+/** The logo mark: an Allen bolt head seen from above. */
+function mark(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number) {
+ ctx.fillStyle = "#121212";
+ ctx.beginPath();
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
+ ctx.fill();
+ const hex = (rr: number) => {
+ ctx.beginPath();
+ for (let i = 0; i < 6; i++) {
+ const a = -Math.PI / 2 + (i * Math.PI) / 3;
+ ctx[i ? "lineTo" : "moveTo"](cx + Math.cos(a) * rr, cy + Math.sin(a) * rr);
+ }
+ ctx.closePath();
+ };
+ ctx.fillStyle = "#ffd21f";
+ hex(r * 0.62);
+ ctx.fill();
+ ctx.fillStyle = "#121212";
+ hex(r * 0.3);
+ ctx.fill();
+}
+
+/** A 4:5 picture of the finished piece, sized for a post on X or a story. */
+export async function buildCard(plan: Plan, key: string, stat: string): Promise<Blob | null> {
+ try {
+ await document.fonts?.ready;
+ const art = await shot(`card:${key}`, plan, { kind: "assembled" }, 900, 760);
+ const img = await load(art.url);
+ const c = document.createElement("canvas");
+ c.width = W;
+ c.height = H;
+ const ctx = c.getContext("2d")!;
+ const display = font("--font-display", "system-ui, sans-serif");
+ const body = font("--font-noto", "system-ui, sans-serif");
+
+ ctx.fillStyle = "#f5f4f0";
+ ctx.fillRect(0, 0, W, H);
+ round(ctx, 48, 48, W - 96, H - 96, 56);
+ ctx.fillStyle = "#ffffff";
+ ctx.fill();
+ ctx.lineWidth = 3;
+ ctx.strokeStyle = "#e8e6e0";
+ ctx.stroke();
+
+ ctx.drawImage(img, 90, 96, 900, 760);
+
+ // the stamp: a yellow check, like a finished page in a manual
+ ctx.fillStyle = "#ffd21f";
+ ctx.beginPath();
+ ctx.arc(W - 150, 150, 58, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.lineWidth = 5;
+ ctx.strokeStyle = "#121212";
+ ctx.stroke();
+ ctx.lineWidth = 11;
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ ctx.beginPath();
+ ctx.moveTo(W - 176, 152);
+ ctx.lineTo(W - 156, 172);
+ ctx.lineTo(W - 120, 132);
+ ctx.stroke();
+
+ ctx.fillStyle = "#8a877f";
+ ctx.font = `600 30px ${body}`;
+ ctx.letterSpacing = "4px";
+ ctx.fillText("I BUILT", 110, 950);
+ ctx.letterSpacing = "0px";
+ ctx.fillStyle = "#121212";
+ fit(ctx, plan.spec.name, W - 220, 132, display, 800);
+ ctx.fillText(plan.spec.name, 104, 1070);
+ ctx.fillStyle = "#4a4945";
+ fit(ctx, plan.spec.variant, W - 220, 42, body, 500);
+ ctx.fillText(plan.spec.variant, 110, 1130);
+
+ ctx.fillStyle = "#121212";
+ ctx.font = `700 38px ${body}`;
+ ctx.fillText(stat, 110, 1206);
+
+ ctx.strokeStyle = "#e8e6e0";
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ ctx.moveTo(110, 1236);
+ ctx.lineTo(W - 110, 1236);
+ ctx.stroke();
+ mark(ctx, 134, 1270, 22);
+ ctx.fillStyle = "#121212";
+ ctx.font = `800 30px ${display}`;
+ ctx.fillText("bygga", 168, 1281);
+ ctx.fillStyle = "#8a877f";
+ ctx.font = `500 26px ${body}`;
+ const host = location.host.replace(/^www\./, "");
+ ctx.textAlign = "right";
+ ctx.fillText(`Every IKEA step in 3D, ${host}`, W - 110, 1280);
+ ctx.textAlign = "left";
+
+ return await new Promise<Blob | null>((r) => c.toBlob(r, "image/png"));
+ } catch {
+ return null;
+ }
+}
diff --git a/src/components/workshop/Workshop.tsx b/src/components/workshop/Workshop.tsx
index df1a900..c6ed490 100644
--- a/src/components/workshop/Workshop.tsx
+++ b/src/components/workshop/Workshop.tsx
@@ -7,7 +7,7 @@ import { catalogSpec } from "@/lib/catalog";
import { buildPlan } from "@/lib/plan";
import { totals } from "@/lib/plan/contents";
import { lineup } from "@/lib/plan/lineup";
-import { listProgress, removeProgress, type Progress } from "@/lib/store";
+import { isBuilt, listProgress, removeProgress, type Progress } from "@/lib/store";
import type { Plan, ProductSpec } from "@/lib/types";
import { useMounted } from "@/lib/useMounted";
import { peekShot, shot, type Shot } from "@/engine/thumbs";
@@ -28,7 +28,14 @@ function fmtTime(min: number) {
return r ? `${h} h ${r} min` : `${h} h`;
}
-const spentOf = (r: Row) => (r.p.startedAt && r.p.doneAt && r.p.doneAt > r.p.startedAt ? Math.max(1, Math.round((r.p.doneAt - r.p.startedAt) / 60000)) : null);
+/** Building time, only when the steps were followed (older saves only had start and end). */
+function spentOf(r: Row) {
+ const p = r.p;
+ if (p.builtAt) return p.builtFull && p.builtMs ? Math.max(1, Math.round(p.builtMs / 60000)) : null;
+ const m = p.startedAt && p.doneAt && p.doneAt > p.startedAt ? Math.round((p.doneAt - p.startedAt) / 60000) : 0;
+ // a wall clock that ran overnight isn't a build time
+ return m > 0 && m < r.spec.minutes * 3 ? m : null;
+}
export default function Workshop() {
const mounted = useMounted();
@@ -41,7 +48,7 @@ export default function Workshop() {
const spec = p.spec ?? catalogSpec(p.slug);
if (!spec) return null;
try {
- return { p, spec, plan: buildPlan(spec), done: p.phase === "done" };
+ return { p, spec, plan: buildPlan(spec), done: isBuilt(p) };
} catch {
return null;
}
@@ -49,8 +56,9 @@ export default function Workshop() {
.filter(Boolean) as Row[];
}, [mounted, removed]);
- const built = rows.filter((r) => r.done).sort((a, b) => (a.p.doneAt ?? a.p.updatedAt) - (b.p.doneAt ?? b.p.updatedAt));
- const going = rows.filter((r) => !r.done);
+ const built = rows.filter((r) => r.done).sort((a, b) => (a.p.builtAt ?? a.p.doneAt ?? a.p.updatedAt) - (b.p.builtAt ?? b.p.doneAt ?? b.p.updatedAt));
+ // a second one of something already built shows in both lists
+ const going = rows.filter((r) => r.p.phase !== "done" && (!r.done || (r.p.startedAt ?? 0) > (r.p.builtAt ?? Infinity)));
const minutes = built.reduce((s, r) => s + (spentOf(r) ?? r.spec.minutes), 0);
const fittings = built.reduce((s, r) => s + totals(r.plan).fittings, 0);
const panels = built.reduce((s, r) => s + totals(r.plan).panels, 0);
@@ -262,9 +270,9 @@ function ScalePerson() {
function GoingRow({ r, onRemove }: { r: Row; onRemove: () => void }) {
const p = r.p;
- const pct = p.phase === "steps" ? (p.step + 1) / Math.max(1, p.steps) : p.phase === "parts" ? 0.06 : 0.03;
+ const pct = p.phase === "steps" ? p.step / Math.max(1, p.steps) : p.phase === "parts" ? 0.06 : 0.03;
const href = `/build/${p.slug}${p.spec ? `?q=${encodeURIComponent(p.spec.name)}` : ""}`;
- const status = p.phase === "steps" ? `Step ${p.step + 1} of ${p.steps}` : p.phase === "parts" ? "Checking parts" : "Checking tools";
+ const status = p.phase === "steps" ? (p.step + 1 >= p.steps ? "On the last step" : `Step ${p.step + 1} of ${p.steps}`) : p.phase === "parts" ? "Checking parts" : "Checking tools";
return (
<motion.div className="going" layout initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, height: 0, marginTop: 0 }} transition={{ duration: 0.3 }}>
<Link href={href} className="going-link">
@@ -292,7 +300,7 @@ function GoingRow({ r, onRemove }: { r: Row; onRemove: () => void }) {
function BuiltCard({ r, onRemove }: { r: Row; onRemove: () => void }) {
const p = r.p;
- const when = new Date(p.doneAt ?? p.updatedAt);
+ const when = new Date(p.builtAt ?? p.doneAt ?? p.updatedAt);
const spent = spentOf(r);
return (
<motion.div className="built" layout initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.96 }} transition={{ duration: 0.3 }}>
@@ -403,7 +411,7 @@ function earned(built: Row[]) {
if (r.spec.archetype === "bed") s.add("bed");
if (r.spec.archetype === "shelf") s.add("books");
const spent = spentOf(r);
- if (spent && spent < r.spec.minutes) s.add("fast");
+ if (spent && spent < r.spec.minutes && spent >= r.spec.minutes * 0.2) s.add("fast");
}
return s;
}
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 61f232b..06b89f8 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -19,8 +19,22 @@ export interface Progress {
doneAt?: number;
updatedAt: number;
spec?: ProductSpec;
+ /** Time actually spent building, with long breaks left out. */
+ activeMs?: number;
+ /** Steps that were on screen at least once. */
+ seen?: number[];
+ /** First time it was finished, and how: survives reviewing the steps or building it again. */
+ builtAt?: number;
+ builtMs?: number;
+ builtFull?: boolean;
}
+/** Built at least once. Older saves only knew the phase. */
+export const isBuilt = (p: Progress) => !!p.builtAt || p.phase === "done";
+
+/** A gap longer than this between taps counts as a break, not building time. */
+export const BREAK_MS = 20 * 60_000;
+
const KEY = "bygga:builds";
function read(): Record<string, Progress> {