Files
Aislo/B05_Profile/B05_Profile_UI_Structures_Panel.ts
T
eomsangdonandClaude Opus 5 deaf51778f feat(B05): 구조물 컨테이너 병합 2단계 — 측점 표기·기준점 입력·계곡 통과 시설 UI
PLAN 2026-08-17 「B05 구조물 컨테이너 병합」 프론트엔드.

- B05_Profile_Util_Station.ts 신설: 측점번호+잔여거리("3+18.0") ↔ 누가거리
  변환·서식·해석. 누가거리 직접 입력도 허용, 부동소수 올림 보정.
- 구조물 패널: 위치 입력을 측점 표기 텍스트로 재편. 점형 = 기준 측점 1칸,
  구간형 = 기준점(비우면 시작)+시작+종료 3칸, 시작≤기준≤종료 검증과 잘못된
  입력 붉힘. 목록 표기도 측점식. 구간형 마크 드래그는 기준점 기준으로 시작·
  종료가 따라온다. 상세(detail) 옵션은 폼에서 숨긴다 — B05는 유무·종류·위치
  단계(2026-08-17 사용자 확정).
- 우클릭 메뉴 필터 완화: managed_by와 b05 phase 필수만 제외 — 상세 필수였던
  타입(옹벽·돌쌓기 등)도 우클릭 한 번으로 추가된다.
- B05_Profile_UI_Drainage_Facility.ts 신설(패널 700줄 제한 대응 분리): 관 마커
  선택 시 시설 종류(배관/BOX암거/물넘이/세월교)·구간·세월교 관 종류/크기/수량
  폼. FacilityStore가 시설 확장 정보를 보관하고 세부유역 재계산·저장 요청에
  되붙인다(관 이동 후에도 최근접 승계 — 백엔드 carry와 같은 기준). 응답이
  정본이라 apply()에서 전량 재구성.
- B04_PreProcess_Api_Fetch.ts: PipeFacility·DetailPipeInput 타입, 요청·응답에
  시설 필드 반영.

npm run typecheck·npm run build 통과. 통합 서클마크 표시와 구 비정규 측점
이관·폐기(3단계)는 배관 측점선 체계 이전과 묶어 다음 작업 — PLAN.md 체크리스트
에 미완 사유 기록.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 09:06:19 +09:00

576 lines
22 KiB
TypeScript

