Files
Aislo/A00_Common/design/design_structure_form.ts
T

362 lines
15 KiB
TypeScript

/* =============================================================================
* design_structure_form.ts
* 구조물 명세(`design_structure_spec`) 그리기 — B05 · B06 「구조물 배치」 칸이 같은 노드를 씀.
*
* · 필수 컨테이너 = 늘 보임(한 벌) · 선택 컨테이너 = [추가] 로 인스턴스를 늘리고 인스턴스마다 [빼기] ·
* `max` 에 차면 [추가] 숨김
* · 항목: 고르기(상위 값에 따른 선택지 · 저장 키) · 숫자(맞물림 = 길이 · 전 · 후) · 글(손 입력) · 자동(읽기만)
* · 인스턴스마다 「구조물 조합」 잇기 줄(`buildSummaryRow` · 고르기 모달 = 패널의 그룹 [고르기] 길 그대로) —
* 값은 패널 `group_items` 에 `linkOf` 키로 둠(빼면 뒤 인스턴스 잇기를 한 칸씩 당김)
* · 값은 폼이 쥠 — 저장은 패널이 `read()` 로 읽어 정본 자리(옵션)에 씀
* · 칸 표식 = `data-spec-item="{컨테이너}.{항목}"`(정의 규칙 · 그룹 상자가 안 건드리게 옵션 키 표식 안 씀)
* ========================================================================== */
import {
branchOf,
choiceLabel,
choicesOf,
containerTitle,
itemLabel,
linkOf,
readState,
solveSplit,
TEXT_MAX,
writeOptions,
type SpecContainer,
type SpecItem,
type SpecNames,
type SpecState,
type SplitRole,
type StructureSpec,
} from "./design_structure_spec";
import {
group,
grid,
labeled,
numberInput,
stepper,
} from "../../B05_Profile/B05_Profile_UI_Drainage_Facility_Fields";
import { buildSummaryRow } from "../../B05_Profile/B05_Profile_UI_Structures_Summary_Row";
import type { GroupItems, SummaryItem } from "../../common_util/common_util_summary_item";
/** 잇기 값 자리 — 패널 그룹 값(`group_items`)을 그대로 씀. */
export interface SpecLinks {
get: () => GroupItems;
pick: (key: string) => void;
/** [해제] — 패널이 풀고 반영. */
clear: (key: string) => void;
/** 값만 옮김(빼기 뒤 당김) — 반영은 뒤이은 폼 변경 알림이 함. */
set: (key: string, item: SummaryItem | null) => void;
}
export interface SpecFormHooks {
/** 자동 항목 값 글(빈 글 = 「—」). */
auto?: (c: SpecContainer, item: SpecItem, state: SpecState) => string;
onChange?: (c: SpecContainer, item: SpecItem) => void;
/** 선택 컨테이너 개수를 밖에서 정함(54-1 배관 흙막이 = 추가 기슭막이(단)) — 수면 그만큼 늘 보임 ·
* [추가] · [빼기] 없음 · 줄면 끝에서부터 가림(값은 남음 · 54-10) · null = 모름(저장된 것 그대로) ·
* undefined = 손 [추가]. */
count?: (c: SpecContainer) => number | null | undefined;
/** 컨테이너 칸 끝에 덧붙이는 칸(54-27 배관 유출 「추가 흙막이(단)」 · 값은 저장 옵션 밖). */
fields?: (c: SpecContainer, values: Record<string, string>) => HTMLElement[];
/** 그림이 쓰는 값(54-13) — 자동 규칙일 때 그 값 · 꼬리(「자동」) ·
* null = 없음. 보여 주기만(값 · 저장은 사용자가 고를 때만). `values` = 보이는 값(위 칸 반영). */
shown?: (
c: SpecContainer,
item: SpecItem,
values: Record<string, string>,
index: number,
) => { value: string; tag: string } | null;
}
export interface SpecForm {
root: HTMLElement;
/** 명세 · 저장 값으로 다시 그림. `names` = 정의 이름 바꿈 · `groupNames` = 정의 그룹 이름. */
write: (
spec: StructureSpec,
options: Record<string, string | number>,
names?: SpecNames,
groupNames?: Record<string, string>,
/** 정의 기본값(저장 키 → 값) — 필수 상자 빈 고르기 칸이 받는 값(54-43). */
defaults?: Record<string, string | number>,
) => void;
read: () => Record<string, string | number>;
state: () => SpecState;
/** 한 항목 값을 바꿔 그림(B06 조정창 맞춤 등) — change 알림은 안 함. */
setValue: (containerId: string, itemId: string, value: string) => void;
/** 필수 컨테이너 끝에 붙일 자리(B06 조정 행). */
slot: (containerId: string) => HTMLElement;
/** 잇기 값이 바뀌었을 때 줄을 다시 그림. */
paintLinks: () => void;
refresh: () => void;
/** 밖에서 정한 개수(`hooks.count`)가 바뀌었을 때 — 맞춰 그리고 바뀌었으면 change 알림. */
recount: () => void;
}
export function createSpecForm(links: SpecLinks | null, hooks: SpecFormHooks = {}): SpecForm {
const root = document.createElement("div");
root.className = "b05-structure__spec";
let spec: StructureSpec | null = null;
let state: SpecState = {};
let names: SpecNames = {};
let groupNames: Record<string, string> = {};
let defaults: Record<string, string | number> = {};
const recent = new Map<Instance, SplitRole[]>();
const slots = new Map<string, HTMLElement>();
const rows: Array<{ key: string; set: (item: SummaryItem | null) => void }> = [];
type Instance = Record<string, string>;
const slotOf = (id: string): HTMLElement => {
let slot = slots.get(id);
if (!slot) {
slot = document.createElement("div");
slot.className = "b05-structure__adjust-slot";
slots.set(id, slot);
}
return slot;
};
const control = (
c: SpecContainer,
item: SpecItem,
values: Instance,
tag?: string,
): HTMLElement => {
if (item.kind === "select") {
const select = document.createElement("select");
const choices = choicesOf(item, values);
const now = values[item.id] ?? "";
const drawn = choices.find((ch) => ch.value === now);
// 그림이 쓰는 값은 빈 보기 자리에 꼬리를 달아 보임 — 고른 값과 구별(54-13)
const name = drawn ? choiceLabel(c, item, drawn, names) : now;
const blank = !tag ? "" : name ? `${name} (${tag})` : tag;
// 필수 상자 = 빈 보기 없음(54-43) · 선택 상자 빈 보기 = 빈 글
select.replaceChildren(
...(c.required && !tag ? [] : [new Option(blank, "")]),
...choices.map((ch) => new Option(choiceLabel(c, item, ch, names), ch.value)),
);
// 선택지 밖 옛 값은 그 값만 남겨 보임(지운 값을 몰래 바꾸지 않음)
if (!tag && now && !drawn) select.add(new Option(now, now));
select.value = tag ? "" : now;
return select;
}
if (item.kind === "text") {
const input = document.createElement("input");
input.type = "text";
input.maxLength = TEXT_MAX;
input.value = values[item.id] ?? "";
return input;
}
// 빈 칸 = 그냥 빈 칸(54-43 · 자리표시 글 없음)
const input = numberInput(String(item.step ?? 0.1), "0");
if (item.kind === "auto") {
// 보여 주는 칸(54-1) — 손 입력 칸 아님
const shown = document.createElement("output");
shown.className = "b05-structure__auto";
shown.textContent = hooks.auto?.(c, item, state) || "—";
shown.title = "자동 계산";
return shown;
}
input.value = values[item.id] ?? "";
return stepper(input, item.step ?? 0.1);
};
const onEdit = (
c: SpecContainer,
item: SpecItem,
values: Instance,
raw: string,
view: Instance,
): void => {
// 그림 값을 보이던 위 칸 아래를 고침 = 그 위 값을 고른 것 — 다른 갈래 값은 비움(54-13)
const parent = item.by?.item;
if (parent && view[parent] !== values[parent]) {
values[parent] = view[parent];
for (const child of c.items) if (child.by?.item === parent) values[child.id] = "";
}
values[item.id] = raw;
if (item.split) {
const order = [item.split, ...(recent.get(values) ?? []).filter((r) => r !== item.split)];
recent.set(values, order);
const role = (r: SplitRole) => c.items.find((i) => i.split === r)!;
const solved = solveSplit(
{
length: values[role("length").id],
before: values[role("before").id],
after: values[role("after").id],
},
order,
);
for (const r of ["length", "before", "after"] as SplitRole[])
values[role(r).id] = solved[r] ?? "";
}
// 위 항목이 바뀌면 갈래(선택지 · 저장 키)가 달라짐 — 선택지 밖 값은 비움
for (const child of c.items.filter((i) => i.by?.item === item.id)) {
const allowed = choicesOf(child, values);
if (child.kind === "select" && !allowed.some((ch) => ch.value === values[child.id]))
values[child.id] = "";
}
paint();
hooks.onChange?.(c, item);
};
const instanceBox = (c: SpecContainer, values: Instance, index: number): HTMLElement => {
const title = containerTitle(c, names, groupNames[c.link]);
// 하나만 서는 상자(max 1)는 번호 없음(54-50)
const box = group(c.required || c.max === 1 ? title : `${title} ${index + 1}`);
box.root.dataset.specContainer = c.id;
box.root.dataset.specIndex = String(index); // 칸을 고친 뒤 다시 그려도 몇째 상자인지(54-30)
// 필수 상자 빈 고르기 칸 = 정의 기본값(없으면 첫 보기)을 실제 값으로 — 저장도 그 값(54-43)
if (c.required)
for (const item of c.items) {
if (item.kind !== "select" || values[item.id] || (item.by && !branchOf(item, values)))
continue;
const choices = choicesOf(item, values);
const key = branchOf(item, values)?.key;
const wanted = String((key ? defaults[key] : undefined) ?? item.default ?? "");
values[item.id] = (choices.find((ch) => ch.value === wanted) ?? choices[0])?.value ?? "";
}
// 보이는 값 = 고른 값 + 그림이 쓰는 값(54-13) · 위 칸이 다른 갈래를 보이면 아래 칸은 빈 채로
const view: Instance = { ...values };
const tags = new Map<string, string>();
for (const item of c.items) {
if (item.by && view[item.by.item] !== values[item.by.item]) view[item.id] = "";
const drawn = item.kind === "select" ? hooks.shown?.(c, item, view, index) : null;
if (!drawn) continue;
view[item.id] = drawn.value;
tags.set(item.id, drawn.tag);
}
const fields = c.items
.filter((item) => item.kind === "auto" || !item.by || branchOf(item, view))
.map((item) => {
const input = control(c, item, view, tags.get(item.id));
const wrap = labeled(itemLabel(c, item, names), input);
wrap.dataset.specItem = `${c.id}.${item.id}`;
if (tags.has(item.id)) wrap.dataset.specShown = tags.get(item.id);
const target = input.querySelector?.("input, select") ?? input;
target.addEventListener("change", () =>
onEdit(c, item, values, (target as HTMLInputElement | HTMLSelectElement).value, view),
);
return wrap;
});
box.body.append(grid(...fields, ...(hooks.fields?.(c, values) ?? [])));
if (c.required) {
const slot = slotOf(c.id);
// B06 조정 강조(테두리 · 이름표)는 칸 상자에 붙음 — 다시 그려도 이어 감(53-1)
const prev = slot.closest("fieldset");
if (prev?.classList.contains("is-active")) {
const legend = box.root.querySelector("legend")!;
legend.dataset.baseLabel = legend.textContent ?? "";
legend.textContent = prev.querySelector("legend")?.textContent ?? legend.textContent;
box.root.classList.add("is-active");
}
box.body.append(slot);
}
if (links) {
const key = linkOf(c, index + 1);
const row = buildSummaryRow();
row.root.querySelector(".b05-structure__summary-label")!.textContent = "구조물 조합";
row.root.dataset.specLink = key;
row.set(links.get()[key] ?? null);
row.bind({ pick: () => links.pick(key), clear: () => links.clear(key) });
rows.push({ key, set: row.set });
box.body.append(row.root);
}
if (!c.required && hooks.count?.(c) === undefined) {
const remove = document.createElement("button");
remove.type = "button";
remove.className = "b05-route__irregular-btn";
remove.textContent = "빼기";
remove.dataset.specRemove = c.id;
remove.addEventListener("click", () => {
const list = state[c.id];
// 잇기는 인스턴스 차례를 따름 — 뒤 것을 한 칸씩 당기고 마지막 키는 풂
if (links) {
const now = links.get();
for (let n = index + 1; n < list.length; n++)
links.set(linkOf(c, n), now[linkOf(c, n + 1)] ?? null);
links.set(linkOf(c, list.length), null);
}
list.splice(index, 1);
paint();
hooks.onChange?.(c, c.items[0]);
});
box.root.querySelector("legend")!.append(" ", remove);
}
return box.root;
};
// 새로 서는 상자 = 명세 기본값을 칸에 실제 값으로(54-36 · 이미 있는 상자 값은 그대로)
const fresh = (c: SpecContainer): Instance =>
Object.fromEntries(c.items.flatMap((i) => (i.default ? [[i.id, i.default]] : [])));
/** 밖에서 정한 개수 — 모자라면 새 인스턴스를 늘림(늘었으면 true) · 넘친 인스턴스 · 잇기는
* 가리기만 하고 값에 남김(54-10 · 파일에 그대로). */
const fit = (c: SpecContainer, list: Instance[]): boolean => {
const n = hooks.count?.(c);
if (c.required || n === undefined || n === null || n <= list.length) return false;
while (list.length < n) list.push(fresh(c));
return true;
};
const shown = (c: SpecContainer, list: Instance[]): Instance[] => {
const n = c.required ? null : hooks.count?.(c);
return n === undefined || n === null ? list : list.slice(0, n);
};
function paint(quiet = true): void {
rows.length = 0;
const boxes: HTMLElement[] = [];
const fitted: SpecContainer[] = [];
for (const c of spec?.containers ?? []) {
const list = (state[c.id] ??= c.required ? [{}] : []);
if (fit(c, list)) fitted.push(c);
shown(c, list).forEach((values, index) => boxes.push(instanceBox(c, values, index)));
if (c.required || (c.max && list.length >= c.max) || hooks.count?.(c) !== undefined) continue;
const add = document.createElement("button");
add.type = "button";
add.className = "b05-route__irregular-btn b05-structure__spec-add";
add.textContent = `+ ${containerTitle(c, names, groupNames[c.link])}`;
add.title = "추가";
add.dataset.specAdd = c.id;
add.addEventListener("click", () => {
list.push(fresh(c));
paint();
hooks.onChange?.(c, c.items[0]);
});
boxes.push(add);
}
root.replaceChildren(...boxes);
// 개수가 밖에서 바뀌었으면 값 변경으로 알림(불러오기 때는 안 함)
if (!quiet) fitted.forEach((c) => hooks.onChange?.(c, c.items[0]));
// 상자를 새로 세움 — 고른 상자 강조를 다시 얹을 곳(B06 · 54-30 · 시험 흉내 DOM 은 없음)
root.dispatchEvent?.(new Event("specpaint", { bubbles: true }));
}
return {
root,
write(next, options, nextNames = {}, nextGroups = {}, nextDefaults = {}) {
spec = next;
defaults = nextDefaults;
names = nextNames;
groupNames = nextGroups;
state = readState(next, options);
recent.clear();
paint();
},
read: () => (spec ? writeOptions(spec, state) : {}),
state: () => state,
setValue(containerId, itemId, value) {
const values = state[containerId]?.[0];
if (!values) return;
values[itemId] = value;
paint();
},
slot: slotOf,
paintLinks() {
const now = links?.get() ?? {};
rows.forEach((row) => row.set(now[row.key] ?? null));
},
refresh: () => paint(),
recount: () => paint(false),
};
}