diff --git a/A00_Common/line_stack_screen.ts b/A00_Common/line_stack_screen.ts index d37ca76ef..0fb1bbb6b 100644 --- a/A00_Common/line_stack_screen.ts +++ b/A00_Common/line_stack_screen.ts @@ -662,6 +662,8 @@ export function createStackScreen(opt: StackScreenOptions) { return { root, + /** 화면을 닫거나 다른 문서로 바꿀 때 — 창 크기 듣기 해제(안 부르면 열 때마다 하나씩 남음) */ + destroy: (): void => window.removeEventListener("resize", fit), /** 로직 · SK 키로 그림(빈 키 = 저장 전 새 것) — 같은 키는 그대로 · `force` = 다시 읽음(탭 바꿈) */ draw: (next: string, force = false): void => { if (force || next !== shown) loading = open(next); diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab.ts b/M01_MasterData/M01_MasterData_UI_LogicLab.ts index a406920eb..d15e0934e 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab.ts @@ -83,6 +83,8 @@ function loadDrafts(): Record { export interface LogicHandle { /** 밖(요소 화면)에서 이 키를 바로 엶 — 소요량·계수 표의 「쓰는 로직」 눌렀을 때. */ openKey: (key: string) => Promise; + /** 화면을 버릴 때 — 줄 쌓기 창 크기 듣기 해제 */ + destroy: () => void; } export async function mountM01LogicLab( @@ -512,5 +514,5 @@ export async function mountM01LogicLab( hideLoadingOverlay(); } setLogicOpener((key) => void openKeyOn(key)); - return { openKey: openKeyOn }; + return { openKey: openKeyOn, destroy: stack.destroy }; } diff --git a/M01_MasterData/M01_MasterData_UI_Page.ts b/M01_MasterData/M01_MasterData_UI_Page.ts index efe9b1c63..b25f37b62 100644 --- a/M01_MasterData/M01_MasterData_UI_Page.ts +++ b/M01_MasterData/M01_MasterData_UI_Page.ts @@ -32,6 +32,7 @@ import { fetchSessionUser } from "../A06_Login/A06_Login_Api_Fetch"; import { saveFiles, type FileInfo } from "./M01_MasterData_Api_Fetch"; import { discard, isStale, onDraftChange, payload, totalCount } from "./M01_MasterData_Draft"; import { buildHeadBar, buildHeadFilters } from "./M01_MasterData_UI_Head"; +import { setLogicApiPaths } from "./M01_MasterData_UI_Logic_Api"; import { renderRows } from "./M01_MasterData_UI_Rows"; import { renderMachines } from "./M01_MasterData_UI_Machine"; import { openMachineDetail } from "./M01_MasterData_UI_MachineDetail"; @@ -64,7 +65,12 @@ const MACHINE_BACK = "m01.machine.back"; const machineUrl = (target?: string): string => `#/${ROUTES.M01_MASTER_DATA}${target ? `?machine=${encodeURIComponent(target)}` : ""}`; +let lastLogic: LogicHandle | null = null; + export async function renderM01MasterData(root: HTMLElement): Promise { + lastLogic?.destroy(); // 지난 화면의 줄 쌓기 창 크기 듣기 해제 + lastLogic = null; + setLogicApiPaths(); // M02 단가산출이 바꿔 둔 상세 부품 길 → M01 기본 길로 const user = await fetchSessionUser().catch(() => null); if (user?.role !== "SYSTEM_ADMIN") { showToast(L("M01_AdminOnly"), "error"); @@ -300,6 +306,7 @@ function buildPage(): HTMLElement { void import("./M01_MasterData_UI_LogicLab").then(async (m) => { const pending = takePendingLogicKey(); logicHandle = await m.mountM01LogicLab(logicHost, side, pending ?? undefined); + lastLogic = logicHandle; }); }; diff --git a/M01_MasterData/M01_MasterData_UI_Parts.ts b/M01_MasterData/M01_MasterData_UI_Parts.ts index e6b864cc3..246e44db2 100644 --- a/M01_MasterData/M01_MasterData_UI_Parts.ts +++ b/M01_MasterData/M01_MasterData_UI_Parts.ts @@ -36,16 +36,22 @@ const T = { const tx = (k: keyof typeof T): string => T[k][currentLanguageIndex === 1 ? 1 : 0]; const KINDS = ["기계경비식", "작업량 틀", "계수식"] as const; +/** 읽기 창은 앱 하나 — 창 크기 듣기가 부품 칸을 그릴 때마다 늘지 않음 */ +let partsStack: ReturnType | null = null; + /** 표 아래 부품 칸 — 기계(상세구분 있음) · 계수만 · 그 밖 = 비움 */ export function renderParts(host: HTMLElement, pick: Pick, openLogic: (key: string) => void): void { host.replaceChildren(); const group = pick.group === "계수" ? "계수식" : pick.group === "기계" ? "기계" : ""; if (!group || (group === "기계" && !pick.detail)) return; - let stack: ReturnType | null = null; /** 줄 쌓기 읽기 창 — 고침 없음 · [단가산출 기초에서 열기] = 수식 탭에서 고침 */ const show = (p: Part): void => { - stack ??= createStackScreen({ base: "/m01/logic/doc", admin: false, cache: "m01_parts_view" }); - const view = stack; + partsStack ??= createStackScreen({ + base: "/m01/logic/doc", + admin: false, + cache: "m01_parts_view", + }); + const view = partsStack; openModal({ title: `${p.키} · ${p.이름}`, closeLabel: tx("Close"), diff --git a/M02_MasterTemplete/M02_Labor_Spec.py b/M02_MasterTemplete/M02_Labor_Spec.py index dcd7a8c0a..c7e800ab8 100644 --- a/M02_MasterTemplete/M02_Labor_Spec.py +++ b/M02_MasterTemplete/M02_Labor_Spec.py @@ -5,7 +5,7 @@ 규격 수량이 있는 줄 = 고른 열 값이 `{손}` 자리 · 없는 줄 · 빈 열 = 문서 `수량` 그대로(공통). 규격 없음 = 옛 문서(열 하나 · 셈 그대로 · 옮김 없음). 짝(CLAUDE.md 5장 ①): `at` ↔ `M02_MasterTemplete_Labor_Calc.ts` `atSpec` — -거울 시험 `resources/tester/test_m02_labor_calc_mirror.py`. +거울 시험 `resources/tester/test_m02_labor_calc_mirror.py`. 화면 짝 = `M02_MasterTemplete_Labor_Spec.ts`(규격 줄 · 열 펼침 · 같은 `규격` 칸 이름). 사본(`M02_Item_Source.build_source`) = 설계가 고른 열(summary_item `spec`)을 `{손}` 으로 굳히고 `규격` 은 그 열 하나만 남김(`freeze`). """ diff --git a/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts b/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts index 8dd2e7d24..0d78feee3 100644 --- a/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts +++ b/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Detail.ts @@ -490,6 +490,7 @@ export function mountSangeunDetail( destroy: () => { alive = false; if (tabs.dirty()) void tabs.discard(); // 페이지가 버리고 떠남 — 수식 캐시도 비움 + tabs.destroy(); host.replaceChildren(); }, }; diff --git a/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts b/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts index 75df34578..2e09f9c5e 100644 --- a/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts +++ b/M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts @@ -48,6 +48,8 @@ export function createSangeunTabs( dirty: () => boolean; save: () => Promise; discard: () => Promise; + /** 줄 쌓기 화면의 창 크기 듣기 해제 */ + destroy: () => void; } { const tools = el("span", { className: "m02-sk__tools", attrs: { "data-sk-tools": "" } }); // [단가 갱신] · [재생성](808-1) const stack = createStackScreen({ @@ -78,5 +80,6 @@ export function createSangeunTabs( dirty: () => stack.dirty(), save: () => stack.save(), discard: () => stack.discard(), + destroy: () => stack.destroy(), }; } diff --git a/M02_MasterTemplete/M02_MyMachine.py b/M02_MasterTemplete/M02_MyMachine.py index 33859078c..2ceab589c 100644 --- a/M02_MasterTemplete/M02_MyMachine.py +++ b/M02_MasterTemplete/M02_MyMachine.py @@ -43,6 +43,8 @@ COSTS = ("노무비", "재료비", "경비") RATIOS = ("내용시간", "연간표준가동시간", "상각비율", "정비비율", "연간관리비율") COEFS = ("상각비계수", "정비비계수", "관리비계수") NUMS = ("가격", *RATIOS, *COEFS, "손료계수", "주연료", "전력") +# 기계 칸 단위 — 짝(표 셋): `common_util_line_stack_unit.ts` MACHINE_UNIT · `build_기계_건설품셈.py` UNIT · +# 거울 시험 `resources/tester/test_854_3_machine_unit_mirror.py`(칸을 더하거나 글을 바꾸면 셋 모두) UNITS = { "가격": "천원", "내용시간": "시간", "연간표준가동시간": "시간", "상각비율": "", "정비비율": "", "연간관리비율": "", **{k: "10^-7/시간" for k in (*COEFS, "손료계수")}, "주연료": "ℓ/hr", diff --git a/M02_MasterTemplete/M02_MyMachine_Draft.py b/M02_MasterTemplete/M02_MyMachine_Draft.py index f289820e1..319c07d87 100644 --- a/M02_MasterTemplete/M02_MyMachine_Draft.py +++ b/M02_MasterTemplete/M02_MyMachine_Draft.py @@ -8,6 +8,7 @@ `TOUCH` = 사본 단가 줄을 새 값으로(`renew`) · 실패 = 만든 파일 지움 · 고친 줄 되돌림(번호표는 그대로). 사본 줄 보기(`copy_row`) = 그 SK 사본에 박힌 기계 줄 · 지금 줄 · 새 값 여부. 개인 층만(`mym._user` — 그 밖 404). +화면 짝 = `common_util/common_util_line_stack_draft.ts`(칸 이름 · 표지 꼴 「EQP초안-N」). """ from __future__ import annotations diff --git a/M02_MasterTemplete/M02_Share_Request.py b/M02_MasterTemplete/M02_Share_Request.py index 1d078f0c5..15f985b72 100644 --- a/M02_MasterTemplete/M02_Share_Request.py +++ b/M02_MasterTemplete/M02_Share_Request.py @@ -9,7 +9,7 @@ 그 회사 전부 · 일반은 자기 것 · 승인 · 거절 = 회사 층 쓰기(일반 403) · 다른 회사 장부는 안 봄(시스템 관리자만 `company`). 같은 항목(주인 · 종류 · 키)이 「요청」 상태면 다시 요청 = 409 「요청 중」. -⚠ 등록은 `main.py`(로그인만). +⚠ 등록은 `main.py`(로그인만). 화면 짝 = `M02_MasterTemplete_ShareRequest.ts`(장부 칸 이름). """ from __future__ import annotations diff --git a/common_util/common_util_line_stack_unit.ts b/common_util/common_util_line_stack_unit.ts index e2b070470..f05be2c55 100644 --- a/common_util/common_util_line_stack_unit.ts +++ b/common_util/common_util_line_stack_unit.ts @@ -14,7 +14,8 @@ import type { DocVar, MoneyLine, Node } from "./common_util_formula_doc"; import { evalNode, tryParse, type Values } from "./common_util_formula_doc_view"; -/** 기계 표 칸 단위(`build_기계_건설품셈.py` UNIT · `M02_MyMachine.py` UNITS · 845-1 문서 단위와 같은 글) */ +/** 기계 표 칸 단위(`build_기계_건설품셈.py` UNIT · `M02_MyMachine.py` UNITS · 845-1 문서 단위와 같은 글 · + * 거울 시험 `test_854_3_machine_unit_mirror.py` — 칸을 더하거나 글을 바꾸면 셋 모두 · 화면 표시용 ㎾h 만 다름) */ export const MACHINE_UNIT: Record = { 가격: "천원", 내용시간: "시간", diff --git a/resources/master_data/scripts/build_기계_건설품셈.py b/resources/master_data/scripts/build_기계_건설품셈.py index 94d2a926a..4d0de79b8 100644 --- a/resources/master_data/scripts/build_기계_건설품셈.py +++ b/resources/master_data/scripts/build_기계_건설품셈.py @@ -425,6 +425,8 @@ def load(): return t83, t84, t85 +# 기계 칸 단위 — 짝(표 셋): `common_util_line_stack_unit.ts` MACHINE_UNIT · `M02_MyMachine.py` UNITS · +# 거울 시험 `resources/tester/test_854_3_machine_unit_mirror.py`(칸을 더하거나 글을 바꾸면 셋 모두) UNIT = { "가격": "천원", "내용시간": "시간", diff --git a/resources/master_data/scripts/master_doc_link.py b/resources/master_data/scripts/master_doc_link.py index 6cc42b297..64d3d9b38 100644 --- a/resources/master_data/scripts/master_doc_link.py +++ b/resources/master_data/scripts/master_doc_link.py @@ -6,7 +6,7 @@ 마스터 색인(`Master`) · 요소 값(준용 · 자재 고르기 · 단위 환산 = `master_material` · `master_pick`)만 씀. 표 찾기(범위 규칙 · 여러 줄 가름)는 여기 -· TS 짝 = `common_util/common_util_formula_doc_calc.ts` `findRow`. +· TS 짝 = `common_util/common_util_formula_doc_table.ts` `findRow` · `cellArith`(거울 시험 test_802_1_formula_doc.py). 수식 문서 저장 자리 = `resources/master_data/수식문서/수식_<옛 로직 파일 꼬리>.json` (로직 파일마다 한 벌). """ diff --git a/resources/tester/helper_854_3_screen_leak.cjs b/resources/tester/helper_854_3_screen_leak.cjs new file mode 100644 index 000000000..40c071558 --- /dev/null +++ b/resources/tester/helper_854_3_screen_leak.cjs @@ -0,0 +1,115 @@ +/* 854-3 헬퍼 — 줄 쌓기 화면 열고 닫기를 되풀이해도 창 크기 듣기가 안 늘고 · M01 화면 들어올 때 상세 길이 M01 로 돌아옴 + * 가짜 DOM · 진짜 코드(line_stack_screen · Sangeun_Tabs · M01 Logic_Api · M01 Page) · 나머지 이웃 파일은 빈 부품 */ +const fs = require("fs"); +const path = require("path"); +const ROOT = path.resolve(__dirname, "..", ".."); +const ts = require(path.join(ROOT, "config", "node_modules", "typescript")); + +class Fake { + constructor(tag) { + this.tagName = String(tag).toUpperCase(); + this.children = []; + this.parentElement = null; + this.dataset = {}; + this.style = { setProperty() {} }; + this.offsetHeight = 0; + this.clientHeight = 0; + this.hidden = false; + } + append(...xs) { + for (const x of xs) if (x instanceof Fake) (x.parentElement = this), this.children.push(x); + } + replaceChildren(...xs) { + this.children = []; + this.append(...xs); + } + addEventListener() {} + setAttribute() {} +} + +let listeners = 0; // window 의 resize 듣기 수 +globalThis.window = globalThis; +globalThis.addEventListener = (type) => type === "resize" && listeners++; +globalThis.removeEventListener = (type) => type === "resize" && listeners--; +globalThis.getComputedStyle = () => ({ overflowY: "visible" }); +globalThis.innerHeight = 800; +globalThis.HTMLElement = Fake; +globalThis.document = { createElement: (t) => new Fake(t), body: new Fake("body") }; +globalThis.sessionStorage = { getItem: () => null, setItem() {}, removeItem() {} }; + +const empty = () => new Proxy(function () {}, { get: (_, k) => (k === "then" ? undefined : empty()), apply: () => undefined }); +const own = { + ui_template_elements: { showToast() {}, el: (tag, o = {}) => { const n = new Fake(tag); n.append(...(o.children ?? [])); return n; } }, +}; + +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(".")) return `${path.resolve(path.dirname(from), p)}.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) => { + const name = path.basename(p); + if (p.endsWith(".css")) return {}; + if (stubs[name]) return stubs[name]; + const r = resolve(at, p); + // 읽어 올 몸 = 진짜 · 그 밖 = 빈 부품 + return r && real.has(path.basename(r, ".ts")) ? load(r) : empty(); + }; + new Function("exports", "module", "require", js)(box.exports, box, need); + return box.exports; + } + return (rel) => load(path.join(ROOT, rel)); +} +const real = new Set([ + "line_stack_screen", + "M02_MasterTemplete_Sangeun_Tabs", + "M01_MasterData_UI_Logic_Api", + "M01_MasterData_UI_Page", +]); +const state = { user: null }; +const load = makeLoader({ + ...own, + A06_Login_Api_Fetch: { fetchSessionUser: async () => state.user }, +}); + +const out = { screen: [], tabs: [], page: {} }; + +// ① 줄 쌓기 화면 — 열고 닫기 다섯 번 +const { createStackScreen } = load("A00_Common/line_stack_screen.ts"); +const base = listeners; +for (let i = 0; i < 5; i++) { + const s = createStackScreen({ base: "/m01/logic/doc", admin: false, cache: "x" }); + out.screen.push(listeners - base); // 열린 동안 +1 + s.destroy(); + out.screen.push(listeners - base); +} + +// ② M02 단가산출 줄 쌓기 그릇 — 열고 닫기 다섯 번 +const { createSangeunTabs } = load("M02_MasterTemplete/M02_MasterTemplete_Sangeun_Tabs.ts"); +const b2 = listeners; +for (let i = 0; i < 5; i++) { + const t = createSangeunTabs(new Fake("div"), { edit: false, scope: { layer: "system", owner: null } }); + out.tabs.push(listeners - b2); + t.destroy(); + out.tabs.push(listeners - b2); +} + +// ③ M01 화면에 들어오면 상세 길이 M01 기본으로 +const api = load("M01_MasterData/M01_MasterData_UI_Logic_Api.ts"); +api.setLogicApiPaths({ read: "/m02/logic-lib", calc: "/m02/logic-lib" }); +out.page.before = api.logicApiPaths().read; +const { renderM01MasterData } = load("M01_MasterData/M01_MasterData_UI_Page.ts"); +renderM01MasterData(new Fake("div")).then(() => { + out.page.after = api.logicApiPaths().read; + console.log(JSON.stringify(out)); +}); diff --git a/resources/tester/test_854_3_machine_unit_mirror.py b/resources/tester/test_854_3_machine_unit_mirror.py new file mode 100644 index 000000000..23a0fd4d1 --- /dev/null +++ b/resources/tester/test_854_3_machine_unit_mirror.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +"""PLAN 854-3 — 기계 칸 단위 표 셋 거울: 화면(`common_util_line_stack_unit.ts` MACHINE_UNIT) · +내 기계(`M02_MyMachine.UNITS`) · 기계 표 빌더(`build_기계_건설품셈.UNIT`). + +같은 칸 이름은 단위가 같음 — 화면 표시용 글자 바꿈(kWh → ㎾h)만 규칙으로 봄 · +빌더의 「주연료의 %」 는 설명 붙은 % 라 % 로 봄. +세 표 어디에도 없는 TS 칸은 시간당 금액 칸(노무비 · 재료비 · 경비)뿐. +""" + +from __future__ import annotations + +import importlib +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "resources" / "master_data" / "scripts")) + +from M02_MasterTemplete import M02_MyMachine as my # noqa: E402 + +build = importlib.import_module("build_기계_건설품셈") + +MONEY_ONLY_TS = {"노무비", "재료비", "경비"} + + +def _ts_table() -> dict[str, str]: + src = (ROOT / "common_util" / "common_util_line_stack_unit.ts").read_text(encoding="utf-8") + body = re.search(r"MACHINE_UNIT: Record = \{(.*?)\n\};", src, re.S) + assert body, "MACHINE_UNIT 표를 못 찾음" + return dict(re.findall(r'^\s*([^\s:]+): "([^"]*)",?$', body.group(1), re.M)) + + +def _screen(unit: str) -> str: # 화면 표시용 글자 바꿈 — 파이썬 글 → 화면 글 + return unit.replace("kWh", "㎾h").replace("주연료의 %", "%") + + +def test_machine_unit_tables_mirror() -> None: + ts = _ts_table() + assert len(ts) == 16 + py = {"내 기계": my.UNITS, "빌더": build.UNIT} + for name, table in py.items(): + for col, unit in table.items(): + if not unit: # 무차원 = 화면 표 밖 + continue + assert col in ts, f"{name} 칸 「{col}」 이 화면 표에 없음" + assert ts[col] == _screen(unit), f"{name} 「{col}」 단위 {unit!r} ≠ 화면 {ts[col]!r}" + for col in ts: + assert col in MONEY_ONLY_TS or any(col in t for t in py.values()), ( + f"화면 칸 「{col}」 짝 없음" + ) diff --git a/resources/tester/test_854_3_screen_leak.py b/resources/tester/test_854_3_screen_leak.py new file mode 100644 index 000000000..a07c85045 --- /dev/null +++ b/resources/tester/test_854_3_screen_leak.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +"""PLAN 854-3 — 줄 쌓기 창 크기 듣기 해제 · M01 상세 길 되돌림(가짜 DOM · 진짜 코드). + +① 줄 쌓기 화면 · M02 단가산출 그릇 = 열고 닫기를 다섯 번 되풀이해도 열린 동안 하나 · 닫으면 0 +② M02 가 상세 길을 M02 로 바꿔 둔 뒤 M01 화면에 들어오면 M01 기본 길(`/m01`) +""" + +from __future__ import annotations + +import json +import os +import subprocess + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def _run() -> dict: + proc = subprocess.run( + ["node", os.path.join(HERE, "helper_854_3_screen_leak.cjs")], + capture_output=True, + text=True, + encoding="utf-8", + ) + assert proc.returncode == 0, proc.stderr[-3000:] + return json.loads(proc.stdout) + + +def test_listeners_do_not_grow_and_m01_path_returns() -> None: + got = _run() + assert got["screen"] == [1, 0] * 5 + assert got["tabs"] == [1, 0] * 5 + + +def test_m01_entry_resets_logic_api_paths() -> None: + # M02 단가산출이 상세 길을 M02 로 바꿔 둔 뒤 M01 화면에 들어오면 M01 기본 길 + assert _run()["page"] == {"before": "/m02/logic-lib", "after": "/m01"}