/* =============================================================================
* B05_Profile_UI_Structures_Panel.ts
* 구조물 배치 사이드바 섹션 — 구조물군(A~G) → 타입 → 배치형태별 위치 → 옵션 입력.
*
* 타입 목록과 옵션 칸은 화면에 박아 두지 않고 서버 레지스트리(`GET /structure-types`)에서
* 받아 그린다. 구조물 종류가 늘어도 이 파일을 고치지 않게 하려는 것이다.
*
* 배관(구조물군 A)은 배수유역도의 관 지점이 정본이라 이 목록에서 다루지 않는다 —
* 기존 「구조물 배치」 섹션(비정규 측점)이 그대로 담당한다.
* ========================================================================== */
import {
defaultOptions,
isB05Option,
structureAnchorM,
type StructureInstance,
type StructurePlacement,
type StructureSide,
type StructureType,
} from "./B05_Profile_Api_Structures";
import { formatStation, parseStationText } from "./B05_Profile_Util_Station";
/** 구조물군 표시 이름. 리스트 기호(A~G)만으로는 무엇인지 알기 어렵다. */
const GROUP_LABELS: Record<string, string> = {
A: "A 횡단배수",
B: "B 종단배수",
C: "C 사면안정",
D: "D 계류·사방",
E: "E 안전·부대·용지",
F: "F 생태·녹화",
G: "G 노면공",
호환: "기타",
};
const SIDE_LABELS: Array<[StructureSide, string]> = [
["left", "좌측"],
["right", "우측"],
["center", "중심"],
["cross", "횡단"],
];
/** 구간형 신규 추가 시 기본 구간 길이(m). 사용자가 종점을 바로 고칠 수 있게 짧게 잡는다. */
const DEFAULT_INTERVAL_LENGTH_M = 15;
export interface StructuresSection {
root: HTMLElement;
/** 서버에서 받은 타입 목록을 채운다(최초 1회). */
setTypes: (types: StructureType[]) => void;
/** 서버 정본으로 목록을 교체한다(진입·복원·저장 후). */
setStructures: (structures: StructureInstance[]) => void;
getStructures: () => StructureInstance[];
/** 종단도·3D에서 고른 구조물을 폼에 올린다. null이면 선택 해제. */
selectById: (structureId: string | null) => void;
/** 종단 그래프 우클릭으로 타입을 지정해 추가한다. */
addAt: (chainageM: number, typeId: string) => void;
/** 종단 그래프에서 마크를 끌어 옮긴다. 옮겼으면 true. */
moveById: (structureId: string, toChainageM: number) => boolean;
removeById: (structureId: string) => boolean;
}
interface StructuresCallbacks {
/** 목록이 바뀔 때(추가·수정·삭제) 전체 목록을 넘긴다. */
onChange: (structures: StructureInstance[]) => void;
/** 목록에서 고르거나 해제할 때. */
onSelect: (structure: StructureInstance | null) => void;
/** 측점간격(m) — 측점번호+잔여거리 ↔ 누가거리 환산에 쓴다(비정규 측점과 동일). */
getInterval: () => number;
}
function field(labelText: string, input: HTMLElement): HTMLLabelElement {
const wrapper = document.createElement("label");
wrapper.className = "b05-route__field";
const caption = document.createElement("span");
caption.textContent = labelText;
wrapper.append(caption, input);
return wrapper;
}
function numberInput(step = "0.1", min = "0"): HTMLInputElement {
const input = document.createElement("input");
input.type = "number";
input.step = step;
input.min = min;
return input;
}
function select(options: ReadonlyArray<[string, string]>): HTMLSelectElement {
const element = document.createElement("select");
element.replaceChildren(...options.map(([value, label]) => new Option(label, value)));
return element;
}
export function createStructuresSection(callbacks: StructuresCallbacks): StructuresSection {
const root = document.createElement("section");
root.className = "b05-route__panel-section ui-collapsible ui-sidebar-section";
const heading = document.createElement("h3");
heading.className = "ui-collapsible__title";
heading.textContent = "구조물 추가";
const body = document.createElement("div");
body.className = "b05-route__panel-body";
root.append(heading, body);
const groupSelect = select([]);
const typeSelect = select([]);
const sideSelect = select(SIDE_LABELS);
// 위치는 측점번호+잔여거리 표기("3+18.0")로 받는다 — 누가거리 직접 입력("76.5")도 허용.
const stationInput = (): HTMLInputElement => {
const input = document.createElement("input");
input.type = "text";
input.placeholder = "예: 3+18.0";
input.inputMode = "decimal";
return input;
};
const anchorField = stationInput();
const startField = stationInput();
const endField = stationInput();
const offsetField = numberInput();
offsetField.value = "0";
const memoField = document.createElement("input");
memoField.type = "text";
memoField.placeholder = "메모(선택)";
const anchorWrap = field("위치 (측점)", anchorField);
const startWrap = field("시작 측점", startField);
const endWrap = field("종료 측점", endField);
const positionRow = document.createElement("div");
positionRow.className = "b05-route__irregular-row";
positionRow.append(anchorWrap, startWrap, endWrap);
const sideRow = document.createElement("div");
sideRow.className = "b05-route__irregular-row";
sideRow.append(field("설치측", sideSelect), field("이격 (m)", offsetField));
// 옵션 칸은 타입마다 다르므로 선택할 때마다 새로 그린다.
const optionRow = document.createElement("div");
optionRow.className = "b05-route__irregular-row";
const primary = document.createElement("button");
primary.type = "button";
primary.className = "b05-route__irregular-btn is-primary";
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.className = "b05-route__irregular-btn is-danger";
removeButton.textContent = "삭제";
const resetButton = document.createElement("button");
resetButton.type = "button";
resetButton.className = "b05-route__irregular-btn";
resetButton.textContent = "리셋";
const actions = document.createElement("div");
actions.className = "b05-route__irregular-actions";
actions.append(primary, removeButton, resetButton);
const list = document.createElement("ul");
list.className = "b05-route__irregular-list";
const help = document.createElement("p");
help.className = "b05-route__note";
help.textContent =
"구조물군과 종류를 고르고 측점(예: 3+18.0)을 입력해 추가합니다. 구간형은 기준점에 " +
"마크가 찍히고 시작~종료 측점을 받습니다(기준점을 비우면 시작 측점). 상세 치수는 " +
"B06/B07 단계에서 입력합니다. 배관 등 계곡 통과 시설은 배수유역 항목에서 관리합니다.";
body.append(
field("구조물군", groupSelect),
field("종류", typeSelect),
positionRow,
sideRow,
optionRow,
actions,
list,
help,
);
let types: StructureType[] = [];
let structures: StructureInstance[] = [];
let editingId: string | null = null;
let optionInputs: Array<{
key: string;
required: boolean;
input: HTMLInputElement | HTMLSelectElement;
read: () => string | number;
isEmpty: () => boolean;
}> = [];
function typeMap(): Map<string, StructureType> {
return new Map(types.map((type) => [type.type_id, type]));
}
function currentType(): StructureType | null {
return typeMap().get(typeSelect.value) ?? null;
}
function placementOf(typeId: string): StructurePlacement {
return typeMap().get(typeId)?.placement ?? "point";
}
const interval = (): number => callbacks.getInterval();
/** 측점 텍스트("3+18.0"·"76.5")를 누가거리로 읽는다. 못 읽으면 칸을 붉히고 null. */
function readStation(input: HTMLInputElement, required: boolean): number | null {
const parsed = parseStationText(input.value, interval());
const invalid = parsed === null && (required || input.value.trim() !== "");
input.classList.toggle("is-invalid", invalid);
return parsed;
}
/** 배치형태에 맞춰 위치 칸을 바꾼다 — 점형·부지형은 기준 측점 하나,
* 구간형은 기준점(마킹) + 시작·종료 측점(2026-08-17 사용자 확정). */
function syncPlacementFields(): void {
const placement = currentType()?.placement ?? "point";
const isInterval = placement === "interval";
startWrap.hidden = !isInterval;
endWrap.hidden = !isInterval;
anchorWrap.querySelector("span")!.textContent = isInterval ? "기준점 (측점)" : "위치 (측점)";
anchorField.placeholder = isInterval ? "비우면 시작 측점" : "예: 3+18.0";
}
/** 타입의 옵션 스키마대로 입력 칸을 다시 그린다 — 상세(detail) 옵션은 B06/B07
* 몫이라 그리지 않는다(B05 = 유무·종류·위치 단계, 2026-08-17 사용자 확정). */
function renderOptionFields(values: Record<string, string | number> = {}): void {
const type = currentType();
optionInputs = [];
optionRow.replaceChildren();
const visible = type ? type.options.filter(isB05Option) : [];
if (!type || !visible.length) {
optionRow.hidden = true;
return;
}
optionRow.hidden = false;
visible.forEach((option) => {
const preset = values[option.key] ?? option.default ?? "";
let input: HTMLInputElement | HTMLSelectElement;
if (option.input === "select") {
// 필수 선택지는 첫 항목을 슬쩍 고른 것처럼 두지 않는다 — 재료·형식은 설계자가
// 고르는 값이라, 안 고른 상태를 빈칸으로 드러낸다(2026-08-16 크로스체크 지적 2).
const choices = option.choices.map((choice) => [choice, choice] as [string, string]);
input = select(option.required ? [["", "선택하세요"], ...choices] : choices);
input.value = String(preset || (option.required ? "" : (option.choices[0] ?? "")));
} else if (option.input === "number") {
input = numberInput("0.1", "0");
input.value = String(preset ?? "");
// 미확정 항목(기본값 없음)은 비워 두면 저장이 거절된다 — 칸에서 미리 알린다.
if (option.required) (input as HTMLInputElement).placeholder = "필수 입력";
} else {
input = document.createElement("input");
(input as HTMLInputElement).type = "text";
input.value = String(preset ?? "");
}
const label = option.unit ? `${option.label} (${option.unit})` : option.label;
optionRow.append(field(label, input));
optionInputs.push({
key: option.key,
required: !!option.required,
input,
read: () => (option.input === "number" ? Number(input.value) || 0 : input.value),
isEmpty: () => input.value.trim() === "",
});
});
}
/** 고른 구조물군의 타입만 종류 목록에 채운다. */
function syncTypeOptions(keepTypeId?: string): void {
const group = groupSelect.value;
const candidates = types.filter((type) => type.group === group && !type.managed_by);
typeSelect.replaceChildren(...candidates.map((type) => new Option(type.name, type.type_id)));
if (keepTypeId && candidates.some((type) => type.type_id === keepTypeId)) {
typeSelect.value = keepTypeId;
}
syncPlacementFields();
renderOptionFields();
}
function syncButtons(): void {
primary.textContent = editingId ? "수정" : "추가";
removeButton.disabled = editingId === null;
}
function labelOf(structure: StructureInstance): string {
const type = typeMap().get(structure.type_id);
const name = type?.name ?? structure.type_id;
const step = interval();
// 표기는 측점번호+잔여거리(2026-08-17 사용자 확정). 구간형은 시작~종료를 보인다.
const position =
structure.placement === "interval"
? `${formatStation(structure.start_m ?? 0, step)}~${formatStation(structure.end_m ?? 0, step)}`
: formatStation(structure.chainage_m ?? 0, step);
return `${position} · ${name}`;
}
function renderList(): void {
list.replaceChildren();
if (!structures.length) {
const empty = document.createElement("li");
empty.className = "b05-route__irregular-empty";
empty.textContent = "추가된 구조물이 없습니다.";
list.append(empty);
return;
}
[...structures]
.sort((left, right) => structureAnchorM(left) - structureAnchorM(right))
.forEach((structure) => {
const item = document.createElement("li");
item.className = "b05-route__irregular-item";
item.classList.toggle("is-selected", structure.structure_id === editingId);
const name = document.createElement("strong");
name.textContent = labelOf(structure);
const info = document.createElement("span");
const sideLabel = SIDE_LABELS.find(([value]) => value === structure.side)?.[1] ?? "";
info.textContent = [sideLabel, structure.memo].filter(Boolean).join(" · ");
item.append(name, info);
item.addEventListener("click", () =>
loadForm(structure.structure_id === editingId ? null : structure),
);
list.append(item);
if (structure.structure_id === editingId) item.scrollIntoView({ block: "nearest" });
});
}
function loadForm(target: StructureInstance | null): void {
editingId = target?.structure_id ?? null;
const step = interval();
if (target) {
const type = typeMap().get(target.type_id);
if (type) {
groupSelect.value = type.group;
syncTypeOptions(target.type_id);
}
anchorField.value = formatStation(structureAnchorM(target), step);
startField.value =
target.start_m !== null && target.start_m !== undefined
? formatStation(target.start_m, step)
: "";
endField.value =
target.end_m !== null && target.end_m !== undefined
? formatStation(target.end_m, step)
: "";
sideSelect.value = target.side;
offsetField.value = String(target.offset_m ?? 0);
memoField.value = target.memo ?? "";
renderOptionFields(target.options);
} else {
anchorField.value = "";
startField.value = "";
endField.value = "";
offsetField.value = "0";
memoField.value = "";
renderOptionFields();
}
[anchorField, startField, endField].forEach((input) => input.classList.remove("is-invalid"));
syncPlacementFields();
syncButtons();
renderList();
callbacks.onSelect(target);
}
function readOptions(): Record<string, string | number> {
const values: Record<string, string | number> = {};
optionInputs.forEach((input) => {
// 빈 칸은 아예 넣지 않는다 — 빈 숫자를 0으로 저장하면 "0으로 확정"과 구분이 안 된다.
if (input.isEmpty()) return;
values[input.key] = input.read();
});
return values;
}
function emit(): void {
renderList();
callbacks.onChange([...structures]);
}
function commit(): void {
const type = currentType();
if (!type) return;
const placement = type.placement;
let anchor: number | null;
let start: number | null = null;
let end: number | null = null;
if (placement === "interval") {
start = readStation(startField, true);
end = readStation(endField, true);
if (start === null || end === null || end <= start) {
(start === null ? startField : endField).focus();
return;
}
// 기준점(마킹 위치) — 비우면 시작 측점. 시작~종료를 벗어나면 서버도 거절한다.
anchor = readStation(anchorField, false) ?? start;
if (anchor < start || anchor > end) {
anchorField.classList.add("is-invalid");
anchorField.focus();
return;
}
} else {
anchor = readStation(anchorField, true);
if (anchor === null) {
anchorField.focus();
return;
}
}
// 필수 옵션(미확정 기본값 없음)이 비어 있으면 추가하지 않는다 — 서버도 거절한다.
// 상세(detail) 옵션은 폼에 없으므로 여기 걸리지 않는다(B06/B07에서 받는다).
const missing = optionInputs.find((entry) => entry.required && entry.isEmpty());
if (missing) {
missing.input.focus();
return;
}
const base = {
type_id: type.type_id,
placement,
chainage_m: anchor,
start_m: start,
end_m: end,
side: sideSelect.value as StructureSide,
offset_m: Number(offsetField.value) || 0,
options: readOptions(),
memo: memoField.value.trim(),
placement_source: "manual" as const,
status: "draft" as const,
revision: 0,
geometry: null,
};
if (editingId) {
const index = structures.findIndex((entry) => entry.structure_id === editingId);
if (index >= 0) structures[index] = { ...structures[index], ...base };
} else {
structures.push({ ...base, structure_id: null });
}
loadForm(null);
emit();
}
groupSelect.addEventListener("change", () => {
syncTypeOptions();
// 종류가 바뀌면 기존 항목 수정이 아니라 새 항목 추가로 넘어간다(옵션 스키마가 달라진다).
if (editingId) {
editingId = null;
syncButtons();
renderList();
callbacks.onSelect(null);
}
});
typeSelect.addEventListener("change", () => {
syncPlacementFields();
renderOptionFields();
if (editingId) {
editingId = null;
syncButtons();
renderList();
callbacks.onSelect(null);
}
});
primary.addEventListener("click", commit);
removeButton.addEventListener("click", () => {
if (!editingId) return;
const index = structures.findIndex((entry) => entry.structure_id === editingId);
if (index >= 0) structures.splice(index, 1);
loadForm(null);
emit();
});
resetButton.addEventListener("click", () => loadForm(null));
body.insertBefore(field("메모", memoField), actions);
syncButtons();
renderList();
return {
root,
setTypes(next) {
types = next;
const groups = [...new Set(next.filter((type) => !type.managed_by).map((t) => t.group))];
groupSelect.replaceChildren(
...groups.map((group) => new Option(GROUP_LABELS[group] ?? group, group)),
);
// 배관(A군)은 배수유역 정본이 관리하므로 기본 선택은 그다음 군으로 둔다.
groupSelect.value = groups.includes("B") ? "B" : (groups[0] ?? "");
syncTypeOptions();
},
setStructures(next) {
// 서버 정본 주입 — onChange를 울리지 않는다. 울리면 Page가 다시 저장을 걸어
// 저장→재조회→주입→저장의 무한 고리가 된다(변경 알림은 사용자 조작에서만).
structures = next.map((entry) => ({ ...entry }));
loadForm(null);
renderList();
},
getStructures: () => [...structures],
selectById(structureId) {
if (structureId === null) {
loadForm(null);
return;
}
loadForm(structures.find((entry) => entry.structure_id === structureId) ?? null);
},
addAt(chainageM, typeId) {
const type = typeMap().get(typeId);
// 배관 등 계곡 통과 시설은 관 지점 정본 소관이라 이 목록에 넣을 수 없다(서버도 거절).
if (!type || type.managed_by) return;
const placement = placementOf(typeId);
const step = interval();
// B05 단계 필수 옵션이 있는 타입만 폼을 연다 — 상세(detail) 필수는 B06/B07
// 몫이라 바로 추가해도 서버가 받는다(2026-08-17 phase 분리).
if (type.options.some((option) => option.required && isB05Option(option))) {
groupSelect.value = type.group;
syncTypeOptions(typeId);
typeSelect.value = typeId;
editingId = null;
anchorField.value = formatStation(chainageM, step);
startField.value = placement === "interval" ? formatStation(chainageM, step) : "";
endField.value =
placement === "interval"
? formatStation(chainageM + DEFAULT_INTERVAL_LENGTH_M, step)
: "";
sideSelect.value = "center";
offsetField.value = "0";
memoField.value = "";
syncPlacementFields();
renderOptionFields();
syncButtons();
renderList();
root.scrollIntoView({ block: "nearest" });
const firstRequired = optionInputs.find((entry) => entry.required);
(firstRequired?.input ?? anchorField).focus();
return;
}
structures.push({
structure_id: null,
type_id: typeId,
placement,
chainage_m: chainageM,
start_m: placement === "interval" ? chainageM : null,
end_m: placement === "interval" ? chainageM + DEFAULT_INTERVAL_LENGTH_M : null,
side: "center",
offset_m: 0,
options: defaultOptions(type),
memo: "",
placement_source: "manual",
status: "draft",
revision: 0,
geometry: null,
});
emit();
},
moveById(structureId, toChainageM) {
const index = structures.findIndex((entry) => entry.structure_id === structureId);
if (index < 0) return false;
const target = structures[index];
if (target.placement === "interval") {
// 구간은 길이를 유지한 채 통째로 옮긴다 — 기준점을 끌면 시작·종료가 따라온다.
const length = (target.end_m ?? 0) - (target.start_m ?? 0);
const anchorOffset = structureAnchorM(target) - (target.start_m ?? 0);
const start = toChainageM - anchorOffset;
structures[index] = {
...target,
chainage_m: toChainageM,
start_m: start,
end_m: start + length,
};
} else {
structures[index] = { ...target, chainage_m: toChainageM };
}
emit();
return true;
},
removeById(structureId) {
const index = structures.findIndex((entry) => entry.structure_id === structureId);
if (index < 0) return false;
structures.splice(index, 1);
if (editingId === structureId) loadForm(null);
emit();
return true;
},
};
}