refactor(859-5 ②): 구조물 정의 코드 M02 StructOptions → M01_MasterData/StructOptions

- 파일 23 개 git mv · 이름 M02_SO_* → M01_SO_* · 내용 · 동작 · 화면 글 그대로
- 서버 주소 /api/m02 → /api/m01(이름만 · 10 길 · 수 469 그대로) · main.py 등록 이름 m01_so_*
- 화면 부름 = common_util_m02_call 의 call 에 base 인자(기본 /m02 · 구조물 정의만 /m01)
- import 고침 = B05 · B07 · B08 · M01 · M02 · main · 시험 · 도우미
- 소스 글자만 보던 시험 셋 지움(구조물 정의 옮김에 걸림 · 결과를 안 봄):
  test_m02_structure_options 좌측 줄 · test_m02_structure_option_groups 좌측 정의 줄 · test_136_3 M02 미리보기 단추 CSS
- test_553_5 부품 훑기 폴더 = 옮긴 자리

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 21:42:33 +09:00
co-authored by Claude Opus 5.5
parent 47d2fe7192
commit e4b9b3e5a3
77 changed files with 207 additions and 234 deletions
+1 -1
View File
@@ -233,7 +233,7 @@ def rename_moved(base: Path, wanted: dict[str, tuple[str, dict[str, Any]]]) -> l
def group_names() -> dict[str, str]:
"""옵션 그룹 id → 이름(지금 정의) — 복사본 manifest `그룹` 으로 굳힘(142-2)."""
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
from M01_MasterData.StructOptions.M01_SO_Groups import groups_of
return {g["id"]: g["name"] for rows in groups_of().values() for g in rows}
@@ -5,7 +5,7 @@
* ========================================================================== */
import { createSelectField } from "@ui/ui_template_elements";
import { fetchStructureDef } from "./StructOptions/M02_SO_Api";
import { fetchStructureDef } from "../M01_MasterData/StructOptions/M01_SO_Api";
import { precomboClasses } from "./M02_MasterTemplete_UI_Side_Precombo";
import { tc } from "./M02_MasterTemplete_Labor_Text";
@@ -33,7 +33,7 @@ import { openStandardSheet } from "./M02_MasterTemplete_Labor_Sheet";
import type { LaborFixed, LaborRef } from "./M02_MasterTemplete_Labor_Calc";
import { tc } from "./M02_MasterTemplete_Labor_Text";
import { precomboClasses } from "./M02_MasterTemplete_UI_Side_Precombo";
import { fetchStructureDef } from "./StructOptions/M02_SO_Api";
import { fetchStructureDef } from "../M01_MasterData/StructOptions/M01_SO_Api";
import "../M01_MasterData/M01_MasterData_UI_Logic_Style.css"; // 창 겉틀
import "./M02_MasterTemplete_Labor.css";
import { openModal } from "@ui/ui_template_modal";
@@ -9,7 +9,7 @@
import type { TreeMenuItem } from "@ui/ui_template_tree";
import type { Kind } from "./M02_MasterTemplete_Api_Fetch";
import type { StructDef } from "./StructOptions/M02_SO_Def_Model";
import type { StructDef } from "../M01_MasterData/StructOptions/M01_SO_Def_Model";
import { tc } from "./M02_MasterTemplete_Labor_Text";
import type { Selection } from "./M02_MasterTemplete_UI_Main";
import {
+1 -1
View File
@@ -150,9 +150,9 @@ def _with_group_items(items: list[dict[str, Any]], project_root=None) -> list[di
복사본 `{구조물 id}__{그룹 id}`. 그룹 = 지금 정의 + 복사본에 굳힌 정의(142-2 · 이름 · 사라진
그룹도) · 미지정 그룹 = 「미지정」 알림에 셈."""
from common_util.common_util_summary_item import GROUP_JOIN
from M01_MasterData.StructOptions.M01_SO_Groups import groups_of
from M02_MasterTemplete.M02_Item_Snapshot import copied_groups
from M02_MasterTemplete.M02_Table_Fill_Spec import container_rows
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
defined = groups_of()
out: list[dict[str, Any]] = []
@@ -1,29 +0,0 @@
/* =============================================================================
* M02_SO_Api.ts
* 구조물 정의 서버 호출 — 서버 = `M02_SO_Router.py`(마스터 템플릿 `구조물정의.json` 한 벌 · PLAN 48)
* ========================================================================== */
import { call } from "../M02_MasterTemplete_Api_Fetch";
import type { StructDef } from "./M02_SO_Def_Model";
/* --- 구조물 정의(PLAN 48 · 마스터 템플릿 `구조물정의.json` · 판 번호 · 이력) --- */
/** 지난 판 한 줄 */
export interface DefVersion {
판: number;
저장일: string;
}
/** 정의 한 벌 — 읽기 = 로그인 누구나 */
export const fetchStructureDef = (): Promise<StructDef> => call("/structure-definition");
/** 통째로 고쳐 씀(시스템 관리자만) — 읽어 간 판이 지금 판과 다르면 StaleError · 돌려받는 것 = 판 +1 정의 */
export const saveStructureDef = (판: number, 정의: StructDef): Promise<StructDef> =>
call("/structure-definition", { method: "PUT", body: JSON.stringify({ 판, 정의 }) });
/** 지난 판 목록(`구조물정의_이력/판_N.json`) */
export const fetchStructureDefHistory = (): Promise<DefVersion[]> =>
call("/structure-definition/history");
export const fetchStructureDefAt = (판: number): Promise<StructDef> =>
call(`/structure-definition/history/${판}`);
@@ -1,225 +0,0 @@
"""구조물 표 검사(PLAN 322-2 · 1-3 규칙) — 반영 · 부품 꼴 · 표 줄과 부품이 맞음 · 만든 뒤 고정.
- 반영 = `{종류: {목록 · 횡단도 · 카드이름 · 형상 · 형상칸 · 3D}}` · 값 = 부품 상자에 있는 것
- 부품 = `{"갈래.부품": false}`(끈 것만)
- 표 줄(정의 ⊕ 처음값) — 형상 none 이면 횡단도도 none(218) · 부품 자리꼴 · 정본 = 그 종류 줄 ·
부품이 읽는 칸 중 기본값 없는 칸(비워 두는 뜻 칸 빼고)은 새로 숨기지 못함(정의 「표시」 · 숨기면
그림이 늘 기본값을 씀 · 앞 판에서 이미 숨긴 칸은 그대로 둠)
- 앞 판이 없으면(옛 판 읽기) 꼴만 검사
- 앞 판과 비교 — 종류 지우기 없음 · 자리꼴 · 정본 · 군 글자 고정 · 선택지 값 고정(이름은 이름 표로)
화면 짝 = `M02_SO_Def_Check.ts`(같은 글)
거울 시험 = `resources/tester/test_322_2_check_mirror.py`.
"""
from __future__ import annotations
import re
from typing import Any
from common_util.common_util_structure_catalog import load_parts, resolve_catalog
BRANCHES = ("횡단도", "카드이름", "형상", "3D")
# 화면 글(322-2 다듬기 · TS `M02_SO_Def_Reflect` 짝) — 자리꼴 · 정본 한국어 · 부품 짧은 이름
PLACE_KO = {"point": "점", "interval": "구간", "site": "터"}
OWNER_KO = {"pipe_points": "관 지점", "structures": "구조물"}
def short_name(full: str) -> str:
"""괄호 설명을 뗀 부품 이름(TS `shortName` 짝)."""
return re.sub(r"\s*\(.*\)\s*$", "", full)
OFF_VALUE = {"횡단도": "none", "카드이름": "name", "형상": "none", "3D": "none"}
LISTS = ("both", "b06", "hidden")
_FIELDS = {"목록", "형상칸", *BRANCHES}
def _shape_errors(doc: dict[str, Any], known: set[str]) -> list[str]:
"""반영 · 부품 꼴."""
parts = load_parts()["parts"]
out: list[str] = []
reflect = doc.get("반영", {})
if not isinstance(reflect, dict):
out.append("반영은 {종류: 묶음} 이어야 함")
else:
for tid, row in reflect.items():
if tid not in known or not isinstance(row, dict):
out.append(f"반영 「{tid}」 — 없는 종류이거나 묶음 아님")
continue
for field, value in row.items():
where = f"반영 「{tid}.{field}」"
if field not in _FIELDS:
out.append(f"{where} — 모르는 칸")
elif field == "목록":
if value not in LISTS:
out.append(f"{where} — both · b06 · hidden 중 하나")
elif field == "형상칸":
ok = isinstance(value, dict) and all(
(isinstance(v, str) and bool(v.strip()))
if k == "form"
else (k == "weep" and isinstance(v, bool))
for k, v in value.items()
)
if not ok:
out.append(f"{where} — form 글 · weep 참거짓")
elif not isinstance(value, str) or (
value != OFF_VALUE[field] and value not in parts[field]
):
shown = value if isinstance(value, str) else _js(value)
out.append(f"{where} — 없는 부품 「{shown}」")
off = doc.get("부품", {})
if not isinstance(off, dict):
out.append("부품은 {갈래.부품: 참거짓} 이어야 함")
else:
for key, value in off.items():
branch, _, part = key.partition(".")
if part not in parts.get(branch, {}):
out.append(f"부품 「{key}」 — 없는 부품")
elif not isinstance(value, bool):
out.append(f"부품 「{key}」 — 참거짓")
return out
def _js(value: Any) -> str:
"""TS `String(value)` 와 같은 글(검사 글 짝)."""
if value is None:
return "null"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (list, tuple)):
return ",".join(_js(v) for v in value)
if isinstance(value, dict):
return "[object Object]"
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value)
def _hidden_in(doc: dict[str, Any] | None, tid: str) -> list[str]:
row = ((doc or {}).get("표시") or {}).get(tid) or {}
return [key for key, shown in row.items() if shown is False]
def _row_errors(doc: dict[str, Any], before: dict[str, Any] | None) -> list[str]:
"""표 줄 — 218 규칙 · 부품 자리꼴 · 정본 · 읽는 칸 보임(새로 숨김만)."""
parts = load_parts()["parts"]
rows = resolve_catalog(doc)
raw = resolve_catalog({**doc, "부품": {}}) # 부품 끄기 전 — 끈 탓 가름(323-9)
off_users: dict[str, list[str]] = {} # 끈 형상 부품 → 횡단도를 바꿔야 하는 종류
out: list[str] = []
for t in doc.get("types") or []:
row = rows.get(t["type_id"])
if row is None:
continue
if row["shape"] == "none" and row["station"] != "none":
was = raw[t["type_id"]]["shape"]
if was != "none" and (doc.get("부품") or {}).get(f"형상.{was}") is False:
label = f"{row['groupName']} · {row['name']}"
off_users.setdefault(was, []).append(label)
else:
out.append(f"「{row['name']}」 형상이 「없음」이면 횡단도도 「안 만듦」")
# 앞 판 없음 = 새로 숨긴 것 없음 · 복사한 종류 = 본보기가 앞 판에서 숨긴 칸도 그대로(323-7)
kept = [k for tid in (t["type_id"], row["base"]) for k in _hidden_in(before or doc, tid)]
hidden = [key for key in _hidden_in(doc, t["type_id"]) if key not in kept]
# 숨기면 그림이 기본값을 씀 — 기본값도 비워 두는 뜻도 없는 칸만 못 숨김
keys = {
o["key"]
for o in t.get("options") or []
if o.get("default") is None and not o.get("empty_means")
}
used = (
("횡단도", row["station"]),
("카드이름", row["title"]),
("형상", row["shape"]),
("3D", row["model3d"]),
)
labels = {o["key"]: o.get("label") or o["key"] for o in t.get("options") or []}
for branch, part_id in used:
part = parts[branch].get(part_id)
if part is None:
continue
name = short_name(part["이름"])
place = PLACE_KO.get(row["placement"], row["placement"])
owner = OWNER_KO.get(row["owner"], row["owner"])
if row["placement"] not in part["자리꼴"] or row["owner"] not in part["정본"]:
out.append(f"「{row['name']}」 {branch} 「{name}」 — {place} · {owner}에 안 맞음")
for key in part["읽는 칸"]:
if key in keys and key in hidden:
out.append(
f"「{row['name']}」 {branch} 「{name}」 이 쓰는 칸 「{labels[key]}」 — "
"숨길 수 없음"
)
for part_id, names in off_users.items():
name = short_name((parts["형상"].get(part_id) or {}).get("이름", part_id))
out.append(
f"부품 「{name}」 끔 — 이 부품을 쓰는 종류({', '.join(names)})의 "
"횡단도를 「안 만듦」으로 바꿔야 저장"
)
return out
def _template_errors(doc: dict[str, Any]) -> list[str]:
"""본보기(복사한 종류 · 323-7) — 원본(구조물 정본 · 본보기 아닌 종류) · 같은 군 · 자리꼴 ·
정본(TS 짝)."""
out: list[str] = []
kinds = doc.get("종류") or {}
now = {t["type_id"]: t for t in doc.get("types") or []}
for tid, row in kinds.items():
src = (row or {}).get("본보기") if isinstance(row, dict) else None
if src is None or tid not in now:
continue
t, base = now[tid], now.get(src)
name = t.get("name") or tid
if base is None or src == tid or (kinds.get(src) or {}).get("본보기"):
out.append(f"「{name}」 본보기 「{src}」 — 원본 종류여야 함")
continue
same = all(
t.get(k) == base.get(k) for k in ("group", "placement", "managed_by")
) and not base.get("managed_by")
if not same:
out.append(
f"「{name}」 본보기 「{base.get('name') or src}」 와 군 · 자리꼴 · 정본이 같아야 함"
)
return out
def _fixed_errors(doc: dict[str, Any], before: dict[str, Any]) -> list[str]:
"""앞 판과 비교 — 만든 뒤 고정."""
out: list[str] = []
now = {t["type_id"]: t for t in doc.get("types") or []}
base_of = lambda d, tid: ((d.get("종류") or {}).get(tid) or {}).get("본보기") # noqa: E731
for old in before.get("types") or []:
tid = old["type_id"]
name = old.get("name") or tid
t = now.get(tid)
if t is None:
out.append(f"종류 「{name}」 — 지울 수 없음")
continue
fixed = (
("자리꼴", old.get("placement"), t.get("placement")),
("정본", old.get("managed_by"), t.get("managed_by")),
("군 글자", old.get("group"), t.get("group")),
("본보기", base_of(before, tid), base_of(doc, tid)),
)
for what, a, b in fixed:
if a != b:
out.append(f"「{name}」 {what} — 만든 뒤 고정")
options = {o["key"]: o for o in t.get("options") or []}
for o in old.get("options") or []:
n = options.get(o["key"])
if o.get("input") != "select" or n is None:
continue
if sorted(o.get("choices") or []) != sorted(n.get("choices") or []):
label = o.get("label") or o["key"]
out.append(f"「{name}」 「{label}」 선택지 값 — 고칠 수 없음(이름만 고침)")
return out
def catalog_errors(doc: dict[str, Any], before: dict[str, Any] | None) -> list[str]:
"""구조물 표 검사 — 틀린 것 글들(빈 목록 = 통과). `before` = 지금 판(없으면 고정 검사 안 함)."""
known = {t["type_id"] for t in doc.get("types") or [] if isinstance(t, dict)}
shape = _shape_errors(doc, known)
if shape:
return shape
templates = _template_errors(doc)
return templates + (_row_errors(doc, before) + _fixed_errors(doc, before) if before else [])
@@ -1,418 +0,0 @@
/* =============================================================================
* M02_SO_Def.ts
* 구조물 정의 편집 화면(PLAN 48-2 · 메인 칸) — 탭 셋(322-2): 「한눈 표」(종류마다 반영 한 줄 ·
* `M02_SO_Def_Table`) · 「종류별」(왼쪽 구조물군 · 종류 목록 · 오른쪽 고른 종류 이름 · 반영 · 명세 이름 나무 ·
* 줄마다 보임 · 미리보기) · 「부품」(`M02_SO_Def_Parts`) ·
* 아래 검사(화면 = 서버 짝 `M02_SO_Def_Check`) · [저장](판 +1 · 목록 + enabled 함께 · 시스템 관리자만) ·
* 지난 판 목록(누르면 그 판을 읽기만으로 봄).
* 다른 역할은 읽기만. 고칠 사본은 저장 전까지 서버에 안 감 · 정본 = `구조물정의.json`(48-1).
* ========================================================================== */
import { createButton, createTag, el, showToast } from "@ui/ui_template_elements";
import { StaleError } from "../M02_MasterTemplete_Api_Fetch";
import {
fetchStructureDef,
fetchStructureDefAt,
fetchStructureDefHistory,
saveStructureDef,
type DefVersion,
} from "./M02_SO_Api";
import { buildLayoutBlock } from "./M02_SO_Def_Layout";
import {
baseShown,
clone,
problems,
stepFamily,
stepType,
type StructDef,
} from "./M02_SO_Def_Model";
import { buildOptionsBlock } from "./M02_SO_Def_Options";
import { buildRulesBlock } from "./M02_SO_Def_Rules";
import { buildSpecBlock } from "./M02_SO_Def_Spec";
import { specFor } from "../../A00_Common/design/logic/design_structure_pipe";
import { catalogProblems, type CheckDef } from "./M02_SO_Def_Check";
import { buildParts } from "./M02_SO_Def_Parts";
import { differs, setReflect, tidy } from "./M02_SO_Def_Reflect";
import { buildReflectBlock, buildTable } from "./M02_SO_Def_Table";
import { checkBox, pickBox, textBox } from "./M02_SO_Def_Ui";
import { addFromTemplate, templates } from "./M02_SO_Def_Add";
import { buildGroupBlock } from "./M02_SO_Groups";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
import { createTabs } from "@ui/ui_template_tabs";
import { dateTimeText } from "../../common_util/common_util_time";
/** 옛 편집기(옵션 · 배치 · 그룹 · 규칙 · 기준 측점) — 모든 종류에서 숨김(52-12 · 정의 화면 = 이름만) */
const OLD_EDITOR = false;
export interface DefScreenOptions {
/** 시스템 관리자 — 아니면 읽기만 */
isAdmin: boolean;
/** 메인 칸에 화면을 띄움 — 고침 표시 손잡이를 돌려받음 */
show: (label: string, node: HTMLElement) => (dirty: boolean) => void;
}
const why = (error: unknown): string => (error instanceof Error ? error.message : "");
/** 작은 단추 */
function smallButton(
label: string,
run: () => void,
off = false,
variant: "ghost" | "danger" = "ghost",
): HTMLButtonElement {
const b = createButton({ label, variant, size: "sm" });
b.disabled = off;
b.addEventListener("click", run);
return b;
}
/** 화면을 받아 띄움 — 못 받으면 알림만 · 띄웠으면 참 */
export async function openDefScreen(opt: DefScreenOptions): Promise<boolean> {
let def: StructDef;
try {
def = await fetchStructureDef();
} catch (error) {
showToast(to("Load_Failed", why(error)), "error");
return false;
}
drawDef(def, opt);
return true;
}
function drawDef(first: StructDef, opt: DefScreenOptions): void {
/** 지금 판(서버) · 고칠 사본 · 보는 지난 판(있으면 읽기만) */
let base = first;
let work = clone(first);
let past: StructDef | null = null;
let dirty = false;
let current: string | null = null;
const open = new Set<string>(); // 선택지를 펼친 옵션
let versions: DefVersion[] | null = null;
type Tab = "table" | "kinds" | "parts";
let tab: Tab = "table";
const shown = (): StructDef => past ?? work;
const canEdit = (): boolean => opt.isAdmin && !past;
const kindList = el("div", { className: "m02-opts__kinds", attrs: { "data-sod-kinds": "" } });
const detail = el("div", { className: "m02-opts__list", attrs: { "data-sod-detail": "" } });
// 판 띠 = 띠 알림 부품 꼴(정보 · 지난 판 = 경고)
const banner = el("div", {
className: "ui-banner ui-banner--info m02-sod__banner",
attrs: { "data-sod-banner": "" },
});
const issues = el("div", { className: "m02-sod__issues", attrs: { "data-sod-issues": "" } });
const historyBox = el("div", {
className: "m02-sod__history",
attrs: { "data-sod-history": "" },
});
/** 검사 글 — 이름 · 배치 · 규칙(`problems`) + 구조물 표(서버 짝 · 앞 판 = 지금 서버 판) */
const allProblems = (): string[] =>
past ? [] : [...problems(work), ...catalogProblems(work as CheckDef, base as CheckDef)];
const tabBar = el("div", { className: "m02-sod__tabs", attrs: { "data-sod-tabs": "" } });
const body = el("div", { className: "m02-sod__body" });
const panes = el("div", { className: "m02-opts__panes", children: [kindList, detail] });
const changed = (): void => {
dirty = differs(work, base);
sync();
paint();
};
const paintKinds = (): void => {
const d = shown();
const edit = canEdit();
const parts: HTMLElement[] = [];
// 종류 더하기(323-7) — 본보기 고름 + 단추 · 새 종류를 골라 둠(이름 · 반영은 오른쪽에서 고침)
if (edit) {
const pairs = templates(d);
let pick = pairs.find(([key]) => key === current)?.[0] ?? pairs[0]?.[0] ?? "";
const box = pickBox(pairs, pick, (v) => (pick = v), { edit, attr: "data-sod-add-from" });
box.title = to("AddKindNote");
const add = smallButton(to("AddKind"), () => {
const key = addFromTemplate(d, pick);
if (!key) return;
current = key;
changed();
});
add.setAttribute("data-sod-add", "");
parts.push(el("div", { className: "m02-sod__family", children: [box, add] }));
}
const families = Object.keys(d.구조물군);
families.forEach((g, gi) => {
parts.push(
el("div", {
className: "m02-sod__family",
attrs: { "data-sod-family": g },
children: [
textBox(d.구조물군[g], (v) => (d.구조물군[g] = v), changed, {
edit,
attr: "data-sod-family-name",
}),
...(edit
? [
smallButton(to("GroupUp"), () => stepFamily(d, g, -1) && changed(), gi === 0),
smallButton(
to("GroupDown"),
() => stepFamily(d, g, 1) && changed(),
gi === families.length - 1,
),
]
: []),
],
}),
);
const kinds = d.types.filter((t) => t.group === g);
kinds.forEach((t, ti) => {
const off = t.enabled === false;
const groups = d.그룹[t.type_id]?.length ?? 0;
const b = el("button", {
className: `m02-opts__kind ui-list-row ui-sidebar-row${t.type_id === current ? " is-active" : ""}${off ? " is-off" : ""}`,
attrs: { type: "button", "data-sod-kind": t.type_id, "data-size": "32" },
children: [
el("span", { text: t.name }),
...(groups ? [createTag(to("GroupTag", String(groups)), "accent")] : []),
...(off ? [createTag(to("Off"), "neutral")] : []),
],
});
b.addEventListener("click", () => {
current = t.type_id;
paint();
});
parts.push(
el("div", {
className: "m02-sod__kindrow",
children: [
b,
...(edit
? [
smallButton(
to("GroupUp"),
() => stepType(d, t.type_id, -1) && changed(),
ti === 0,
),
smallButton(
to("GroupDown"),
() => stepType(d, t.type_id, 1) && changed(),
ti === kinds.length - 1,
),
]
: []),
],
}),
);
});
});
kindList.replaceChildren(...parts);
};
const paintDetail = (): void => {
const d = shown();
const type = d.types.find((t) => t.type_id === current);
if (!type) {
detail.replaceChildren(createEmpty({ text: to("Pick"), small: true }));
return;
}
const edit = canEdit();
const extra = (): NonNullable<StructDef["종류"][string]> => (d.종류[type.type_id] ??= {});
// 이름만 고침(PLAN 52-11 · 52-12) — 명세 종류 = 명세 나무 · 나머지 = 정의 그룹 나무
const spec = specFor(type.type_id);
detail.replaceChildren(
el("div", {
className: "m02-sod__kindhead",
children: [
textBox(type.name, (v) => (type.name = v), changed, {
edit,
attr: "data-sod-kind-name",
cls: "m02-sod__name",
}),
el("small", { className: "ui-text ui-text--muted m02-opts__key", text: type.type_id }),
// 안 씀 = 목록 B06 만(enabled 는 목록 짝 · 322-2) · 숨김(hidden)은 한눈 표 목록 칸에서
checkBox(
to("Unused"),
type.enabled === false,
(v) => (setReflect(d, type.type_id, "목록", v ? "b06" : "both"), changed()),
{ edit, attr: "data-sod-kind-off" },
),
...(!OLD_EDITOR
? []
: [
checkBox(
to("BaseStationShow"),
baseShown(d, type.type_id),
(v) => {
if (v) delete extra().기준측점;
else extra().기준측점 = false;
changed();
},
{ edit, attr: "data-sod-base" },
),
]),
...(d.종류[type.type_id]?.동작 ?? []).map((a) => {
const tag = createTag(a, "neutral");
tag.title = d.동작[a] ?? "";
return tag;
}),
],
}),
...(!OLD_EDITOR
? [
buildReflectBlock(d, type, edit, changed),
buildSpecBlock({ def: d, base, type, spec, edit, changed }),
]
: [
buildOptionsBlock({ def: d, type, edit, open, changed }),
buildLayoutBlock({ def: d, type, edit, changed }),
buildGroupBlock({ list: (d.그룹[type.type_id] ??= []), edit, changed }),
buildRulesBlock({ def: d, type, edit, changed }),
]),
);
};
const paintTabs = (): void => {
const pairs: Array<[Tab, string]> = [
["table", to("TabTable")],
["kinds", to("TabKinds")],
["parts", to("TabParts")],
];
// 탭 부품(보조 탭) — 칸마다 data-sod-tab 그대로
const tabs = createTabs({
kind: "pill",
tabs: pairs.map(([key, label]) => ({ key, label })),
value: tab,
onChange: (key) => ((tab = key as Tab), paint()),
});
tabs.root.querySelectorAll<HTMLElement>("[data-tab]").forEach((b) => {
b.setAttribute("data-sod-tab", b.dataset.tab ?? "");
});
tabBar.replaceChildren(tabs.root);
const edit = canEdit();
if (tab === "table")
body.replaceChildren(buildTable({ def: shown(), edit, changed, issues: allProblems() }));
else if (tab === "parts") body.replaceChildren(buildParts({ def: shown(), edit, changed }));
else body.replaceChildren(panes);
};
const paintFoot = (): void => {
banner.replaceChildren(
...(past
? [
el("span", { text: to("PastView", String(past.판)) }),
smallButton(to("PastBack"), () => ((past = null), paint(), paintHistory())),
]
: [
el("span", { text: to("Version", String(base.판)) }),
...(opt.isAdmin ? [] : [createTag(to("ReadOnly"), "neutral")]),
]),
);
banner.classList.toggle("is-past", !!past);
banner.classList.toggle("ui-banner--warning", !!past);
banner.classList.toggle("ui-banner--info", !past);
const list = allProblems();
issues.replaceChildren(...list.map((t) => createText(t, "error")));
save.disabled = !opt.isAdmin || !!past || !dirty || list.length > 0;
};
const paint = (): void => {
paintKinds();
paintDetail();
paintTabs();
paintFoot();
};
const reload = async (): Promise<void> => {
try {
base = await fetchStructureDef();
work = clone(base);
dirty = false;
sync();
} catch (again) {
showToast(to("Load_Failed", why(again)), "error");
}
};
const save = createButton({ label: to("Save"), variant: "filled" });
save.setAttribute("data-sod-save", "");
save.addEventListener("click", async () => {
if (allProblems().length) return;
save.disabled = true; // 연달아 눌러도 한 번만
try {
base = await saveStructureDef(base.판, tidy(work));
work = clone(base);
dirty = false;
versions = null;
sync();
showToast(to("SavedVersion", String(base.판)), "success");
} catch (error) {
if (error instanceof StaleError) {
showToast(to("Stale"), "error");
await reload();
} else showToast(to("Failed", why(error)), "error");
} finally {
paint();
paintHistory();
}
});
/** 지난 판 목록 — 펼칠 때 받음 · 누르면 그 판을 읽기만으로 */
const paintHistory = (): void => {
if (!versions) return historyBox.replaceChildren();
historyBox.replaceChildren(
...(versions.length
? versions.map((v) => {
const b = createButton({
label: to("PastItem", `${v.판} · ${dateTimeText(v.저장일)}`),
variant: past?.판 === v.판 ? "filled" : "ghost",
size: "sm",
});
b.setAttribute("data-sod-past", String(v.판));
b.addEventListener("click", async () => {
try {
past = await fetchStructureDefAt(v.판);
} catch (error) {
return showToast(to("Load_Failed", why(error)), "error");
}
paint();
paintHistory();
});
return b;
})
: [createEmpty({ text: to("PastNone"), small: true })]),
);
};
const history = createButton({ label: to("PastList"), variant: "ghost" });
history.setAttribute("data-sod-history-toggle", "");
history.addEventListener("click", async () => {
if (versions) {
versions = null;
return paintHistory();
}
try {
versions = (await fetchStructureDefHistory()).sort((a, b) => b.판 - a.판);
} catch (error) {
return showToast(to("Load_Failed", why(error)), "error");
}
paintHistory();
});
const node = el("div", {
className: "m02-opts m02-sod",
children: [
createText(to("DefNote")),
banner,
tabBar,
body,
issues,
el("div", {
className: "m02-side__row",
children: [...(opt.isAdmin ? [save] : []), history],
}),
historyBox,
],
});
const setDirty = opt.show(to("Screen"), node);
const sync = (): void => setDirty(dirty);
paint();
}
@@ -1,45 +0,0 @@
/* =============================================================================
* M02_SO_Def_Add.ts
* 종류 더하기(PLAN 323-7) — 본보기(구조물 정본 원본 종류)를 그대로 복사한 새 종류.
*
* 키 자동(`{본보기}_xxxxxx` · 만든 뒤 안 바뀜) · 이름 「{본보기} 2」(겹치면 3 …) · 군 · 자리꼴 · 옵션 · 표시 · 그룹 ·
* 배치 · 규칙 · 종류 덧칸(동작 · 이름 표) · 반영 그대로 · `종류.{새}.본보기 = 원본` — 구조물 표가 본보기 처음값을
* 이어받고(`resolveCatalog` · 일곱 갈래 = 목록 · 횡단도 · 카드이름 · 형상 · 형상칸 · 3D · 자리꼴), 손코딩 동작 ·
* 명세도 본보기 키로 고름(`baseType`). 관 지점 정본 종류는 본보기에서 뺌(관 시설 폼 · 정본 목록이 따로).
* ========================================================================== */
import { clone, newKey, type StructDef } from "./M02_SO_Def_Model";
/** 본보기로 고를 수 있는 종류 — 구조물 정본 · 원본(본보기 아님) · [키, 이름] (정의 차례). */
export const templates = (def: StructDef): Array<[string, string]> =>
def.types
.filter((t) => !t.managed_by && !def.종류[t.type_id]?.본보기)
.map((t) => [t.type_id, t.name] as [string, string]);
/** 본보기를 복사해 그 뒤에 새 종류를 끼움 — 새 키(못 하면 null). */
export function addFromTemplate(def: StructDef, sourceId: string): string | null {
const index = def.types.findIndex((t) => t.type_id === sourceId);
const src = def.types[index];
if (!src || src.managed_by || def.종류[sourceId]?.본보기) return null;
const key = newKey(
`${sourceId}_`,
def.types.map((t) => t.type_id),
);
const names = new Set(def.types.map((t) => t.name));
let n = 2;
while (names.has(`${src.name} ${n}`)) n += 1;
const copy = clone(src);
copy.type_id = key;
copy.name = `${src.name} ${n}`;
delete copy.drawing_views; // 안 읽는 칸(323-7)
def.types.splice(index + 1, 0, copy);
def.종류[key] = { ...clone(def.종류[sourceId] ?? {}), 본보기: sourceId };
for (const table of [def.표시, def.그룹, def.배치] as Array<Record<string, unknown>>)
if (table[sourceId] !== undefined) table[key] = clone(table[sourceId]);
def.규칙.push(
...def.규칙.filter((r) => r.종류 === sourceId).map((r) => ({ ...clone(r), 종류: key })),
);
const reflect = (def as { 반영?: Record<string, unknown> }).반영;
if (reflect?.[sourceId] !== undefined) reflect[key] = clone(reflect[sourceId]);
return key;
}
@@ -1,243 +0,0 @@
/* =============================================================================
* M02_SO_Def_Check.ts
* 구조물 표 검사(PLAN 322-2 · 1-3 규칙) — 정의 `반영` · `부품` 꼴 · 표 줄과 부품이 맞음 · 만든 뒤 고정.
*
* · 반영 = `{종류: {목록 · 횡단도 · 카드이름 · 형상 · 형상칸 · 3D}}` · 값 = 부품 상자에 있는 것
* · 부품 = `{"갈래.부품": false}`(끈 것만)
* · 표 줄(정의 ⊕ 처음값) — 형상 none 이면 횡단도도 none(218) · 부품 자리꼴 · 정본 = 그 종류 줄 ·
* 부품이 읽는 칸 중 기본값 없는 칸(비워 두는 뜻 칸 빼고)은 새로 숨기지 못함(정의 「표시」 · 숨기면
* 그림이 늘 기본값을 씀 · 앞 판에서 이미 숨긴 칸은 그대로 둠)
* · 앞 판이 없으면(옛 판 읽기) 꼴만 검사
* · 앞 판과 비교 — 종류 지우기 없음 · 자리꼴 · 정본 · 군 글자 고정 · 선택지 값 고정(이름은 이름 표로)
* 서버 짝 = `M02_SO_Check.py`(같은 글) · 거울 시험 = `resources/tester/test_322_2_check_mirror.py`.
* ========================================================================== */
import PARTS from "../../common_util/common_util_structure_parts.json" with { type: "json" };
import {
resolveCatalog,
type CatalogDefinition,
} from "../../common_util/common_util_structure_catalog";
import { OWNER_KO, PLACE_KO, shortName } from "./M02_SO_Def_Reflect";
type Branch = "횡단도" | "카드이름" | "형상" | "3D";
interface Part {
이름: string;
"읽는 칸": string[];
자리꼴: string[];
정본: string[];
}
const PARTS_BY = (PARTS as unknown as { parts: Record<Branch, Record<string, Part>> }).parts;
export const BRANCHES: readonly Branch[] = ["횡단도", "카드이름", "형상", "3D"];
/** 갈래마다 「없음」 값 — 카드이름은 종류 이름(name). */
export const OFF_VALUE: Record<Branch, string> = {
횡단도: "none",
카드이름: "name",
형상: "none",
"3D": "none",
};
export const LISTS = ["both", "b06", "hidden"] as const;
const FIELDS = new Set(["목록", "형상칸", ...BRANCHES]);
/** 검사가 읽는 정의 칸. */
export interface CheckDef extends CatalogDefinition {
types?: ReadonlyArray<{
type_id: string;
name?: string;
group?: string;
placement?: string;
managed_by?: string | null;
options?: ReadonlyArray<{
key: string;
input?: string;
choices?: readonly string[];
default?: unknown;
empty_means?: string | null;
label?: string;
}>;
}>;
표시?: Record<string, Record<string, boolean>>;
}
const isObject = (v: unknown): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v);
/** 부품 상자에 있는 부품 — 제 칸만(물려받은 이름 아님). */
const partOf = (branch: string, id: string): Part | undefined => {
const box = (PARTS_BY as Record<string, Record<string, Part>>)[branch];
return box && Object.hasOwn(box, id) ? box[id] : undefined;
};
/** 반영 · 부품 꼴. */
function shapeErrors(doc: CheckDef, known: Set<string>): string[] {
const out: string[] = [];
const reflect: unknown = doc.반영 ?? {};
if (!isObject(reflect)) out.push("반영은 {종류: 묶음} 이어야 함");
else
for (const [tid, row] of Object.entries(reflect)) {
if (!known.has(tid) || !isObject(row)) {
out.push(`반영 「${tid}」 — 없는 종류이거나 묶음 아님`);
continue;
}
for (const [field, value] of Object.entries(row)) {
const where = `반영 「${tid}.${field}」`;
if (!FIELDS.has(field)) out.push(`${where} — 모르는 칸`);
else if (field === "목록") {
if (!(LISTS as readonly unknown[]).includes(value))
out.push(`${where} — both · b06 · hidden 중 하나`);
} else if (field === "형상칸") {
const ok =
isObject(value) &&
Object.entries(value).every(([k, v]) =>
k === "form"
? typeof v === "string" && !!v.trim()
: k === "weep" && typeof v === "boolean",
);
if (!ok) out.push(`${where} — form 글 · weep 참거짓`);
} else {
const branch = field as Branch;
if (typeof value !== "string" || (value !== OFF_VALUE[branch] && !partOf(branch, value)))
out.push(`${where} — 없는 부품 「${String(value)}」`);
}
}
}
const parts: unknown = doc.부품 ?? {};
if (!isObject(parts)) out.push("부품은 {갈래.부품: 참거짓} 이어야 함");
else
for (const [key, value] of Object.entries(parts)) {
const at = key.indexOf(".");
if (at < 0 || !partOf(key.slice(0, at), key.slice(at + 1)))
out.push(`부품 「${key}」 — 없는 부품`);
else if (typeof value !== "boolean") out.push(`부품 「${key}」 — 참거짓`);
}
return out;
}
const hiddenIn = (doc: CheckDef | null, tid: string): string[] =>
Object.entries(doc?.표시?.[tid] ?? {})
.filter(([, shown]) => shown === false)
.map(([key]) => key);
/** 표 줄 — 218 규칙 · 부품 자리꼴 · 정본 · 읽는 칸 보임(새로 숨김만). */
function rowErrors(doc: CheckDef, before: CheckDef | null): string[] {
const out: string[] = [];
const rows = resolveCatalog(doc);
const raw = resolveCatalog({ ...doc, 부품: {} }); // 부품 끄기 전 — 끈 탓 가름(323-9)
const offUsers = new Map<string, string[]>(); // 끈 형상 부품 → 횡단도를 바꿔야 하는 종류
for (const t of doc.types ?? []) {
const row = rows.get(t.type_id);
if (!row) continue;
if (row.shape === "none" && row.station !== "none") {
const was = raw.get(t.type_id)?.shape ?? "none";
if (was !== "none" && doc.부품?.[`형상.${was}`] === false)
offUsers.set(was, [...(offUsers.get(was) ?? []), `${row.groupName} · ${row.name}`]);
else out.push(`「${row.name}」 형상이 「없음」이면 횡단도도 「안 만듦」`);
}
// 앞 판 없음 = 새로 숨긴 것 없음 · 복사한 종류 = 본보기가 앞 판에서 숨긴 칸도 그대로(323-7)
const kept = [t.type_id, row.base].flatMap((id) => hiddenIn(before ?? doc, id));
const hidden = hiddenIn(doc, t.type_id).filter((key) => !kept.includes(key));
// 숨기면 그림이 기본값을 씀 — 기본값도 비워 두는 뜻도 없는 칸만 못 숨김
const keys = new Set(
(t.options ?? [])
.filter((o) => (o.default === null || o.default === undefined) && !o.empty_means)
.map((o) => o.key),
);
const labelOf = (key: string): string =>
(t.options ?? []).find((o) => o.key === key)?.label ?? key;
const used: Array<[Branch, string]> = [
["횡단도", row.station],
["카드이름", row.title],
["형상", row.shape],
["3D", row.model3d],
];
for (const [branch, id] of used) {
const part = partOf(branch, id);
if (!part) continue;
const name = shortName(part.이름);
const place = PLACE_KO[row.placement] ?? row.placement;
const owner = OWNER_KO[row.owner] ?? row.owner;
if (!part.자리꼴.includes(row.placement) || !part.정본.includes(row.owner))
out.push(`「${row.name}」 ${branch} 「${name}」 — ${place} · ${owner}에 안 맞음`);
for (const key of part["읽는 칸"])
if (keys.has(key) && hidden.includes(key))
out.push(
`「${row.name}」 ${branch} 「${name}」 이 쓰는 칸 「${labelOf(key)}」 — 숨길 수 없음`,
);
}
}
offUsers.forEach((names, id) =>
out.push(
`부품 「${shortName(partOf("형상", id)?.이름 ?? id)}」 끔 — 이 부품을 쓰는 종류(${names.join(", ")})의 ` +
"횡단도를 「안 만듦」으로 바꿔야 저장",
),
);
return out;
}
/** 앞 판과 비교 — 만든 뒤 고정. */
/** 본보기(복사한 종류 · 323-7) — 원본(구조물 정본 · 본보기 아닌 종류) · 같은 군 · 자리꼴 · 정본(파이썬 짝). */
function templateErrors(doc: CheckDef): string[] {
const out: string[] = [];
const kinds = doc.종류 ?? {};
const now = new Map((doc.types ?? []).map((t) => [t.type_id, t]));
for (const [tid, row] of Object.entries(kinds)) {
const src = row?.본보기;
const t = now.get(tid);
if (src == null || !t) continue;
const base = now.get(src);
const name = t.name || tid;
if (!base || src === tid || kinds[src]?.본보기) {
out.push(`「${name}」 본보기 「${src}」 — 원본 종류여야 함`);
continue;
}
const same =
(["group", "placement", "managed_by"] as const).every(
(k) => (t[k] ?? null) === (base[k] ?? null),
) && !base.managed_by;
if (!same)
out.push(`「${name}」 본보기 「${base.name || src}」 와 군 · 자리꼴 · 정본이 같아야 함`);
}
return out;
}
function fixedErrors(doc: CheckDef, before: CheckDef): string[] {
const out: string[] = [];
const now = new Map((doc.types ?? []).map((t) => [t.type_id, t]));
const baseOf = (d: CheckDef, tid: string) => d.종류?.[tid]?.본보기 ?? null;
for (const old of before.types ?? []) {
const t = now.get(old.type_id);
const name = old.name ?? old.type_id;
if (!t) {
out.push(`종류 「${name}」 — 지울 수 없음`);
continue;
}
const fixed: Array<[string, unknown, unknown]> = [
["자리꼴", old.placement, t.placement],
["정본", old.managed_by ?? null, t.managed_by ?? null],
["군 글자", old.group, t.group],
["본보기", baseOf(before, old.type_id), baseOf(doc, old.type_id)],
];
for (const [what, a, b] of fixed) if (a !== b) out.push(`「${name}」 ${what} — 만든 뒤 고정`);
const options = new Map((t.options ?? []).map((o) => [o.key, o]));
for (const o of old.options ?? []) {
const n = options.get(o.key);
if (o.input !== "select" || !n) continue;
const a = [...(o.choices ?? [])].sort().join("\u0000");
const b = [...(n.choices ?? [])].sort().join("\u0000");
if (a !== b)
out.push(`「${name}」 「${o.label ?? o.key}」 선택지 값 — 고칠 수 없음(이름만 고침)`);
}
}
return out;
}
/** 구조물 표 검사 — 틀린 것 글들(빈 목록 = 통과). `before` = 지금 서버 판(없으면 고정 검사 안 함). */
export function catalogProblems(doc: CheckDef, before: CheckDef | null): string[] {
const known = new Set((doc.types ?? []).map((t) => t.type_id));
const shape = shapeErrors(doc, known);
if (shape.length) return shape;
const templates = templateErrors(doc);
return [
...templates,
...(before ? [...rowErrors(doc, before), ...fixedErrors(doc, before)] : []),
];
}
@@ -1,120 +0,0 @@
/* =============================================================================
* M02_SO_Def_Layout.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **배치 격자**(B05 · B06 좌측 구조물 칸 = 두 칸)
* 옵션마다 줄 · 칸 · 너비 + 미리보기(기준 측점은 맨 위 한 줄 · 겹치면 빨강).
* 자리를 안 정한 옵션은 차례대로 빈 칸을 채움 · 숫자를 고치면 그 옵션 자리만 정의 `배치` 에 남음.
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import {
baseShown,
GRID_COLS,
live,
overlaps,
placeAll,
type Spot,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { head, numberBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
export interface LayoutBlockOptions {
def: StructDef;
type: TypeDef;
edit: boolean;
changed: () => void;
}
const ROW_MAX = 60;
/** 미리보기 — 두 칸 격자 · 옵션마다 상자 */
function preview(def: StructDef, type: TypeDef, cells: Map<string, Spot>): HTMLElement {
const bad = new Set(overlaps(cells));
const base = baseShown(def, type.type_id);
const offset = base ? 1 : 0;
const boxes: HTMLElement[] = [];
if (base)
boxes.push(
el("div", {
className: "m02-sod__cell is-base",
text: to("BaseStation"),
attrs: { style: `grid-row: 1; grid-column: 1 / span ${GRID_COLS}` },
}),
);
for (const o of live(type.options)) {
const c = cells.get(o.key)!;
boxes.push(
el("div", {
className: `m02-sod__cell${bad.has(o.key) ? " is-bad" : ""}`,
text: o.label,
attrs: {
"data-sod-cell": o.key,
title: o.label,
style: `grid-row: ${c.줄 + offset}; grid-column: ${c.칸} / span ${c.너비}`,
},
}),
);
}
return el("div", {
className: "m02-sod__grid",
attrs: {
"data-sod-preview": "",
style: `grid-template-columns: repeat(${GRID_COLS}, minmax(0, 1fr))`,
},
children: boxes,
});
}
export function buildLayoutBlock(opt: LayoutBlockOptions): HTMLElement {
const { def, type, edit, changed } = opt;
const cells = placeAll(type.options, def.배치[type.type_id]);
const rows = live(type.options).map((o) => {
const c = cells.get(o.key)!;
const fix = (patch: Partial<Spot>): void => {
(def.배치[type.type_id] ??= {})[o.key] = { ...c, ...patch };
changed();
};
return el("div", {
className: "m02-sod__place",
attrs: { "data-sod-place-row": o.key },
children: [
el("span", { className: "m02-sod__placename", text: o.label }),
el("small", { text: to("GridRow") }),
numberBox(c.줄, (n) => fix({ 줄: n }), {
edit,
min: 1,
max: ROW_MAX,
attr: "data-sod-row",
}),
el("small", { text: to("GridCol") }),
numberBox(c.칸, (n) => fix({ 칸: n }), {
edit,
min: 1,
max: GRID_COLS,
attr: "data-sod-col",
}),
el("small", { text: to("GridWidth") }),
numberBox(c.너비, (n) => fix({ 너비: n }), {
edit,
min: 1,
max: GRID_COLS,
attr: "data-sod-width",
}),
],
});
});
return el("div", {
className: "m02-sod__block",
children: [
...head(to("LayoutHead"), to("LayoutNote")),
el("div", {
className: "m02-sod__layout",
children: [
el("div", { className: "m02-sod__places", children: rows }),
preview(def, type, cells),
],
}),
],
});
}
@@ -1,277 +0,0 @@
/* =============================================================================
* M02_SO_Def_Model.ts
* 구조물 정의 편집 화면(PLAN 48-2)의 자료 꼴 · 순수 손질 함수 — 화면 그리기 없음.
* 정본 = 마스터 템플릿 `구조물정의.json`(48-1 · 틀 `docs/raw/M02_구조물옵션정의/정의_틀.md`).
* 키는 만들 때 자동 · 안 바뀜 · 이름 자유 · 지움 = 「안 씀」(`enabled: false`).
* 선택지는 글 그대로가 값 — 이름을 바꾸면 이 정의 안의 기본값 · 규칙도 같이 바꿈.
* ========================================================================== */
export type OptionForm = "select" | "number" | "text" | "bool";
export interface Spot {
줄: number;
칸: number;
너비: number;
}
export interface OptionDef {
key: string;
label: string;
input: OptionForm;
choices?: string[];
unit?: string | null;
default?: unknown;
enabled?: boolean;
phase?: "b05" | "detail";
[more: string]: unknown;
}
export interface TypeDef {
type_id: string;
group: string;
name: string;
options: OptionDef[];
enabled?: boolean;
[more: string]: unknown;
}
export type ShapeKey = "길이" | "높이" | "전" | "후";
export const SHAPE_KEYS: readonly ShapeKey[] = ["길이", "높이", "전", "후"];
export interface GroupDef {
id: string;
이름: string;
옵션: string[];
형상?: Partial<Record<ShapeKey, { 받기: boolean; 뜻: string }>>;
}
/** 만약 상위 옵션 = 값들 중 하나 → 하위 옵션의 선택지 · 보이기 · 기본값(하나 이상) */
export interface RuleDef {
종류: string;
만약: { 옵션: string; 값들: string[] };
그러면: { 옵션: string; 선택지?: string[]; 보이기?: boolean; 기본값?: unknown };
}
export interface StructDef {
판: number;
구조물군: Record<string, string>;
동작: Record<string, string>;
types: TypeDef[];
/** 이름 = 구조물 명세 이름 바꿈 표(PLAN 52 · 키 `{컨테이너}[.{항목}[={값}]]`) */
/** 본보기 = 복사한 종류의 원본 키(323-7 · 만든 뒤 고정 · 처음값 · 손코딩 동작을 이어받음). */
종류: Record<
string,
{ 기준측점?: boolean; 동작?: string[]; 이름?: Record<string, string>; 본보기?: string }
>;
표시: Record<string, Record<string, false>>;
그룹: Record<string, GroupDef[]>;
배치: Record<string, Record<string, Spot>>;
규칙: RuleDef[];
[more: string]: unknown;
}
export const NAME_MAX = 40;
/** B05 · B06 좌측 구조물 칸 = 두 칸 격자 */
export const GRID_COLS = 2;
/** 깊은 사본 — 고칠 사본을 서버 문서와 떼어 놓음 */
export const clone = <T>(value: T): T => structuredClone(value);
/** 새 키 — 머리글 + 영문 소문자 · 숫자 6자 · 이미 있는 키와 안 겹침 */
export function newKey(prefix: string, taken: Iterable<string>): string {
const used = new Set(taken);
for (;;) {
const key = `${prefix}${Math.random().toString(36).slice(2, 8)}`;
if (key.length > prefix.length + 3 && !used.has(key)) return key;
}
}
/** 목록 안에서 한 칸 옮김 — 끝이면 그대로 · 옮겼으면 참 */
export function step<T>(list: T[], index: number, delta: number): boolean {
const at = index + delta;
if (index < 0 || at < 0 || at >= list.length) return false;
[list[index], list[at]] = [list[at], list[index]];
return true;
}
/** 쓰는 것만 — 「안 씀」(enabled 거짓) 뺌 */
export const live = <T extends { enabled?: boolean }>(list: readonly T[]): T[] =>
list.filter((x) => x.enabled !== false);
/** 기준 측점 칸 보이기 — 없으면 보임 */
export const baseShown = (def: StructDef, typeId: string): boolean =>
def.종류[typeId]?.기준측점 !== false;
/** 이름 검사 — 1~40자 · 같은 목록 안에서 안 겹침 · 틀린 이름들 */
export function badNames(names: readonly string[]): string[] {
const seen = new Set<string>();
const bad: string[] = [];
for (const raw of names) {
const name = raw.trim();
if (!name || name.length > NAME_MAX || seen.has(name)) bad.push(name || "(빈 이름)");
seen.add(name);
}
return bad;
}
/** 구조물군 순서 바꿈 — `{키: 이름}` 묶음의 키 차례 */
export function stepFamily(def: StructDef, key: string, delta: number): boolean {
const entries = Object.entries(def.구조물군);
if (
!step(
entries,
entries.findIndex(([k]) => k === key),
delta,
)
)
return false;
def.구조물군 = Object.fromEntries(entries);
return true;
}
/** 종류 순서 바꿈 — 같은 군 안 앞뒤 종류와 `types` 자리를 바꿈 */
export function stepType(def: StructDef, typeId: string, delta: number): boolean {
const t = def.types.find((x) => x.type_id === typeId);
if (!t) return false;
const same = def.types.filter((x) => x.group === t.group);
const other = same[same.indexOf(t) + delta];
if (!other) return false;
const i = def.types.indexOf(t);
const j = def.types.indexOf(other);
[def.types[i], def.types[j]] = [def.types[j], def.types[i]];
return true;
}
/** 선택지 이름 바꿈 — 그 옵션 기본값 · 이 종류 규칙의 값들 · 선택지 · 기본값도 같이 */
export function renameChoice(
def: StructDef,
typeId: string,
o: OptionDef,
from: string,
to: string,
): void {
if (from === to || !o.choices) return;
o.choices = o.choices.map((c) => (c === from ? to : c));
if (o.default === from) o.default = to;
for (const r of def.규칙) {
if (r.종류 !== typeId) continue;
if (r.만약.옵션 === o.key) r.만약.값들 = r.만약.값들.map((v) => (v === from ? to : v));
if (r.그러면.옵션 === o.key) {
if (r.그러면.선택지) r.그러면.선택지 = r.그러면.선택지.map((v) => (v === from ? to : v));
if (r.그러면.기본값 === from) r.그러면.기본값 = to;
}
}
}
/** 선택지 뺌 — 기본값 · 규칙에서도 뺌(규칙 값들이 비면 그 규칙은 검사에서 걸림) */
export function dropChoice(def: StructDef, typeId: string, o: OptionDef, value: string): void {
o.choices = (o.choices ?? []).filter((c) => c !== value);
if (o.default === value) o.default = null;
for (const r of def.규칙) {
if (r.종류 !== typeId) continue;
if (r.만약.옵션 === o.key) r.만약.값들 = r.만약.값들.filter((v) => v !== value);
if (r.그러면.옵션 === o.key) {
if (r.그러면.선택지) r.그러면.선택지 = r.그러면.선택지.filter((v) => v !== value);
if (r.그러면.기본값 === value) delete r.그러면.기본값;
}
}
}
/** 배치 격자 — 정한 자리 먼저 · 안 정한 옵션은 차례대로 빈 칸 채움 · 안 씀은 빠짐 */
export function placeAll(
options: readonly OptionDef[],
spots: Record<string, Spot> = {},
cols = GRID_COLS,
): Map<string, Spot> {
const out = new Map<string, Spot>();
const taken = new Set<string>();
const mark = (c: Spot): void => {
for (let i = 0; i < c.너비; i += 1) taken.add(`${c.줄}:${c.칸 + i}`);
};
const shown = live(options);
for (const o of shown) {
const s = spots[o.key];
if (!s) continue;
const width = Math.max(1, Math.min(cols, s.너비 || 1));
const cell = { 줄: s.줄, 칸: Math.min(s.칸, cols - width + 1), 너비: width };
out.set(o.key, cell);
mark(cell);
}
let row = 1;
let col = 1;
for (const o of shown) {
if (out.has(o.key)) continue;
while (taken.has(`${row}:${col}`)) {
col += 1;
if (col > cols) ((row += 1), (col = 1));
}
const cell = { 줄: row, 칸: col, 너비: 1 };
out.set(o.key, cell);
mark(cell);
}
return out;
}
/** 겹친 칸 — 두 옵션이 같은 줄 · 칸을 쓰면 그 키들 */
export function overlaps(cells: Map<string, Spot>): string[] {
const owner = new Map<string, string>();
const bad = new Set<string>();
for (const [key, c] of cells)
for (let i = 0; i < c.너비; i += 1) {
const at = `${c.줄}:${c.칸 + i}`;
const other = owner.get(at);
if (other) bad.add(other).add(key);
else owner.set(at, key);
}
return [...bad];
}
/** 규칙 한 줄이 틀렸나 — 서버 검사(`M02_SO_Definition._rule_errors`)와 같은 뜻 */
export function ruleBad(def: StructDef, r: RuleDef): boolean {
const t = def.types.find((x) => x.type_id === r.종류);
const src = t?.options.find((o) => o.key === r.만약.옵션);
const dst = t?.options.find((o) => o.key === r.그러면.옵션);
if (!src || !dst || src === dst || !r.만약.값들.length) return true;
if (src.input === "select" && !r.만약.값들.every((v) => src.choices?.includes(v))) return true;
const { 선택지, 보이기, 기본값 } = r.그러면;
if (선택지 === undefined && 보이기 === undefined && 기본값 === undefined) return true;
let allowed = dst.choices ?? [];
if (선택지 !== undefined) {
if (dst.input !== "select" || !선택지.every((v) => allowed.includes(v))) return true;
allowed = 선택지;
}
return 기본값 !== undefined && dst.input === "select" && !allowed.includes(String(기본값));
}
/** 저장 전 검사 — 화면에 띄울 까닭 글들(빈 목록 = 저장 됨) */
export function problems(def: StructDef): string[] {
const out: string[] = [];
const fam = badNames(Object.values(def.구조물군));
if (fam.length) out.push(`구조물군 이름: ${fam.join(", ")}`);
for (const g of Object.keys(def.구조물군)) {
const bad = badNames(def.types.filter((t) => t.group === g).map((t) => t.name));
if (bad.length) out.push(`${def.구조물군[g]} 종류 이름: ${bad.join(", ")}`);
}
for (const t of def.types) {
const opt = badNames(t.options.map((o) => o.label));
if (opt.length) out.push(`${t.name} 옵션 이름: ${opt.join(", ")}`);
for (const o of t.options) {
if (o.input !== "select") continue;
const ch = badNames(o.choices ?? []);
if (ch.length) out.push(`${t.name}.${o.label} 선택지: ${ch.join(", ")}`);
if (!o.choices?.length) out.push(`${t.name}.${o.label} 고르기 꼴은 선택지가 있어야 함`);
}
const grp = badNames((def.그룹[t.type_id] ?? []).map((g) => g.이름));
const spec = Object.entries(def.종류[t.type_id]?.이름 ?? {})
.filter(([, v]) => !v.trim() || v.length > NAME_MAX)
.map(([k]) => k);
if (spec.length) out.push(`${t.name} 명세 이름: ${spec.join(", ")}`);
if (grp.length) out.push(`${t.name} 그룹 이름: ${grp.join(", ")}`);
const lap = overlaps(placeAll(t.options, def.배치[t.type_id]));
if (lap.length) out.push(`${t.name} 배치 겹침: ${lap.join(", ")}`);
}
def.규칙.forEach((r, i) => {
if (ruleBad(def, r)) out.push(`규칙 ${i + 1} 이 틀림`);
});
return out;
}
@@ -1,233 +0,0 @@
/* =============================================================================
* M02_SO_Def_Options.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **옵션 목록**
* (이름 · 꼴 · 단위 · 기본값 · 보이기 · 들어갈 자리 · 안 씀 · 순서 · [옵션 더함]) +
* 고르기 꼴의 **선택지 목록**(이름 바꿈 · 빼기 · 순서 · [선택지 더함]).
* 옵션 키는 더할 때 자동 · 안 바뀜 · 선택지는 글이 곧 값(이름 바꿈 = 기본값 · 규칙도 같이) ·
* 저장은 화면 [저장](`M02_SO_Def.ts`).
* ========================================================================== */
import { createButton, createTag, el, showConfirmDialog } from "@ui/ui_template_elements";
import {
dropChoice,
newKey,
renameChoice,
type OptionDef,
type OptionForm,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { checkBox, head, moveButtons, pickBox, textBox } from "./M02_SO_Def_Ui";
import { buildPlaceSelect } from "./M02_SO_Groups";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
export interface OptionsBlockOptions {
def: StructDef;
type: TypeDef;
edit: boolean;
/** 선택지를 펼친 옵션 키 — 다시 그려도 남음 */
open: Set<string>;
changed: () => void;
}
const FORMS: readonly OptionForm[] = ["select", "number", "text", "bool"];
const FORM_TEXT = {
select: "FormSelect",
number: "FormNumber",
text: "FormText",
bool: "FormBool",
} as const;
/** 기본값 칸 — 꼴에 맞춤(고르기 = 선택지 · 예/아니오 · 숫자 · 글) · 비우면 기본값 없음 */
function defaultBox(o: OptionDef, edit: boolean, changed: () => void): HTMLElement {
const attr = "data-sod-default";
const now = o.default == null ? "" : String(o.default);
if (o.input === "select" || o.input === "bool") {
const pairs: [string, string][] =
o.input === "select"
? (o.choices ?? []).map((c) => [c, c])
: [
["true", to("Yes")],
["false", to("No")],
];
return pickBox(
[["", to("NoDefault")], ...pairs],
now,
(v) => {
o.default = v === "" ? null : o.input === "bool" ? v === "true" : v;
changed();
},
{ edit, attr, cls: "m02-sod__default" },
);
}
return textBox(
now,
(v) => {
const n = Number(v);
o.default = v.trim() === "" ? null : o.input === "number" && Number.isFinite(n) ? n : v;
},
changed,
{ edit, attr, cls: "m02-sod__default", place: to("NoDefault") },
);
}
/** 선택지 목록 — 이름(떠날 때 바꿈) · 빼기 · 순서 · [선택지 더함] */
function choicesBlock(opt: OptionsBlockOptions, o: OptionDef): HTMLElement {
const { def, type, edit, changed } = opt;
const list = (o.choices ??= []);
const rows = list.map((c) => {
let next = c;
const del = createButton({ label: to("ChoiceDrop"), variant: "danger", size: "sm" });
del.addEventListener("click", async () => {
if (!(await showConfirmDialog(to("ChoiceDropAsk", c), to("ChoiceDrop")))) return;
dropChoice(def, type.type_id, o, c);
changed();
});
return el("div", {
className: "m02-sod__choice",
attrs: { "data-sod-choice": c },
children: [
textBox(
c,
(v) => (next = v.trim()),
() => {
if (next && next !== c && !list.includes(next))
renameChoice(def, type.type_id, o, c, next);
changed();
},
{ edit, attr: "data-sod-choice-name" },
),
...moveButtons(list, c, changed, edit),
...(edit ? [del] : []),
],
});
});
const add = createButton({ label: to("ChoiceAdd"), variant: "ghost", size: "sm" });
add.setAttribute("data-sod-choice-add", "");
add.addEventListener("click", () => {
let n = list.length + 1;
while (list.includes(to("ChoiceNew", String(n)))) n += 1;
list.push(to("ChoiceNew", String(n)));
changed();
});
return el("div", {
className: "m02-sod__choices",
children: [
createText(to("ChoiceNote")),
...(rows.length ? rows : [createText(to("ChoiceNone"), "error")]),
...(edit ? [add] : []),
],
});
}
/** 옵션 한 줄(+ 펼친 선택지) */
function optionRow(opt: OptionsBlockOptions, o: OptionDef): HTMLElement {
const { def, type, edit, open, changed } = opt;
const off = o.enabled === false;
const hidden = def.표시[type.type_id]?.[o.key] === false;
const form = pickBox(
FORMS.map((f) => [f, to(FORM_TEXT[f])] as const),
o.input,
(v) => {
o.input = v as OptionForm;
o.default = null; // 꼴이 바뀌면 옛 기본값은 뜻이 없음
if (o.input === "select") open.add(o.key);
changed();
},
{ edit, attr: "data-sod-form", cls: "m02-sod__form" },
);
const choices =
o.input === "select"
? createButton({
label: to("Choices", String(o.choices?.length ?? 0)),
variant: open.has(o.key) ? "filled" : "ghost",
size: "sm",
})
: null;
choices?.setAttribute("data-sod-choices", o.key);
choices?.addEventListener("click", () => {
if (open.has(o.key)) open.delete(o.key);
else open.add(o.key);
changed();
});
const show = checkBox(
to("Shown"),
!hidden,
(v) => {
const row = (def.표시[type.type_id] ??= {});
if (v) delete row[o.key];
else row[o.key] = false;
if (!Object.keys(row).length) delete def.표시[type.type_id];
changed();
},
{ edit, attr: "data-sod-shown" },
);
const row = el("div", {
className: `m02-sod__option${off ? " is-off" : ""}`,
attrs: { "data-sod-option": o.key },
children: [
textBox(o.label, (v) => (o.label = v), changed, {
edit,
attr: "data-sod-name",
cls: "m02-sod__name",
}),
el("small", { className: "ui-text ui-text--muted m02-opts__key", text: o.key }),
...(o.phase === "detail" ? [createTag(to("Detail"), "accent")] : []),
form,
textBox(o.unit ?? "", (v) => (o.unit = v.trim() || null), changed, {
edit,
attr: "data-sod-unit",
cls: "m02-sod__unit",
place: to("Unit"),
max: 12,
}),
defaultBox(o, edit, changed),
show,
buildPlaceSelect((def.그룹[type.type_id] ??= []), o.key, edit, changed),
checkBox(to("Unused"), off, (v) => ((o.enabled = !v), changed()), {
edit,
attr: "data-sod-off",
}),
...moveButtons(type.options, o, changed, edit),
...(choices ? [choices] : []),
],
});
return o.input === "select" && open.has(o.key)
? el("div", { className: "m02-sod__optwrap", children: [row, choicesBlock(opt, o)] })
: row;
}
/** 옵션 목록 칸 — 제목 · 안내 · 옵션 줄 · [옵션 더함] */
export function buildOptionsBlock(opt: OptionsBlockOptions): HTMLElement {
const { type, edit, changed } = opt;
const add = createButton({ label: to("OptionAdd"), variant: "ghost", size: "sm" });
add.setAttribute("data-sod-option-add", "");
add.addEventListener("click", () => {
const n = type.options.length + 1;
const o: OptionDef = {
key: newKey(
"opt_",
type.options.map((x) => x.key),
),
label: to("OptionNew", String(n)),
input: "select",
choices: [to("ChoiceNew", "1")],
default: null,
};
type.options.push(o);
opt.open.add(o.key);
changed();
});
return el("div", {
className: "m02-sod__block",
children: [
...head(to("OptionHead"), to("OptionNote")),
...(type.options.length
? type.options.map((o) => optionRow(opt, o))
: [createEmpty({ text: to("NoOptionKind"), small: true })]),
...(edit ? [el("div", { className: "m02-side__row", children: [add] })] : []),
],
});
}
@@ -1,105 +0,0 @@
/* =============================================================================
* M02_SO_Def_Parts.ts
* 구조물 정의 「부품」 탭(PLAN 322-2) — 코드가 그리는 방법(부품 상자 `common_util_structure_parts.json`).
* 갈래마다 부품 · 이름 · 읽는 칸 · 맞는 자리꼴 · 정본 · 쓰는 종류 · 켬/끔(정의 `부품` = 끈 것만).
* 끈 부품을 쓰는 종류는 그 갈래가 없음(카드 이름은 종류 이름)으로 — 표 줄(`resolveCatalog`)이 따름.
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import type { StructDef } from "./M02_SO_Def_Model";
import {
OWNER_KO,
PART_BOX,
partsOff,
PLACE_KO,
setPartOn,
shortName,
usersOf,
} from "./M02_SO_Def_Reflect";
import { checkBox, head } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
type Branch = keyof typeof PART_BOX;
export function buildParts(opt: {
def: StructDef;
edit: boolean;
changed: () => void;
}): HTMLElement {
const { def, edit, changed } = opt;
const off = partsOff(def);
/** 옵션 키 → 정의 이름(단위) — 그 부품을 쓰는 종류의 칸 이름 먼저 · 없으면 아무 종류 · 그래도 없으면 키. */
const labelOf = (key: string, users: readonly string[]): string => {
const types = [
...def.types.filter((t) => users.includes(t.type_id)),
...def.types.filter((t) => !users.includes(t.type_id)),
];
const o = types.flatMap((t) => t.options).find((x) => x.key === key);
return o ? (o.unit ? `${o.label} (${o.unit})` : o.label) : key;
};
const blocks = (Object.keys(PART_BOX) as Branch[]).flatMap((branch) => [
...head(branch),
el("table", {
className: "ui-table ui-table--data m02-sod__table m02-sod__table--wrap",
attrs: { "data-sod-parts": branch },
children: [
el("thead", {
children: [
el("tr", {
children: (["ColName", "PartRead", "PartFits", "PartUsers", "PartOn"] as const).map(
(key) => el("th", { text: to(key) }),
),
}),
],
}),
el("tbody", {
children: Object.entries(PART_BOX[branch]).map(([id, part]) => {
const key = `${branch}.${id}`;
// 끈 부품을 쓰던 종류도 보이게 — 끈 동안은 표가 none 으로 풀므로 켠 꼴로 셈
const users = usersOf({ ...def, 부품: {} } as StructDef, branch, id);
return el("tr", {
attrs: { "data-sod-part": key },
className: off[key] === false ? "is-off" : "",
children: [
// 영어 키는 툴팁만(322-2 다듬기) — 이름 = 짧은 이름 · 읽는 칸 = 정의 칸 이름
el("td", { text: shortName(part.이름), attrs: { title: `${id} · ${part.이름}` } }),
el("td", {
text:
part["읽는 칸"]
.map((k) =>
labelOf(
k,
users.map((row) => row.typeId),
),
)
.join(" · ") || "—",
}),
el("td", {
text: `${part.자리꼴.map((p) => PLACE_KO[p] ?? p).join(" · ")} / ${part.정본
.map((o) => OWNER_KO[o] ?? o)
.join(" · ")}`,
}),
el("td", { text: users.map((row) => row.name).join(" · ") || "—" }),
el("td", {
children: [
checkBox(
to("PartOn"),
off[key] !== false,
(on) => (setPartOn(def, key, on), changed()),
{ edit, attr: "data-sod-part-on" },
),
],
}),
],
});
}),
}),
],
}),
]);
return el("div", {
className: "m02-sod__tablewrap",
children: [createText(to("PartsNote")), ...blocks],
});
}
@@ -1,214 +0,0 @@
/* =============================================================================
* M02_SO_Def_Reflect.ts
* 구조물 표 편집(PLAN 322-2)의 순수 손질 — 정의 사본의 `반영` · `부품` · 목록 + enabled · 형상칸.
*
* · 지금 값 = 구조물 표 한 줄(`resolveCatalog` · 정의 반영 ⊕ 처음값 ⊕ 부품 끔)
* · 반영에는 처음 값과 다른 칸만 남김(같으면 지움 = 「기본」) · [처음 값으로] = 그 종류 반영 지움
* · 목록과 enabled 는 함께 씀 — enabled = 목록 both 일 때만 참(옛 짝 · 브레인 322-1 답 ①)
* 화면 그리기 없음 — 표 · 종류별 · 부품 탭이 이 함수들로 사본을 고침.
* ========================================================================== */
import PARTS from "../../common_util/common_util_structure_parts.json" with { type: "json" };
import {
resolveCatalog,
type CatalogDefinition,
type CatalogRow,
} from "../../common_util/common_util_structure_catalog";
import { clone, type StructDef } from "./M02_SO_Def_Model";
export type ReflectField = "목록" | "횡단도" | "카드이름" | "형상" | "3D";
type Reflect = Partial<Record<ReflectField, string>> & { 형상칸?: Record<string, unknown> };
interface Part {
이름: string;
"읽는 칸": string[];
자리꼴: string[];
정본: string[];
}
type Branch = Exclude<ReflectField, "목록">;
export const PART_BOX = (PARTS as unknown as { parts: Record<Branch, Record<string, Part>> }).parts;
const START = (PARTS as unknown as { 처음값: Record<string, Reflect> }).처음값;
/** 화면 글(322-2 다듬기 · 영어 키 안 보임) — 자리꼴 · 정본 · 부품 짧은 이름(괄호 설명은 툴팁). */
export const PLACE_KO: Record<string, string> = { point: "점", interval: "구간", site: "터" };
export const OWNER_KO: Record<string, string> = { pipe_points: "관 지점", structures: "구조물" };
export const shortName = (full: string): string => full.replace(/\s*\(.*\)\s*$/, "");
/** 칸 → 표 줄 열쇠. */
const ROW_KEY: Record<ReflectField, keyof CatalogRow> = {
목록: "list",
횡단도: "station",
카드이름: "title",
형상: "shape",
"3D": "model3d",
};
export const reflectOf = (def: StructDef): Record<string, Reflect> =>
((def as { 반영?: Record<string, Reflect> }).반영 ??= {});
export const partsOff = (def: StructDef): Record<string, boolean> =>
((def as { 부품?: Record<string, boolean> }).부품 ??= {});
/** 사본 전체 표 — 종류마다 한 줄. */
export const rowsOf = (def: StructDef): Map<string, CatalogRow> =>
resolveCatalog(def as unknown as CatalogDefinition);
/** 칸 지금 값. */
export const valueOf = (row: CatalogRow, field: ReflectField): string =>
String(row[ROW_KEY[field]]);
/** 반영이 없을 때(처음 값 · 목록은 enabled 짝) 그 칸 값. */
export function defaultOf(def: StructDef, typeId: string, field: ReflectField): string {
const copy = { ...def, 반영: { ...reflectOf(def) } } as unknown as StructDef;
const own = { ...(reflectOf(copy)[typeId] ?? {}) };
delete own[field];
reflectOf(copy)[typeId] = own;
const row = rowsOf(copy).get(typeId);
return row ? valueOf(row, field) : "";
}
/** 반영에 적힌 칸인가(아니면 「기본」). */
export const isSet = (def: StructDef, typeId: string, field: ReflectField | "형상칸"): boolean =>
field in (reflectOf(def)[typeId] ?? {});
const dropEmpty = (def: StructDef, typeId: string): void => {
const all = reflectOf(def);
if (all[typeId] && !Object.keys(all[typeId]).length) delete all[typeId];
};
/** 칸 고침 — 처음 값과 같으면 반영에서 지움 · 목록이면 enabled 도(both 일 때만 참). */
export function setReflect(
def: StructDef,
typeId: string,
field: ReflectField,
value: string,
): void {
const type = def.types.find((t) => t.type_id === typeId);
if (field === "목록" && type) type.enabled = value === "both";
const own = (reflectOf(def)[typeId] ??= {});
delete own[field];
if (defaultOf(def, typeId, field) !== value) own[field] = value;
dropEmpty(def, typeId);
}
/** 형상칸 한 칸 고침(form 글 · weep 참거짓) — 처음 값과 같으면 지움. */
export function setShapeOpt(def: StructDef, typeId: string, key: string, value: unknown): void {
const own = (reflectOf(def)[typeId] ??= {});
const opts = { ...(own.형상칸 ?? {}) };
const start = START[typeId]?.형상칸?.[key];
if (value === start || value === "" || (value === false && start === undefined)) delete opts[key];
else opts[key] = value;
if (Object.keys(opts).length) own.형상칸 = opts;
else delete own.형상칸;
dropEmpty(def, typeId);
}
/** [처음 값으로] — 그 종류 반영 지움 · enabled = 처음 목록 both 일 때만 참. */
export function resetRow(def: StructDef, typeId: string): void {
delete reflectOf(def)[typeId];
const type = def.types.find((t) => t.type_id === typeId);
if (type) type.enabled = START[typeId] ? START[typeId].목록 === "both" : type.enabled;
}
/** [저장] 전 — 모든 종류 enabled = 지금 목록 both 일 때만 참(목록 + enabled 함께 씀). */
export function syncEnabled(def: StructDef): void {
const rows = rowsOf(def);
for (const type of def.types) {
const row = rows.get(type.type_id);
if (row) type.enabled = row.list === "both";
}
}
/** 부품 켬끔 — 끔만 남김. */
export function setPartOn(def: StructDef, key: string, on: boolean): void {
const off = partsOff(def);
if (on) delete off[key];
else off[key] = false;
}
/** 못 숨김 칸 — 종류가 지금 쓰는 부품들이 읽는 칸 중 기본값도 비워 두는 뜻도 없는 옵션
* (숨기면 그림이 받을 값이 없음 · 검사 짝 `M02_SO_Def_Check`). */
export function readKeys(def: StructDef, typeId: string): Set<string> {
const row = rowsOf(def).get(typeId);
if (!row) return new Set();
const type = def.types.find((t) => t.type_id === typeId);
const bare = new Set(
(type?.options ?? [])
.filter((o) => (o.default === null || o.default === undefined) && !o.empty_means)
.map((o) => o.key),
);
const used: Array<[Branch, string]> = [
["횡단도", row.station],
["카드이름", row.title],
["형상", row.shape],
["3D", row.model3d],
];
return new Set(
used
.flatMap(([branch, id]) => PART_BOX[branch][id]?.["읽는 칸"] ?? [])
.filter((key) => bare.has(key)),
);
}
/** 그 갈래 부품을 지금 쓰는 종류들. */
export function usersOf(def: StructDef, branch: Branch, id: string): CatalogRow[] {
const field = ROW_KEY[branch];
return [...rowsOf(def).values()].filter((row) => row[field] === id);
}
/** 정의 「표시」 숨김 키(그 종류). */
export const hiddenKeys = (def: StructDef, typeId: string): Set<string> =>
new Set(
Object.entries(def.표시[typeId] ?? {})
.filter(([, shown]) => shown === false)
.map(([key]) => key),
);
/** 옵션 키들 보임 켬끔 — 정의 옵션인 키만(숨김 = false 만 남김). */
export function setShown(
def: StructDef,
typeId: string,
keys: readonly string[],
on: boolean,
): void {
const type = def.types.find((t) => t.type_id === typeId);
const known = new Set((type?.options ?? []).map((o) => o.key));
const row = (def.표시[typeId] ??= {});
for (const key of keys.filter((k) => known.has(k))) {
if (on) delete row[key];
else row[key] = false;
}
if (!Object.keys(row).length) delete def.표시[typeId];
}
/** 저장할 꼴 — 목록 + enabled 함께(322-2) · 빈 묶음 걷어냄(그룹 목록 · 배치 · 종류 덧칸 · 표시 · 반영) */
export function tidy(def: StructDef): StructDef {
const out = clone(def);
syncEnabled(out);
const reflect = (out.반영 ?? {}) as Record<string, unknown>;
for (const part of [out.그룹, out.배치, out.종류, out.표시, reflect] as Record<string, unknown>[])
for (const [k, v] of Object.entries(part))
if (Array.isArray(v) ? !v.length : !Object.keys(v as object).length) delete part[k];
return out;
}
/** 열쇠 차례 무관 글 — 같은 값이면 같은 글. */
const stable = (value: unknown): string =>
Array.isArray(value)
? `[${value.map(stable).join(",")}]`
: value && typeof value === "object"
? `{${Object.keys(value)
.sort()
.map((k) => `${JSON.stringify(k)}:${stable((value as Record<string, unknown>)[k])}`)
.join(",")}}`
: JSON.stringify(value ?? null);
/** 저장할 것이 있나 — 저장할 꼴(tidy)끼리 견줌 · 빈 반영 · 부품 칸은 없는 셈(바꿨다 되돌리면 꺼짐 · 322-2). */
export function differs(work: StructDef, base: StructDef): boolean {
const canon = (def: StructDef): string => {
const out = tidy(def) as Record<string, unknown>;
for (const key of ["반영", "부품"])
if (out[key] && !Object.keys(out[key] as object).length) delete out[key];
return stable(out);
};
return canon(work) !== canon(base);
}
@@ -1,239 +0,0 @@
/* =============================================================================
* M02_SO_Def_Rules.ts
* 구조물 정의 편집 화면(PLAN 48-2) — 고른 종류의 **규칙 표**(정의 `규칙` 중 그 종류 것만)
* 「만약 상위 옵션 = 값들 중 하나 → 하위 옵션의 선택지 · 보이기 · 기본값」 한 줄씩 · [규칙 더함] · 지우기.
* 「그대로」 칸은 정의에 안 남김 · 셋 다 그대로면 틀린 줄(빨강) · 적용은 B05 · B06(48-4).
* ========================================================================== */
import { createButton, el } from "@ui/ui_template_elements";
import {
live,
ruleBad,
type OptionDef,
type RuleDef,
type StructDef,
type TypeDef,
} from "./M02_SO_Def_Model";
import { head, pickBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
import { createEmpty } from "@ui/ui_template_empty";
import { createCheckbox } from "@ui/ui_template_checkbox";
export interface RulesBlockOptions {
def: StructDef;
type: TypeDef;
edit: boolean;
changed: () => void;
}
const bool = (): [string, string][] => [
["true", to("Yes")],
["false", to("No")],
];
/** 여럿 고르기 — 체크한 것만 차례대로 */
function multiPick(
all: readonly string[],
picked: readonly string[],
set: (v: string[]) => void,
edit: boolean,
attr: string,
): HTMLElement {
const on = new Set(picked);
return el("div", {
className: "m02-sod__rulechoices",
attrs: { [attr]: "" },
children: all.map((c) => {
const { root } = createCheckbox(c, {
checked: on.has(c),
disabled: !edit,
value: c,
onChange: (checked) => {
if (checked) on.add(c);
else on.delete(c);
set(all.filter((x) => on.has(x)));
},
});
root.classList.add("m02-sod__check");
return root;
}),
});
}
/** 글 칸 — 쉼표로 여럿 */
function listText(
value: string[],
set: (v: string[]) => void,
edit: boolean,
attr: string,
): HTMLElement {
const box = el("input", {
className: "ui-input ui-input--sm m02-sod__rulepick",
attrs: { type: "text", [attr]: "", placeholder: to("RuleValues") },
}) as HTMLInputElement;
box.value = value.join(", ");
box.disabled = !edit;
box.addEventListener("change", () =>
set(
box.value
.split(",")
.map((s) => s.trim())
.filter(Boolean),
),
);
return box;
}
/** 만약 값들 — 고르기 = 선택지 체크 · 예/아니오 = 하나 · 그 밖 = 쉼표 글 */
function whenValues(
src: OptionDef | undefined,
rule: RuleDef,
edit: boolean,
changed: () => void,
): HTMLElement {
const set = (v: string[]): void => ((rule.만약.값들 = v), changed());
if (src?.input === "select")
return multiPick(src.choices ?? [], rule.만약.값들, set, edit, "data-sod-rule-value");
if (src?.input === "bool")
return pickBox(bool(), rule.만약.값들[0] ?? "true", (v) => set([v]), {
edit,
attr: "data-sod-rule-value",
cls: "m02-sod__rulepick",
});
return listText(rule.만약.값들, set, edit, "data-sod-rule-value");
}
/** 그러면 기본값 — 「그대로」 + (좁힌) 선택지 · 예/아니오 · 글 */
function thenDefault(
dst: OptionDef | undefined,
rule: RuleDef,
edit: boolean,
changed: () => void,
): HTMLElement {
const then = rule.그러면;
const now = then.기본값 === undefined ? "" : String(then.기본값);
const set = (v: string): void => {
if (v === "") delete then.기본값;
else
then.기본값 =
dst?.input === "bool"
? v === "true"
: dst?.input === "number" && Number.isFinite(Number(v))
? Number(v)
: v;
changed();
};
const pairs: [string, string][] =
dst?.input === "select"
? (then.선택지 ?? dst.choices ?? []).map((c) => [c, c])
: dst?.input === "bool"
? bool()
: [];
if (pairs.length || (dst?.input !== "number" && dst?.input !== "text"))
return pickBox([["", to("KeepDefault")], ...pairs], now, set, {
edit,
attr: "data-sod-rule-default",
cls: "m02-sod__rulepick",
});
const box = el("input", {
className: "ui-input ui-input--sm m02-sod__rulepick",
attrs: { type: "text", "data-sod-rule-default": "", placeholder: to("KeepDefault") },
}) as HTMLInputElement;
box.value = now;
box.disabled = !edit;
box.addEventListener("change", () => set(box.value.trim()));
return box;
}
function ruleRow(opt: RulesBlockOptions, rule: RuleDef, index: number): HTMLElement {
const { def, type, edit, changed } = opt;
const byKey = new Map(type.options.map((o) => [o.key, o]));
const names = live(type.options).map((o) => [o.key, o.label] as [string, string]);
const src = byKey.get(rule.만약.옵션);
const dst = byKey.get(rule.그러면.옵션);
const then = rule.그러면;
const del = createButton({ label: to("GroupDel"), variant: "danger", size: "sm" });
del.addEventListener("click", () => (def.규칙.splice(def.규칙.indexOf(rule), 1), changed()));
const show = then.보이기 === undefined ? "" : then.보이기 ? "1" : "0";
return el("div", {
className: `m02-sod__rule${ruleBad(def, rule) ? " is-bad" : ""}`,
attrs: { "data-sod-rule": String(index) },
children: [
el("small", { text: to("RuleIf") }),
pickBox(names, rule.만약.옵션, (v) => ((rule.만약 = { 옵션: v, 값들: [] }), changed()), {
edit,
attr: "data-sod-rule-top",
cls: "m02-sod__rulepick",
}),
el("small", { text: "=" }),
whenValues(src, rule, edit, changed),
el("small", { text: to("RuleThen") }),
pickBox(names, then.옵션, (v) => ((rule.그러면 = { 옵션: v }), changed()), {
edit,
attr: "data-sod-rule-target",
cls: "m02-sod__rulepick",
}),
...(dst?.input === "select"
? [
el("small", { text: to("RuleChoices") }),
multiPick(
dst.choices ?? [],
then.선택지 ?? [],
(v) => {
if (v.length) then.선택지 = v;
else delete then.선택지;
changed();
},
edit,
"data-sod-rule-choice",
),
]
: []),
pickBox(
[
["", to("Keep")],
["1", to("Show")],
["0", to("Hide")],
],
show,
(v) => {
if (v === "") delete then.보이기;
else then.보이기 = v === "1";
changed();
},
{ edit, attr: "data-sod-rule-show", cls: "m02-sod__rulepick" },
),
thenDefault(dst, rule, edit, changed),
...(edit ? [del] : []),
],
});
}
export function buildRulesBlock(opt: RulesBlockOptions): HTMLElement {
const { def, type, edit, changed } = opt;
const mine = def.규칙.filter((r) => r.종류 === type.type_id);
const opts = live(type.options);
const add = createButton({ label: to("RuleAdd"), variant: "ghost", size: "sm" });
add.setAttribute("data-sod-rule-add", "");
add.disabled = opts.length < 2;
add.addEventListener("click", () => {
const top = opts.find((o) => o.input === "select") ?? opts[0];
const target = opts.find((o) => o.key !== top.key)!;
def.규칙.push({
종류: type.type_id,
만약: { 옵션: top.key, 값들: top.choices?.length ? [top.choices[0]] : [] },
그러면: { 옵션: target.key, 보이기: false },
});
changed();
});
return el("div", {
className: "m02-sod__block",
children: [
...head(to("RuleHead"), to("RuleNote")),
...(mine.length
? mine.map((r) => ruleRow(opt, r, def.규칙.indexOf(r)))
: [createEmpty({ text: to("RuleNone"), small: true })]),
...(edit ? [el("div", { className: "m02-side__row", children: [add] })] : []),
],
});
}
@@ -1,177 +0,0 @@
/* =============================================================================
* M02_SO_Def_Spec.ts
* 구조물 명세가 있는 종류(PLAN 52 · `STRUCTURE_SPECS`)의 이름 고치기 칸(52-11) — 나무 꼴
* 컨테이너 제목 › 항목 이름 › 값 이름 · 이름만 고침 · 키 · 필수/선택 · 꼴은 읽기만 ·
* 아래 미리보기 = B05 · B06 이 그리는 같은 명세 폼(`createSpecForm`)에 고친 이름을 얹음.
* 명세 없는 종류(정의 그룹 꼴 · 52-12) = 그룹 제목 › 칸 이름 › 선택지 이름 · 미리보기 = B05 칸 부품
* (`field` · `optionControl` · 그룹 상자)으로 같은 차례.
* 구조물군 · 종류 이름은 왼쪽 목록 · 머리 칸이 그대로 고침.
* 줄마다 보임(322-2 · 정의 「표시」 · 컨테이너 = 그 안 칸 전부) · 부품이 읽는 칸 = 「못 숨김」(앞 판에서
* 이미 숨긴 칸은 다시 보이기만) · 미리보기도 숨김을 따름.
* ========================================================================== */
import { createTag, el } from "@ui/ui_template_elements";
import { createSpecForm } from "../../A00_Common/design/design_structure_form";
import {
specItemKeys,
type StructureSpec,
} from "../../A00_Common/design/logic/design_structure_spec";
import { group } from "../../B05_Profile/B05_Profile_UI_Drainage_Facility_Fields";
import { field, optionControl } from "../../B05_Profile/B05_Profile_UI_Structures_Fields";
import type { StructDef, TypeDef } from "./M02_SO_Def_Model";
import {
groupNameRows,
setSpecName,
specNameRows,
type SpecNameRow,
} from "./M02_SO_Def_Spec_Model";
import { hiddenKeys, readKeys, setShown } from "./M02_SO_Def_Reflect";
import { checkBox, head, textBox } from "./M02_SO_Def_Ui";
import { to, type OptionsTextKey } from "./M02_SO_Text";
import { createEmpty } from "@ui/ui_template_empty";
const TAG: Record<NonNullable<SpecNameRow["tag"]>, OptionsTextKey> = {
required: "SpecRequired",
optional: "SpecOptional",
select: "FormSelect",
number: "FormNumber",
text: "FormText",
auto: "FormAuto",
bool: "FormBool",
};
/** 정의 그룹 꼴 미리보기 — 그룹 밖 칸 · 그룹 상자(제목 = 그룹 이름) · 선택지 = 이름 표 글(값 그대로). */
function groupPreview(def: StructDef, type: TypeDef): HTMLElement {
const names = def.종류[type.type_id]?.이름 ?? {};
const hidden = hiddenKeys(def, type.type_id);
const options = type.options.filter((o) => o.enabled !== false && !hidden.has(o.key));
const cell = (o: (typeof options)[number]): HTMLElement =>
field(
o.unit ? `${o.label} (${o.unit})` : o.label,
optionControl(
{
input: o.input === "select" || o.input === "number" ? o.input : "text",
choices: o.choices ?? [],
default: null,
required: !!o.required,
},
undefined,
(c) => names[`${o.key}=${c}`] ?? c,
),
);
const groups = def.그룹[type.type_id] ?? [];
const inGroup = new Set(groups.flatMap((g) => g.옵션));
const grid = (cells: HTMLElement[]): HTMLElement =>
el("div", { className: "b05-structure__grid", children: cells });
return el("div", {
children: [
grid(options.filter((o) => !inGroup.has(o.key)).map(cell)),
...groups.map((g) => {
const box = group(g.이름);
box.body.append(grid(options.filter((o) => g.옵션.includes(o.key)).map(cell)));
return box.root;
}),
],
});
}
/** 이름 줄이 쓰는 정의 옵션 키 — 명세 상자 = 그 안 칸 전부 · 칸 = 저장 · 갈래 키 · 그룹 = 그 옵션들. */
function rowKeys(type: TypeDef, spec: StructureSpec | undefined, nameKey: string): string[] {
if (!nameKey || nameKey.includes("=")) return [];
if (!spec) {
if (!nameKey.startsWith("#")) return [nameKey];
return [];
}
const [cid, iid] = nameKey.split(".");
const c = spec.containers.find((x) => x.id === cid);
const items = (c?.items ?? []).filter((i) => !iid || i.id === iid);
const own = new Set(type.options.map((o) => o.key));
return items.flatMap(specItemKeys).filter((key) => own.has(key));
}
/** 줄 보임 칸 — 키 없는 줄은 비움 · 부품이 읽는 보이는 칸은 못 숨김. */
function shownBox(
opt: { def: StructDef; base: StructDef; type: TypeDef; edit: boolean; changed: () => void },
keys: string[],
): HTMLElement[] {
if (!keys.length) return [];
const { def, base, type, edit, changed } = opt;
const hidden = hiddenKeys(def, type.type_id);
const kept = hiddenKeys(base, type.type_id);
const read = readKeys(def, type.type_id);
const shown = keys.some((key) => !hidden.has(key));
const locked = shown && keys.some((key) => read.has(key) && !kept.has(key));
return [
checkBox(to("ShownCol"), shown, (v) => (setShown(def, type.type_id, keys, v), changed()), {
edit: edit && !locked,
attr: "data-sod-spec-shown",
}),
...(locked ? [createTag(to("CannotHide"), "neutral")] : []),
];
}
export function buildSpecBlock(opt: {
def: StructDef;
/** 지금 서버 판 — 이미 숨긴 칸(못 숨김 예외)을 가름 */
base: StructDef;
type: TypeDef;
/** 없으면 정의 그룹 꼴(52-12) */
spec: StructureSpec | undefined;
edit: boolean;
changed: () => void;
}): HTMLElement {
const { def, type, spec, edit, changed } = opt;
const rows = (spec ? specNameRows(def, spec) : groupNameRows(def, type)).map((row) =>
el("div", {
className: `m02-sod__specrow is-level-${row.level}`,
attrs: { "data-sod-spec": row.nameKey },
children: [
row.nameKey
? textBox(row.label, (v) => setSpecName(def, type.type_id, row, v), changed, {
edit,
attr: "data-sod-spec-name",
cls: "m02-sod__name",
})
: el("span", { text: to("SpecLoose") }),
el("small", { className: "ui-text ui-text--muted m02-opts__key", text: row.key }),
...(row.tag ? [createTag(to(TAG[row.tag]), "neutral")] : []),
...shownBox(
opt,
row.group && !spec
? ((def.그룹[type.type_id] ?? []).find((g) => g.id === row.group)?.옵션 ?? [])
: rowKeys(type, spec, row.nameKey),
),
],
}),
);
// 미리보기 — 값 없는 새 구조물 폼 · 잇기 줄 없음(조합은 프로젝트 몫)
let preview: HTMLElement;
if (spec) {
const form = createSpecForm(null);
const groups = Object.fromEntries((def.그룹[type.type_id] ?? []).map((g) => [g.id, g.이름]));
form.write(
spec,
{},
def.종류[type.type_id]?.이름 ?? {},
groups,
{},
hiddenKeys(def, type.type_id),
);
preview = form.root;
} else preview = groupPreview(def, type);
preview.inert = true;
return el("div", {
className: "m02-sod__block",
attrs: { "data-sod-spec-block": "" },
children: [
...head(to("SpecHead"), to("SpecNote")),
...(rows.length ? rows : [createEmpty({ text: to("SpecNone"), small: true })]),
...head(to("SpecPreview")),
el("div", {
className: "m02-sod__specpreview",
attrs: { "data-sod-spec-preview": "" },
children: [preview],
}),
],
});
}
@@ -1,157 +0,0 @@
/* =============================================================================
* M02_SO_Def_Spec_Model.ts
* 구조물 명세(PLAN 52 · `design_structure_spec`) 이름 고치기(52-11)의 자료 손질 — 화면 그리기 없음.
*
* · 명세 = 구조 정본(키 · 컨테이너 · 필수/선택 · 꼴) — 여기서는 **이름만** 고침
* · 이름 자리 = 정의 `종류.{종류}.이름`(키 `{컨테이너}` · `{컨테이너}.{항목}` · `{컨테이너}.{항목}={값}`)
* · 필수 컨테이너 제목 = 이름 표에 없으면 정의 그룹(`그룹.{종류}` 의 `id = link`) 이름 — B05 그리기
* (`containerTitle`)와 같은 차례로 읽고 그 자리에 씀
* · 명세 없는 종류(정의 그룹 꼴 · 52-12) = 그룹 제목(`그룹.이름`) › 칸 이름(옵션 `label`) ›
* 선택지 이름(이름 표 키 `{옵션}={값}` · 값은 그대로) — 그룹 밖 칸은 맨 앞 머리 줄 아래
* import 는 꼴만 — 시험이 이 파일만 옮겨 돌림.
* ========================================================================== */
import type { StructureSpec } from "../../A00_Common/design/logic/design_structure_spec";
import type { StructDef, TypeDef } from "./M02_SO_Def_Model";
export interface SpecNameRow {
/** 0 = 컨테이너 · 1 = 항목 · 2 = 값 */
level: 0 | 1 | 2;
/** 이름 표 키 — 빈 글 = 고칠 이름 없는 머리 줄(그룹 밖 칸) */
nameKey: string;
/** 읽기만 표시 — 컨테이너 id · 항목 id · 값 */
key: string;
/** 지금 이름 */
label: string;
/** 읽기만 표시 — 필수/선택 · 꼴 */
tag: "required" | "optional" | "select" | "number" | "auto" | "text" | "bool" | null;
/** 필수 컨테이너 제목이 정의 그룹 이름에서 옴 — 고치면 그 그룹 이름에 씀 */
group: string | null;
/** 정의 옵션 이름(`label`)에서 옴 — 고치면 그 옵션 이름에 씀 */
option: string | null;
}
/** 명세 차례대로 이름 줄 — 같은 이름 키(갈래마다 겹친 값)는 한 줄. */
export function specNameRows(def: StructDef, spec: StructureSpec): SpecNameRow[] {
const names = def.종류[spec.typeId]?.이름 ?? {};
const groups = def.그룹[spec.typeId] ?? [];
const rows: SpecNameRow[] = [];
const seen = new Set<string>();
const push = (row: SpecNameRow): void => {
if (seen.has(row.nameKey)) return;
seen.add(row.nameKey);
rows.push(row);
};
for (const c of spec.containers) {
const group =
c.required && names[c.id] === undefined ? groups.find((g) => g.id === c.link) : undefined;
push({
level: 0,
nameKey: c.id,
key: c.id,
label: names[c.id] ?? group?.이름 ?? c.title,
tag: c.required ? "required" : "optional",
group: group ? group.id : null,
option: null,
});
for (const item of c.items) {
const itemKey = `${c.id}.${item.id}`;
push({
level: 1,
nameKey: itemKey,
key: item.id,
label: names[itemKey] ?? item.label,
tag: item.kind,
group: null,
option: null,
});
const choices = [
...(item.choices ?? []),
...Object.values(item.by?.map ?? {}).flatMap((b) => b.choices ?? []),
];
for (const ch of choices) {
const choiceKey = `${itemKey}=${ch.value}`;
push({
level: 2,
nameKey: choiceKey,
key: ch.value,
label: names[choiceKey] ?? ch.label,
tag: null,
group: null,
option: null,
});
}
}
}
return rows;
}
/** 정의 그룹 꼴 종류(명세 없음) 이름 줄 — 그룹 밖 칸 · 그룹마다 제목 › 칸 › 선택지(B05 그리기 차례). */
export function groupNameRows(def: StructDef, type: TypeDef): SpecNameRow[] {
const names = def.종류[type.type_id]?.이름 ?? {};
const options = type.options.filter((o) => o.enabled !== false);
const groups = def.그룹[type.type_id] ?? [];
const inGroup = new Set(groups.flatMap((g) => g.옵션));
const rows: SpecNameRow[] = [];
const optionRows = (keys: readonly string[]): void => {
for (const o of options.filter((x) => keys.includes(x.key))) {
rows.push({
level: 1,
nameKey: o.key,
key: o.key,
label: o.label,
tag: o.input,
group: null,
option: o.key,
});
for (const ch of o.input === "select" ? (o.choices ?? []) : []) {
const nameKey = `${o.key}=${ch}`;
rows.push({
level: 2,
nameKey,
key: ch,
label: names[nameKey] ?? ch,
tag: null,
group: null,
option: null,
});
}
}
};
const loose = options.filter((o) => !inGroup.has(o.key)).map((o) => o.key);
if (loose.length) {
rows.push({ level: 0, nameKey: "", key: "", label: "", tag: null, group: null, option: null });
optionRows(loose);
}
for (const g of groups) {
rows.push({
level: 0,
nameKey: `#${g.id}`,
key: g.id,
label: g.이름,
tag: null,
group: g.id,
option: null,
});
optionRows(g.옵션);
}
return rows;
}
/** 이름 하나를 사본에 씀 — 그룹에서 온 제목은 그 그룹 이름 · 옵션 칸은 옵션 이름 · 나머지는 이름 표. */
export function setSpecName(def: StructDef, typeId: string, row: SpecNameRow, value: string): void {
const option = row.option
? def.types.find((t) => t.type_id === typeId)?.options.find((o) => o.key === row.option)
: undefined;
if (option) {
option.label = value;
return;
}
const group = row.group ? def.그룹[typeId]?.find((g) => g.id === row.group) : undefined;
if (group) {
group.이름 = value;
return;
}
const kind = (def.종류[typeId] ??= {});
(kind.이름 ??= {})[row.nameKey] = value;
}
@@ -1,332 +0,0 @@
/* =============================================================================
* M02_SO_Def_Table.ts
* 구조물 정의 「한눈 표」 탭(PLAN 322-2) — 종류마다 B05 · B06 반영 한 줄.
* 군 · 종류(▲▼) · 이름 · 목록 · 자리꼴 · 정본(읽기만 「고정」) · 횡단도 · 카드 이름 · 형상(+ 형상칸) ·
* 알약 색 · 3D · 검사. 흐린 칸 = 처음 값(「기본」) · 진한 칸 = 바꾼 값 · [처음 값으로] = 그 종류 반영 지움.
* 칸 손질 = `M02_SO_Def_Reflect` · 검사 글 = `M02_SO_Def_Check`(서버 짝) · 「종류별」 탭이 같은 칸(`reflectCells`)을 씀.
* ========================================================================== */
import { createButton, createTag, el } from "@ui/ui_template_elements";
import type { CatalogRow } from "../../common_util/common_util_structure_catalog";
import { stepFamily, stepType, type StructDef, type TypeDef } from "./M02_SO_Def_Model";
import { REVET_FORMS } from "../../B06_Section/logic/B06_Section_UI_Cross_Culvert_Const";
import {
isSet,
OWNER_KO,
PART_BOX,
PLACE_KO,
shortName,
resetRow,
rowsOf,
setReflect,
setShapeOpt,
valueOf,
type ReflectField,
} from "./M02_SO_Def_Reflect";
import { checkBox, pickBox, textBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
type Pairs = ReadonlyArray<readonly [string, string]>;
const LIST_PAIRS = (): Pairs => [
["both", to("ListBoth")],
["b06", to("ListB06")],
["hidden", to("ListHidden")],
];
/** 갈래 고르기 — 없음(횡단도 = 안 만듦 · 카드 이름 = 종류 이름) + 부품 상자 차례 · 글 = 짧은 이름
* (영어 키 · 괄호 설명은 툴팁 · 322-2 다듬기). */
const OFF_TEXT: Record<Exclude<ReflectField, "목록">, () => string> = {
횡단도: () => to("StationNone"),
카드이름: () => to("TitleName"),
형상: () => to("OffNone"),
"3D": () => to("OffNone"),
};
const partPairs = (branch: Exclude<ReflectField, "목록">): Pairs => [
[branch === "카드이름" ? "name" : "none", OFF_TEXT[branch]()],
...Object.entries(PART_BOX[branch]).map(([id, part]) => [id, shortName(part.이름)] as const),
];
/** 고르기 항목 툴팁 = 키 · 부품 긴 이름. */
function tipOptions(box: HTMLSelectElement, branch: ReflectField): void {
if (branch === "목록") return;
for (const option of Array.from(box.options)) {
const part = PART_BOX[branch][option.value];
option.title = part ? `${option.value} · ${part.이름}` : option.value;
}
}
interface CellCtx {
def: StructDef;
type: TypeDef;
row: CatalogRow;
edit: boolean;
changed: () => void;
}
/** 반영 칸 하나 — 처음 값이면 흐리게 「기본」 · 바꿨으면 진하게. */
function reflectCell(ctx: CellCtx, field: ReflectField): HTMLElement {
const { def, type, row, edit, changed } = ctx;
const pairs = field === "목록" ? LIST_PAIRS() : partPairs(field);
const box = pickBox(
pairs,
valueOf(row, field),
(v) => {
setReflect(def, type.type_id, field, v);
changed();
},
{ edit, attr: `data-sod-reflect-${field}` },
);
tipOptions(box, field);
return mark(isSet(def, type.type_id, field), box);
}
/** 흐림(기본) · 진함(바꿈) 꼴. */
function mark(changed: boolean, ...children: HTMLElement[]): HTMLElement {
return el("div", {
className: `m02-sod__cell ${changed ? "is-changed" : "is-default"}`,
children: [...children, ...(changed ? [] : [createTag(to("Default"), "neutral")])],
});
}
/** 형상칸 — 벽(형상 wall)만: 기본 형태(그림 형태 고르기) · 물빼기. */
function shapeOptsCell(ctx: CellCtx): HTMLElement {
const { def, type, row, edit, changed } = ctx;
if (row.shape !== "wall") return el("span", { className: "ui-text ui-text--muted", text: "—" });
const form = String(row.shapeOpts.form ?? "");
const forms = !form || REVET_FORMS.includes(form) ? REVET_FORMS : [form, ...REVET_FORMS];
const box = pickBox(
forms.map((f) => [f, f] as const),
form,
(v) => (setShapeOpt(def, type.type_id, "form", v), changed()),
{ edit, attr: "data-sod-shape-form" },
);
box.title = to("WallForm");
return mark(
isSet(def, type.type_id, "형상칸"),
box,
checkBox(
to("Weep"),
row.shapeOpts.weep === true,
(v) => (setShapeOpt(def, type.type_id, "weep", v), changed()),
{ edit, attr: "data-sod-shape-weep" },
),
);
}
/** 알약 색(style.color). */
function colorCell(ctx: CellCtx): HTMLElement {
const box = el("input", {
className: "m02-sod__color",
attrs: { type: "color", "data-sod-color": "" },
}) as HTMLInputElement;
const style = (ctx.type.style ?? {}) as { color?: string };
box.value = style.color ?? "#888888";
box.disabled = !ctx.edit;
box.addEventListener("change", () => {
ctx.type.style = { ...style, color: box.value };
ctx.changed();
});
return box;
}
/** 자리꼴 · 정본 = 한국어 글 · 「고정」(키는 툴팁). */
const fixed = (text: string, key: string): HTMLElement =>
el("span", {
className: "m02-sod__fixed",
attrs: { title: key },
children: [el("span", { text }), createTag(to("Fixed"), "neutral")],
});
/** 「종류별」 탭이 쓰는 반영 칸들 — [글, 칸] 짝. */
export function reflectCells(
def: StructDef,
type: TypeDef,
edit: boolean,
changed: () => void,
): Array<[string, HTMLElement]> {
const row = rowsOf(def).get(type.type_id);
if (!row) return [];
const ctx = { def, type, row, edit, changed };
return [
[to("ColList"), reflectCell(ctx, "목록")],
[to("ColPlacement"), fixed(PLACE_KO[row.placement] ?? row.placement, row.placement)],
[to("ColOwner"), fixed(OWNER_KO[row.owner] ?? row.owner, row.owner)],
[to("ColStation"), reflectCell(ctx, "횡단도")],
[to("ColTitle"), reflectCell(ctx, "카드이름")],
[to("ColShape"), reflectCell(ctx, "형상")],
[to("ColShapeOpts"), shapeOptsCell(ctx)],
[to("ColColor"), colorCell(ctx)],
[to("Col3D"), reflectCell(ctx, "3D")],
];
}
function moveButton(label: string, run: () => boolean, off: boolean, changed: () => void) {
const b = createButton({ label, variant: "ghost", size: "sm" });
b.disabled = off;
b.addEventListener("click", () => run() && changed());
return b;
}
/** 그 종류 검사 글 — 이름 · 키가 든 줄. */
const issuesOf = (issues: readonly string[], type: TypeDef): string[] =>
issues.filter((t) => t.includes(`「${type.name}」`) || t.includes(`「${type.type_id}`));
export function buildTable(opt: {
def: StructDef;
edit: boolean;
changed: () => void;
issues: readonly string[];
}): HTMLElement {
const { def, edit, changed, issues } = opt;
const heads = [
"ColFamily",
"ColKind",
"ColName",
"ColList",
"ColPlacement",
"ColOwner",
"ColStation",
"ColTitle",
"ColShape",
"ColShapeOpts",
"ColColor",
"Col3D",
"ColCheck",
] as const;
const td = (child: HTMLElement | string): HTMLElement =>
el("td", typeof child === "string" ? { text: child } : { children: [child] });
const body: HTMLElement[] = [];
const families = Object.keys(def.구조물군);
families.forEach((g, gi) => {
const name = textBox(def.구조물군[g], (v) => (def.구조물군[g] = v), changed, {
edit,
attr: "data-sod-family-name",
});
const familyRow = el("tr", {
className: "m02-sod__familyrow",
attrs: { "data-sod-table-family": g },
children: [
el("td", {
attrs: { colspan: String(heads.length) },
children: [
el("strong", { text: g }),
name,
...(edit
? [
moveButton(to("GroupUp"), () => stepFamily(def, g, -1), gi === 0, changed),
moveButton(
to("GroupDown"),
() => stepFamily(def, g, 1),
gi === families.length - 1,
changed,
),
]
: []),
],
}),
],
});
body.push(familyRow);
const kinds = def.types.filter((t) => t.group === g);
kinds.forEach((type, ti) => {
const cells = new Map(reflectCells(def, type, edit, changed));
const bad = issuesOf(issues, type);
const reset = createButton({ label: to("Reset"), variant: "ghost", size: "sm" });
reset.disabled = !edit || !(def as { 반영?: Record<string, unknown> }).반영?.[type.type_id];
reset.addEventListener("click", () => (resetRow(def, type.type_id), changed()));
body.push(
el("tr", {
attrs: { "data-sod-table-kind": type.type_id },
children: [
td(""),
el("td", {
attrs: { title: type.type_id }, // 영어 키는 툴팁만(322-2 다듬기)
children: [
...(edit
? [
moveButton(
to("GroupUp"),
() => stepType(def, type.type_id, -1),
ti === 0,
changed,
),
moveButton(
to("GroupDown"),
() => stepType(def, type.type_id, 1),
ti === kinds.length - 1,
changed,
),
]
: []),
],
}),
td(
textBox(type.name, (v) => (type.name = v), changed, {
edit,
attr: "data-sod-kind-name",
}),
),
...[
"ColList",
"ColPlacement",
"ColOwner",
"ColStation",
"ColTitle",
"ColShape",
"ColShapeOpts",
"ColColor",
"Col3D",
].map((key) => td(cells.get(to(key as (typeof heads)[number])) ?? "")),
el("td", {
attrs: { "data-sod-table-check": "" },
children: [
bad.length ? createText(bad.join(" · "), "error") : createTag(to("Ok"), "accent"),
reset,
],
}),
],
}),
);
});
});
return el("div", {
className: "m02-sod__tablewrap",
children: [
createText(to("TableNote")),
el("table", {
className: "ui-table ui-table--data m02-sod__table",
attrs: { "data-sod-table": "" },
children: [
el("thead", {
children: [el("tr", { children: heads.map((h) => el("th", { text: to(h) })) })],
}),
el("tbody", { children: body }),
],
}),
],
});
}
/** 「종류별」 탭 머리 아래 반영 칸 묶음(한눈 표 한 줄과 같은 칸). */
export function buildReflectBlock(
def: StructDef,
type: TypeDef,
edit: boolean,
changed: () => void,
): HTMLElement {
return el("div", {
className: "m02-sod__block",
attrs: { "data-sod-reflect-block": "" },
children: [
el("h4", { className: "m02-opts__group", text: to("ReflectHead") }),
el("div", {
className: "m02-sod__reflect",
children: reflectCells(def, type, edit, changed).map(([label, cell]) =>
el("label", {
className: "m02-sod__reflectrow",
children: [el("span", { text: label }), cell],
}),
),
}),
],
});
}
@@ -1,125 +0,0 @@
/* =============================================================================
* M02_SO_Def_Ui.ts
* 구조물 정의 편집 화면(PLAN 48-2)의 작은 입력 부품 — 글 · 숫자 · 체크 · 고르기 · 위아래 단추.
* 값은 받은 손잡이로 사본만 고침 · 글은 칸을 떠날 때(`change`) 다시 그림(초점 안 끊김).
* ========================================================================== */
import { createButton, el } from "@ui/ui_template_elements";
import { step } from "./M02_SO_Def_Model";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createCheckbox } from "@ui/ui_template_checkbox";
/** 글 칸 — 글자마다 `set` · 떠날 때 `done` */
export function textBox(
value: string,
set: (v: string) => void,
done: () => void,
opt: { edit: boolean; attr?: string; place?: string; cls?: string; max?: number },
): HTMLInputElement {
const box = el("input", {
className: `ui-input ui-input--sm ${opt.cls ?? ""}`,
attrs: {
type: "text",
maxlength: String(opt.max ?? 40),
...(opt.attr ? { [opt.attr]: "" } : {}),
},
}) as HTMLInputElement;
box.value = value;
box.placeholder = opt.place ?? "";
box.disabled = !opt.edit;
box.addEventListener("input", () => {
set(box.value);
box.classList.toggle("is-invalid", !box.value.trim() && !opt.place);
});
box.addEventListener("change", done);
return box;
}
/** 숫자 칸 — 범위 밖 · 빈 칸은 무름 */
export function numberBox(
value: number,
set: (v: number) => void,
opt: { edit: boolean; min: number; max: number; attr?: string },
): HTMLInputElement {
const box = el("input", {
className: "ui-input ui-input--sm m02-sod__num",
attrs: {
type: "number",
min: String(opt.min),
max: String(opt.max),
...(opt.attr ? { [opt.attr]: "" } : {}),
},
}) as HTMLInputElement;
box.value = String(value);
box.disabled = !opt.edit;
box.addEventListener("change", () => {
const n = Math.round(Number(box.value));
if (box.value === "" || !Number.isFinite(n) || n < opt.min || n > opt.max) {
box.value = String(value);
return;
}
set(n);
});
return box;
}
/** 체크 + 글 */
export function checkBox(
label: string,
on: boolean,
set: (v: boolean) => void,
opt: { edit: boolean; attr?: string },
): HTMLLabelElement {
// 체크 부품 — 속성(data-sod-*)은 칸에 그대로
const { root, input } = createCheckbox(label, {
checked: on,
disabled: !opt.edit,
onChange: set,
});
if (opt.attr) input.setAttribute(opt.attr, "");
root.classList.add("m02-sod__check");
return root;
}
/** 고르기 — [값, 글] 짝 */
export function pickBox(
pairs: readonly (readonly [string, string])[],
value: string,
set: (v: string) => void,
opt: { edit: boolean; attr?: string; cls?: string },
): HTMLSelectElement {
const box = el("select", {
className: `ui-input ui-input--sm ${opt.cls ?? ""}`,
attrs: opt.attr ? { [opt.attr]: "" } : {},
}) as HTMLSelectElement;
box.append(...pairs.map(([v, t]) => new Option(t, v)));
box.value = value;
box.disabled = !opt.edit;
box.addEventListener("change", () => set(box.value));
return box;
}
/** 위로 · 아래로 단추 둘 — 고치는 사람만 · 옮겼으면 `changed` */
export function moveButtons<T>(
list: T[],
item: T,
changed: () => void,
edit: boolean,
): HTMLElement[] {
if (!edit) return [];
const index = list.indexOf(item);
const make = (label: string, delta: number, off: boolean): HTMLButtonElement => {
const b = createButton({ label, variant: "ghost", size: "sm" });
b.disabled = off;
b.addEventListener("click", () => step(list, list.indexOf(item), delta) && changed());
return b;
};
return [make(to("GroupUp"), -1, index <= 0), make(to("GroupDown"), 1, index >= list.length - 1)];
}
/** 절 제목 + 안내 한 줄 */
export const head = (title: string, note?: string): HTMLElement[] => [
el("h4", { className: "m02-opts__group", text: title }),
...(note ? [createText(note)] : []),
];
@@ -1,241 +0,0 @@
"""M02 구조물 정의 한 벌(PLAN 48-1) — 정본 `resources/master_template/구조물정의.json`.
틀 = `docs/raw/M02_구조물옵션정의/정의_틀.md`. 읽기 = 로그인 누구나 · 쓰기 = 시스템 관리자만.
판 = 정수 · 저장마다 +1 · 앞 판은 `구조물정의_이력/판_N.json` 으로 남김(지난 정의 값 읽기용).
검사 = 칸 꼴 · 키 겹침 · 표시 · 그룹 · 배치 · 규칙 대상 있음 — 틀리면 422 · 낡은 판 409.
"""
from __future__ import annotations
import json
from collections.abc import Callable
from pathlib import Path
from typing import Any
from pydantic import ValidationError
from B05_Profile import B05_Profile_Structures_Schema as schema
from common_util.common_util_json import atomic_write_json
from common_util.common_util_time import utc_from_timestamp
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions.M02_SO_Check import catalog_errors
FILE = "구조물정의.json"
HISTORY = "구조물정의_이력"
# 반영 · 부품 = 구조물 표 칸(322-2 · 없으면 처음값 · 검사 = `M02_SO_Check`)
TOP = {"판", "schema_version", "comment", "구조물군", "동작", "types", "반영", "부품"}
SECTIONS = {"종류": dict, "표시": dict, "그룹": dict, "배치": dict, "규칙": list}
SPOT = ("줄", "칸", "너비")
def read() -> dict[str, Any]:
return schema.load_definition()
def history_path(version: int) -> Path:
return Path(schema.DEFINITION_PATH).parent / HISTORY / f"판_{version}.json"
def history() -> list[dict[str, Any]]:
"""지난 판 목록 `[{판, 저장일}]` — 이력 `판_N.json` · 저장일 = 파일 고친 때(분까지)."""
folder = history_path(1).parent
rows = []
for path in folder.glob("판_*.json") if folder.is_dir() else []:
number = path.stem.removeprefix("판_")
if number.isdigit():
when = utc_from_timestamp(path.stat().st_mtime)
rows.append({"판": int(number), "저장일": when})
return sorted(rows, key=lambda r: r["판"], reverse=True)
def read_version(version: int) -> dict[str, Any]:
"""지난 판 한 벌(읽기만) — 없으면 404."""
path = history_path(version)
if not path.is_file():
raise store.StoreError(404, f"판 {version} 이력이 없음")
return json.loads(path.read_text("utf-8"))
def _type_errors(doc: dict[str, Any]) -> tuple[list[str], dict[str, dict[str, Any]]]:
"""(틀린 것 · 종류 → {옵션 키: 옵션}) — 종류 꼴 · 키 겹침 · 구조물군 있음."""
errors: list[str] = []
keys: dict[str, dict[str, Any]] = {}
groups = doc.get("구조물군")
if not isinstance(groups, dict):
errors.append("구조물군은 {키: 이름} 묶음이어야 함")
groups = {}
for row in doc.get("types") if isinstance(doc.get("types"), list) else []:
try:
t = schema.StructureType.model_validate(
schema.without_retired(row) if isinstance(row, dict) else row
)
except ValidationError as e:
errors.append(
f"종류 「{row.get('type_id') if isinstance(row, dict) else row}」 꼴 — {e}"
)
continue
if t.type_id in keys:
errors.append(f"종류 키 「{t.type_id}」 겹침")
if t.group not in groups:
errors.append(f"「{t.type_id}」 구조물군 「{t.group}」 이 구조물군에 없음")
opts: dict[str, Any] = {}
for o in t.options:
if o.key in opts:
errors.append(f"「{t.type_id}」 옵션 키 「{o.key}」 겹침")
if o.input == "select" and not o.choices:
errors.append(f"「{t.type_id}.{o.key}」 고르기 꼴은 선택지가 있어야 함")
opts[o.key] = o
keys[t.type_id] = opts
if not isinstance(doc.get("types"), list) or not keys:
errors.append("types 는 종류 목록이어야 함")
return errors, keys
def _names_ok(value: Any) -> bool:
"""구조물 명세 이름 바꿈 표 — `{컨테이너[.항목[=값]]: 빈 글 아닌 이름}`."""
return isinstance(value, dict) and all(
isinstance(k, str) and isinstance(v, str) and v.strip() for k, v in value.items()
)
def _kind_errors(doc: dict[str, Any], keys: dict[str, dict[str, Any]]) -> list[str]:
"""종류마다 덧칸 — `{기준측점: 참거짓, 동작: [동작 이름], 이름: {명세 이름 키: 이름}}`(이름 = PLAN 52)."""
errors: list[str] = []
acts = doc.get("동작") if isinstance(doc.get("동작"), dict) else {}
for tid, row in doc["종류"].items():
if tid not in keys or not isinstance(row, dict):
errors.append(f"종류 덧칸 「{tid}」 — 없는 종류이거나 묶음 아님")
continue
for name, value in row.items():
if name == "기준측점" and isinstance(value, bool):
continue
if name == "동작" and isinstance(value, list) and all(a in acts for a in value):
continue
if name == "이름" and _names_ok(value):
continue
if name == "본보기" and isinstance(value, str) and value in keys:
continue # 복사한 종류의 원본(323-7) — 같은 군 등은 `_template_errors`
errors.append(
f"종류 덧칸 「{tid}.{name}」 이 틀림(기준측점 참거짓 · 동작 = 동작 이름들 · "
"이름 = 글 묶음 · 본보기 = 있는 종류 키)"
)
return errors
def _spot_errors(doc: dict[str, Any], keys: dict[str, dict[str, Any]]) -> list[str]:
"""배치 — `{종류: {옵션 키: {줄, 칸, 너비}}}` · 1 이상 정수."""
errors: list[str] = []
for tid, row in doc["배치"].items():
if tid not in keys or not isinstance(row, dict):
errors.append(f"배치 「{tid}」 — 없는 종류이거나 묶음 아님")
continue
for key, spot in row.items():
ok = isinstance(spot, dict) and set(spot) <= set(SPOT)
ok = ok and all(type(v) is int and v >= 1 for v in spot.values())
if key not in keys[tid] or not ok:
errors.append(
f"배치 「{tid}.{key}」 — 없는 옵션이거나 줄 · 칸 · 너비가 1 이상 정수 아님"
)
return errors
def _rule_errors(doc: dict[str, Any], keys: dict[str, dict[str, Any]]) -> list[str]:
"""규칙 — `{종류, 만약: {옵션, 값들}, 그러면: {옵션, 선택지? · 보이기? · 기본값?}}`."""
errors: list[str] = []
for i, rule in enumerate(doc["규칙"], 1):
where = f"규칙 {i}"
if not isinstance(rule, dict) or rule.get("종류") not in keys:
errors.append(f"{where} — 없는 종류")
continue
opts = keys[rule["종류"]]
when, then = rule.get("만약"), rule.get("그러면")
if not isinstance(when, dict) or not isinstance(then, dict):
errors.append(f"{where} — 만약 · 그러면은 묶음이어야 함")
continue
src, dst = opts.get(when.get("옵션")), opts.get(then.get("옵션"))
if src is None or dst is None or src is dst:
errors.append(f"{where} — 만약 · 그러면 옵션이 없거나 같음")
continue
values = when.get("값들")
if not isinstance(values, list) or not values:
errors.append(f"{where} — 값들이 비었음")
elif src.input == "select" and not set(map(str, values)) <= set(src.choices):
errors.append(f"{where} — 값들이 「{src.key}」 선택지에 없음")
effects = set(then) - {"옵션"}
if not effects or not effects <= {"선택지", "보이기", "기본값"}:
errors.append(f"{where} — 그러면은 선택지 · 보이기 · 기본값 중 하나 이상")
allowed = dst.choices
if "선택지" in then:
pick = then["선택지"]
if dst.input != "select" or not isinstance(pick, list) or not set(pick) <= set(allowed):
errors.append(f"{where} — 선택지는 「{dst.key}」 고르기 선택지 안에서만")
else:
allowed = pick
if "보이기" in then and not isinstance(then["보이기"], bool):
errors.append(f"{where} — 보이기는 참거짓")
if "기본값" in then and dst.input == "select" and str(then["기본값"]) not in allowed:
errors.append(f"{where} — 기본값이 「{dst.key}」 선택지에 없음")
return errors
def check(doc: Any, before: dict[str, Any] | None = None) -> list[str]:
"""정의 한 벌 검사 — 틀린 것 목록(빈 목록 = 통과). `before` = 지금 판(만든 뒤 고정 · 322-2)."""
from M02_MasterTemplete.StructOptions import M02_SO_Groups as groups
from M02_MasterTemplete.StructOptions import M02_SO_Options as options
if not isinstance(doc, dict):
return ["정의는 묶음이어야 함"]
errors = [f"모르는 칸 「{k}」" for k in doc if k not in TOP and k not in SECTIONS]
errors += [
f"「{k}」 꼴이 틀림" for k, kind in SECTIONS.items() if not isinstance(doc.get(k), kind)
]
if not isinstance(doc.get("동작"), dict):
errors.append("동작은 {이름: 뜻} 묶음이어야 함")
if errors:
return errors
found, keys = _type_errors(doc)
errors += found
plain = {tid: set(opts) for tid, opts in keys.items()}
for fn, section in ((options._clean, "표시"), (groups._clean, "그룹")):
try:
fn(doc[section], plain)
except store.StoreError as e:
errors += e.detail["errors"] if isinstance(e.detail, dict) else [str(e.detail)]
errors += _kind_errors(doc, keys) + _spot_errors(doc, keys) + _rule_errors(doc, keys)
return errors + ([] if errors else catalog_errors(doc, before))
def _commit(change: Callable[[dict[str, Any]], dict[str, Any]], version: Any) -> dict[str, Any]:
"""판이 같을 때만 고쳐 씀 — 앞 판은 이력으로 · 새 판 = 앞 판 + 1."""
path = Path(schema.DEFINITION_PATH)
with store._LOCK:
current = read()
have = int(current.get("판", 1))
if str(version) != str(have):
raise store.StoreError(409, {"stale": [FILE], "판": have})
doc = {**change(current), "판": have}
errors = check(doc, current)
if errors:
raise store.StoreError(422, {"errors": errors})
atomic_write_json(history_path(have), current)
atomic_write_json(path, {**doc, "판": have + 1})
return read()
def save(doc: Any, version: Any) -> dict[str, Any]:
"""정의 통째로 고쳐 씀(시스템 관리자) — 돌려주는 것 = 새 정의."""
if not isinstance(doc, dict):
raise store.StoreError(400, "정의는 묶음이어야 함")
# 옛 칸(drawing_views)은 [저장] 때 빠짐(323-7 · 아무도 안 읽음)
types = doc.get("types")
if isinstance(types, list):
doc = {
**doc,
"types": [schema.without_retired(t) if isinstance(t, dict) else t for t in types],
}
return _commit(lambda _: dict(doc), version)
def save_sections(changes: dict[str, Any], version: Any) -> dict[str, Any]:
"""정의 몇 칸만 고쳐 씀(옵션 보이기 · 그룹 화면)."""
return _commit(lambda current: {**current, **changes}, version)
@@ -1,150 +0,0 @@
"""M02 구조물 옵션 그룹 — 구조물 종류 안에 이름 붙은 묶음(PLAN 46-2).
정본 = 구조물 정의 한 벌(`M02_SO_Definition` · PLAN 48-1)의 「그룹」 칸 =
`{type_id: [{"id": "g1a2b3c", "이름": "유입구 기슭막이", "옵션": [...], "형상"?: {...}}]}`
— 없는 종류 = 그룹 없음 · 빈 그룹(옵션 0)도 그룹 · 형상 = 길이 · 높이 · 전 · 후 받기 + 뜻.
그룹 하나 = 프로젝트 B05 · B06 폼의 보조 컨테이너 하나(제목 = 이름) — 그 안에서 구조물 조합
항목 하나를 지정(구조물 기록 `group_items[그룹 id]`). 그룹에 안 넣은 옵션 = 본체 칸(`summary_item`).
옵션 하나는 한 종류 안에서 그룹 하나에만. 시스템 공통 · 고쳐 씀은 시스템 관리자(길이 막음).
판 = 정의 판(글) · 낡은 판으로 쓰면 409 · 저장마다 정의 판 +1 · 이력.
"""
from __future__ import annotations
import logging
import re
from typing import Any
from B05_Profile.B05_Profile_Structures_Schema import load_definition, load_structure_types
from M02_MasterTemplete import M02_MasterTemplete_Store as store
GROUP_ID = re.compile(r"^g[0-9a-z]{1,16}$")
NAME_MAX = 40
SHAPE = ("길이", "높이", "전", "후") # 그룹이 받을 형상 칸 — `{칸: {받기: 참거짓, 뜻: 글}}`
logger = logging.getLogger(__name__)
def _load() -> tuple[dict[str, Any], str]:
"""(그룹 표 · 판) — 정의 한 벌(`M02_SO_Definition`)의 「그룹」 칸 · 판 = 정의 판 글."""
doc = load_definition()
return doc.get("그룹") or {}, str(doc.get("판", 1))
def groups_of() -> dict[str, list[dict[str, Any]]]:
"""종류 → `[{id, name, options}]` — 폼 응답용 · 깨진 표 · 모르는 종류는 빼고 로그만."""
try:
doc = _load()[0]
except store.StoreError as e:
logger.warning("구조물 옵션 그룹 표를 못 읽어 그룹 없음으로 봄 — %s", e.detail)
return {}
known = {t.type_id: {o.key for o in t.options} for t in load_structure_types()}
out: dict[str, list[dict[str, Any]]] = {}
for type_id, rows in doc.items():
if type_id not in known or not isinstance(rows, list):
continue
for row in rows:
if not isinstance(row, dict) or not GROUP_ID.match(str(row.get("id", ""))):
continue
keys = [k for k in row.get("옵션") or [] if k in known[type_id]]
out.setdefault(type_id, []).append(
{"id": row["id"], "name": str(row.get("이름") or row["id"]), "options": keys}
)
return out
def listing() -> dict[str, Any]:
"""`{판, 그룹, 종류}` — 종류 = 레지스트리 전부(옵션 없는 종류도 · 빈 그룹을 둘 수 있음)."""
doc, version = _load()
kinds = [
{
"type_id": t.type_id,
"group": t.group,
"name": t.name,
"enabled": t.enabled,
"options": [
{"key": o.key, "label": o.label, "phase": o.phase, "required": o.required}
for o in t.options
],
}
for t in load_structure_types()
]
return {"판": version, "그룹": doc, "종류": kinds}
def _shape_ok(shape: Any) -> bool:
return isinstance(shape, dict) and all(
k in SHAPE
and isinstance(v, dict)
and isinstance(v.get("받기"), bool)
and isinstance(v.get("뜻", ""), str)
and set(v) <= {"받기", "뜻"}
for k, v in shape.items()
)
def _clean(groups: Any, keys: dict[str, set[str]] | None = None) -> dict[str, list[dict[str, Any]]]:
"""받은 표 검사 — 없는 종류 · 키 · 겹친 id · 이름 · 옵션 두 그룹 · 틀린 형상 422."""
if not isinstance(groups, dict):
raise store.StoreError(400, "그룹은 종류별 묶음이어야 함")
if keys is None:
keys = {t.type_id: {o.key for o in t.options} for t in load_structure_types()}
errors: list[str] = []
out: dict[str, list[dict[str, Any]]] = {}
for type_id, rows in groups.items():
if type_id not in keys:
errors.append(f"없는 구조물 종류 「{type_id}」")
continue
if not isinstance(rows, list):
errors.append(f"「{type_id}」 는 그룹 목록이어야 함")
continue
ids: set[str] = set()
names: set[str] = set()
owner: dict[str, str] = {}
clean: list[dict[str, Any]] = []
for row in rows:
if not isinstance(row, dict):
errors.append(f"「{type_id}」 그룹은 묶음이어야 함")
continue
gid = str(row.get("id", ""))
name = str(row.get("이름", "")).strip()
opts = row.get("옵션") or []
if not GROUP_ID.match(gid) or gid in ids:
errors.append(f"「{type_id}」 그룹 id 「{gid}」 가 틀리거나 겹침")
if not name or len(name) > NAME_MAX or name in names:
errors.append(
f"「{type_id}」 그룹 이름 「{name}」 은 1~{NAME_MAX}자 · 겹치면 안 됨"
)
if not isinstance(opts, list):
errors.append(f"「{type_id}.{name}」 옵션은 목록이어야 함")
opts = []
for key in opts:
if key not in keys[type_id]:
errors.append(f"「{type_id}」 에 없는 옵션 「{key}」")
elif key in owner:
errors.append(
f"「{type_id}.{key}」 는 「{owner[key]}」 · 「{name}」 두 그룹에 있음"
)
else:
owner[key] = name
if "형상" in row and not _shape_ok(row["형상"]):
errors.append(
f"「{type_id}.{name}」 형상은 {{길이 · 높이 · 전 · 후: {{받기, 뜻}}}}"
)
ids.add(gid)
names.add(name)
kept = {"id": gid, "이름": name, "옵션": [k for k in opts if k in keys[type_id]]}
clean.append({**kept, "형상": row["형상"]} if "형상" in row else kept)
if clean:
out[type_id] = clean
if errors:
raise store.StoreError(422, {"errors": errors})
return out
def save(groups: Any, version: str) -> dict[str, Any]:
"""고쳐 씀 — 판이 같을 때만. 돌려주는 것 = 새 `listing()`."""
from M02_MasterTemplete.StructOptions.M02_SO_Definition import save_sections
save_sections({"그룹": _clean(groups)}, version)
return listing()
@@ -1,164 +0,0 @@
/* =============================================================================
* M02_SO_Groups.ts
* 구조물 정의 화면의 **옵션 그룹** 부품(PLAN 46-2 · 48-2) — 고른 종류의 그룹 목록
* (이름 · 위로 · 아래로 · 지우기 · 형상 칸 길이 · 높이 · 전 · 후 받기 켬끔과 뜻 · [그룹 추가]) ·
* 옵션 줄마다 「들어갈 자리」 고르기(본체 · 그룹).
* 값은 화면이 쥔 고칠 사본에만 — 저장은 화면 [저장](`M02_SO_Def.ts`).
* 그룹 하나 = 프로젝트 B05 · B06 폼의 보조 컨테이너 하나 · 옵션이 없어도 됨(서버 `M02_SO_Groups.py`).
* ========================================================================== */
import { createButton, el, showConfirmDialog } from "@ui/ui_template_elements";
import { SHAPE_KEYS, type GroupDef } from "./M02_SO_Def_Model";
import { checkBox, textBox } from "./M02_SO_Def_Ui";
import { to } from "./M02_SO_Text";
import { createText } from "@ui/ui_template_text";
import { createEmpty } from "@ui/ui_template_empty";
const NAME_MAX = 40;
/** 새 그룹 id — 서버 규칙 `g[0-9a-z]{1,16}` · 같은 종류 안에서 안 겹치게 */
export function newGroupId(list: readonly GroupDef[]): string {
const taken = new Set(list.map((g) => g.id));
for (;;) {
const id = `g${Math.random().toString(36).slice(2, 8)}`;
if (/^g[0-9a-z]{1,16}$/.test(id) && !taken.has(id)) return id;
}
}
/** 그 옵션이 든 그룹 id — 없으면 null(본체) */
export function groupOf(list: readonly GroupDef[], key: string): string | null {
return list.find((g) => g.옵션.includes(key))?.id ?? null;
}
/** 옵션을 그룹(null = 본체)으로 옮김 — 한 옵션은 한 그룹에만 */
export function moveOption(list: GroupDef[], key: string, gid: string | null): void {
for (const g of list) g.옵션 = g.옵션.filter((k) => k !== key);
const target = gid ? list.find((g) => g.id === gid) : null;
if (target) target.옵션.push(key);
}
export interface GroupBlockOptions {
/** 고른 종류의 그룹(고칠 사본 — 이 부품이 직접 고침) */
list: GroupDef[];
edit: boolean;
/** 고쳤음 — 화면이 고침 표시 · 다시 그리기 */
changed: () => void;
}
/** 그룹 형상 줄 — 칸마다 받기 체크 + 뜻(무엇을 정하는지 한 줄) */
function shapeLine(group: GroupDef, edit: boolean, changed: () => void): HTMLElement {
const shape = (group.형상 ??= {});
return el("div", {
className: "m02-sog__shape",
attrs: { "data-sog-shape": group.id },
children: SHAPE_KEYS.map((k) => {
const f = shape[k] ?? { 받기: false, 뜻: "" };
const on = checkBox(
to(`Shape_${k}` as const),
f.받기,
(v) => ((shape[k] = { ...f, 받기: v }), changed()),
{ edit, attr: `data-sog-shape-${SHAPE_KEYS.indexOf(k)}` },
);
const mean = textBox(f.뜻, (v) => (shape[k] = { ...(shape[k] ?? f), 뜻: v }), changed, {
edit: edit && f.받기,
cls: "m02-sog__mean",
place: to("ShapeMean"),
});
return el("div", { className: "m02-sog__shapecell", children: [on, mean] });
}),
});
}
/** 그룹 목록 칸 — 제목 · 안내 · 그룹 줄 · [그룹 추가] */
export function buildGroupBlock(opt: GroupBlockOptions): HTMLElement {
const { list } = opt;
const rows = list.map((group, index) => {
const name = el("input", {
className: "ui-input ui-input--sm m02-sog__name",
attrs: { type: "text", maxlength: String(NAME_MAX), "data-sog-name": group.id },
}) as HTMLInputElement;
name.value = group.이름;
name.placeholder = to("GroupName");
name.disabled = !opt.edit;
// 글자마다 사본만 고침(다시 그리면 초점이 끊김) · 칸을 떠날 때 다시 그림(선택지 이름)
name.addEventListener("input", () => {
group.이름 = name.value;
name.classList.toggle("is-invalid", !name.value.trim());
});
name.addEventListener("change", () => opt.changed());
const step = (delta: number): void => {
const at = index + delta;
if (at < 0 || at >= list.length) return;
[list[index], list[at]] = [list[at], list[index]];
opt.changed();
};
const up = createButton({ label: to("GroupUp"), variant: "ghost", size: "sm" });
const down = createButton({ label: to("GroupDown"), variant: "ghost", size: "sm" });
const del = createButton({ label: to("GroupDel"), variant: "danger", size: "sm" });
up.disabled = !opt.edit || index === 0;
down.disabled = !opt.edit || index === list.length - 1;
del.disabled = !opt.edit;
up.addEventListener("click", () => step(-1));
down.addEventListener("click", () => step(1));
del.addEventListener("click", async () => {
if (!(await showConfirmDialog(to("GroupDelAsk", group.이름), to("GroupDel")))) return;
list.splice(list.indexOf(group), 1);
opt.changed();
});
const line = el("div", {
className: "m02-sog__row",
attrs: { "data-sog-group": group.id },
children: [
name,
el("small", {
className: "ui-text ui-text--muted m02-opts__key",
text: to("GroupCount", String(group.옵션.length)),
}),
...(opt.edit ? [up, down, del] : []),
],
});
return el("div", {
className: "m02-sog__item",
children: [line, shapeLine(group, opt.edit, opt.changed)],
});
});
const add = createButton({ label: to("GroupAdd"), variant: "ghost", size: "sm" });
add.setAttribute("data-sog-add", "");
add.addEventListener("click", () => {
let n = list.length + 1;
while (list.some((g) => g.이름 === to("GroupNew", String(n)))) n += 1;
list.push({ id: newGroupId(list), 이름: to("GroupNew", String(n)), 옵션: [] });
opt.changed();
});
return el("div", {
className: "ui-card m02-sog",
attrs: { "data-pad": "12" },
children: [
el("h4", { className: "m02-opts__group", text: to("GroupHead") }),
createText(to("GroupNote")),
...(rows.length ? rows : [createEmpty({ text: to("GroupNone"), small: true })]),
...(opt.edit ? [el("div", { className: "m02-side__row", children: [add] })] : []),
],
});
}
/** 옵션 줄의 「들어갈 자리」 고르기 — 본체 · 그룹 이름들 */
export function buildPlaceSelect(
list: GroupDef[],
key: string,
edit: boolean,
changed: () => void,
): HTMLSelectElement {
const select = el("select", {
className: "ui-input ui-input--sm m02-sog__place",
attrs: { "data-sog-place": key },
}) as HTMLSelectElement;
select.append(new Option(to("Main"), ""), ...list.map((g) => new Option(g.이름 || g.id, g.id)));
select.value = groupOf(list, key) ?? "";
select.disabled = !edit || !list.length;
select.addEventListener("change", () => {
moveOption(list, key, select.value || null);
changed();
});
return select;
}
@@ -1,161 +0,0 @@
"""M02 구조물 옵션 보이기 — 구조물 종류마다 B05/B06 폼에 보일 옵션을 사용자가 체크.
정본 = 구조물 정의(`M02_SO_Definition` · PLAN 48-1) 「표시」 칸 = `{type_id: {option_key: false}}`
— 없는 종류 · 키는 보임.
저장은 **숨김(false)만** 남김 — 「모두 보임」 = `{}`.
옵션 정의 · 옛 값은 그대로 — 폼이 그리는 것만 갈림(`GET /api/projects/structure-types` `visible`).
판 = 정의 판(글) · 낡은 판으로 쓰면 409 · 저장마다 정의 판 +1 · 이력.
"""
from __future__ import annotations
import logging
from typing import Any
from pydantic import BaseModel, Field
from B05_Profile.B05_Profile_Structures_Schema import (
StructureOptionField,
StructureType,
StructureTypesResponse,
load_definition,
load_structure_types,
registry_schema_version,
)
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions.M02_SO_Groups import groups_of
logger = logging.getLogger(__name__)
class OptionWithVisible(StructureOptionField):
"""폼 옵션 한 칸 + 보임 여부(서버가 채움)."""
visible: bool = True
class OptionGroup(BaseModel):
"""옵션 그룹 한 개(PLAN 46-2 · `M02_SO_Groups`) — 폼의 보조 컨테이너 하나 · 빈 옵션도 됨."""
id: str
name: str
options: list[str] = Field(default_factory=list)
class TypeWithVisible(StructureType):
options: list[OptionWithVisible] = Field(default_factory=list)
groups: list[OptionGroup] = Field(default_factory=list)
class TypesWithVisible(StructureTypesResponse):
"""`GET /structure-types` 응답 — 옵션마다 `visible` 칸 · 종류마다 `groups`."""
types: list[TypeWithVisible]
def _load() -> tuple[dict[str, Any], str]:
"""(표시 표 · 판) — 정의 한 벌(`M02_SO_Definition`)의 「표시」 칸 · 판 = 정의 판 글."""
doc = load_definition()
return doc.get("표시") or {}, str(doc.get("판", 1))
def _shown(doc: dict[str, Any], type_id: str, key: str) -> bool:
row = doc.get(type_id)
return not (isinstance(row, dict) and row.get(key) is False)
def hidden_keys() -> dict[str, set[str]]:
"""숨긴 옵션(종류 → 키 집합) — 저장 검증이 숨긴 옵션을 필수로 안 침 · 깨진 표는 모두 보임."""
try:
doc = _load()[0]
except store.StoreError as e:
logger.warning("구조물 옵션 표시 표를 못 읽어 모두 보임으로 봄 — %s", e.detail)
return {}
return {
type_id: {key for key, shown in row.items() if shown is False}
for type_id, row in doc.items()
if isinstance(row, dict)
}
def with_visible() -> TypesWithVisible:
"""레지스트리 정본 + 보임 여부 — 파일이 깨졌으면 모두 보임(폼이 죽지 않게 · 로그만)."""
try:
doc = _load()[0]
except store.StoreError as e:
logger.warning("구조물 옵션 표시 표를 못 읽어 모두 보임으로 냄 — %s", e.detail)
doc = {}
groups = groups_of()
types = [
{
**t.model_dump(),
"options": [
{**o.model_dump(), "visible": _shown(doc, t.type_id, o.key)} for o in t.options
],
"groups": groups.get(t.type_id, []),
}
for t in load_structure_types()
]
return TypesWithVisible.model_validate(
{"schema_version": registry_schema_version(), "types": types}
)
def listing() -> dict[str, Any]:
"""`{판, 표시, 종류}` — 표시 = 숨긴 것만 · 종류 = 옵션이 있는 종류와 그 옵션."""
doc, version = _load()
hidden: dict[str, dict[str, bool]] = {}
kinds = []
for t in load_structure_types():
if not t.options:
continue
off = {o.key: False for o in t.options if not _shown(doc, t.type_id, o.key)}
if off:
hidden[t.type_id] = off
kinds.append(
{
"type_id": t.type_id,
"group": t.group,
"name": t.name,
"enabled": t.enabled,
"options": [
{"key": o.key, "label": o.label, "phase": o.phase, "required": o.required}
for o in t.options
],
}
)
return {"판": version, "표시": hidden, "종류": kinds}
def _clean(shown: Any, keys: dict[str, set[str]] | None = None) -> dict[str, dict[str, bool]]:
"""받은 표 검사 → 숨김만 남김. 없는 종류 · 키 · 참거짓 아닌 값은 422."""
if not isinstance(shown, dict):
raise store.StoreError(400, "표시는 종류별 묶음이어야 함")
if keys is None:
keys = {t.type_id: {o.key for o in t.options} for t in load_structure_types()}
errors: list[str] = []
out: dict[str, dict[str, bool]] = {}
for type_id, row in shown.items():
if type_id not in keys:
errors.append(f"없는 구조물 종류 「{type_id}」")
elif not isinstance(row, dict):
errors.append(f"「{type_id}」 는 옵션별 묶음이어야 함")
else:
for key, value in row.items():
if key not in keys[type_id]:
errors.append(f"「{type_id}」 에 없는 옵션 「{key}」")
elif not isinstance(value, bool):
errors.append(f"「{type_id}.{key}」 는 참 · 거짓이어야 함")
elif not value:
out.setdefault(type_id, {})[key] = False
if errors:
raise store.StoreError(422, {"errors": errors})
return out
def save(shown: Any, version: str) -> dict[str, Any]:
"""고쳐 씀 — 판이 같을 때만. 돌려주는 것 = 새 `listing()`."""
from M02_MasterTemplete.StructOptions.M02_SO_Definition import save_sections
save_sections({"표시": _clean(shown)}, version)
return listing()
@@ -1,53 +0,0 @@
/* =============================================================================
* M02_SO_Options.ts
* 좌측 「구조물 옵션 정의」 줄(구조물 집계 양식 아래 별도 · 시스템 층) — 누르면 메인 칸에
* 정의 편집 화면(PLAN 48-2 · `M02_SO_Def.ts`) · 고쳐 씀은 시스템 관리자만 · 다른 역할은 읽기만.
* 옛 「보이기 · 그룹」 화면(46장)은 정의 화면의 옵션 줄 「보이기」 · 그룹 칸으로 들어감.
* ========================================================================== */
import { el } from "@ui/ui_template_elements";
import { openDefScreen } from "./M02_SO_Def";
import "@ui/ui_template_card.css";
import "./M02_SO_Style.css";
import { to } from "./M02_SO_Text";
export interface OptionsSectionOptions {
isAdmin: boolean;
/** 저장 안 한 고침을 버릴지 확인 — 취소면 false */
confirmLeave: () => Promise<boolean>;
/** 메인 칸에 화면을 띄움 — 고침 표시 손잡이를 돌려받음 */
show: (label: string, node: HTMLElement) => (dirty: boolean) => void;
/** 화면을 열었음 — 좌측 다른 고름 표시를 지움 */
onOpen: () => void;
}
export interface OptionsSection {
title: string;
body: HTMLElement;
/** 다른 화면을 열었음 — 고름 표시만 지움 */
clear: () => void;
}
export function buildOptionsSection(opt: OptionsSectionOptions): OptionsSection {
const row = el("button", {
className: "m02-side__item ui-sidebar-row",
text: to("Row"),
attrs: { type: "button", "data-options-row": "" },
});
const body = el("div", { className: "m02-side__items ui-sidebar-list", children: [row] });
/** 이 화면이 열려 있는 동안 참 — 다른 것이 열리면 `clear` 가 내림 */
let opened = false;
const mark = (on: boolean): void => {
opened = on;
row.classList.toggle("is-active", on);
};
row.addEventListener("click", async () => {
if (opened || !(await opt.confirmLeave())) return;
if (!(await openDefScreen({ isAdmin: opt.isAdmin, show: opt.show }))) return;
opt.onOpen();
mark(true);
});
return { title: to("Title"), body, clear: () => mark(false) };
}
@@ -1,113 +0,0 @@
"""M02 구조물 옵션 보이기 · 그룹 · 정의 길 — 정본 `M02_SO_Definition.py`(PLAN 48-1) 한 벌.
`router` = 고쳐 씀 · 관리 읽기(`main.py` 가 `system_admin_only` 로 붙임) ·
`read_router` = 읽기만(로그인 누구나 · `main.py` 가 `protected` 로 붙임) · 정의 쓰기는 여기서
시스템 관리자만(`access.require(write=True)` · 아니면 403).
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from B05_Profile.B05_Profile_Structures_Schema import definition_version
from common_util.common_util_auth import verify_session
from M02_MasterTemplete import M02_Layer_Access as access
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete.StructOptions import M02_SO_Definition as definition
from M02_MasterTemplete.StructOptions import M02_SO_Groups as groups
from M02_MasterTemplete.StructOptions import M02_SO_Options as options
router = APIRouter(prefix="/api/m02", tags=["M02 MasterTemplete"])
read_router = APIRouter(prefix="/api/m02", tags=["M02 MasterTemplete"])
class OptionsBody(BaseModel):
판: str = "" # 옵션 표시 표 판 — 어긋나면 409
표시: dict[str, Any] # {종류: {옵션 키: 참 · 거짓}} — 거짓만 남김
class GroupsBody(BaseModel):
판: str = "" # 그룹 표 판 — 어긋나면 409
그룹: dict[str, Any] # {종류: [{id, 이름, 옵션[]}]}
class DefinitionBody(BaseModel):
판: int # 읽어 간 정의 판 — 어긋나면 409
정의: dict[str, Any] # 정의 한 벌(틀 = docs/raw/M02_구조물옵션정의/정의_틀.md)
def _call(fn, *args):
with store.at(store.FOLDER):
try:
return fn(*args)
except store.StoreError as e:
raise HTTPException(status_code=e.status, detail=e.detail) from e
@router.get("/structure-options")
def get_structure_options() -> dict:
"""`{판, 표시, 종류}` — 표시 = 숨긴 것만 · 종류 = 옵션 있는 종류와 그 옵션."""
return _call(options.listing)
@router.put("/structure-options")
def put_structure_options(body: OptionsBody) -> dict:
"""고쳐 씀(낡은 판이면 409 · 없는 종류 · 키는 422) — 돌려주는 것 = 새 `{판, 표시, 종류}`."""
return _call(options.save, body.표시, body.판)
@router.get("/structure-option-groups")
def get_structure_option_groups() -> dict:
"""`{판, 그룹, 종류}` — 그룹 = `{type_id: [{id, 이름, 옵션}]}` · 종류 = 레지스트리 전부."""
return _call(groups.listing)
@router.put("/structure-option-groups")
def put_structure_option_groups(body: GroupsBody) -> dict:
"""고쳐 씀(낡은 판 409 · 없는 종류 · 키 · 겹침 422) — 돌려주는 것 = 새 `{판, 그룹, 종류}`."""
return _call(groups.save, body.그룹, body.판)
@read_router.get("/layers/system/structure-options")
def get_structure_options_read(session=Depends(verify_session)) -> dict:
"""구조물 옵션 보이기 읽기 — 로그인 누구나(마스터 한 벌 · 고쳐 씀은 시스템 관리자만)."""
access.require(session, "system", None)
return _call(options.listing)
@read_router.get("/structure-definition")
def get_structure_definition(session=Depends(verify_session)) -> dict:
"""구조물 정의 한 벌(판 · 구조물군 · 동작 · types · 종류 · 표시 · 그룹 · 배치 · 규칙)."""
access.require(session, "system", None)
return _call(definition.read)
@read_router.get("/structure-definition/version")
def get_structure_definition_version(session=Depends(verify_session)) -> dict:
"""지금 정의 판 `{판}` — B05 · B06 종류 캐시가 판을 볼 때(322-0 · 한 벌을 다 받지 않음)."""
access.require(session, "system", None)
return {"판": definition_version()}
@read_router.get("/structure-definition/history")
def get_structure_definition_history(session=Depends(verify_session)) -> list[dict]:
"""지난 판 목록 `[{판, 저장일}]`(새 판부터) — 로그인 누구나(PLAN 48-2)."""
access.require(session, "system", None)
return _call(definition.history)
@read_router.get("/structure-definition/history/{version}")
def get_structure_definition_at(version: int, session=Depends(verify_session)) -> dict:
"""지난 판 한 벌(읽기만) — 없으면 404."""
access.require(session, "system", None)
return _call(definition.read_version, version)
@read_router.put("/structure-definition")
def put_structure_definition(body: DefinitionBody, session=Depends(verify_session)) -> dict:
"""정의 고쳐 씀 — 시스템 관리자만(403) · 낡은 판 409 · 검사 422 · 판 +1 · 앞 판은 이력."""
access.require(session, "system", None, write=True)
return _call(definition.save, body.정의, body.판)
@@ -1,414 +0,0 @@
/* 좌측 「구조물 옵션 보이기」 화면(메인 칸) — 왼쪽 종류(군별) · 오른쪽 옵션 체크 */
.m02-opts {
display: flex;
flex-direction: column;
gap: var(--spacing-12);
max-width: 64rem;
font-size: var(--text-body-sm);
}
/* 종류 제목 */
.m02-options__head {
margin: 0;
color: var(--color-text);
font-size: var(--text-body);
}
.m02-opts__panes {
display: grid;
grid-template-columns: minmax(14rem, 20rem) 1fr;
gap: var(--spacing-16);
align-items: start;
}
.m02-opts__kinds,
.m02-opts__list {
max-height: calc(100dvh - 20rem);
overflow-y: auto;
display: flex;
flex-direction: column;
gap: var(--spacing-4);
min-width: 0;
}
.m02-opts__group {
margin: var(--spacing-8) 0 0;
color: var(--color-text-muted);
font-size: var(--text-body-sm);
}
/* 종류 줄 = 목록 줄 부품(ui-list-row) · 여기는 글 · 꼬리표 늘어놓기만 */
.m02-opts__kind {
flex-wrap: wrap;
justify-content: flex-start;
gap: var(--spacing-4);
}
/* 옵션 줄 = 왼쪽 보이기 체크 · 라벨 · 키 · 표시 / 오른쪽 들어갈 자리(본체 · 그룹) */
.m02-opts__option {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--spacing-8);
padding: var(--spacing-4) 0;
border-bottom: 1px solid var(--color-border);
}
.m02-opts__check {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: var(--spacing-8);
min-width: 0;
cursor: pointer;
}
/* 옵션 그룹(PLAN 46-2) — 그룹 줄 = 이름 · 옵션 수 · 위로 · 아래로 · 지우기 */
/* 겉 = 카드 부품(ui-card · 여백 12) */
.m02-sog {
display: flex;
flex-direction: column;
gap: var(--spacing-4);
}
.m02-sog__row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-8);
}
.m02-sog__name {
flex: 1 1 12rem;
min-width: 0;
}
.m02-sog__place {
flex: none;
width: 11rem;
}
/* 키 글 = 보조 글 부품(ui-text) · 글줄 안에 놓임 */
.m02-opts__key {
display: inline-flex;
}
/* 구조물 정의 편집 화면(PLAN 48-2) — 판 띠 · 종류 머리 · 옵션 · 선택지 · 배치 격자 · 규칙 · 지난 판 */
.m02-sod {
max-width: 80rem;
}
/* 판 띠 = 띠 알림 부품(정보 · 지난 판 = 경고) · 여기는 한 줄 늘어놓기만 */
.m02-sod__banner {
align-items: center;
}
.m02-sod__family,
.m02-sod__kindrow,
.m02-sod__kindhead,
.m02-sod__option,
.m02-sod__choice,
.m02-sod__place,
.m02-sod__rule {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-8);
}
.m02-sod__family {
margin-top: var(--spacing-8);
}
.m02-sod__family > .ui-input {
flex: 1 1 8rem;
min-width: 0;
font-weight: 600;
}
.m02-sod__kindrow {
flex-wrap: nowrap;
}
.m02-sod__kindrow > .m02-opts__kind {
flex: 1 1 auto;
min-width: 0;
}
.m02-sod__kindrow > button:not(.m02-opts__kind),
.m02-sod__family > button {
flex: none;
white-space: nowrap;
}
.m02-sod__block {
display: flex;
flex-direction: column;
gap: var(--spacing-4);
padding-top: var(--spacing-8);
border-top: 1px solid var(--color-border);
}
.m02-sod__option {
padding: var(--spacing-4) 0;
border-bottom: 1px solid var(--color-border);
}
.is-off > .ui-input,
.m02-opts__kind.is-off > span:first-child {
color: var(--color-text-muted);
text-decoration: line-through;
}
.m02-sod__name {
flex: 1 1 10rem;
min-width: 0;
}
.m02-sod__form,
.m02-sod__default {
width: 8rem;
}
.m02-sod__unit,
.m02-sod__num {
width: 4.5rem;
}
.m02-sod__check {
display: inline-flex;
align-items: center;
gap: var(--spacing-4);
white-space: nowrap;
cursor: pointer;
}
.m02-sod__choices {
display: flex;
flex-direction: column;
gap: var(--spacing-4);
margin: 0 0 var(--spacing-8) var(--spacing-24);
padding-left: var(--spacing-8);
border-left: 2px solid var(--color-border);
}
/* 배치 격자 — 왼쪽 칸 숫자 · 오른쪽 미리보기 */
.m02-sod__layout {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(12rem, 22rem);
gap: var(--spacing-16);
align-items: start;
}
.m02-sod__place {
flex-wrap: nowrap;
}
.m02-sod__placename {
flex: 1 1 6rem;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.m02-sod__place > .m02-sod__num {
flex: none;
width: 4rem;
}
.m02-sod__grid {
display: grid;
gap: var(--spacing-4);
padding: var(--spacing-8);
border: 1px dashed var(--color-border);
border-radius: var(--radius-sm);
}
.m02-sod__cell {
overflow: hidden;
padding: var(--spacing-4);
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
background: var(--color-surface-raised);
font-size: 11px;
white-space: nowrap;
text-overflow: ellipsis;
}
.m02-sod__cell.is-base {
background: var(--color-accent-soft);
}
.m02-sod__cell.is-bad,
.m02-sod__rule.is-bad {
border-color: var(--color-danger);
}
.m02-sod__rule {
padding: var(--spacing-4);
border: 1px solid transparent;
border-radius: var(--radius-sm);
}
.m02-sod__rulepick {
width: 9rem;
}
.m02-sod__rulechoices {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-8);
}
/* 그룹 형상 칸 — 길이 · 높이 · 전 · 후 받기 + 뜻 */
.m02-sog__item {
display: flex;
flex-direction: column;
gap: var(--spacing-4);
padding-bottom: var(--spacing-4);
border-bottom: 1px solid var(--color-border);
}
.m02-sog__shape {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
gap: var(--spacing-4) var(--spacing-12);
}
.m02-sog__shapecell {
display: flex;
align-items: center;
gap: var(--spacing-4);
}
.m02-sog__mean {
flex: 1 1 auto;
min-width: 0;
}
.m02-sod__issues:empty,
.m02-sod__history:empty {
display: none;
}
.m02-sod__history {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-4);
}
/* 구조물 명세 이름 고치기(PLAN 52-11) — 컨테이너 › 항목 › 값 들여쓰기 */
.m02-sod__specrow {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-8);
}
.m02-sod__specrow.is-level-0 {
margin-top: var(--spacing-8);
font-weight: 600;
}
.m02-sod__specrow.is-level-1 {
padding-left: 1.5rem;
}
.m02-sod__specrow.is-level-2 {
padding-left: 3rem;
}
.m02-sod__specpreview {
max-width: 28rem;
}
/* 미리보기 상자 이름표 [삭제] — B05 상자 안 작은 단추 틀과 같은 꼴(136-3 · M02 는 B05 CSS 를 안 읽음) */
.m02-sod__block .b05-structure__group > legend > button {
box-sizing: border-box;
height: 26px;
min-height: 0;
padding-block: 0;
padding-inline: var(--spacing-8);
font-size: var(--text-caption);
line-height: 1;
}
/* ── 322-2 탭 셋 · 한눈 표 · 부품 ── */
/* 탭 = 탭 부품(보조 탭) · 여기는 위아래 간격만 */
.m02-sod__tabs {
margin: var(--spacing-8) 0;
}
.m02-sod__tablewrap {
overflow-x: auto;
}
/* 표 = 표 부품 데이터표(ui-table--data) · 여기는 폭 · 줄바꿈만 */
table.m02-sod__table {
width: auto;
min-width: 100%;
}
.m02-sod__table th,
.m02-sod__table td {
white-space: nowrap;
}
.m02-sod__familyrow td {
background: var(--color-surface-raised);
}
.m02-sod__table tr.is-off {
opacity: 0.5;
}
.m02-sod__cell {
display: inline-flex;
align-items: center;
gap: var(--spacing-4);
}
.m02-sod__cell.is-default {
opacity: 0.6;
}
.m02-sod__cell.is-changed {
font-weight: 600;
}
.m02-sod__fixed {
display: inline-flex;
align-items: center;
gap: var(--spacing-4);
opacity: 0.7;
}
.m02-sod__color {
width: 32px;
height: 22px;
padding: 0;
border: none;
background: none;
}
.m02-sod__reflect {
display: grid;
grid-template-columns: 1fr;
gap: var(--spacing-4);
}
.m02-sod__reflectrow {
display: grid;
grid-template-columns: 7em 1fr;
align-items: center;
gap: var(--spacing-4);
}
/* 부품 탭 — 긴 글은 줄바꿈해 표가 화면 안에(322-2 다듬기) */
table.m02-sod__table--wrap {
table-layout: fixed;
width: 100%;
}
.m02-sod__table--wrap td,
.m02-sod__table--wrap th {
white-space: normal;
word-break: keep-all;
overflow-wrap: anywhere;
}
/* M01 본 칸(716-1) — 정의 화면을 얹는 틀: 머리 줄 아래 화면 */
.m02-sod__host {
display: flex;
flex-direction: column;
gap: var(--spacing-12);
min-width: 0;
}
@@ -1,189 +0,0 @@
/* =============================================================================
* M02_SO_Text.ts
* 좌측 「구조물 옵션 보이기」 줄 · 상세 화면(보이기 · 그룹) 글자 — [한국어, 영어]
* ========================================================================== */
import { currentLanguageIndex } from "@ui/ui_template_locale";
const TEXT = {
Title: ["구조물 옵션 정의", "Structure option definition"],
Row: [
"구조물군 · 종류 · 옵션 · 배치 · 그룹 · 규칙",
"Families · types · options · layout · groups · rules",
],
Screen: ["구조물 옵션 정의", "Structure option definition"],
GroupHead: ["그룹", "Groups"],
GroupNote: [
"그룹 하나 = 프로젝트 B05 · B06 폼의 보조 컨테이너 하나(제목 = 그룹 이름) · 그 안에서 구조물 조합 항목을 따로 지정 · 옵션이 없어도 연결됨 · 그룹에 안 넣은 옵션은 본체",
"One group = one sub-container in the B05 · B06 form (title = group name) with its own structure combo · works without options · ungrouped options stay in the main body",
],
GroupAdd: ["그룹 추가", "Add group"],
GroupName: ["그룹 이름", "Group name"],
GroupNew: ["새 그룹 {value}", "New group {value}"],
GroupUp: ["위로", "Up"],
AddKind: ["종류 추가", "Add type"],
AddKindNote: [
"본보기 종류를 그대로 복사한 새 종류(이름 「본보기 2」) — 옵션 · 그룹 · 반영 · 그리는 법이 같음 · 이름 · 반영은 고쳐서 [저장]",
"New type copied from the template (name “template 2”) — same options, groups, reflect and drawing; edit name / reflect, then [Save]",
],
GroupDown: ["아래로", "Down"],
GroupDel: ["지우기", "Delete"],
GroupDelAsk: [
"그룹 「{value}」 을 지움 — 그 옵션은 본체로 돌아감 · 프로젝트에 이미 지정한 조합은 값만 남음",
"Delete group “{value}” — its options return to the main body; project links keep their values",
],
GroupCount: ["옵션 {value}", "{value} options"],
GroupNone: [
"그룹 없음 — 모든 옵션이 본체 · 집계 항목 하나",
"No groups — all options in the main body",
],
GroupTag: ["그룹 {value}", "{value} groups"],
Main: ["본체", "Main body"],
OptionHead: ["옵션", "Options"],
OptionNote: [
"이름 · 꼴 · 단위 · 기본값 · 들어갈 자리(본체 · 그룹) · 안 씀 · 순서 — 키(작은 글)는 안 바뀜 · 고르기 꼴은 [선택지]로 목록을 고침",
"Name · form · unit · default · container · unused · order — keys never change",
],
OptionAdd: ["옵션 더함", "Add option"],
OptionNew: ["새 옵션 {value}", "New option {value}"],
FormSelect: ["고르기", "Select"],
FormNumber: ["숫자", "Number"],
FormText: ["글", "Text"],
FormBool: ["예/아니오", "Yes/No"],
FormAuto: ["자동", "Auto"],
SpecHead: ["구조물 명세 이름", "Structure spec names"],
SpecNote: [
"제목 › 칸 이름 › 선택지 이름만 고침 — 키(작은 글) · 필수/선택 · 꼴 · 칸 추가 · 빼기는 읽기만 · [저장]하면 B05 · B06 이 이 이름으로 그림",
"Rename titles › fields › choices only — keys, required/optional, form and adding/removing fields are read-only",
],
SpecLoose: ["그룹 밖 칸", "Fields outside groups"],
SpecNone: ["고칠 이름 없음 — 칸이 없는 종류", "No names to edit — this kind has no fields"],
SpecRequired: ["필수", "Required"],
SpecOptional: ["선택", "Optional"],
SpecPreview: ["미리보기 — B05 · B06 폼", "Preview — B05 · B06 form"],
Yes: ["예", "Yes"],
No: ["아니오", "No"],
Unit: ["단위", "Unit"],
NoDefault: ["기본값 없음", "No default"],
Unused: ["안 씀", "Unused"],
Choices: ["선택지 {value}", "{value} choices"],
ChoiceAdd: ["선택지 더함", "Add choice"],
ChoiceNew: ["새 선택지 {value}", "New choice {value}"],
ChoiceNone: ["선택지 없음 — 고르기 꼴은 하나 이상", "No choices — select needs at least one"],
ChoiceNote: [
"선택지 글이 곧 저장 값 — 이름을 바꾸면 기본값 · 규칙도 같이 바뀜 · 이미 저장한 프로젝트 값은 「지난 정의 값」으로 남음",
"Choice text is the stored value — renaming updates defaults and rules here",
],
ChoiceDrop: ["빼기", "Remove"],
ChoiceDropAsk: [
"선택지 「{value}」 를 뺌 — 기본값 · 규칙에서도 빠짐 · 이미 저장한 프로젝트 값은 「지난 정의 값」으로 남음",
"Remove choice “{value}” — also from defaults and rules",
],
Shown: ["보이기", "Shown"],
RuleValues: ["값(쉼표로 여럿)", "Values (comma separated)"],
RuleChoices: ["선택지", "Choices"],
LayoutHead: ["배치 격자", "Layout grid"],
LayoutNote: [
"B05 · B06 좌측 구조물 칸(두 칸)의 배치 — 옵션마다 줄 · 칸 · 너비 · 기준 측점은 맨 위 한 줄 · 겹치면 빨강 · 안 정한 옵션은 차례대로",
"Left panel layout (two columns) — row · column · width per option · overlaps in red",
],
GridRow: ["줄", "Row"],
GridCol: ["칸", "Col"],
GridWidth: ["너비", "Width"],
BaseStation: ["기준 측점", "Base station"],
BaseStationShow: ["기준 측점 표시", "Show base station"],
Shape_길이: ["길이", "Length"],
Shape_높이: ["높이", "Height"],
Shape_전: ["기준 측점 전", "Before"],
Shape_후: ["기준 측점 후", "After"],
ShapeMean: ["무엇을 정하는지", "What it controls"],
RuleHead: ["규칙", "Rules"],
RuleNote: [
"만약 상위 옵션 = 값 → 하위 옵션의 선택지 · 보이기 · 기본값 — 「그대로」 칸은 손대지 않음 · 틀린 줄은 빨강",
"If parent = value → child choices · visibility · default",
],
RuleNone: ["규칙 없음", "No rules"],
RuleAdd: ["규칙 더함", "Add rule"],
RuleIf: ["만약", "If"],
RuleThen: ["→", "→"],
Keep: ["보이기 그대로", "Keep visibility"],
Show: ["보임", "Show"],
Hide: ["숨김", "Hide"],
KeepDefault: ["기본값 그대로", "Keep default"],
DefNote: [
"구조물군 · 종류 · 옵션 · 선택지 · 배치 · 그룹 · 규칙 정의 — [저장]하면 판이 하나 오르고 B05 · B06 에 바로 적용 · 지난 판은 이력으로 남음",
"Structure definition — Save bumps the version; past versions stay in history",
],
Version: ["판 {value}", "Version {value}"],
ReadOnly: ["읽기만", "Read only"],
SavedVersion: ["저장함 — 판 {value}", "Saved — version {value}"],
PastList: ["지난 판", "Past versions"],
PastItem: ["판 {value}", "v{value}"],
PastNone: ["지난 판 없음", "No past versions"],
PastView: ["판 {value} 보는 중 — 읽기만", "Viewing version {value} — read only"],
PastBack: ["지금 판으로", "Back to current"],
NoOptionKind: [
"이 종류는 옵션이 없음 — 그룹만 만들 수 있음(그룹마다 조합 연결)",
"No options — groups only (each links a combo)",
],
Off: ["안 쓰는 종류", "Not offered"],
Pick: ["왼쪽에서 구조물 종류를 고름", "Pick a structure type on the left"],
Detail: ["B06 전용", "B06 only"],
Save: ["저장", "Save"],
TabTable: ["한눈 표", "Overview"],
TabKinds: ["종류별", "By type"],
TabParts: ["부품", "Parts"],
TableNote: [
"종류마다 B05 · B06 반영 한 줄 — 목록 · 횡단도 · 카드 이름 · 형상 · 3D 는 코드 부품 중에서 고름 · 흐린 칸 = 처음 값(기본) · 진한 칸 = 바꾼 값 · 자리꼴 · 정본은 만든 뒤 고정",
"One row per type — pick parts for list · cross section · card name · shape · 3D; faded = default, bold = changed",
],
ColFamily: ["군", "Family"],
ColKind: ["종류", "Type"],
ColName: ["이름", "Name"],
ColList: ["목록", "List"],
ColPlacement: ["자리꼴", "Placement"],
ColOwner: ["정본", "Owner"],
ColStation: ["횡단도", "Cross section"],
ColTitle: ["카드 이름", "Card name"],
ColShape: ["형상", "Shape"],
ColShapeOpts: ["형상칸", "Shape fields"],
ColColor: ["알약 색", "Pill color"],
Col3D: ["3D", "3D"],
ColCheck: ["검사", "Check"],
ListBoth: ["B05 · B06", "B05 · B06"],
ListB06: ["B06 만", "B06 only"],
ListHidden: ["안 보임", "Hidden"],
OffNone: ["없음", "None"],
StationNone: ["안 만듦", "Not made"],
TitleName: ["종류 이름", "Type name"],
Default: ["기본", "Default"],
Fixed: ["고정", "Fixed"],
Reset: ["처음 값으로", "Reset"],
Ok: ["통과", "OK"],
WallForm: ["기본 형태", "Default form"],
Weep: ["물빼기", "Weep holes"],
ReflectHead: ["B05 · B06 반영", "B05 · B06 use"],
ShownCol: ["보임", "Shown"],
CannotHide: ["못 숨김", "Required"],
PartsNote: [
"코드가 그리는 방법(부품) — 끄면 그 부품을 쓰는 종류는 그 갈래가 없음으로 · 읽는 칸 = 그 부품이 쓰는 옵션(숨기지 못함)",
"Code drawing parts — turning a part off makes its users fall back to none; read fields cannot be hidden",
],
PartRead: ["읽는 칸", "Reads"],
PartFits: ["맞는 자리꼴 · 정본", "Fits"],
PartUsers: ["쓰는 종류", "Used by"],
PartOn: ["켬", "On"],
Stale: [
"그 사이 정의가 바뀜 — 새로 받았으니 다시 고쳐 주세요",
"Changed meanwhile — reloaded, please edit again",
],
Load_Failed: ["구조물 정의를 못 받음 — {value}", "Could not load the definition — {value}"],
Failed: ["구조물 정의를 못 저장함 — {value}", "Could not save the definition — {value}"],
} as const satisfies Record<string, readonly [string, string]>;
export type OptionsTextKey = keyof typeof TEXT;
export function to(key: OptionsTextKey, value = ""): string {
const entry = TEXT[key];
return (entry[currentLanguageIndex as 0 | 1] ?? entry[0]).replace("{value}", value);
}