/* ============================================================================= * line_stack_diff.ts * 바뀐 자리 표시 2 단계(PLAN 848-8 · 요구 889) — 줄 쌓기 왼쪽 · 옵션 가로를 다 그린 뒤 한 번 훑어 칸마다 「바뀜」 상태를 닮 * 지도 = `common_util_line_stack_diff.docDiff`(지금 문서 대 서버 `층바탕.위` · 그 위 `층바탕.빌더`) * 칸 = 옵션 가로 · 공식 묶음 값 · 식 글 · 표 값 · 단위 · 금액 줄 이름(자원) · 이름 · 단가 식 · 수량 · 단위 · 비목 · 그룹 이름 · 글 줄 * 테두리 = 부품 `setUiDiff`(나 = 파랑 굵은 선 · 위 = 표시 없음) · 풍선 = 「원래 값 …」(위 = 「기초 고치기 전 …」) · * 칸 되돌림 = 칸 옆 작은 [↶](나 · 되돌릴 값 있을 때) · 줄 되돌림 = 줄 끝 [↶] · 더한 줄 · 차례 바뀐 줄 = 줄 틀(손잡이 쪽 선) · * 빠진 줄 = 그룹 머리 [되살림 n](테두리 상태 단추) · 고침 = 부른 쪽 `change`(캐시 · [저장] 때 서버가 다시 셈) * `edit` 없음(읽기 계정 · 저장 전 문서) = 테두리 · 풍선만 * ========================================================================== */ import { createButton, createIconButton, setUiDiff } from "@ui/ui_template_button"; import { eqText } from "@ui/ui_template_equation"; import { el } from "@ui/ui_template_elements"; import { varId, type DocVar } from "../common_util/common_util_formula_doc"; import { docDiff, LINE_FIELDS, resetPath, restoreLines, type DiffMark, } from "../common_util/common_util_line_stack_diff"; import { ownedOf, type StackDoc, type StackItem } from "../common_util/common_util_line_stack"; import { machineText } from "./formula_doc_options"; import { lt } from "./line_stack_text"; export interface DiffHooks { head: HTMLElement; left: HTMLElement; doc: StackDoc; items: StackItem[]; /** 위 층 문서 · 그 위(빌더 — 기초 손고침 · SK 만) */ up: StackDoc; top?: StackDoc | null; edit: boolean; change: (fn: (d: StackDoc, items: StackItem[]) => void) => void; name: (key: string) => string; } /** 되돌릴 값 글 — 식 › 값 › 표 칸 › 자원 이름 */ function say(h: DiffHooks, was: unknown): string { if (was === undefined || was === null || was === "") return "—"; if (typeof was !== "object") return machineText(was, () => undefined) ?? eqText(was as never); const w = was as { 식?: string; 연결?: DocVar["연결"]; 이름?: string; 규격?: string }; if ("규격" in w || ("이름" in w && !("연결" in w) && !("식" in w))) return `${w.이름 ?? ""} ${w.규격 ?? ""}`.trim() || "—"; if (w.식) return w.식; const l = w.연결; if (l?.값 !== undefined && l.값 !== null) return say(h, l.값); if (l?.표) return [lt("Tbl"), ...Object.values(l.조건 ?? {}), l.칸].filter(Boolean).join(" · "); if (l?.키) return w.이름 || h.name(l.키) || l.키; return w.이름 || "—"; } export function applyDiff(h: DiffHooks): void { const g = docDiff(h.doc, h.up, h.top); const tip = (m: DiffMark): string => `${lt(m.diff === "mine" ? "Ctl_Was" : "Diff_Upper_Was")} ${say(h, m.was)}`; /** 칸 묶음 → 가장 센 표시(나 › 위) */ const pick = (paths: string[]): [string, DiffMark][] => paths.flatMap((p) => (g.marks.get(p) ? [[p, g.marks.get(p)!] as [string, DiffMark]] : [])); const top = (got: [string, DiffMark][]): DiffMark | undefined => got.find(([, m]) => m.diff === "mine")?.[1] ?? got[0]?.[1]; const back = (got: [string, DiffMark][], title: string): HTMLElement | null => { const mine = got.filter(([, m]) => m.diff === "mine" && m.back); if (!h.edit || !mine.length) return null; const b = createIconButton({ icon: "undo", title, size: 24, onClick: () => h.change((d, items) => mine.forEach(([p, m]) => resetPath(d, items, p, m.was))), // prettier-ignore }); b.dataset.diffBack = mine.map(([p]) => p).join(" "); return b; }; /** 칸(입력 · 고르기 · 단추)에 테두리 · 풍선 · 곁에 [↶] */ const mark = (node: Element | null, paths: string[], after: Element | null = node): void => { if (!(node instanceof HTMLElement)) return; const got = pick(paths); const m = top(got); const field = node.matches(".ui-input, .ui-select, .ui-btn, .lstk-expr") ? node : (node.querySelector(".ui-input, .ui-select, .ui-btn") ?? node); setUiDiff(field, m?.diff === "mine" ? "mine" : null); // 위 = 테두리 없음(풍선만 · 892) if (!m) return; field.title = `${field.title ? `${field.title} — ` : ""}${tip(m)}`; const b = back(got, `${tip(m)} — ${lt("Diff_Back")}`); if (b && after) after.insertAdjacentElement("afterend", b); }; // ── 옵션 가로 ── const byKey = new Map((h.doc.변수 ?? []).map((v) => [v.열쇠, varId(v)])); h.head.querySelectorAll("[data-option]").forEach((f) => { const id = byKey.get(f.dataset.option); if (!id) return; mark(f, [`v:${id}`]); const b = f.nextElementSibling; if (b instanceof HTMLElement && b.dataset.diffBack) { const pair = el("span", { className: "lstk-dpair" }); // 칸 + [↶] 한 칸(옵션 가로 칸 폭) f.replaceWith(pair); pair.append(f, b); } }); // ── 공식 묶음(값 · 식 글 · 표 값 · 고침 칸) ── h.left.querySelectorAll(".lstk-frow[data-sym]").forEach((row) => { const id = row.dataset.sym!; if (row.classList.contains("is-open")) { const [, expr, unit] = row.querySelectorAll(":scope > .ui-field"); mark(expr ?? null, [`v:${id}`]); mark(unit ?? null, [`u:${id}`]); return; } const at = [ row.querySelector(":scope > .ui-field"), row.querySelector(":scope > .lstk-expr"), row.querySelector(`[data-table-pick]`), ].filter(Boolean) as Element[]; at.forEach((x, k) => mark(x, [`v:${id}`], k === at.length - 1 ? x : null)); }); // ── 금액 줄 · 글 줄 ── const owned = ownedOf(h.doc); h.left.querySelectorAll(".lstk-line[data-loc]").forEach((card) => { const [k, j] = card.dataset.loc!.split(".").map(Number); const line = h.items[k]?.줄[j]; if (line?.꼴 === "글") return mark(card.querySelector(".ui-field"), [`g:${k}.${j}`]); if (line?.꼴 !== "금액") return; const i = line.i; const own = owned.get(i); const qty = String(h.doc.금액?.[i]?.수량 ?? ""); const by = (label: string): Element | null => card.querySelector(`:scope > .ui-field [aria-label="${CSS.escape(label)}"]`)?.closest(".ui-field") ?? null; // prettier-ignore const qs = (q: string): Element | null => card.querySelector(`:scope > ${q}`); const sym = h.doc.변수?.some((v) => varId(v) === qty) ? [`v:${qty}`] : []; mark(qs("[data-repick]"), [...(own ? [`v:${own}`] : []), `m:${i}:이름`]); mark(by(lt("Name")), [`m:${i}:이름`]); mark(by(lt("Price")), [`m:${i}:단가`]); mark(qs(".lstk-qty > [data-qty]"), [`m:${i}:수량`, ...sym], qs(".lstk-qty")); mark(qs(".lstk-upick .ui-btn"), [`m:${i}:단위`], qs(".lstk-upick")); mark(qs(".ui-field select"), [`m:${i}:비목`]); setUiDiff(card, g.lines.get(i) === "mine" ? "mine" : null); const all = pick([...LINE_FIELDS.map((f) => `m:${i}:${f}`), ...(own ? [`v:${own}`] : [])]); const fields = new Set(all.filter(([, m]) => m.diff === "mine" && m.back).map(([p]) => (p === `v:${own}` ? `m:${i}:이름` : p))); // prettier-ignore const lb = fields.size > 1 ? back(all, lt("Diff_Line_Back")) : null; // 칸 둘 넘게 고친 줄 if (lb) { lb.dataset.diffLine = String(i); card.querySelector(":scope > .lstk-x")?.insertAdjacentElement("beforebegin", lb); } }); // ── 그룹 머리 — 이름 · 빠진 줄 되살림 ── h.left.querySelectorAll(".lstk-item[data-loc]").forEach((box) => { const k = Number(box.dataset.loc); const head = box.querySelector(":scope > .lstk-ihead"); if (!head) return; mark(head.querySelector(":scope > .ui-field"), [`t:${k}`]); const gone = g.gone.get(k); if (!gone) return; const what = gone.at.map((b) => String(gone.src.금액?.[b]?.이름 ?? "—")).join(" · "); const b = createButton({ label: `${lt("Diff_Gone")} ${gone.at.length}`, variant: "ghost", size: 24, iconStart: "undo", disabled: !h.edit, onClick: () => h.change((d, items) => restoreLines(d, items, gone.src, gone.at, k)), }); setUiDiff(b, gone.diff === "mine" ? "mine" : null); b.title = `${lt(gone.diff === "mine" ? "Diff_Gone_Tip" : "Diff_Gone_Up")} — ${what}`; b.dataset.diffGone = String(k); head.querySelector(":scope > .ui-row-menu")?.insertAdjacentElement("beforebegin", b); }); }