Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PSXsvyDxjNmufteN5bqmt
300 lines
11 KiB
TypeScript
300 lines
11 KiB
TypeScript
/* =============================================================================
|
|
* M01_SL_Entry.ts
|
|
* 시트 로직(시험) — 들어가는 단추 · 큰 창 · 시작 화면(내 시트 로직 · 새로 · 기존 로직 가져오기) · 잇기
|
|
* 모양은 `docs/raw/M01_쉬운단가/시트로직_정함.md` · 이 폴더째 지워도 됨(폴더 밖 참조는 LogicLab.ts 두 줄 + 서버 등록 한 줄).
|
|
* 고치는 화면은 M01_SL_Entry_Paper.ts · SheetLogic 의 다른 파일은 창을 열 때 import() 로 늦게 불러옴.
|
|
* 열기 = slGet → 바깥 값(slOutside → applyOutside) → 고치는 화면 · 가져오기 = 기존 로직 줄 + 품셈 표 → importLogicReport.
|
|
* ========================================================================== */
|
|
|
|
import { currentLanguageIndex } from "@ui/ui_template_locale";
|
|
import {
|
|
createButton,
|
|
createInputField,
|
|
el,
|
|
showConfirmDialog,
|
|
showToast,
|
|
} from "@ui/ui_template_elements";
|
|
import { openModal } from "@ui/ui_template_modal";
|
|
import { listEasy, openEasy, plainError, type EasyListItem } from "../EasyCalc/M01_EasyCalc_Api";
|
|
import type { SlListItem } from "./M01_SL_Api";
|
|
import type { SheetLogic } from "./M01_SL_Model";
|
|
import type { SlImportTable } from "./M01_SL_Import";
|
|
import { fillOutside, loadMods, showPaper, type Mods } from "./M01_SL_Entry_Paper";
|
|
import "./M01_SL_Entry.css";
|
|
|
|
const TEXT = {
|
|
Open: ["시트 로직(시험)", "Sheet logic (trial)"],
|
|
Title: ["시트 로직", "Sheet logic"],
|
|
CloseWindow: ["창 닫기", "Close window"],
|
|
Loading: ["불러오는 중", "Loading"],
|
|
LoadFailed: ["목록을 못 불러옴 — {v}", "Could not load the list — {v}"],
|
|
OpenFailed: ["열지 못함 — {v}", "Could not open — {v}"],
|
|
Trial: ["시험판 — 임시 폴더에 저장", "Trial — saved in a temporary folder"],
|
|
Start_Mine: ["내 시트 로직", "My sheet logics"],
|
|
Start_MineNone: ["아직 없음", "None yet"],
|
|
Start_New: ["새로 만들기(빈 판)", "New (blank)"],
|
|
Start_Import: ["기존 로직 가져오기", "Import an existing logic"],
|
|
Start_Trial: ["먼저 볼 시험 로직", "Trial logics to start with"],
|
|
Start_Search: ["이름으로 찾기 — 예: 돌쌓기", "Search by name — e.g. stone wall"],
|
|
Start_Count: ["{n} 개 중 {m} 개 보임 — 더 좁혀 찾기", "Showing {m} of {n} — narrow the search"],
|
|
Start_None: ["찾은 것 없음", "Nothing found"],
|
|
Per: ["{u} 당", "per {u}"],
|
|
Outside: ["바깥 값을 못 받음 — {v}", "Couldn't get outside values — {v}"],
|
|
Leave_Ask: [
|
|
"저장 안 한 것이 있음 — 저장하지 않고 닫을까요?",
|
|
"There are unsaved changes — close without saving?",
|
|
],
|
|
Leave_Ok: ["저장 안 하고 닫기", "Close without saving"],
|
|
} as const;
|
|
|
|
type TextKey = keyof typeof TEXT;
|
|
|
|
const te = (key: TextKey, vars: Record<string, string | number> = {}): string =>
|
|
Object.entries(vars).reduce(
|
|
(text, [k, v]) => text.replace(`{${k}}`, String(v)),
|
|
(TEXT[key][currentLanguageIndex as 0 | 1] ?? TEXT[key][0]) as string,
|
|
);
|
|
|
|
/** 「기존 로직 가져오기」 에 먼저 보이는 시험 로직 여섯(정함 9) */
|
|
const TRIAL_KEYS = ["GF000208", "GF000219", "GF000025", "GF000249", "GF000133", "GC000051"];
|
|
/** 찾은 것 목록에 한 번에 보이는 줄 수 */
|
|
const SHOWN = 50;
|
|
|
|
/** 「원/㎡」 → 「1㎡」 · 「100㎡」 은 앞에 1 을 안 붙임 */
|
|
const amountOf = (resultUnit: string): string => {
|
|
const unit = resultUnit.replace(/^원\//, "");
|
|
return /^\d/.test(unit) ? unit : `1${unit}`;
|
|
};
|
|
const isMoney = (resultUnit: string): boolean => resultUnit.startsWith("원/");
|
|
const muted = (text: string): HTMLElement => el("p", { className: "m01-sl__muted", text });
|
|
|
|
/** 「로직 만들기(시험)」 옆에 놓는 단추 — 누르면 큰 창 */
|
|
export function createSheetLogicButton(): HTMLButtonElement {
|
|
return createButton({ label: te("Open"), variant: "filled", onClick: openSheetLogic });
|
|
}
|
|
|
|
function openSheetLogic(): void {
|
|
let body: HTMLElement;
|
|
/** 고치는 화면이 열려 있을 때만 */
|
|
let paper: ReturnType<typeof showPaper> | null = null;
|
|
let logics: EasyListItem[] | null = null;
|
|
let query = "";
|
|
const mods = loadMods();
|
|
|
|
const mayLeave = async (): Promise<boolean> =>
|
|
!paper?.dirty() || showConfirmDialog(te("Leave_Ask"), te("Leave_Ok"));
|
|
|
|
/** Ctrl+Z · Ctrl+S — 이 창 안에서만(시트 편집기가 먼저 먹은 키는 그쪽 몫) */
|
|
const onKey = (ev: KeyboardEvent): void => {
|
|
if (!paper || !(ev.ctrlKey || ev.metaKey) || ev.defaultPrevented) return;
|
|
const key = ev.key.toLowerCase();
|
|
if (key === "z" && !ev.shiftKey) {
|
|
ev.preventDefault();
|
|
paper.undo();
|
|
} else if (key === "s") {
|
|
ev.preventDefault();
|
|
void paper.save();
|
|
}
|
|
};
|
|
|
|
/** 결과 단위 후보 — 품셈 로직에 다섯 번 넘게 쓰인 「원/…」 차례(설명 붙은 드문 단위는 뺌) */
|
|
const unitChoices = (): string[] => {
|
|
const count = new Map<string, number>();
|
|
for (const x of logics ?? []) {
|
|
if (isMoney(x.resultUnit)) count.set(x.resultUnit, (count.get(x.resultUnit) ?? 0) + 1);
|
|
}
|
|
const units = [...count.entries()]
|
|
.filter(([u, n]) => n >= 5 && !/[\s()「·]/.test(u))
|
|
.sort((a, b) => b[1] - a[1])
|
|
.map(([u]) => u);
|
|
return units.length ? units : ["원/㎡"];
|
|
};
|
|
|
|
/** 고치는 화면 열기 — 바깥 값을 넣은 뒤 · 새로 · 가져오기는 처음부터 「저장 안 함」 */
|
|
const open = async (
|
|
M: Mods,
|
|
sl: SheetLogic,
|
|
saved: boolean,
|
|
notes: string[] = [],
|
|
): Promise<void> => {
|
|
let filled = sl;
|
|
try {
|
|
const got = await fillOutside(M, sl);
|
|
filled = got.sl;
|
|
if (got.errors.length) notes = [...notes, te("Outside", { v: got.errors.join(" · ") })];
|
|
} catch (e) {
|
|
notes = [...notes, te("Outside", { v: M.api.slPlain(e) })];
|
|
}
|
|
paper = showPaper(M, body, filled, {
|
|
saved,
|
|
units: unitChoices(),
|
|
notes,
|
|
onClose: () =>
|
|
void (async () => {
|
|
if (await mayLeave()) void showStart();
|
|
})(),
|
|
});
|
|
};
|
|
|
|
const run = (job: (M: Mods) => Promise<void>): void => {
|
|
body.replaceChildren(muted(te("Loading")));
|
|
void mods.then(job).catch((e: unknown) => {
|
|
showToast(te("OpenFailed", { v: plainError(e) }), "error");
|
|
void showStart();
|
|
});
|
|
};
|
|
|
|
const openSaved = (key: string): void => run(async (M) => open(M, await M.api.slGet(key), true));
|
|
|
|
const openNew = (): void =>
|
|
run(async (M) => open(M, M.model.newLogic("", unitChoices()[0]), false));
|
|
|
|
/** 기존 로직 가져오기 — 로직 줄 + 그 줄이 쓰는 품셈 표(열 때 받음) → 시트 로직(저장 전) */
|
|
const doImport = (key: string): void =>
|
|
run(async (M) => {
|
|
const { row } = await openEasy(key);
|
|
const lb = await import("../LogicBuilder/M01_LB_Api");
|
|
const keys = [...new Set(JSON.stringify(row).match(/Q[A-Z]\d{6}/g) ?? [])];
|
|
const got = await Promise.all(
|
|
keys.map((k) =>
|
|
lb.fetchLbTable(k).then(
|
|
(t) => [k, t.table] as const,
|
|
() => null,
|
|
),
|
|
),
|
|
);
|
|
// 서버 표 통째(조건 · 값칸 · 줄 포함) — LB Api 타입이 느슨해 Import 모양으로 봄
|
|
const tables = Object.fromEntries(got.filter((x) => x !== null)) as unknown as Record<
|
|
string,
|
|
SlImportTable
|
|
>;
|
|
const report = M.imp.importLogicReport(row, { tables });
|
|
await open(M, report.sl, false, report.problems);
|
|
});
|
|
|
|
/* ---------- 시작 화면 ---------- */
|
|
|
|
const listButton = (name: string, unit: string, onClick: () => void, title = ""): HTMLElement => {
|
|
const row = el("button", {
|
|
className: "m01-sl__item",
|
|
attrs: { type: "button", title },
|
|
children: [
|
|
el("span", { className: "m01-sl__item-name", text: name }),
|
|
el("span", { className: "m01-sl__item-unit", text: unit }),
|
|
],
|
|
});
|
|
row.addEventListener("click", onClick);
|
|
return row;
|
|
};
|
|
const perText = (u: string): string => (isMoney(u) ? te("Per", { u: amountOf(u) }) : u);
|
|
const importRow = (item: EasyListItem): HTMLElement =>
|
|
listButton(item.name, perText(item.resultUnit), () => doImport(item.key), item.where);
|
|
const mineRow = (item: SlListItem): HTMLElement =>
|
|
listButton(item.이름, perText(item.결과단위), () => openSaved(item.key), item.saved);
|
|
|
|
const showStart = async (): Promise<void> => {
|
|
paper = null;
|
|
const status = el("p", { className: "m01-sl__muted", text: te("Loading") });
|
|
const trialHost = el("div", { className: "m01-sl__list" });
|
|
const foundHost = el("div", { className: "m01-sl__list" });
|
|
const mineHost = el("div", { className: "m01-sl__list", children: [muted(te("Loading"))] });
|
|
void mods
|
|
.then((M) => M.api.slList())
|
|
.then(
|
|
(mine) =>
|
|
mineHost.replaceChildren(
|
|
...(mine.length ? mine.map(mineRow) : [muted(te("Start_MineNone"))]),
|
|
),
|
|
(e: unknown) => mineHost.replaceChildren(muted(te("LoadFailed", { v: plainError(e) }))),
|
|
);
|
|
const search = createInputField({
|
|
type: "search",
|
|
placeholder: te("Start_Search"),
|
|
value: query,
|
|
onInput: (v) => {
|
|
query = v;
|
|
drawFound();
|
|
},
|
|
});
|
|
|
|
const drawFound = (): void => {
|
|
if (!logics) return;
|
|
const words = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
const hits = words.length
|
|
? logics.filter((x) => words.every((w) => x.name.toLowerCase().includes(w)))
|
|
: [];
|
|
status.textContent = !words.length
|
|
? ""
|
|
: !hits.length
|
|
? te("Start_None")
|
|
: hits.length > SHOWN
|
|
? te("Start_Count", { n: hits.length.toLocaleString(), m: SHOWN })
|
|
: "";
|
|
foundHost.replaceChildren(...hits.slice(0, SHOWN).map(importRow));
|
|
};
|
|
|
|
body.replaceChildren(
|
|
el("p", { className: "m01-sl__trial-note", text: te("Trial") }),
|
|
el("div", {
|
|
className: "m01-sl__start",
|
|
children: [
|
|
el("div", {
|
|
className: "m01-sl__start-col",
|
|
children: [
|
|
bigButton(te("Start_New"), openNew),
|
|
el("h4", { text: te("Start_Mine") }),
|
|
mineHost,
|
|
],
|
|
}),
|
|
el("div", {
|
|
className: "m01-sl__start-col",
|
|
children: [
|
|
el("h4", { text: te("Start_Import") }),
|
|
el("h5", { text: te("Start_Trial") }),
|
|
trialHost,
|
|
search.root,
|
|
status,
|
|
foundHost,
|
|
],
|
|
}),
|
|
],
|
|
}),
|
|
);
|
|
|
|
try {
|
|
logics ??= await listEasy("");
|
|
} catch (error) {
|
|
status.textContent = te("LoadFailed", { v: plainError(error) });
|
|
return;
|
|
}
|
|
const byKey = new Map(logics.map((x) => [x.key, x]));
|
|
trialHost.replaceChildren(
|
|
...TRIAL_KEYS.flatMap((k) => {
|
|
const item = byKey.get(k);
|
|
return item ? [importRow(item)] : [];
|
|
}),
|
|
);
|
|
status.textContent = "";
|
|
drawFound();
|
|
};
|
|
|
|
// 화면 함수들을 다 만든 뒤에 엶 — mount 가 바로 showStart 를 부름
|
|
openModal({
|
|
title: te("Title"),
|
|
closeLabel: te("CloseWindow"),
|
|
dialogClass: "m01-sl",
|
|
beforeClose: mayLeave,
|
|
mount: (host) => {
|
|
body = host;
|
|
(host.parentElement ?? host).addEventListener("keydown", onKey);
|
|
void showStart();
|
|
},
|
|
});
|
|
}
|
|
|
|
function bigButton(label: string, onClick: () => void): HTMLButtonElement {
|
|
const button = createButton({ label, variant: "filled", onClick });
|
|
button.classList.add("m01-sl__big");
|
|
return button;
|
|
}
|