Files
Aislo/resources/tester/helper_845_2_unit_show.cjs
T
eomsangdonandClaude Opus 5.5 c8cd98dec1 feat(846-2): 기계 줄 시간당 작업량 화면 — 산출근거 「시간당 작업량」 줄 먼저 · 비목 ÷ 시간당 작업량 · 제어 구역 일당 / 시간당 식 고르기 · 변수 칸 · 기계 보기 작업량 식
- 산출근거: 일당 「시간당 작업량 = 시공량 560 ㎥/일 ÷ (1 대 × 8 시간) = 70 ㎥/시간」 · 시간당 식 = q · K · f · E · cm 값 줄 + 한 층 분수 Q 식 · 비목 줄 「59,020 원/시간 ÷ 70 ㎥/시간 = 843.1 원」(금액 그대로)
- 제어 구역: 「시간당 작업량」 묶음 맨 위 — 방식 고르기(식 없는 기계 = 잠김 + 까닭) · 시간당 = 작업량 틀 변수 칸(고침 · 원래 값) · 덮음 = 기계덮음.<기계>.작업량
- 기계 보기: 왼쪽 작업량 카드(기계 정본 변수) · 오른쪽 풀이 · 서버가 작업량 틀 연결을 실음(M02_MyMachine_Sheet._work)
- 시험: test_846_2_work_view 새로 · test_845_2 GC000088 비목 줄 기대값을 새 꼴로 고침(846-2 표시 변경) · 헬퍼 가짜 DOM 이 진짜 DOM 처럼 요소를 옮김(같은 요소 두 줄 재사용 흠을 잡게)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:00:35 +09:00

343 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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 },
M02_DF_UnitPick: {
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 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) });
walk(ch);
}
};
walk(root);
return [...opts.buildOptions(doc, {}, true, noop).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 ((r.cls.includes("is-sub") ? sub : c.기계) && Math.max(0, ...texs.map(depth)) > 1) bad.push(["겹분수", r.t]);
// 머리 [결과 단위] = 문서 결과단위 글 그대로(자료 몫 — 「원(원문 단위 없음)」 등 설명 포함)
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.할일 === "단위") {
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));