Repository Public
1// UQO Éval — Métré : Plan Studio v2 — éditeur de plan d'architecte (murs à épaisseur, portes/fenêtres dans les murs, pièces, cotations,2// niveaux, saisie des longueurs au clavier, orthogonal, aimant, zoom/pan, annuler/rétablir, export PDF/PNG/SVG) + pages vierges,3// gabarits, plan de site satellite géoréférencé et import PDF/PNG/JPG/DXF. Tout alimente le registre de métré.4"use client";5import { useCallback, useEffect, useMemo, useRef, useState } from "react";6import dynamic from "next/dynamic";7import type { WorkspaceData } from "./ProjectWorkspace";8import { api, Btn, Err, Input, num } from "./ui";9import type { Calibration, ObjectKind, PlanObject, PlanPage, Point } from "@/lib/metre/types";10import { dist, polygonAreaPx, polylineLengthPx } from "@/lib/metre/geometry";11import { DEFAULT_PARTITION_THICKNESS_M, DEFAULT_WALL_HEIGHT_M, DEFAULT_WALL_THICKNESS_M, fmtArea, fmtLength, planQuantities, projectOnPolyline, snapPoint } from "@/lib/metre/plan-geometry";12import { renderPlanInner } from "@/lib/metre/plan-render";1314const MapPicker = dynamic(() => import("./MapPicker"), { ssr: false });1516type Tool = "select" | "pan" | "wall" | "partition" | "room" | "rect" | "door" | "window" | "dimension" | "text" | "stairs" | "column" | "footprint" | "lot" | "line" | "calibrate";17interface ToolDef { t: Tool; key: string; ico: string; fr: string; en: string; kind?: ObjectKind; closed?: boolean }18const TOOLS: ToolDef[] = [19 { t: "select", key: "V", ico: "↖", fr: "Sélection", en: "Select" }, { t: "pan", key: "H", ico: "✋", fr: "Déplacer", en: "Pan" },20 { t: "wall", key: "W", ico: "▬", fr: "Mur ext.", en: "Ext. wall", kind: "wall" }, { t: "partition", key: "I", ico: "┃", fr: "Cloison", en: "Partition", kind: "wall" },21 { t: "door", key: "D", ico: "◗", fr: "Porte", en: "Door", kind: "opening" }, { t: "window", key: "N", ico: "▭", fr: "Fenêtre", en: "Window", kind: "opening" },22 { t: "room", key: "R", ico: "◫", fr: "Pièce", en: "Room", kind: "room", closed: true }, { t: "rect", key: "X", ico: "▢", fr: "Rectangle", en: "Rectangle", kind: "room", closed: true },23 { t: "dimension", key: "M", ico: "⟷", fr: "Cote", en: "Dimension", kind: "dimension" }, { t: "text", key: "T", ico: "T", fr: "Texte", en: "Text", kind: "text" },24 { t: "stairs", key: "S", ico: "≣", fr: "Escalier", en: "Stairs", kind: "stairs", closed: true }, { t: "column", key: "C", ico: "■", fr: "Colonne", en: "Column", kind: "column" },25 { t: "footprint", key: "F", ico: "⬚", fr: "Empreinte", en: "Footprint", kind: "footprint", closed: true }, { t: "lot", key: "L", ico: "⌗", fr: "Lot", en: "Lot", kind: "lot", closed: true },26 { t: "line", key: "P", ico: "╱", fr: "Ligne", en: "Line", kind: "line" }, { t: "calibrate", key: "K", ico: "⊢", fr: "Calibrer", en: "Calibrate" },27];28const uuid = () => crypto.randomUUID();29const KIND_FR: Record<string, [string, string]> = { wall: ["Mur", "Wall"], opening: ["Ouverture", "Opening"], room: ["Pièce", "Room"], dimension: ["Cote", "Dimension"], text: ["Texte", "Text"], stairs: ["Escalier", "Stairs"], column: ["Colonne", "Column"], footprint: ["Empreinte", "Footprint"], lot: ["Lot", "Lot"], line: ["Ligne", "Line"], slab: ["Dalle", "Slab"], foundation: ["Fondation", "Foundation"], roof: ["Toit", "Roof"], area: ["Aire", "Area"], annotation: ["Note", "Note"] };3031type PageX = PlanPage & { filename: string };3233export default function PlanStudio({ d, fr, canWrite, reload, initialCreate }: { d: WorkspaceData; fr: boolean; canWrite: boolean; reload: () => Promise<void>; initialCreate?: "blank" | "template" | "map" | "import" | null }) {34 const pages = useMemo<PageX[]>(() => d.plans.flatMap((f) => f.pages.map((p) => ({ ...p, filename: f.filename }))), [d.plans]);35 const [pageSel, setPageSel] = useState<string | null>(null);36 const [creating, setCreating] = useState<null | "menu" | "blank" | "template" | "map" | "import">(initialCreate ?? (pages.length ? null : "menu"));37 const pageId = pageSel && pages.some((p) => p.id === pageSel) ? pageSel : pages[0]?.id ?? null;38 const page = pages.find((p) => p.id === pageId) ?? null;39 const imperial = d.project.unitSystem === "imperial";40 return (41 <div className="space-y-3">42 <div className="flex flex-wrap items-center justify-between gap-2">43 <div className="pl-levels">{pages.map((p) => <button key={p.id} type="button" className={p.id === pageId && !creating ? "active" : ""} onClick={() => { setPageSel(p.id); setCreating(null); }} title={p.filename}>{p.level ?? p.label ?? p.filename} {p.calibration ? "" : "○"}</button>)}{canWrite && <button type="button" className={creating ? "active" : ""} onClick={() => setCreating(creating ? null : "menu")}>+ {fr ? "Nouveau plan" : "New plan"}</button>}</div>44 {page && <span className="vp-mono text-[10.5px] uppercase text-ink-3">{page.source === "map" ? (fr ? "plan de site géoréférencé" : "georeferenced site plan") : page.source === "blank" ? (fr ? "plan vierge" : "blank plan") : page.source === "template" ? (fr ? "gabarit" : "template") : (fr ? "import" : "import")} · {page.widthPx} × {page.heightPx} px{page.calibration ? ` · ${num(page.calibration.pxPerMeter, "fr", 1)} px/m` : ` · ${fr ? "NON CALIBRÉ" : "NOT CALIBRATED"}`}</span>}45 </div>46 {creating && <NewPage mode={creating} setMode={setCreating} d={d} fr={fr} onDone={async (id) => { await reload(); if (id) setPageSel(id); setCreating(null); }} />}47 {page && !creating && <Editor key={page.id} page={page} fr={fr} canWrite={canWrite} projectId={d.project.id} measurements={d.measurements} reload={reload} imperial={imperial} onPageDeleted={() => setPageSel(null)} />}48 {!page && !creating && <div className="mt-card text-[13.5px] text-ink-2">{fr ? "Aucun plan. Créez un plan vierge, partez d'un gabarit, capturez une vue satellite ou importez un fichier." : "No plan yet. Create a blank plan, start from a template, capture a satellite view or import a file."}</div>}49 </div>50 );51}5253/* ============================================================ nouvelle page */5455function NewPage({ mode, setMode, d, fr, onDone }: { mode: "menu" | "blank" | "template" | "map" | "import"; setMode: (m: "menu" | "blank" | "template" | "map" | "import" | null) => void; d: WorkspaceData; fr: boolean; onDone: (pageId: string | null) => Promise<void> }) {56 const [levels, setLevels] = useState<string[]>(["Site", "Sous-sol", "Rez-de-chaussée", "Étage", "Toit"]);57 const [templates, setTemplates] = useState<{ key: string; kind: string; fr: string; en: string; footprint: string; storeys: number; units: number; areaM2: number; levels: string[] }[]>([]);58 const [kinds, setKinds] = useState<{ key: string; fr: string; en: string }[]>([]);59 const [kindFilter, setKindFilter] = useState<string>("");60 const [f, setF] = useState({ widthM: 24, heightM: 16, pxPerMeter: 50, level: "Rez-de-chaussée", template: "bungalow-c" });61 const [busy, setBusy] = useState<string | null>(null); const [err, setErr] = useState<string | null>(null);62 useEffect(() => { api<{ levels: string[] }>(`/projects/${d.project.id}/pages`).then((r) => setLevels(r.levels)).catch(() => undefined); api<{ kinds: typeof kinds; templates: typeof templates }>("/templates").then((r) => { setKinds(r.kinds); setTemplates(r.templates); }).catch(() => undefined); }, [d.project.id]);63 const create = async (body: Record<string, unknown>) => { setBusy("…"); setErr(null); try { const r = await api<{ page: PlanPage }>(`/projects/${d.project.id}/pages`, { method: "POST", json: body }); await onDone(r.page.id); } catch (e) { setErr((e as Error).message); } finally { setBusy(null); } };64 const lvl = <label className="block"><span className="klabel">{fr ? "Niveau" : "Level"}</span><select value={f.level} onChange={(e) => setF({ ...f, level: e.target.value })} className="vp-input !min-h-0 text-[13px]">{levels.map((l) => <option key={l}>{l}</option>)}</select></label>;65 if (mode === "menu") return (66 <div className="pl-new">67 <button type="button" className="mt-action" onClick={() => setMode("blank")}><b>✎ {fr ? "Plan vierge à l'échelle" : "Blank plan to scale"}</b><span>{fr ? "Grille 1 m, calibration exacte ; dessinez murs, pièces, portes et fenêtres comme un architecte." : "1 m grid, exact calibration; draw walls, rooms, doors and windows like an architect."}</span></button>68 <button type="button" className="mt-action" onClick={() => setMode("template")}><b>⌂ {fr ? "Partir d'un gabarit" : "Start from a template"}</b><span>{fr ? "Bungalow, cottage, garage : murs, pièces et ouvertures déjà tracés, à modifier." : "Bungalow, cottage, garage: walls, rooms and openings already drawn, ready to edit."}</span></button>69 <button type="button" className="mt-action" onClick={() => setMode("map")}><b>🛰 {fr ? "Plan de site (carte satellite)" : "Site plan (satellite map)"}</b><span>{fr ? "Image satellite géoréférencée de la propriété ; tracez le lot, l'empreinte, l'entrée, la terrasse." : "Georeferenced satellite image of the property; trace lot, footprint, driveway, deck."}</span></button>70 <button type="button" className="mt-action" onClick={() => setMode("import")}><b>⇪ {fr ? "Importer PDF · PNG · JPG · DXF" : "Import PDF · PNG · JPG · DXF"}</b><span>{fr ? "Plans existants (vectoriels ou numérisés) à calibrer, DXF calibré automatiquement." : "Existing plans (vector or scanned) to calibrate; DXF calibrated automatically."}</span></button>71 </div>72 );73 return (74 <div className="mt-card">75 <div className="flex items-center justify-between"><h2>{mode === "blank" ? (fr ? "Plan vierge" : "Blank plan") : mode === "template" ? (fr ? "Gabarit" : "Template") : mode === "map" ? (fr ? "Plan de site" : "Site plan") : (fr ? "Importer" : "Import")}</h2><button type="button" className="vp-mono text-[10.5px] uppercase text-ink-3" onClick={() => setMode("menu")}>← {fr ? "autres options" : "other options"}</button></div>76 {mode === "blank" && (<div className="space-y-3"><div className="grid gap-3 sm:grid-cols-4"><label className="block"><span className="klabel">{fr ? "Largeur (m)" : "Width (m)"}</span><Input type="number" min={3} max={200} value={f.widthM} onChange={(e) => setF({ ...f, widthM: Number(e.target.value) })} className="!min-h-0" /></label><label className="block"><span className="klabel">{fr ? "Hauteur (m)" : "Height (m)"}</span><Input type="number" min={3} max={200} value={f.heightM} onChange={(e) => setF({ ...f, heightM: Number(e.target.value) })} className="!min-h-0" /></label><label className="block"><span className="klabel">{fr ? "Échelle (px/m)" : "Scale (px/m)"}</span><Input type="number" min={10} max={200} value={f.pxPerMeter} onChange={(e) => setF({ ...f, pxPerMeter: Number(e.target.value) })} className="!min-h-0" /></label>{lvl}</div><p className="text-[12px] text-ink-3">{fr ? "Page" : "Page"} {f.widthM * f.pxPerMeter} × {f.heightM * f.pxPerMeter} px · {fr ? "grille principale de 1 m, aimant de 10 cm." : "main grid 1 m, snap 10 cm."}</p><Btn tone="primary" disabled={!!busy} onClick={() => void create({ kind: "blank", ...f })}>{busy ?? (fr ? "Créer le plan" : "Create plan")}</Btn></div>)}77 {mode === "template" && (<div className="space-y-3">78 <div className="flex flex-wrap items-center gap-2"><button type="button" className={`chip ${!kindFilter ? "on" : ""} vp-mono text-[10.5px] rounded-full border px-2.5 py-1`} onClick={() => setKindFilter("")}>{fr ? "tous" : "all"} ({templates.length})</button>{kinds.map((k) => <button key={k.key} type="button" className={`vp-mono text-[10.5px] rounded-full border px-2.5 py-1 ${kindFilter === k.key ? "border-accent text-accent bg-[#e6f0f4]" : "border-[var(--line)] text-ink-2"}`} onClick={() => setKindFilter(k.key)}>{fr ? k.fr : k.en} ({templates.filter((t) => t.kind === k.key).length})</button>)}</div>79 <div className="tpl-grid">{templates.filter((t) => !kindFilter || t.kind === kindFilter).map((t) => (80 <button key={t.key} type="button" className={`tpl-card ${f.template === t.key ? "sel" : ""}`} onClick={() => setF({ ...f, template: t.key })} onDoubleClick={() => void create({ kind: "template", template: t.key, pxPerMeter: 50 })}>81 <object data={`/api/metre/templates?key=${t.key}`} type="image/svg+xml" className="thumb" aria-label={fr ? t.fr : t.en} />82 <b>{fr ? t.fr : t.en}</b><span>{t.footprint} · {t.storeys} {fr ? "niv." : "lvl"} · {t.units} {fr ? "log." : "unit"} · {Math.round(t.areaM2)} m² · {t.levels.join(" / ")}</span>83 </button>))}</div>84 <div className="flex flex-wrap items-center gap-3"><Btn tone="primary" disabled={!!busy} onClick={() => void create({ kind: "template", template: f.template, pxPerMeter: 50 })}>{busy ?? (fr ? `Créer tous les niveaux du gabarit « ${templates.find((t) => t.key === f.template)?.fr ?? f.template} »` : `Create all levels of “${templates.find((t) => t.key === f.template)?.en ?? f.template}”`)}</Btn><span className="text-[12px] text-ink-3">{fr ? "Les niveaux (sous-sol, rez-de-chaussée, étages) sont créés avec murs, cloisons, pièces, portes et fenêtres ; la fiche technique du projet est préremplie pour le relevé des quantités." : "Levels (basement, ground, upper) are created with walls, partitions, rooms, doors and windows; the project technical sheet is prefilled for the quantity survey."}</span></div>85 </div>)}86 {mode === "map" && <MapPicker fr={fr} initial={{ lat: 45.4765, lng: -75.7013, q: [d.project.address, d.project.municipality].filter(Boolean).join(", ") || null, mamh: d.project.propertyId }} onCapture={async (v) => { await create({ kind: "map", ...v }); }} onCancel={() => setMode("menu")} />}87 {mode === "import" && <Uploader projectId={d.project.id} fr={fr} onDone={() => onDone(null)} />}88 <Err msg={err} />89 </div>90 );91}9293function Uploader({ projectId, fr, onDone }: { projectId: string; fr: boolean; onDone: () => Promise<void> }) {94 const [busy, setBusy] = useState<string | null>(null); const [err, setErr] = useState<string | null>(null);95 const onFile = async (file: File) => {96 setErr(null); setBusy(fr ? "lecture…" : "reading…");97 try {98 const form = new FormData();99 if (/\.dxf$/i.test(file.name)) { form.append("dxf", file, file.name); setBusy(fr ? "import DXF…" : "DXF import…"); const r = await api<{ objects: number; unit: string | null; skipped: Record<string, number> }>(`/projects/${projectId}/plans`, { method: "POST", body: form }); if (!r.unit) setErr(fr ? "DXF sans $INSUNITS : calibrez la page manuellement." : "DXF without $INSUNITS: calibrate manually."); await onDone(); return; }100 form.append("original", file, file.name);101 if (file.type === "application/pdf" || /\.pdf$/i.test(file.name)) {102 const pdfjs = await import("pdfjs-dist"); pdfjs.GlobalWorkerOptions.workerSrc = "/metre/pdf.worker.min.mjs";103 const doc = await pdfjs.getDocument({ data: await file.arrayBuffer() }).promise; const n = Math.min(doc.numPages, 60);104 for (let i = 1; i <= n; i++) { setBusy(`${fr ? "rendu page" : "rendering page"} ${i}/${n}`); const pg = await doc.getPage(i); const base = pg.getViewport({ scale: 1 }); const scale = Math.min(3, 4000 / Math.max(base.width, base.height)); const vp = pg.getViewport({ scale }); const canvas = document.createElement("canvas"); canvas.width = Math.round(vp.width); canvas.height = Math.round(vp.height); const ctx = canvas.getContext("2d")!; ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); await pg.render({ canvasContext: ctx, viewport: vp, canvas }).promise; const blob = await new Promise<Blob>((res) => canvas.toBlob((b) => res(b!), "image/png")); form.append(`page-${i}`, blob, `page-${i}.png`); }105 } else { const bmp = await createImageBitmap(file); const scale = Math.min(1, 4000 / Math.max(bmp.width, bmp.height)); const canvas = document.createElement("canvas"); canvas.width = Math.round(bmp.width * scale); canvas.height = Math.round(bmp.height * scale); canvas.getContext("2d")!.drawImage(bmp, 0, 0, canvas.width, canvas.height); const blob = await new Promise<Blob>((res) => canvas.toBlob((b) => res(b!), "image/png")); form.append("page-1", blob, "page-1.png"); }106 setBusy(fr ? "téléversement…" : "uploading…"); await api(`/projects/${projectId}/plans`, { method: "POST", body: form }); await onDone();107 } catch (e) { setErr((e as Error).message); } finally { setBusy(null); }108 };109 return (<div className="space-y-2"><label className="btn btn-primary cursor-pointer">{busy ?? (fr ? "Choisir un fichier (PDF, PNG, JPG, DXF)" : "Choose a file (PDF, PNG, JPG, DXF)")}<input type="file" accept="application/pdf,image/png,image/jpeg,.dxf" className="hidden" disabled={!!busy} onChange={(e) => { const f = e.target.files?.[0]; if (f) void onFile(f); e.target.value = ""; }} /></label><p className="text-[12px] text-ink-3">{fr ? "Les pages PDF/images sont rendues dans votre navigateur ; l'original est conservé avec son empreinte SHA-256. Calibrez ensuite avec l'outil ⊢ (deux points de distance connue)." : "PDF/image pages are rendered in your browser; the original is kept with its SHA-256. Then calibrate with the ⊢ tool (two points of known distance)."}</p><Err msg={err} /></div>);110}111112/* ================================================================= éditeur */113114interface Draft { tool: Tool; points: Point[] }115interface ViewT { k: number; tx: number; ty: number }116117function Editor({ page, fr, canWrite, projectId, measurements, reload, imperial, onPageDeleted }: { page: PageX; fr: boolean; canWrite: boolean; projectId: string; measurements: WorkspaceData["measurements"]; reload: () => Promise<void>; imperial: boolean; onPageDeleted: () => void }) {118 const [objects, setObjects] = useState<PlanObject[]>([]);119 const [cal, setCal] = useState<Calibration | null>(page.calibration);120 const [tool, setTool] = useState<Tool>(page.calibration ? "wall" : "calibrate");121 const [draft, setDraft] = useState<Draft | null>(null);122 const [typed, setTyped] = useState("");123 const [cursor, setCursor] = useState<Point | null>(null);124 const [snapKind, setSnapKind] = useState("");125 const [sel, setSel] = useState<string | null>(null);126 const [view, setView] = useState<ViewT>({ k: 1, tx: 0, ty: 0 });127 const [snap, setSnap] = useState(true); const [ortho, setOrtho] = useState(true); const [showDims, setShowDims] = useState(true); const [showLabels, setShowLabels] = useState(true); const [showGrid, setShowGrid] = useState(page.source === "blank" || page.source === "template");128 const [hidden, setHidden] = useState<Set<string>>(new Set());129 const [calPts, setCalPts] = useState<Point[]>([]); const [calLen, setCalLen] = useState({ value: "", unit: imperial ? "ft" : "m" });130 const [status, setStatus] = useState(""); const [err, setErr] = useState<string | null>(null);131 const [drag, setDrag] = useState<{ kind: "vertex" | "object" | "pan"; id?: string; idx?: number; start: Point; orig?: Point[]; view?: ViewT } | null>(null);132 const [spaceDown, setSpaceDown] = useState(false);133 const [full, setFull] = useState(false); const [panel, setPanel] = useState(true);134 const undo = useRef<PlanObject[][]>([]); const redo = useRef<PlanObject[][]>([]);135 const wrapRef = useRef<HTMLDivElement>(null); const svgRef = useRef<SVGSVGElement>(null);136 const k = cal?.pxPerMeter ?? null;137 void projectId;138 const toolDisabled = (t: Tool) => !canWrite || (t === "calibrate" && (page.source === "blank" || page.source === "template")) || (!k && t !== "calibrate" && t !== "select" && t !== "pan");139140 useEffect(() => { api<{ objects: PlanObject[] }>(`/pages/${page.id}/objects`).then((r) => setObjects(r.objects)).catch((e) => setErr(e.message)); }, [page.id]);141 const fit = useCallback(() => { const el = wrapRef.current; if (!el) return; const kk = Math.min((el.clientWidth - 20) / page.widthPx, (el.clientHeight - 20) / page.heightPx); setView({ k: kk, tx: (el.clientWidth - page.widthPx * kk) / 2, ty: (el.clientHeight - page.heightPx * kk) / 2 }); }, [page.widthPx, page.heightPx]);142 useEffect(() => { fit(); }, [fit, full, panel]);143 useEffect(() => { if (!full) return; const h = (e: KeyboardEvent) => { if (e.key === "Escape") setFull(false); }; window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h); }, [full]);144145 /* ----------------------------------------------------- persistance + annuler */146 const persistCreate = (o: PlanObject) => api(`/pages/${page.id}/objects`, { method: "POST", json: o }).catch((e) => setErr((e as Error).message));147 const persistUpdate = (o: PlanObject) => api(`/objects/${o.id}`, { method: "PATCH", json: o }).catch((e) => setErr((e as Error).message));148 const persistDelete = (id: string) => api(`/objects/${id}`, { method: "DELETE" }).catch((e) => setErr((e as Error).message));149 const pushUndo = (prev: PlanObject[]) => { undo.current = [...undo.current.slice(-59), prev]; redo.current = []; };150 const syncTo = (target: PlanObject[]) => { const cur = new Map(objects.map((o) => [o.id, o])); const tgt = new Map(target.map((o) => [o.id, o])); for (const o of target) { if (!cur.has(o.id)) void persistCreate(o); else if (cur.get(o.id) !== o) void persistUpdate(o); } for (const o of objects) if (!tgt.has(o.id)) void persistDelete(o.id); setObjects(target); };151 const doUndo = () => { const prev = undo.current.pop(); if (!prev) return; redo.current.push(objects); syncTo(prev); };152 const doRedo = () => { const next = redo.current.pop(); if (!next) return; undo.current.push(objects); syncTo(next); };153 const addObject = (o: PlanObject) => { pushUndo(objects); setObjects((xs) => [...xs, o]); setSel(o.id); void persistCreate(o); };154 const updateObject = (id: string, patch: Partial<PlanObject>, props?: Partial<PlanObject["props"]>) => { const o = objects.find((x) => x.id === id); if (!o) return; const n: PlanObject = { ...o, ...patch, props: { ...o.props, ...(props ?? {}) } }; pushUndo(objects); setObjects((xs) => xs.map((x) => (x.id === id ? n : x))); void persistUpdate(n); };155 const removeObject = (id: string) => { pushUndo(objects); const gone = objects.filter((o) => o.id === id || o.props.deductFrom === id); setObjects((xs) => xs.filter((o) => !gone.includes(o))); for (const o of gone) void persistDelete(o.id); if (sel === id) setSel(null); };156157 /* ----------------------------------------------------- coordonnées et aimant */158 const toPage = (e: { clientX: number; clientY: number }): Point => { const r = svgRef.current!.getBoundingClientRect(); return { x: (e.clientX - r.left - view.tx) / view.k, y: (e.clientY - r.top - view.ty) / view.k }; };159 const gridPx = k ? k * 0.1 : null;160 const anchor = draft?.points.length ? draft.points[draft.points.length - 1] : null;161 const snapped = (p: Point) => (snap ? snapPoint(p, { objects: objects.filter((o) => !hidden.has(o.layer)), draft: draft?.points ?? [], anchor, ortho, grid: gridPx, tolPx: 9 / view.k }) : { p, kind: "free" as const });162163 /* ----------------------------------------------------- création d'objets */164 const def = TOOLS.find((t) => t.t === tool)!;165 const layerFor = (kind: ObjectKind) => (kind === "wall" || kind === "column" ? "murs" : kind === "opening" ? "ouvertures" : kind === "room" ? "pièces" : kind === "dimension" || kind === "text" ? "cotes" : kind === "footprint" || kind === "lot" ? "site" : "default");166 const nameFor = (kind: ObjectKind, extra?: string) => `${extra ?? (fr ? KIND_FR[kind]?.[0] : KIND_FR[kind]?.[1]) ?? kind} ${objects.filter((o) => o.kind === kind).length + 1}`;167 const finishDraft = () => {168 if (!draft) return;169 const t = TOOLS.find((x) => x.t === draft.tool)!;170 if (draft.tool === "rect" || draft.tool === "dimension") { finishRectOrDim(draft.points); return; }171 const pts = draft.points; const isClosed = !!t.closed;172 if (pts.length < (isClosed ? 3 : 2)) { setDraft(null); setTyped(""); return; }173 const kind = t.kind!;174 const props: PlanObject["props"] = draft.tool === "wall" ? { thickness: DEFAULT_WALL_THICKNESS_M, height: DEFAULT_WALL_HEIGHT_M, exterior: true } : draft.tool === "partition" ? { thickness: DEFAULT_PARTITION_THICKNESS_M, height: DEFAULT_WALL_HEIGHT_M, exterior: false } : {};175 const closeWall = kind === "wall" && pts.length >= 4 && dist(pts[0], pts[pts.length - 1]) < 1e-6;176 addObject({ id: uuid(), pageId: page.id, kind, layer: layerFor(kind), name: nameFor(kind, draft.tool === "partition" ? (fr ? "Cloison" : "Partition") : draft.tool === "wall" ? (fr ? "Mur ext." : "Ext. wall") : undefined), points: closeWall ? pts.slice(0, -1) : pts, closed: isClosed || closeWall, props, createdAt: "", updatedAt: "" });177 setDraft(null); setTyped("");178 };179 const finishRectOrDim = (pts: Point[]) => {180 if (pts.length < 2) return;181 if (draft?.tool === "dimension") addObject({ id: uuid(), pageId: page.id, kind: "dimension", layer: "cotes", name: nameFor("dimension"), points: pts.slice(0, 2), closed: false, props: { offset: k ? -k * 0.5 : -30 }, createdAt: "", updatedAt: "" });182 if (draft?.tool === "rect") { const [a, b] = pts; addObject({ id: uuid(), pageId: page.id, kind: "room", layer: "pièces", name: nameFor("room"), points: [a, { x: b.x, y: a.y }, b, { x: a.x, y: b.y }], closed: true, props: {}, createdAt: "", updatedAt: "" }); }183 setDraft(null); setTyped("");184 };185 const nearestWall = (p: Point): { wall: PlanObject; point: Point } | null => { let best: { wall: PlanObject; point: Point; d: number } | null = null; for (const w of objects) { if (w.kind !== "wall") continue; const pr = projectOnPolyline(p, w.points, w.closed); if (pr && (!best || pr.dist < best.d)) best = { wall: w, point: pr.point, d: pr.dist }; } return best && best.d < 25 / view.k ? best : null; };186 const applyTyped = () => {187 if (!draft || !anchor || !k) return;188 const m = Number(typed.replace(",", ".")); if (!(m > 0)) { setTyped(""); return; }189 const len = (imperial ? m * 0.3048 : m) * k;190 const dir = cursor ? Math.atan2(cursor.y - anchor.y, cursor.x - anchor.x) : 0;191 const a = ortho ? Math.round(dir / (Math.PI / 12)) * (Math.PI / 12) : dir;192 const p = { x: anchor.x + Math.cos(a) * len, y: anchor.y + Math.sin(a) * len };193 const pts = [...draft.points, p];194 setTyped("");195 if (draft.tool === "dimension" || draft.tool === "rect") { finishRectOrDim(pts); return; }196 setDraft({ ...draft, points: pts });197 };198199 /* ----------------------------------------------------- souris / tactile */200 const onPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {201 (e.target as Element).setPointerCapture?.(e.pointerId);202 if (e.button === 1 || tool === "pan" || spaceDown) { setDrag({ kind: "pan", start: { x: e.clientX, y: e.clientY }, view }); return; }203 if (e.button !== 0) return;204 const raw = toPage(e);205 if (!canWrite) return;206 if (tool === "calibrate") { setCalPts((c) => [...c, snapped(raw).p].slice(-2)); return; }207 if (tool === "select") {208 const target = (e.target as Element).closest("[data-id]")?.getAttribute("data-id") ?? null;209 const o = target ? objects.find((x) => x.id === target) : null;210 if (o && target === sel) { const vi = o.points.findIndex((p) => dist(p, raw) < 8 / view.k); setDrag(vi >= 0 ? { kind: "vertex", id: sel!, idx: vi, start: raw, orig: o.points } : { kind: "object", id: sel!, start: raw, orig: o.points }); return; }211 setSel(target); if (o) setDrag({ kind: "object", id: target!, start: raw, orig: o.points });212 return;213 }214 const sp = snapped(raw).p;215 if (tool === "door" || tool === "window") {216 const nw = nearestWall(raw); if (!nw) { setStatus(fr ? "cliquez sur un mur" : "click on a wall"); return; }217 const isDoor = tool === "door";218 addObject({ id: uuid(), pageId: page.id, kind: "opening", layer: "ouvertures", name: nameFor("opening", isDoor ? (fr ? "Porte" : "Door") : (fr ? "Fenêtre" : "Window")), points: [nw.point], closed: false, props: { openingKind: isDoor ? "door" : "window", openingWidth: isDoor ? 0.9 : 1.2, openingHeight: isDoor ? 2.1 : 1.2, count: 1, deductFrom: nw.wall.id, swing: 1 }, createdAt: "", updatedAt: "" });219 return;220 }221 if (tool === "text") { const t = prompt(fr ? "Texte" : "Text", ""); if (t) addObject({ id: uuid(), pageId: page.id, kind: "text", layer: "cotes", name: t.slice(0, 40), points: [sp], closed: false, props: { text: t, fontSize: k ? Math.max(11, k * 0.2) : 12 }, createdAt: "", updatedAt: "" }); return; }222 if (tool === "column") { addObject({ id: uuid(), pageId: page.id, kind: "column", layer: "murs", name: nameFor("column"), points: [sp], closed: false, props: { thickness: 0.3, height: DEFAULT_WALL_HEIGHT_M }, createdAt: "", updatedAt: "" }); return; }223 if (tool === "rect" || tool === "dimension") { const pts = [...(draft?.tool === tool ? draft.points : []), sp]; if (pts.length >= 2) { setDraft({ tool, points: pts }); setTimeout(() => finishRectOrDimDeferred(tool, pts), 0); } else setDraft({ tool, points: pts }); return; }224 if (draft && draft.tool === tool && draft.points.length >= 3 && dist(draft.points[0], sp) < 9 / view.k) { setDraft({ ...draft, points: def.kind === "wall" ? [...draft.points, draft.points[0]] : draft.points }); setTimeout(() => finishDraftDeferred.current?.(), 0); return; }225 setDraft((dr) => (dr && dr.tool === tool ? { ...dr, points: [...dr.points, sp] } : { tool, points: [sp] }));226 };227 const finishDraftDeferred = useRef<(() => void) | null>(null);228 useEffect(() => { finishDraftDeferred.current = finishDraft; });229 const finishRectOrDimDeferred = (t: Tool, pts: Point[]) => { if (pts.length < 2) return; if (t === "dimension") addObject({ id: uuid(), pageId: page.id, kind: "dimension", layer: "cotes", name: nameFor("dimension"), points: pts.slice(0, 2), closed: false, props: { offset: k ? -k * 0.5 : -30 }, createdAt: "", updatedAt: "" }); if (t === "rect") { const [a, b] = pts; addObject({ id: uuid(), pageId: page.id, kind: "room", layer: "pièces", name: nameFor("room"), points: [a, { x: b.x, y: a.y }, b, { x: a.x, y: b.y }], closed: true, props: {}, createdAt: "", updatedAt: "" }); } setDraft(null); setTyped(""); };230 const onPointerMove = (e: React.PointerEvent<SVGSVGElement>) => {231 if (drag?.kind === "pan") { setView({ k: drag.view!.k, tx: drag.view!.tx + (e.clientX - drag.start.x), ty: drag.view!.ty + (e.clientY - drag.start.y) }); return; }232 const raw = toPage(e);233 if (drag && drag.orig && drag.id) {234 const dx = raw.x - drag.start.x, dy = raw.y - drag.start.y;235 const pts = drag.kind === "vertex" ? drag.orig.map((p, i) => (i === drag.idx ? snapped({ x: p.x + dx, y: p.y + dy }).p : p)) : drag.orig.map((p) => ({ x: p.x + dx, y: p.y + dy }));236 setObjects((xs) => xs.map((x) => (x.id === drag.id ? { ...x, points: pts } : x)));237 return;238 }239 const s = snapped(raw); setCursor(s.p); setSnapKind(s.kind);240 };241 const onPointerUp = () => {242 if (drag && drag.kind !== "pan" && drag.id && drag.orig) { const o = objects.find((x) => x.id === drag.id); if (o && JSON.stringify(o.points) !== JSON.stringify(drag.orig)) { undo.current = [...undo.current.slice(-59), objects.map((x) => (x.id === drag.id ? { ...x, points: drag.orig! } : x))]; redo.current = []; void persistUpdate(o); } }243 setDrag(null);244 };245 const onWheel = (e: React.WheelEvent<SVGSVGElement>) => { const r = svgRef.current!.getBoundingClientRect(); const mx = e.clientX - r.left, my = e.clientY - r.top; const f = e.deltaY < 0 ? 1.12 : 1 / 1.12; setView((v) => { const nk = Math.min(12, Math.max(0.05, v.k * f)); return { k: nk, tx: mx - (mx - v.tx) * (nk / v.k), ty: my - (my - v.ty) * (nk / v.k) }; }); };246 useEffect(() => { const el = wrapRef.current; if (!el) return; const h = (e: WheelEvent) => e.preventDefault(); el.addEventListener("wheel", h, { passive: false }); return () => el.removeEventListener("wheel", h); }, []);247248 /* ----------------------------------------------------- clavier */249 useEffect(() => {250 const down = (e: KeyboardEvent) => {251 const tag = (e.target as HTMLElement)?.tagName; if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return;252 if (e.key === " ") { setSpaceDown(true); e.preventDefault(); return; }253 if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") { e.preventDefault(); if (e.shiftKey) doRedo(); else doUndo(); return; }254 if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") { e.preventDefault(); doRedo(); return; }255 if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "d") { e.preventDefault(); const o = objects.find((x) => x.id === sel); if (o) addObject({ ...o, id: uuid(), name: `${o.name} (copie)`, points: o.points.map((p) => ({ x: p.x + (k ?? 50) * 0.5, y: p.y + (k ?? 50) * 0.5 })) }); return; }256 if (e.key === "Escape") { setDraft(null); setTyped(""); setCalPts([]); setSel(null); return; }257 if (e.key === "Enter") { if (typed) applyTyped(); else finishDraft(); return; }258 if (e.key === "Backspace") { if (typed) setTyped((t) => t.slice(0, -1)); else if (draft) setDraft((dr) => (dr ? { ...dr, points: dr.points.slice(0, -1) } : dr)); else if (sel) removeObject(sel); return; }259 if (e.key === "Delete") { if (sel) removeObject(sel); return; }260 if (/^[0-9.,]$/.test(e.key) && draft && anchor) { setTyped((t) => (t + e.key).slice(0, 8)); return; }261 if (e.key === "+" || e.key === "=") setView((v) => ({ ...v, k: Math.min(12, v.k * 1.2) })); if (e.key === "-") setView((v) => ({ ...v, k: Math.max(0.05, v.k / 1.2) })); if (e.key === "0") fit();262 if (e.key.toLowerCase() === "g") setShowGrid((g) => !g); if (e.key.toLowerCase() === "o") setOrtho((o) => !o); if (e.key.toLowerCase() === "q") setSnap((s) => !s);263 const t = TOOLS.find((x) => x.key.toLowerCase() === e.key.toLowerCase()); if (t && !e.ctrlKey && !e.metaKey && !e.altKey) { if (toolDisabled(t.t)) return; setTool(t.t); setDraft(null); setTyped(""); }264 };265 const up = (e: KeyboardEvent) => { if (e.key === " ") setSpaceDown(false); };266 window.addEventListener("keydown", down); window.addEventListener("keyup", up);267 return () => { window.removeEventListener("keydown", down); window.removeEventListener("keyup", up); };268 });269270 /* ----------------------------------------------------- actions serveur */271 const measureAll = async () => { setStatus("…"); try { const r = await api<{ measured: number; failed: { name: string; error: string }[] }>(`/pages/${page.id}`, { method: "POST", json: { action: "measure_all" } }); setStatus(`${r.measured} ${fr ? "mesures au registre" : "measurements in ledger"}${r.failed.length ? ` · ${r.failed.length} ${fr ? "échecs" : "failed"}` : ""}`); await reload(); } catch (e) { setErr((e as Error).message); } };272 const measureOne = async (id: string) => { try { const r = await api<{ measurement: { value: number; unit: string } }>(`/objects/${id}/measure`, { method: "POST", json: {} }); setStatus(`${fr ? "mesuré" : "measured"} ${num(r.measurement.value, "fr", 3)} ${r.measurement.unit}`); await reload(); } catch (e) { setErr((e as Error).message); } };273 const calibrate = async () => { if (calPts.length < 2 || !calLen.value) return; try { const r = await api<{ calibration: Calibration }>(`/pages/${page.id}/calibrate`, { method: "POST", json: { p1: calPts[0], p2: calPts[1], realLength: Number(calLen.value), unit: calLen.unit } }); setCal(r.calibration); setCalPts([]); setTool("wall"); setStatus(`${fr ? "calibration" : "calibration"} ${num(r.calibration.pxPerMeter, "fr", 2)} px/m ± ${r.calibration.uncertaintyPct} %`); await reload(); } catch (e) { setErr((e as Error).message); } };274 const pageAction = async (a: "rename" | "duplicate" | "delete") => {275 try {276 if (a === "rename") { const label = prompt(fr ? "Nom du niveau / de la page" : "Level / page name", page.level ?? page.label ?? ""); if (label == null) return; await api(`/pages/${page.id}`, { method: "PATCH", json: { label, level: label } }); }277 if (a === "duplicate") { const label = prompt(fr ? "Nom du nouveau niveau (copie des objets)" : "New level name (objects copied)", "Étage"); if (!label) return; await api(`/pages/${page.id}`, { method: "POST", json: { action: "duplicate", label, level: label } }); }278 if (a === "delete") { if (!confirm(fr ? "Supprimer cette page et ses objets ?" : "Delete this page and its objects?")) return; await api(`/pages/${page.id}`, { method: "DELETE" }); onPageDeleted(); }279 await reload();280 } catch (e) { setErr((e as Error).message); }281 };282 /* ----------------------------------------------------- rendu */283 const selected = objects.find((o) => o.id === sel) ?? null;284 const q = useMemo(() => planQuantities(objects, k), [objects, k]);285 const inner = useMemo(() => renderPlanInner(objects, { widthPx: page.widthPx, heightPx: page.heightPx, pxPerMeter: k, imperial, grid: false, selectedId: sel, showLabels, showDims, hiddenLayers: hidden }), [objects, page.widthPx, page.heightPx, k, imperial, sel, showLabels, showDims, hidden]);286 const gridSvg = useMemo(() => (showGrid && k ? renderPlanInner([], { widthPx: page.widthPx, heightPx: page.heightPx, pxPerMeter: k, imperial, grid: true }) : ""), [showGrid, k, page.widthPx, page.heightPx, imperial]);287 const draftLen = draft && anchor && cursor && k ? dist(anchor, cursor) / k : null;288 const draftPoly = draft ? [...draft.points, ...(cursor && draft.tool !== "rect" ? [cursor] : [])] : [];289 const walls = objects.filter((o) => o.kind === "wall");290 const layers = [...new Set(objects.map((o) => o.layer))];291 const mOf = (id: string) => measurements.filter((m) => m.objectId === id);292293 return (294 <div className={`pl-wrap ${full ? "full" : ""} ${panel ? "" : "nopanel"}`}>295 <div className="pl-tools">296 {TOOLS.map((t, i) => (<span key={t.t} className="contents">{(i === 2 || i === 6 || i === 8 || i === 12 || i === 15) && <span className="sep" />}<button type="button" disabled={toolDisabled(t.t)} className={tool === t.t ? "active" : ""} title={`${fr ? t.fr : t.en} (${t.key})`} onClick={() => { setTool(t.t); setDraft(null); setTyped(""); }}>{t.ico}<small>{t.key}</small></button></span>))}297 </div>298 <div className="pl-center">299 <div className="pl-bar">300 <button type="button" className={`chip ${snap ? "on" : ""}`} onClick={() => setSnap((s) => !s)}>{fr ? "aimant" : "snap"} Q</button>301 <button type="button" className={`chip ${ortho ? "on" : ""}`} onClick={() => setOrtho((o) => !o)}>ortho O</button>302 <button type="button" className={`chip ${showGrid ? "on" : ""}`} onClick={() => setShowGrid((g) => !g)}>{fr ? "grille" : "grid"} G</button>303 <button type="button" className={`chip ${showDims ? "on" : ""}`} onClick={() => setShowDims((v) => !v)}>{fr ? "cotes" : "dims"}</button>304 <button type="button" className={`chip ${showLabels ? "on" : ""}`} onClick={() => setShowLabels((v) => !v)}>{fr ? "étiquettes" : "labels"}</button>305 <span className="mx-1 h-4 w-px bg-[#d9dee2]" />306 <button type="button" className="chip" onClick={doUndo}>↶</button><button type="button" className="chip" onClick={doRedo}>↷</button>307 <button type="button" className="chip" onClick={() => setView((v) => ({ ...v, k: v.k / 1.2 }))}>−</button><span className="vp-mono text-[11px]">{Math.round(view.k * 100)} %</span><button type="button" className="chip" onClick={() => setView((v) => ({ ...v, k: v.k * 1.2 }))}>+</button><button type="button" className="chip" onClick={fit}>{fr ? "ajuster" : "fit"} 0</button>308 <span className="mx-1 h-4 w-px bg-[#d9dee2]" />309 {layers.map((l) => <button key={l} type="button" className={`chip ${hidden.has(l) ? "" : "on"}`} onClick={() => setHidden((h) => { const n = new Set(h); if (n.has(l)) n.delete(l); else n.add(l); return n; })}>{l}</button>)}310 <span className="ml-auto flex flex-wrap gap-1">311 <button type="button" className={`chip ${full ? "on" : ""}`} onClick={() => setFull((v) => !v)} title={fr ? "Plein écran (Échap pour quitter)" : "Full screen (Esc to exit)"}>{full ? "⤡" : "⤢"} {fr ? "plein écran" : "full screen"}</button>312 <button type="button" className={`chip ${panel ? "on" : ""}`} onClick={() => setPanel((v) => !v)}>{fr ? "panneau" : "panel"}</button>313 {canWrite && <Btn small tone="accent" disabled={!k} onClick={() => void measureAll()}>{fr ? "Mesurer tout → registre" : "Measure all → ledger"}</Btn>}314 <a className="btn btn-ghost !min-h-0 !px-3 !py-1.5 text-[12px]" href={`/api/metre/pages/${page.id}/export?format=pdf`}>PDF</a><a className="btn btn-ghost !min-h-0 !px-3 !py-1.5 text-[12px]" href={`/api/metre/pages/${page.id}/export?format=png`}>PNG</a><a className="btn btn-ghost !min-h-0 !px-3 !py-1.5 text-[12px]" href={`/api/metre/pages/${page.id}/export?format=svg`}>SVG</a>315 {canWrite && <><Btn small onClick={() => void pageAction("rename")} title={fr ? "Renommer" : "Rename"}>✎</Btn><Btn small onClick={() => void pageAction("duplicate")} title={fr ? "Dupliquer en nouveau niveau" : "Duplicate as new level"}>⧉</Btn><Btn small onClick={() => void pageAction("delete")} title={fr ? "Supprimer la page" : "Delete page"}>🗑</Btn></>}316 </span>317 </div>318 {tool === "calibrate" && (319 <div className="pl-bar !bg-[#fff8e6]">320 <span className="text-[12px]">{fr ? "Cliquez deux points de distance connue (une cote du plan), puis la longueur :" : "Click two points of known distance (a plan dimension), then the length:"}</span>321 <span className="vp-mono text-[11px]">{calPts.length}/2{calPts.length === 2 ? ` · ${num(dist(calPts[0], calPts[1]), "fr", 1)} px` : ""}</span>322 <Input type="number" step="0.001" min={0} value={calLen.value} onChange={(e) => setCalLen({ ...calLen, value: e.target.value })} className="!min-h-0 w-[110px] !py-1" placeholder={fr ? "longueur" : "length"} />323 <select value={calLen.unit} onChange={(e) => setCalLen({ ...calLen, unit: e.target.value })} className="vp-input !min-h-0 w-[80px] !py-1 text-[12px]"><option value="m">m</option><option value="ft">pi / ft</option><option value="mm">mm</option><option value="cm">cm</option><option value="in">po / in</option></select>324 <Btn small tone="primary" disabled={calPts.length < 2 || !calLen.value} onClick={() => void calibrate()}>{fr ? "Calibrer" : "Calibrate"}</Btn>325 </div>326 )}327 <div ref={wrapRef} className={`pl-canvas ${tool === "pan" || spaceDown ? "pan" : tool === "select" ? "select" : ""}`}>328 <svg ref={svgRef} width="100%" height="100%" onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp} onWheel={onWheel} onContextMenu={(e) => { e.preventDefault(); if (draft) finishDraft(); }} onDoubleClick={() => { if (draft) finishDraft(); }} style={{ display: "block" }}>329 <g transform={`translate(${view.tx} ${view.ty}) scale(${view.k})`}>330 <rect x={-4} y={-4} width={page.widthPx + 8} height={page.heightPx + 8} fill="#000" opacity={0.08} />331 <image href={`/api/metre/pages/${page.id}/image`} width={page.widthPx} height={page.heightPx} />332 {gridSvg && <g dangerouslySetInnerHTML={{ __html: gridSvg }} />}333 <g dangerouslySetInnerHTML={{ __html: inner }} />334 {draft && draftPoly.length > 0 && (() => { const t = TOOLS.find((x) => x.t === draft.tool)!; const isWall = t.kind === "wall"; const th = (draft.tool === "wall" ? DEFAULT_WALL_THICKNESS_M : DEFAULT_PARTITION_THICKNESS_M) * (k ?? 50); return (<g pointerEvents="none">335 {draft.tool === "rect" && cursor && draft.points[0] ? <rect x={Math.min(draft.points[0].x, cursor.x)} y={Math.min(draft.points[0].y, cursor.y)} width={Math.abs(cursor.x - draft.points[0].x)} height={Math.abs(cursor.y - draft.points[0].y)} fill="#00608522" stroke="#006085" strokeWidth={1.5 / view.k} strokeDasharray={`${6 / view.k} ${4 / view.k}`} />336 : <polyline points={draftPoly.map((p) => `${p.x},${p.y}`).join(" ")} fill={t.closed ? "#00608518" : "none"} stroke={isWall ? "#1f2326" : "#006085"} strokeWidth={isWall ? th : 2 / view.k} strokeOpacity={isWall ? 0.5 : 1} strokeLinejoin="miter" strokeDasharray={isWall ? undefined : `${6 / view.k} ${4 / view.k}`} />}337 {draft.points.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={4 / view.k} fill={i === 0 ? "#fff" : "#006085"} stroke="#006085" strokeWidth={1.5 / view.k} />)}338 {draftLen != null && anchor && cursor && <text x={(anchor.x + cursor.x) / 2} y={(anchor.y + cursor.y) / 2 - 10 / view.k} fontSize={12 / view.k} fill="#006085" textAnchor="middle" fontFamily="ui-monospace" paintOrder="stroke" stroke="#fff" strokeWidth={3 / view.k}>{typed ? `${typed} ${imperial ? "pi" : "m"} ⏎` : fmtLength(draftLen, imperial)}</text>}339 </g>); })()}340 {selected && selected.points.map((p, i) => <circle key={i} cx={p.x} cy={p.y} r={5 / view.k} fill="#fff" stroke="#006085" strokeWidth={1.5 / view.k} style={{ cursor: "move" }} data-id={selected.id} />)}341 {cursor && tool !== "select" && tool !== "pan" && <g pointerEvents="none"><line x1={cursor.x - 8 / view.k} y1={cursor.y} x2={cursor.x + 8 / view.k} y2={cursor.y} stroke={snapKind === "vertex" || snapKind === "segment" ? "#b3423a" : "#006085"} strokeWidth={1 / view.k} /><line x1={cursor.x} y1={cursor.y - 8 / view.k} x2={cursor.x} y2={cursor.y + 8 / view.k} stroke={snapKind === "vertex" || snapKind === "segment" ? "#b3423a" : "#006085"} strokeWidth={1 / view.k} />{(snapKind === "vertex" || snapKind === "segment") && <circle cx={cursor.x} cy={cursor.y} r={6 / view.k} fill="none" stroke="#b3423a" strokeWidth={1 / view.k} />}</g>}342 {(tool === "door" || tool === "window") && cursor && (() => { const nw = nearestWall(cursor); return nw ? <circle cx={nw.point.x} cy={nw.point.y} r={7 / view.k} fill="#2bccae55" stroke="#2bccae" strokeWidth={1.5 / view.k} pointerEvents="none" /> : null; })()}343 {calPts.map((p, i) => <g key={i} pointerEvents="none"><circle cx={p.x} cy={p.y} r={6 / view.k} fill="none" stroke="#b3423a" strokeWidth={2 / view.k} /><circle cx={p.x} cy={p.y} r={1.5 / view.k} fill="#b3423a" /></g>)}344 {calPts.length === 2 && <line x1={calPts[0].x} y1={calPts[0].y} x2={calPts[1].x} y2={calPts[1].y} stroke="#b3423a" strokeWidth={2 / view.k} strokeDasharray={`${8 / view.k} ${4 / view.k}`} pointerEvents="none" />}345 {cal && page.source === "import" && <line x1={cal.p1.x} y1={cal.p1.y} x2={cal.p2.x} y2={cal.p2.y} stroke="#2bccae" strokeWidth={1.5 / view.k} opacity={0.5} pointerEvents="none" />}346 </g>347 </svg>348 </div>349 <div className="pl-status">350 <span>{cursor && k ? `x ${fmtLength(cursor.x / k, imperial)} · y ${fmtLength(cursor.y / k, imperial)}` : ""}{draftLen != null ? ` · ${fr ? "segment" : "segment"} ${fmtLength(draftLen, imperial)}` : ""} {typed && <b className="text-accent">⌨ {typed}</b>} {status && <span className="text-accent"> · {status}</span>}</span>351 <span>{fr ? `murs ${fmtLength(q.totals.wallLengthM, imperial)} · pièces ${fmtArea(q.totals.floorAreaM2, imperial)} · ${q.totals.doors} portes · ${q.totals.windows} fenêtres` : `walls ${fmtLength(q.totals.wallLengthM, imperial)} · rooms ${fmtArea(q.totals.floorAreaM2, imperial)} · ${q.totals.doors} doors · ${q.totals.windows} windows`}</span>352 <span>{fr ? "clic : point · 1er point / double-clic / clic droit / Entrée : fermer · chiffres + Entrée : longueur · Échap · Suppr · Ctrl+Z/Y · Ctrl+D · molette : zoom · espace+glisser : déplacer" : "click: point · 1st point / double-click / right-click / Enter: close · digits + Enter: length · Esc · Del · Ctrl+Z/Y · Ctrl+D · wheel: zoom · space+drag: pan"}</span>353 </div>354 <Err msg={err} />355 </div>356 {panel && <aside className="pl-right">357 {selected ? (<>358 <h3>{fr ? KIND_FR[selected.kind]?.[0] : KIND_FR[selected.kind]?.[1]} — {selected.name}</h3>359 <div className="sec space-y-2">360 <label>{fr ? "Nom" : "Name"}<input value={selected.name} disabled={!canWrite} onChange={(e) => setObjects((xs) => xs.map((x) => (x.id === sel ? { ...x, name: e.target.value } : x)))} onBlur={(e) => updateObject(selected.id, { name: e.target.value })} /></label>361 <div className="row">362 <label>{fr ? "Calque" : "Layer"}<input value={selected.layer} disabled={!canWrite} onChange={(e) => setObjects((xs) => xs.map((x) => (x.id === sel ? { ...x, layer: e.target.value } : x)))} onBlur={(e) => updateObject(selected.id, { layer: e.target.value || "default" })} /></label>363 <label>{fr ? "Type" : "Kind"}<select value={selected.kind} disabled={!canWrite} onChange={(e) => updateObject(selected.id, { kind: e.target.value as ObjectKind })}>{Object.keys(KIND_FR).map((kk) => <option key={kk} value={kk}>{fr ? KIND_FR[kk][0] : KIND_FR[kk][1]}</option>)}</select></label>364 </div>365 {selected.kind === "wall" && (<><div className="row"><NumProp key={`${selected.id}:thickness:${String(selected.props.thickness ?? "")}`} label={fr ? "Épaisseur (m)" : "Thickness (m)"} o={selected} k="thickness" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { thickness: v })} /><NumProp key={`${selected.id}:height:${String(selected.props.height ?? "")}`} label={fr ? "Hauteur (m)" : "Height (m)"} o={selected} k="height" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { height: v })} /></div><label className="flex items-center gap-2"><input type="checkbox" checked={!!selected.props.exterior} disabled={!canWrite} onChange={(e) => updateObject(selected.id, {}, { exterior: e.target.checked })} className="!w-auto" /> {fr ? "mur extérieur (enveloppe)" : "exterior wall (envelope)"}</label><label className="flex items-center gap-2"><input type="checkbox" checked={selected.closed} disabled={!canWrite} onChange={(e) => updateObject(selected.id, { closed: e.target.checked })} className="!w-auto" /> {fr ? "boucle fermée" : "closed loop"}</label>366 <p className="text-[11px] text-ink-3">{k ? `${fmtLength(polylineLengthPx(selected.points, selected.closed) / k, imperial)} · ${fr ? "brut" : "gross"} ${fmtArea((polylineLengthPx(selected.points, selected.closed) / k) * (selected.props.height ?? DEFAULT_WALL_HEIGHT_M), imperial)} · ${objects.filter((o) => o.kind === "opening" && o.props.deductFrom === selected.id).length} ${fr ? "ouvertures" : "openings"}` : ""}</p></>)}367 {selected.kind === "opening" && (<>368 <div className="row"><label>{fr ? "Type" : "Type"}<select value={selected.props.openingKind ?? "door"} disabled={!canWrite} onChange={(e) => updateObject(selected.id, {}, { openingKind: e.target.value as "door" | "window" | "opening" })}><option value="door">{fr ? "porte" : "door"}</option><option value="window">{fr ? "fenêtre" : "window"}</option><option value="opening">{fr ? "baie libre" : "free opening"}</option></select></label><label>{fr ? "Mur" : "Wall"}<select value={selected.props.deductFrom ?? ""} disabled={!canWrite} onChange={(e) => updateObject(selected.id, {}, { deductFrom: e.target.value || null })}><option value="">—</option>{walls.map((w) => <option key={w.id} value={w.id}>{w.name}</option>)}</select></label></div>369 <div className="row"><NumProp key={`${selected.id}:openingWidth:${String(selected.props.openingWidth ?? "")}`} label={fr ? "Largeur (m)" : "Width (m)"} o={selected} k="openingWidth" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { openingWidth: v })} /><NumProp key={`${selected.id}:openingHeight:${String(selected.props.openingHeight ?? "")}`} label={fr ? "Hauteur (m)" : "Height (m)"} o={selected} k="openingHeight" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { openingHeight: v })} /></div>370 <div className="row"><NumProp key={`${selected.id}:count:${String(selected.props.count ?? "")}`} label={fr ? "Nombre" : "Count"} o={selected} k="count" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { count: v })} /><label>{fr ? "Battement" : "Swing"}<select value={selected.props.swing ?? 1} disabled={!canWrite} onChange={(e) => updateObject(selected.id, {}, { swing: Number(e.target.value) })}><option value={1}>{fr ? "intérieur · charnière gauche" : "inside · left hinge"}</option><option value={-1}>{fr ? "extérieur · charnière gauche" : "outside · left hinge"}</option><option value={2}>{fr ? "intérieur · charnière droite" : "inside · right hinge"}</option><option value={-2}>{fr ? "extérieur · charnière droite" : "outside · right hinge"}</option></select></label></div>371 <p className="text-[11px] text-ink-3">{fr ? "Déduite du mur net une fois mesurée et vérifiée au registre." : "Deducted from the net wall once measured and verified in the ledger."}</p></>)}372 {(selected.kind === "room" || selected.kind === "footprint" || selected.kind === "lot" || selected.kind === "stairs" || selected.kind === "area") && (<><div className="row"><label>{fr ? "Usage" : "Use"}<input value={selected.props.usage ?? ""} disabled={!canWrite} placeholder={fr ? "chambre, cuisine…" : "bedroom, kitchen…"} onChange={(e) => setObjects((xs) => xs.map((x) => (x.id === sel ? { ...x, props: { ...x.props, usage: e.target.value } } : x)))} onBlur={(e) => updateObject(selected.id, {}, { usage: e.target.value })} /></label><NumProp key={`${selected.id}:height:${String(selected.props.height ?? "")}`} label={fr ? "Hauteur plafond (m)" : "Ceiling (m)"} o={selected} k="height" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { height: v })} /></div><p className="text-[11px] text-ink-3">{k ? `${fmtArea(polygonAreaPx(selected.points) / (k * k), imperial)} · ${fr ? "périmètre" : "perimeter"} ${fmtLength(polylineLengthPx(selected.points, true) / k, imperial)}` : ""}</p></>)}373 {(selected.kind === "slab" || selected.kind === "foundation") && <NumProp key={`${selected.id}:thickness:${String(selected.props.thickness ?? "")}`} label={fr ? "Épaisseur (m)" : "Thickness (m)"} o={selected} k="thickness" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { thickness: v })} />}374 {selected.kind === "roof" && <NumProp key={`${selected.id}:pitch:${String(selected.props.pitch ?? "")}`} label={fr ? "Pente (po/12)" : "Pitch (in/12)"} o={selected} k="pitch" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { pitch: v })} />}375 {selected.kind === "column" && <NumProp key={`${selected.id}:thickness:${String(selected.props.thickness ?? "")}`} label={fr ? "Côté (m)" : "Side (m)"} o={selected} k="thickness" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { thickness: v })} />}376 {selected.kind === "dimension" && <NumProp key={`${selected.id}:offset:${String(selected.props.offset ?? "")}`} label={fr ? "Décalage (px)" : "Offset (px)"} o={selected} k="offset" canWrite={canWrite} onChange={(v) => updateObject(selected.id, {}, { offset: v })} />}377 {(selected.kind === "text" || selected.kind === "annotation") && <label>{fr ? "Texte" : "Text"}<input value={selected.props.text ?? ""} disabled={!canWrite} onChange={(e) => setObjects((xs) => xs.map((x) => (x.id === sel ? { ...x, props: { ...x.props, text: e.target.value } } : x)))} onBlur={(e) => updateObject(selected.id, {}, { text: e.target.value })} /></label>}378 <label>{fr ? "Note" : "Note"}<input value={selected.props.note ?? ""} disabled={!canWrite} onChange={(e) => setObjects((xs) => xs.map((x) => (x.id === sel ? { ...x, props: { ...x.props, note: e.target.value } } : x)))} onBlur={(e) => updateObject(selected.id, {}, { note: e.target.value })} /></label>379 {mOf(selected.id).map((m) => <p key={m.id} className="vp-mono text-[10.5px] text-ink-2">{m.formulaText} = <b>{num(m.value, "fr", 3)} {m.unit}</b>{m.stale ? <span className="text-[var(--amber)]"> ⚠</span> : m.verifiedAt ? <span className="text-accent"> ✓</span> : null}</p>)}380 {canWrite && <div className="flex flex-wrap gap-1 pt-1"><Btn small tone="accent" disabled={!k || selected.kind === "dimension" || selected.kind === "text"} onClick={() => void measureOne(selected.id)}>{fr ? "Mesurer" : "Measure"}</Btn><Btn small onClick={() => addObject({ ...selected, id: uuid(), name: `${selected.name} (copie)`, points: selected.points.map((p) => ({ x: p.x + (k ?? 50) * 0.5, y: p.y + (k ?? 50) * 0.5 })) })}>{fr ? "Dupliquer" : "Duplicate"}</Btn><Btn small onClick={() => removeObject(selected.id)}>{fr ? "Supprimer" : "Delete"}</Btn></div>}381 </div>382 </>) : (<>383 <h3>{fr ? "Quantités du plan" : "Plan quantities"}</h3>384 <div className="sec text-[12px] space-y-1">385 {!k ? <p className="text-ink-3">{fr ? "Calibrez la page pour obtenir des quantités." : "Calibrate the page to get quantities."}</p> : (<>386 <div className="flex justify-between"><span>{fr ? "Murs extérieurs (net)" : "Exterior walls (net)"}</span><b>{fmtArea(q.totals.extWallNetAreaM2, imperial)}</b></div>387 <div className="flex justify-between"><span>{fr ? "Murs (longueur)" : "Walls (length)"}</span><b>{fmtLength(q.totals.wallLengthM, imperial)}</b></div>388 <div className="flex justify-between"><span>{fr ? "Surface des pièces" : "Rooms area"}</span><b>{fmtArea(q.totals.floorAreaM2, imperial)}</b></div>389 {q.footprintM2 != null && <div className="flex justify-between"><span>{fr ? "Empreinte" : "Footprint"}</span><b>{fmtArea(q.footprintM2, imperial)}</b></div>}390 <div className="flex justify-between"><span>{fr ? "Portes / fenêtres" : "Doors / windows"}</span><b>{q.totals.doors} / {q.totals.windows}</b></div>391 {q.rooms.map((r) => <div key={r.id} className="flex justify-between text-ink-2"><span>· {r.name}</span><span>{fmtArea(r.areaM2, imperial)}</span></div>)}392 </>)}393 </div>394 </>)}395 <h3>{fr ? "Objets" : "Objects"} ({objects.length})</h3>396 <div className="pl-list">{objects.map((o) => <button key={o.id} type="button" className={o.id === sel ? "sel" : ""} onClick={() => { setSel(o.id); setTool("select"); }}><span>{(fr ? KIND_FR[o.kind]?.[0] : KIND_FR[o.kind]?.[1]) ?? o.kind} · {o.name}</span><span className="vp-mono text-[10px] text-ink-3">{mOf(o.id).some((m) => m.verifiedAt) ? "✓" : mOf(o.id).length ? "•" : ""}</span></button>)}{!objects.length && <p className="px-3 py-2 text-[12px] text-ink-3">{fr ? "Dessinez des murs (W), posez des portes (D) et des fenêtres (N), nommez les pièces (R)." : "Draw walls (W), place doors (D) and windows (N), name rooms (R)."}</p>}</div>397 </aside>}398 </div>399 );400}401402function NumProp({ o, k, label, canWrite, onChange }: { o: PlanObject; k: keyof PlanObject["props"]; label: string; canWrite: boolean; onChange: (v: number | undefined) => void }) {403 const [v, setV] = useState(String(o.props[k] ?? ""));404 return <label>{label}<input type="number" step="0.01" value={v} disabled={!canWrite} onChange={(e) => setV(e.target.value)} onBlur={() => onChange(v === "" ? undefined : Number(v))} onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }} /></label>;405}406