Files
Aislo/M02_MasterTemplete/M02_MasterTemplete_ItemCards.ts
T
eomsangdonandClaude Sonnet 5.5 083c12ad3a feat(ui_template): 항목 고르기 모달 상세 — 카드 넷 · 프로젝트 복사본 편집 · 뒤로 (PLAN 25-2d)
- 오른쪽 상세를 카드 넷(도면 · 면적산출 · 재료산출 · 선택 입력)으로 — M02 와 같은 카드 한 벌
- 카드 [수정] = 모달 안 편집 화면(CAD · 스프레드시트 · 선택 입력 값 넣기) · [뒤로] = 선택지
- 고침은 프로젝트 복사본만 · 안 가져온 항목은 「프로젝트로 가져와 고침」 · 마스터가 바뀜 표시 + [새로 가져오기]
- 서버 길(sub6 · sub4)이 없으면 약속 모양의 가짜 응답(이음 자리 FAKE)
- B05 구조물 폼이 projectId 를 모달에 넘김 · 모달 넓힘

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EauA2ATmqNRbeV48s9CcBr
2026-09-29 23:31:05 +09:00

297 lines
11 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`)가 그 자리.
* ========================================================================== */
import { createButton, el, showToast } from "@ui/ui_template_elements";
import { attachCollapsible } from "@ui/ui_template_collapsible";
import type { SpreadsheetHandle, Workbook } from "../A00_Common/spreadsheet/spreadsheet";
import type { StructureDoc, StructureNumbers } from "./M02_MasterTemplete_Api_Fetch";
import {
mountDrawingTemplate,
type DrawingTemplateDoc,
type DrawingTemplateHandle,
} from "./M02_MasterTemplete_Drawing";
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}",
};
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[];
}
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;
destroy: () => void;
}
export function createItemCards(opts: ItemCardsOptions): ItemCardsHandle {
let column: string | null = null;
let doc: StructureDoc | null = null;
let preview: DrawingTemplateHandle | 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 infoCard = itemCard(
TEXT.drawingInfo,
el("div", { className: "m02-struct__head", children: [number, columnName, edit] }),
previewHost,
);
/** 면적산출 · 재료산출 카드 — 번호 · [수정] · 스프레드시트 미리보기 */
interface SheetCard {
kind: SheetKind;
root: HTMLElement;
no: HTMLElement;
edit: HTMLButtonElement;
host: HTMLElement;
doc: Workbook | null;
number: string;
handle: SpreadsheetHandle | null;
}
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" });
editButton.addEventListener("click", () => opts.onEdit(kind));
return {
kind,
root: itemCard(
PART_WORD[kind],
el("div", { className: "m02-struct__subhead", children: [no, editButton] }),
host,
),
no,
edit: editButton,
host,
doc: null,
number: "",
handle: null,
};
};
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;
for (const c of sheets) {
c.handle?.destroy();
c.handle = null;
}
};
/** 미리보기 CAD 는 iframe — 안쪽 도구 모음(제목줄 · 리본)을 스타일로 숨김(같은 출처라 접근 가능) */
const hideToolbar = (frame: HTMLIFrameElement): void => {
const apply = (): void => {
const inner = frame.contentDocument;
if (!inner?.head || inner.getElementById("m02-struct-hide")) return;
const style = inner.createElement("style");
style.id = "m02-struct-hide";
style.textContent = ".cad-titlebar, .cad-ribbon { display: none !important; }";
inner.head.append(style);
};
frame.addEventListener("load", apply);
apply();
};
/** 스프레드시트 미리보기 — 보기만(고침은 [수정] 이 여는 전체 화면) · 부품을 늦게 받음 ·
* 그 사이 열이 바뀌면 버림 */
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;
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();
const source = opts.source();
// 미리보기 — 도면 양식과 같은 부품을 읽기만으로. 자동백업 칸은 편집 화면과 갈라 둠.
preview = mountDrawingTemplate(previewHost, doc.도면 as unknown as DrawingTemplateDoc, {
readOnly: true,
name: `preview:${column ?? ""}`,
layer: source.layer,
projectId: source.projectId,
panelsCollapsed: true, // 특성 · 도면층 패널은 접힌 채 — › 를 누르면 펼침
preview: true, // 왼쪽 끌기 = 화면 옮기기 · 두 번 누름 = 전체 맞춤
originMarker: true, // 좌표 0,0 기준점 십자
noArea: true, // 구조물도는 도각이 없음 — 작도 영역 단추 없음
});
const frame = previewHost.querySelector("iframe");
if (frame) hideToolbar(frame);
};
async function load(col: { id: string; label: string } | null): Promise<void> {
const mine = ++seq;
drop();
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;
previewHost.replaceChildren();
for (const c of sheets) {
c.doc = null;
c.number = "";
c.host.replaceChildren();
}
const source = opts.source();
const [drawing, ...books] = await Promise.allSettled([
source.read("structure", col.id),
...sheets.map((c) => source.read(c.kind, col.id)),
]);
if (mine !== seq) return;
if (drawing.status === "fulfilled") doc = drawing.value.문서 as StructureDoc;
// 도번 목록에 있는 열인데 못 읽으면 알림 — 없는 열은 그냥 「도면 없음」
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.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,
destroy: () => {
seq += 1;
drop();
root.remove();
},
};
}