/* 845-2 단위 표시 지킴 헬퍼 — 산출근거(buildOut) · 왼쪽 편집(buildEdit)을 가짜 DOM 으로 차려 줄 글을 냄(화면 없음 · 진짜 코드) */ const fs = require("fs"); const path = require("path"); const ROOT = path.resolve(__dirname, "..", ".."); const ts = require(path.join(ROOT, "config", "node_modules", "typescript")); class FakeNode { constructor(tag) { this.tagName = String(tag).toUpperCase(); this.childNodes = []; this.attributes = {}; this.dataset = {}; this.style = { setProperty: (k, v) => (this.style[k] = v) }; this.className = ""; const self = this; this.classList = { add: (...c) => c.forEach((x) => !self.cls().includes(x) && (self.className = `${self.className} ${x}`.trim())), remove: (...c) => (self.className = self.cls().filter((x) => !c.includes(x)).join(" ")), toggle: (c, on) => { const has = self.cls().includes(c); const want = on === undefined ? !has : !!on; if (want && !has) self.classList.add(c); if (!want && has) self.classList.remove(c); return want; }, contains: (c) => self.cls().includes(c), }; } cls() { return String(this.className || "").split(/\s+/).filter(Boolean); } get children() { return this.childNodes.filter((x) => x instanceof FakeNode); } get firstElementChild() { return this.children[0] ?? null; } get firstChild() { return this.childNodes[0] ?? null; } append(...xs) { for (const x of xs) { if (x === null || x === undefined) continue; // 진짜 DOM 처럼 — 이미 다른 곳에 붙은 요소는 옮김(같은 요소를 두 줄에 쓰면 앞 줄에서 빠짐) if (x instanceof FakeNode && x.parentNode) x.parentNode.childNodes = x.parentNode.childNodes.filter((c) => c !== x); if (x instanceof FakeNode) x.parentNode = this; this.childNodes.push(x instanceof FakeNode ? x : new FakeText(String(x))); } } appendChild(x) { this.append(x); return x; } prepend(...xs) { const keep = this.childNodes; this.childNodes = []; this.append(...xs); this.childNodes.push(...keep); } insertBefore(x) { this.prepend(x); return x; } replaceChildren(...xs) { this.childNodes = []; this.append(...xs); } remove() {} set textContent(t) { this.childNodes = t === "" || t === null || t === undefined ? [] : [new FakeText(String(t))]; } get textContent() { return this.childNodes.map((c) => c.textContent).join(""); } set innerHTML(t) { this.textContent = String(t).replace(/<[^>]*>/g, ""); } get innerHTML() { return this.textContent; } setAttribute(k, v) { this.attributes[k] = String(v); } getAttribute(k) { return this.attributes[k] ?? null; } removeAttribute(k) { delete this.attributes[k]; } hasAttribute(k) { return k in this.attributes; } addEventListener() {} removeEventListener() {} dispatchEvent() { return true; } focus() {} blur() {} click() {} closest() { return null; } contains() { return false; } getBoundingClientRect() { return { x: 0, y: 0, width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0 }; } querySelector(s) { return this.querySelectorAll(s)[0] ?? null; } querySelectorAll(s) { const m = /^\.([\w-]+)$/.exec(s); const tag = /^[a-z]+$/i.test(s) ? s.toUpperCase() : null; const out = []; const walk = (n) => { for (const c of n.children) { if ((m && c.cls().includes(m[1])) || (tag && c.tagName === tag)) out.push(c); walk(c); } }; walk(this); return out; } cloneNode() { return new FakeNode(this.tagName); } } class FakeText { constructor(t) { this.textContent = t; } } function install() { globalThis.Node = FakeNode; globalThis.HTMLElement = FakeNode; globalThis.Element = FakeNode; globalThis.document = { createElement: (t) => new FakeNode(t), createElementNS: (_, t) => new FakeNode(t), createTextNode: (t) => new FakeText(t), createDocumentFragment: () => new FakeNode("fragment"), body: new FakeNode("body"), documentElement: new FakeNode("html"), addEventListener() {}, removeEventListener() {}, querySelector: () => null, querySelectorAll: () => [], }; globalThis.window = globalThis; globalThis.localStorage = { getItem: () => null, setItem() {}, removeItem() {} }; globalThis.sessionStorage = globalThis.localStorage; globalThis.requestAnimationFrame = (f) => setTimeout(f, 0); globalThis.matchMedia = () => ({ matches: false, addEventListener() {} }); globalThis.getComputedStyle = () => ({ getPropertyValue: () => "" }); globalThis.fetch = () => Promise.reject(new Error("no fetch")); globalThis.navigator ??= { language: "ko" }; } /** 모듈 로더 — stubs[이름 끝] 가 있으면 그것 · css = 빈 것 · @ui/@config 길 */ function makeLoader(stubs = {}) { const cache = new Map(); const resolve = (from, p) => { if (p.startsWith("@ui/")) return path.join(ROOT, "ui_template", `${p.slice(4)}.ts`); if (p.startsWith("@config/")) return path.join(ROOT, "config", `${p.slice(8)}.ts`); if (p.startsWith(".")) { const at = path.resolve(path.dirname(from), p); return at.endsWith(".css") ? at : `${at}.ts`; } return null; }; function load(at) { if (cache.has(at)) return cache.get(at); const js = ts.transpileModule(fs.readFileSync(at, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, }).outputText; const box = { exports: {} }; cache.set(at, box.exports); const need = (p) => { if (p.endsWith(".css")) return {}; const name = path.basename(p); if (stubs[name]) return stubs[name]; const r = resolve(at, p); if (!r) { if (stubs[p]) return stubs[p]; return require(p); } return load(r); }; new Function("exports", "module", "require", js)(box.exports, box, need); return box.exports; } return (rel) => load(path.join(ROOT, rel)); } /** 요소 → 읽는 글(조판 = ⟦TeX⟧ · 입력 칸 = [값] · 단위 꼬리 = {단위}) */ function textOf(n) { if (n === null || n === undefined) return ""; if (n instanceof FakeText) return n.textContent; if (typeof n === "string") return n; if (n.tex !== undefined) return `⟦${n.tex}⟧`; if (n.tagName === "INPUT") return `[${n.value ?? ""}]`; if (n.tagName === "SELECT") return `[${n.value ?? ""}▾]`; return n.childNodes.map(textOf).join(""); } // ── 할일 ── stdin = {할일, 문서들 [{키, 문서, 연결}], 보기: [키]} · stdout = 할일 답 install(); const noop = () => undefined; const load = makeLoader({ katex: { render: (t, box) => (box.tex = t) }, formula_doc_options: { machineText: () => null, optionText: (x) => x, liveOptions: (l) => l, nameMachines: noop }, ui_template_unit_pick: { NO_UNIT: "(단위 없음)", createUnitPick: (o) => Object.assign(new FakeNode("select"), { value: o.value }), }, M02_DF_Api: { cfMachineNames: async () => ({}), cfMachineOff: async () => [] }, M02_MyMachine_Text: { mt: (k) => k }, M02_MasterTemplete_Find_Pick: { openFindPicker: noop }, line_stack_pick: { openStackPick: noop, openTablePick: noop }, line_stack_machine: { openMachineWindow: noop }, line_stack_material: { materialMark: () => null, matEntry: () => null, askFileWide: async () => undefined }, line_stack_drag: { attachDrag: noop }, }); const out = load("A00_Common/line_stack_out.ts"); const edit = load("A00_Common/line_stack_edit.ts"); const opts = load("A00_Common/formula_doc_options.ts"); const render = load("A00_Common/formula_doc_render.ts"); const mwork = load("A00_Common/line_stack_machine_work.ts"); const ls = load("common_util/common_util_line_stack.ts"); const unit = load("common_util/common_util_line_stack_unit.ts"); const cacheMod = load("common_util/common_util_formula_doc_cache.ts"); const calc = load("common_util/common_util_formula_doc_calc.ts"); const all = { has: () => true, add: noop, delete: noop }; /** \dfrac 겹 층 */ function depth(s) { const group = (i) => { let d = 0; for (let k = i; k < s.length; k++) { if (s[k] === "{") d++; else if (s[k] === "}" && --d === 0) return k; } return s.length - 1; }; let best = 0; let i = 0; while ((i = s.indexOf("\\dfrac{", i)) >= 0) { const a1 = group(i + 6); const b1 = group(a1 + 1); best = Math.max(best, 1 + Math.max(depth(s.slice(i + 7, a1)), depth(s.slice(a1 + 2, b1)))); i = b1 + 1; } return best; } function right(c) { const cache = cacheMod.createDocCache(); cache.merge(c.연결 || {}); const a = calc.calcDoc(c.문서, cache.links, {}); const root = out.buildOut(c.문서, a, { cache, open: all, toggle: noop, miss: noop, redraw: noop }); return root .querySelectorAll("tr") .filter((tr) => tr.cls().includes("lstk-orow")) .map((tr) => ({ cls: tr.cls().join(" "), t: textOf(tr.children[0]) })); } function left(c) { const cache = cacheMod.createDocCache(); cache.merge(c.연결 || {}); const doc = c.문서; const a = calc.calcDoc(doc, cache.links, {}); const sub = (k) => { try { return cache.links.doc(k) ?? null; } catch { return null; } }; const root = edit.buildEdit({ doc, answer: a, items: ls.stackOf(doc), change: noop, table: async () => null, subDoc: sub, name: () => "", open: new Set((doc.금액 || []).map((_, i) => `mctl:${i}`)), pair: noop, machine: { scope: "x" }, calc: (d, g) => calc.calcDoc(d, cache.links, g, [], new Map(), {}), lists: () => null, look: (p) => cache.links.table(p), }); // prettier-ignore const rows = []; const walk = (n) => { for (const ch of n.children) { if (ch.cls().includes("lstk-frow") || ch.cls().includes("lstk-work")) rows.push({ sym: ch.dataset.sym ?? ch.dataset.mctlField ?? "", t: textOf(ch) }); if ("workQty" in ch.dataset) rows.push({ sym: "수량", t: textOf(ch), 잠김: ch.querySelector("input")?.disabled === true }); // 847-1 walk(ch); } }; walk(root); const hide = render.hiddenByWork(doc, a); // 847-1 화면과 같음(line_stack_screen) return [...opts.buildOptions(doc, {}, true, noop, undefined, hide).map((x) => ({ sym: `opt:${x.dataset.option}`, t: textOf(x) })), ...rows]; } /** 셈 답 요약(846-2 — 계 · 줄마다 작업량 · 금액) */ function sums(c) { const cache = cacheMod.createDocCache(); cache.merge(c.연결 || {}); const a = calc.calcDoc(c.문서, cache.links, {}); return { 계: a.계 ?? null, 줄: (a.줄 || []).map((r) => ({ 금액: r.금액 ?? null, 작업량: r.작업량 ?? null })) }; } /** 전수 지킴 — 줄 글에서 규칙 어긋남만 */ const MONEY = /^(.+?) : (?!—)(.*\S)$/; function guard(c, machine) { const before = JSON.stringify(c.문서); const rows = right(c); const bad = []; let sub = false; for (const r of rows) { if (r.cls.includes("subhead")) sub = machine.has(r.t.replace(/ \[[^\]]*\]$/, "")); const texs = [...r.t.matchAll(/⟦([^⟧]*)⟧/g)].map((m) => m[1]); if ((c.밖 || (r.cls.includes("is-sub") ? sub : c.기계)) && Math.max(0, ...texs.map(depth)) > 1) bad.push(["겹분수", r.t]); // 847-1 밖 = 기계 밖 문서도 // 머리 [결과 단위] = 문서 결과단위 글 그대로(자료 몫 — 「원(원문 단위 없음)」 등 설명 포함) if (!/head/.test(r.cls) && /따름|원문 단위 없음|수\(단위/.test(r.t)) bad.push(["메타 단위", r.t]); const m = MONEY.exec(r.t); if (m && !/^\d+\. /.test(r.t) && !/(원|원\/\S+)$/.test(m[2]) && /\d$/.test(m[2])) bad.push(["금액 원 없음", r.t]); const q = / × ⟦([^⟧]*)⟧ (\S+) = /.exec(r.t); if (q && /\\times|\\div|\+/.test(q[1]) && !q[1].startsWith("\\left(")) bad.push(["수량 식 괄호 없음", r.t]); } return { bad, 같음: JSON.stringify(c.문서) === before }; } const input = JSON.parse(fs.readFileSync(0, "utf8")); const show = new Set(input.보기 || []); const machineNames = new Set(input.기계이름 || []); let res; if (input.할일 === "전수") { res = input.문서들.map((c) => { const g = guard(c, machineNames); return { 키: c.키, ...g, ...(show.has(c.키) ? { 오른쪽: right(c), 왼쪽: left(c), 셈: sums(c) } : {}) }; }); } else if (input.할일 === "숨김") { // 847-1 — 숨긴 기호 · 덮음 고침(putWork) · 기계 바꿈(swapMachine) res = { 숨김: input.문서들.map((c) => { const cache = cacheMod.createDocCache(); cache.merge(c.연결 || {}); return [...render.hiddenByWork(c.문서, calc.calcDoc(c.문서, cache.links, {}))].sort(); }), 덮음: (input.덮음 || []).map(([doc, key, w]) => (mwork.putWork(doc, key, w), doc)), 바꿈: (input.바꿈 || []).map(([w, info, p, same, old]) => mwork.swapMachine(w, info, p, same, old)), }; } else if (input.할일 === "단위") { res = { 글: input.글.map((u) => unit.unitText(u)), 변수: input.변수.map((v) => unit.varUnit(v)), 금액: input.금액.map(([line, price, qty, v, s]) => unit.moneyUnits(line, price, qty, v, s)), }; } process.stdout.write(JSON.stringify(res));