- ItemCards: 글 · 옵션 · 손잡이 합침 · 떠날 때 물음은 도면 + 엑셀 카드 · saveAll · 안 쓰는 hideToolbar 뺌 - Structure: saveCards · dirty 한 벌 - UI_Main: busy() 로 물음 - 시험 test_m02_drawing_card 모양 맞춤 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KYNJBegcapQYMwkKAf8D7S
424 lines
16 KiB
TypeScript
424 lines
16 KiB
TypeScript
/* =============================================================================
|
|
* M02_MasterTemplete_ItemCards.ts
|
|
* 항목 카드 — 도면 정보 · 면적산출 · 재료산출(보기만 + [수정]) + 덧붙는 카드(선택 입력 …).
|
|
* M02 구조물 설계 컨테이너(`M02_MasterTemplete_Structure.ts`)에서 떼어 냄(계획서 25-2d) — 항목 고르기
|
|
* 모달(`ui_template_item_picker_detail.ts`)이 **같은 카드**를 쓰려고. 문서를 어디서 읽는지는
|
|
* 자료 자리(`ItemSource`)가 정함 · 카드는 몰라도 됨. 모양(클래스 · DOM)은 옮기기 전과 같음.
|
|
* 면적산출 · 재료산출 = 스프레드시트 · 부품은 카드를 열 때만 `import()`(다른 페이지 번들에 안 섞임).
|
|
* 덧붙는 카드는 `extraCards` 로 끼움 — 선택 입력 카드(`M02_MasterTemplete_InputsCard.ts`)가 그 자리.
|
|
* `sheetEdit` 가 있으면 면적산출 · 재료산출 카드를 미리보기에서 고침(31-3) — 스프레드시트 `preview`(메뉴 없이
|
|
* 수식 입력 줄 · 칸 고침 · 단축키) + 아래 알약 줄 + 카드 [저장] · 없으면 보기만(고르기 모달).
|
|
* ========================================================================== */
|
|
|
|
import { createButton, el, showConfirmDialog, showToast } from "@ui/ui_template_elements";
|
|
import { attachCollapsible } from "@ui/ui_template_collapsible";
|
|
import { showLoading } from "@ui/ui_template_loading";
|
|
import type {
|
|
LinkOptions,
|
|
SpreadsheetHandle,
|
|
Workbook,
|
|
} from "../A00_Common/spreadsheet/spreadsheet";
|
|
import type { StructureDoc, StructureNumbers } from "./M02_MasterTemplete_Api_Fetch";
|
|
import { mountDrawingCard, type DrawingCardHandle } from "./M02_MasterTemplete_DrawingCard";
|
|
import type { ItemPart, ItemSource } from "./M02_MasterTemplete_ItemSource";
|
|
import "./M02_MasterTemplete_Structure.css";
|
|
|
|
/** 집계표 열 하나에 딸린 문서 셋 — 번호 칸 · 이름 */
|
|
export type EditKind = ItemPart;
|
|
export type SheetKind = Exclude<EditKind, "structure">;
|
|
export const PART_FIELD: Record<EditKind, keyof StructureNumbers> = {
|
|
structure: "도번",
|
|
area: "면적번",
|
|
material: "재료번",
|
|
};
|
|
export const PART_WORD: Record<EditKind, string> = {
|
|
structure: "도면",
|
|
area: "면적산출",
|
|
material: "재료산출",
|
|
};
|
|
|
|
const TEXT = {
|
|
drawingInfo: "도면 정보",
|
|
edit: "도면 수정",
|
|
noNumber: "도번 없음",
|
|
noDrawing: "도면 없음",
|
|
editSheet: "{value} 수정",
|
|
noSheetDoc: "{value} 없음",
|
|
noFieldNumber: "{value} 없음",
|
|
noSheet: "스프레드시트를 못 띄움 — {value}",
|
|
readFailed: "구조물 도면을 못 읽음 — {value}",
|
|
discard: "도면 카드에 저장 안 한 고침이 있음 — 버리고 다른 항목을 열까요?",
|
|
save: "저장",
|
|
saved: "저장했음",
|
|
saveFailed: "저장 못 함 — {value}",
|
|
};
|
|
|
|
const why = (error: unknown): string => (error instanceof Error ? error.message : "");
|
|
const fill = (text: string, value: string): string => text.replace("{value}", value);
|
|
/** 스프레드시트는 면적산출 · 재료산출 카드를 열 때만 받음 */
|
|
const loadSpreadsheet = () => import("../A00_Common/spreadsheet/spreadsheet");
|
|
|
|
/** 카드 틀 — 제목 + 머리 + 본문(좌측 패널과 같은 공용 ui-sidebar 카드) */
|
|
export const itemCard = (title: string, head: HTMLElement, body: HTMLElement): HTMLElement =>
|
|
el("section", {
|
|
className: "m02-struct__card ui-collapsible ui-sidebar-section ui-sidebar-card",
|
|
children: [el("h3", { className: "ui-collapsible__title", text: title }), head, body],
|
|
});
|
|
|
|
export const itemNote = (text: string): HTMLElement =>
|
|
el("p", { className: "m02-struct__empty", text });
|
|
|
|
export interface ItemCardsOptions {
|
|
/** 지금 자료 자리 — 열을 읽을 때마다 부름(층이 바뀌어도 따라감) */
|
|
source: () => ItemSource;
|
|
/** [수정] 단추를 보일까 — 부를 때마다 다시 봄 */
|
|
editable: () => boolean;
|
|
/** [도면 수정] · [면적산출 수정] · [재료산출 수정] */
|
|
onEdit: (kind: EditKind) => void;
|
|
/** 문서에 번호가 없을 때 쓸 번호(집계표 번호 줄) */
|
|
numberOf?: (kind: EditKind, column: string) => string | undefined;
|
|
/** 도면을 못 읽었을 때 알릴까 — 기본 알림(M02 는 번호가 있는 열만) */
|
|
warnOnFail?: (column: string) => boolean;
|
|
/** 세 카드 뒤에 덧붙는 카드(선택 입력 …) */
|
|
extraCards?: HTMLElement[];
|
|
/** 도면 카드에서 저장 안 한 고침이 생김 · 없어짐(PLAN 31-4) */
|
|
onDirty?: (dirty: boolean) => void;
|
|
/** 면적산출 · 재료산출 카드를 미리보기에서 고침(31-3) — 없으면 보기만 */
|
|
sheetEdit?: SheetEditOptions;
|
|
}
|
|
|
|
/** 카드 스프레드시트를 다루는 손잡이 — 알약 · 자재 조합 판이 씀 */
|
|
export interface SheetCardControl {
|
|
column: string;
|
|
label: string;
|
|
host: HTMLElement;
|
|
handle: () => SpreadsheetHandle | null;
|
|
/** 시트만 다시 붙임(저장 안 한 고침은 그대로) — 새 알약 목록으로 */
|
|
remount: (links: LinkOptions | undefined) => void;
|
|
/** 알약 · 판에서 시트 문서를 고쳤음 */
|
|
touched: () => void;
|
|
}
|
|
|
|
export interface SheetEditOptions {
|
|
/** 지금 고칠 수 있나 — 부를 때마다 다시 봄 */
|
|
can: () => boolean;
|
|
/** 아래 알약 줄(입력 연결) · 카드 아래 덧붙는 판(재료산출 = 자재 조합) — 전체 편집기와 같은 부품 */
|
|
links: (
|
|
kind: SheetKind,
|
|
control: SheetCardControl,
|
|
) => Promise<{ links?: LinkOptions; below?: HTMLElement; refresh?: () => void }>;
|
|
/** 카드 [저장] — 전체 편집기와 같은 저장 길 · 새 판을 돌려줌 */
|
|
save: (kind: SheetKind, column: string, doc: unknown, version: string) => Promise<string>;
|
|
}
|
|
|
|
export interface ItemCardsHandle {
|
|
root: HTMLElement;
|
|
/** 그 열을 읽어 카드를 그림 — `null` 이면 카드를 숨김 */
|
|
load: (col: { id: string; label: string } | null) => Promise<void>;
|
|
/** 이름만 새로(CAD 를 다시 안 띄움) */
|
|
setLabel: (label: string) => void;
|
|
/** [수정] 단추 글 — 종류마다 · `null` 은 기본 글 */
|
|
relabel: (labels: Partial<Record<EditKind, string | null>>) => void;
|
|
/** 지금 보이는 열 id */
|
|
column: () => string | null;
|
|
/** 카드(도면 · 면적산출 · 재료산출)에 저장 안 한 고침이 있나 — 페이지가 떠날 때 물음 */
|
|
dirty: () => boolean;
|
|
/** 고친 카드를 모두 저장 — 실패하면 던짐 */
|
|
saveAll: () => Promise<void>;
|
|
destroy: () => void;
|
|
}
|
|
|
|
export function createItemCards(opts: ItemCardsOptions): ItemCardsHandle {
|
|
let column: string | null = null;
|
|
let doc: StructureDoc | null = null;
|
|
let docVersion: string | null = null;
|
|
let preview: DrawingCardHandle | null = null;
|
|
let seq = 0;
|
|
|
|
const numberOf = (kind: EditKind, id: string): string => opts.numberOf?.(kind, id) ?? "";
|
|
|
|
const columnName = el("span", { className: "m02-struct__title" });
|
|
const number = el("span", { className: "m02-struct__no" });
|
|
const edit = createButton({ label: TEXT.edit, variant: "filled", size: "sm" });
|
|
const previewHost = el("div", { className: "m02-struct__preview" });
|
|
const drawingTools = el("span"); // 카드 안 ? · [저장](31-4 · 고칠 수 있을 때)
|
|
const infoCard = itemCard(
|
|
TEXT.drawingInfo,
|
|
el("div", {
|
|
className: "m02-struct__head",
|
|
children: [number, columnName, drawingTools, edit],
|
|
}),
|
|
previewHost,
|
|
);
|
|
|
|
/** 면적산출 · 재료산출 카드 — 번호 · [수정] · 스프레드시트 미리보기 */
|
|
interface SheetCard {
|
|
kind: SheetKind;
|
|
root: HTMLElement;
|
|
no: HTMLElement;
|
|
edit: HTMLButtonElement;
|
|
host: HTMLElement;
|
|
doc: Workbook | null;
|
|
number: string;
|
|
handle: SpreadsheetHandle | null;
|
|
/** 카드 고침(31-3) — [저장] · 읽은 판 · 저장 안 한 고침 */
|
|
save: HTMLButtonElement;
|
|
version: string;
|
|
dirty: boolean;
|
|
}
|
|
const sheetCard = (kind: SheetKind): SheetCard => {
|
|
const no = el("span", { className: "m02-struct__no" });
|
|
const editButton = createButton({
|
|
label: fill(TEXT.editSheet, PART_WORD[kind]),
|
|
variant: "ghost",
|
|
size: "sm",
|
|
});
|
|
const host = el("div", { className: "m02-struct__sheet" });
|
|
const save = createButton({ label: TEXT.save, variant: "filled", size: "sm" });
|
|
save.hidden = true;
|
|
editButton.addEventListener("click", () => opts.onEdit(kind));
|
|
const card: SheetCard = {
|
|
kind,
|
|
root: itemCard(
|
|
PART_WORD[kind],
|
|
el("div", { className: "m02-struct__subhead", children: [no, editButton, save] }),
|
|
host,
|
|
),
|
|
no,
|
|
edit: editButton,
|
|
host,
|
|
doc: null,
|
|
number: "",
|
|
handle: null,
|
|
save,
|
|
version: "",
|
|
dirty: false,
|
|
};
|
|
save.addEventListener("click", () => void saveCard(card).catch(() => undefined));
|
|
return card;
|
|
};
|
|
const sheets = [sheetCard("area"), sheetCard("material")];
|
|
edit.addEventListener("click", () => opts.onEdit("structure"));
|
|
const buttons: Record<EditKind, HTMLButtonElement> = {
|
|
structure: edit,
|
|
area: sheets[0].edit,
|
|
material: sheets[1].edit,
|
|
};
|
|
const defaults: Record<EditKind, string> = {
|
|
structure: TEXT.edit,
|
|
area: fill(TEXT.editSheet, PART_WORD.area),
|
|
material: fill(TEXT.editSheet, PART_WORD.material),
|
|
};
|
|
|
|
const root = el("div", {
|
|
className: "m02-struct ui-sidebar-panel",
|
|
attrs: { hidden: "" },
|
|
children: [infoCard, ...sheets.map((c) => c.root), ...(opts.extraCards ?? [])],
|
|
});
|
|
attachCollapsible(root);
|
|
|
|
const drop = (): void => {
|
|
preview?.destroy();
|
|
preview = null;
|
|
drawingTools.replaceChildren();
|
|
for (const c of sheets) {
|
|
c.handle?.destroy();
|
|
c.handle = null;
|
|
c.dirty = false;
|
|
c.save.hidden = true;
|
|
}
|
|
};
|
|
|
|
/** 카드 [저장] — 읽은 문서(번호 등 계약 밖 칸)에 시트를 덮어 저장(전체 편집기 `doSave` 와 같은 모양) */
|
|
async function saveCard(c: SheetCard): Promise<void> {
|
|
const at = column;
|
|
if (!opts.sheetEdit || !c.handle || !c.dirty || !at) return;
|
|
const doc = {
|
|
...(c.doc as unknown as Record<string, unknown>),
|
|
...c.handle.getDoc(),
|
|
} as Workbook;
|
|
c.save.disabled = true;
|
|
try {
|
|
c.version = await opts.sheetEdit.save(c.kind, at, doc, c.version);
|
|
c.doc = doc;
|
|
c.dirty = false;
|
|
showToast(TEXT.saved, "success");
|
|
} catch (error) {
|
|
showToast(fill(TEXT.saveFailed, why(error)), "error");
|
|
throw error;
|
|
} finally {
|
|
c.save.disabled = !c.dirty;
|
|
}
|
|
}
|
|
|
|
/** 미리보기 수정 — 메뉴 없이 수식 입력 줄 · 칸 고침 · 아래 알약 줄 · 덧붙는 판(재료산출 = 자재 조합) */
|
|
const paintEditable = async (
|
|
c: SheetCard,
|
|
mine: number,
|
|
create: (typeof import("../A00_Common/spreadsheet/spreadsheet"))["createSpreadsheet"],
|
|
): Promise<void> => {
|
|
const grid = el("div", { className: "m02-struct__sheet-grid" });
|
|
c.host.classList.add("is-edit");
|
|
c.host.replaceChildren(grid);
|
|
const mountGrid = (doc: Workbook, links: LinkOptions | undefined): void => {
|
|
c.handle?.destroy();
|
|
c.handle = create(grid, doc, {
|
|
preview: true,
|
|
tabs: false,
|
|
links,
|
|
onChange: () => {
|
|
c.dirty = true;
|
|
c.save.disabled = false;
|
|
extra.refresh?.();
|
|
},
|
|
});
|
|
};
|
|
const control: SheetCardControl = {
|
|
column: column ?? "",
|
|
label: columnName.textContent ?? "",
|
|
host: c.host,
|
|
handle: () => c.handle,
|
|
remount: (links) => {
|
|
const kept = c.handle?.getDoc();
|
|
if (kept) mountGrid(kept, links);
|
|
},
|
|
touched: () => {
|
|
c.dirty = true;
|
|
c.save.disabled = false;
|
|
},
|
|
};
|
|
// 알약을 못 받아도 칸은 고침 — 알약 줄만 없음
|
|
const extra: Awaited<ReturnType<SheetEditOptions["links"]>> = await opts
|
|
.sheetEdit!.links(c.kind, control)
|
|
.catch(() => ({}));
|
|
if (mine !== seq || !c.doc) return;
|
|
mountGrid(c.doc, extra.links);
|
|
if (extra.below) c.host.append(extra.below);
|
|
c.save.hidden = false;
|
|
c.save.disabled = true;
|
|
};
|
|
|
|
/** 스프레드시트 미리보기 — 보기만(고침은 [수정] 이 여는 전체 화면) · 부품을 늦게 받음 ·
|
|
* 그 사이 열이 바뀌면 버림 */
|
|
const paintSheet = async (c: SheetCard, mine: number): Promise<void> => {
|
|
if (!c.doc)
|
|
return void c.host.replaceChildren(itemNote(fill(TEXT.noSheetDoc, PART_WORD[c.kind])));
|
|
try {
|
|
const { createSpreadsheet } = await loadSpreadsheet();
|
|
if (mine !== seq || !c.doc) return;
|
|
if (opts.sheetEdit?.can()) return await paintEditable(c, mine, createSpreadsheet);
|
|
c.handle = createSpreadsheet(c.host, c.doc, { readOnly: true, tabs: false });
|
|
} catch (error) {
|
|
if (mine === seq) c.host.replaceChildren(itemNote(fill(TEXT.noSheet, why(error))));
|
|
}
|
|
};
|
|
|
|
/** 미리보기 · 스프레드시트 — 문서가 없으면 없음 글(서버가 열마다 미리 만들어 둬 보통은 없음) */
|
|
const paintBody = (mine: number): void => {
|
|
drop();
|
|
const at = column ?? "";
|
|
number.textContent = doc?.도번 || numberOf("structure", at) || TEXT.noNumber;
|
|
edit.hidden = !opts.editable();
|
|
for (const c of sheets) {
|
|
c.no.textContent =
|
|
c.number || numberOf(c.kind, at) || fill(TEXT.noFieldNumber, PART_FIELD[c.kind]);
|
|
c.edit.hidden = !opts.editable();
|
|
c.host.replaceChildren();
|
|
void paintSheet(c, mine);
|
|
}
|
|
if (!doc) {
|
|
previewHost.replaceChildren(itemNote(TEXT.noDrawing));
|
|
return;
|
|
}
|
|
previewHost.replaceChildren();
|
|
// 미리보기 — 고칠 수 있으면 메뉴 없이 단축키로 고치고 카드 [저장](31-4 · `DrawingCard`)
|
|
preview = mountDrawingCard(previewHost, {
|
|
doc,
|
|
version: docVersion,
|
|
source: opts.source(),
|
|
column: at,
|
|
editable: opts.editable(),
|
|
onDirty: (d) => opts.onDirty?.(d),
|
|
});
|
|
drawingTools.replaceChildren(preview.tools);
|
|
};
|
|
|
|
async function load(col: { id: string; label: string } | null): Promise<void> {
|
|
// 도면 카드 고침을 저장 안 했으면 버릴지 물음 — 취소면 보던 열 그대로
|
|
if (preview?.dirty() && col?.id !== column && !(await showConfirmDialog(TEXT.discard))) return;
|
|
const mine = ++seq;
|
|
drop();
|
|
opts.onDirty?.(false);
|
|
if (!col) {
|
|
root.hidden = true;
|
|
column = null;
|
|
doc = null;
|
|
return;
|
|
}
|
|
root.hidden = false;
|
|
column = col.id;
|
|
columnName.textContent = col.label;
|
|
number.textContent = numberOf("structure", col.id) || TEXT.noNumber;
|
|
doc = null;
|
|
docVersion = null;
|
|
previewHost.replaceChildren();
|
|
for (const c of sheets) {
|
|
c.doc = null;
|
|
c.number = "";
|
|
c.version = "";
|
|
c.host.classList.remove("is-edit");
|
|
c.host.replaceChildren();
|
|
}
|
|
const source = opts.source();
|
|
// 0.3초 넘으면 카드마다 칸 안 「불러오는 중」(PLAN 30-6) · 못 읽은 것은 아래 그대로(알림 · 「없음」)
|
|
const stops = [previewHost, ...sheets.map((c) => c.host)].map((host) => showLoading(host));
|
|
const [drawing, ...books] = await Promise.allSettled([
|
|
source.read("structure", col.id),
|
|
...sheets.map((c) => source.read(c.kind, col.id)),
|
|
]);
|
|
stops.forEach((stop) => stop());
|
|
if (mine !== seq) return;
|
|
if (drawing.status === "fulfilled") {
|
|
doc = drawing.value.문서 as StructureDoc;
|
|
docVersion = drawing.value.판 ?? null;
|
|
}
|
|
// 도번 목록에 있는 열인데 못 읽으면 알림 — 없는 열은 그냥 「도면 없음」
|
|
else if (opts.warnOnFail?.(col.id) ?? true)
|
|
showToast(fill(TEXT.readFailed, why(drawing.reason)), "error");
|
|
books.forEach((got, i) => {
|
|
if (got.status !== "fulfilled") return;
|
|
const c = sheets[i];
|
|
const book = got.value.문서 as Workbook & Record<string, unknown>;
|
|
c.doc = book;
|
|
c.version = String((got.value as { 판?: string | null }).판 ?? "");
|
|
c.number = String(book?.[PART_FIELD[c.kind]] ?? "");
|
|
});
|
|
paintBody(mine);
|
|
}
|
|
|
|
return {
|
|
root,
|
|
load,
|
|
setLabel: (label) => {
|
|
columnName.textContent = label;
|
|
},
|
|
relabel: (labels) => {
|
|
for (const kind of Object.keys(buttons) as EditKind[]) {
|
|
const button = buttons[kind];
|
|
(button.querySelector(".ui-btn__label") ?? button).textContent =
|
|
labels[kind] ?? defaults[kind];
|
|
}
|
|
},
|
|
column: () => column,
|
|
dirty: () => !!preview?.dirty() || sheets.some((c) => c.dirty),
|
|
saveAll: async () => {
|
|
for (const c of sheets) await saveCard(c);
|
|
},
|
|
destroy: () => {
|
|
seq += 1;
|
|
drop();
|
|
root.remove();
|
|
},
|
|
};
|
|
}
|