/* ============================================================================= * B06_Section_UI_Cross_Design.ts * 측점 표준횡단 설계 지정 컨트롤(지반유형·단면유형·측구위치·측구형식)과 * 설계선·암 경계선·포장층 오버레이. * * 카드 헤더 아래에 세그먼트 버튼을 배치하고, 선택이 바뀌면 onChange로 계산을 * 요청한다. 계산 결과(section.design)는 상위에서 다시 렌더될 때 절·성토 단면적 * 표시와 오버레이로 반영된다. 편절편성은 측구위치가 자동 결정되어 컨트롤을 숨기고, * 양절·양성에서만 배수 방향 선택을 노출한다. * * 암(리핑/발파) 지반에서만: 측구형식(일반/L형) 세그먼트와 암 경계선 상/하/리셋 * 버튼(B05 측점 선 제어 ▲/▼/↺ 패턴 재활용)을 노출한다. 암 경계선 오프셋은 * 서버 재계산 없이 프론트 세션에 보관되고(RockBoundaryControl), 확정 시 DB에 * 병합된다. * ========================================================================== */ import { currentLanguageIndex, ui_locales } from "@ui/ui_template_locale"; import type { CrossSection, DitchSide, DitchType, GroundType, SectionMode, } from "./B06_Section_Api_Fetch"; export { appendPavementOverlay, appendRockBoundaryOverlay, } from "./B06_Section_UI_Cross_Design_Surface"; export { appendCrossDesignOverlay } from "./B06_Section_UI_Cross_Design_Line"; /** 넘침 정리 한 장 몫 — 쓰기·읽기·쓰기 세 토막으로 갈라 두어 프레임 단위로 묶는다. */ interface ReflowCard { reset(): void; /** 패널로 옮길 개수. -1 이면 아직 자리를 안 잡아 건드리지 않는다. */ measure(): number; apply(moveCount: number): void; } const reflowQueue = new Set(); let reflowScheduled = false; /** * 넘침 정리를 **한 프레임에 몰아** 돌린다 — 모든 카드의 쓰기를 먼저 끝내고, 그 다음 * 읽기를 몰아서 하고, 마지막에 쓰기를 몰아서 한다. 강제 레이아웃이 카드 수만큼(67회) * 나던 것이 프레임당 한 번으로 줄어든다. */ function scheduleReflow(card: ReflowCard): void { reflowQueue.add(card); if (reflowScheduled) return; reflowScheduled = true; requestAnimationFrame(() => { reflowScheduled = false; const cards = [...reflowQueue]; reflowQueue.clear(); for (const item of cards) item.reset(); const counts = cards.map((item) => item.measure()); cards.forEach((item, index) => item.apply(counts[index])); }); } /** 카드 버튼줄의 flex 간격(px) — 모든 카드가 같은 CSS 를 쓰므로 한 번만 잰다. * `getComputedStyle` 도 강제 레이아웃을 부르므로 카드 67장마다 부르지 않는다. */ let barGapPx: number | null = null; function L(key: keyof typeof ui_locales): string { return ui_locales[key][currentLanguageIndex]; } /** * 지반유형은 **「토사」 토글 하나**다(2026-09-07 사용자 확정) — 켜면 토사, **끄면 암**(기본). * * 사용자 원문 — 「리핑암과 발파암 버튼을 삭제하면서 구분의 의미가 없어졌어. … 토사버튼만 * 존재하고 이값은 활성화/비활성화로 반영(기본값은 비활성화)」. 까닭은 **암반 지정·범위가 * 실무에서 애매해** 측점마다 암질을 못 박는 것이 오히려 틀리기 때문이고, 연암:경암 · * 발파암:리핑암은 **설계내역에서 설계자가 비율로** 넣기로 했다(계획서 8-1). * * ⚠ 저장값은 종전 그대로 쓴다 — 끔 = `ripping_rock`, 켬 = `soil`. 옛 자료의 `blasting_rock` * 도 「암(끔)」으로 읽힌다. 유토곡선·수량은 암을 한 종류(리핑암)로 잡으며, 갈라 넣는 것은 * 설계내역 몫이다. */ const GROUND_ROCK_DEFAULT: GroundType = "ripping_rock"; const MODE_OPTIONS: Array<[SectionMode, keyof typeof ui_locales]> = [ ["left_cut", "B06_Design_Mode_LeftCut"], ["right_cut", "B06_Design_Mode_RightCut"], ["both_cut", "B06_Design_Mode_BothCut"], ["both_fill", "B06_Design_Mode_BothFill"], ]; /** 자동 판정된 단면 유형의 지역화 라벨(제목행 pill용, D-2/E-3). */ export function sectionModeLabel(mode: SectionMode | undefined): string { const key = MODE_OPTIONS.find(([value]) => value === mode)?.[1]; return key ? ui_locales[key][currentLanguageIndex] : "-"; } // 좌/우 버튼 = 노면 횡단 경사 방향(물을 모으는 쪽 = 측구가 있다면 그 위치). 양성도 측구는 // 없지만 "생략된 측구"를 가정한 경사 방향을 여기서 정한다(N-2-3). const DITCH_OPTIONS: Array<[DitchSide, keyof typeof ui_locales]> = [ ["left", "B06_Design_SlopeDir_Left"], ["right", "B06_Design_SlopeDir_Right"], ]; const DITCH_TYPE_OPTIONS: Array<[DitchType, keyof typeof ui_locales]> = [ ["standard", "B06_Design_DitchType_Standard"], ["l_type", "B06_Design_DitchType_LType"], ]; export interface CrossDesignChange { ground_type: GroundType; section_mode: SectionMode; ditch_side: DitchSide | null; ditch_type: DitchType; paved: boolean; /** 암 지반 2단계 경사(암반 경계 아래=암, 위=토사) 적용 여부. 기본 true, 토글로 해제. */ two_stage_slope: boolean; /** 측구를 둘지 **사용자가 정한 선택**. `null` = 자동 판정. * ⚠ 결과(`design.ditch_enabled` = 실제 섰나)와 **다른 값**이다(2026-09-09 정리). */ ditch_choice: boolean | null; } /** * 암 경계선 세션 제어기. Page가 세션 저장소·카드 갱신과 연결해 구현한다. * 오프셋은 지면선(지반선) 기준 상대값(m, 음수=하향)이다 — 계획선 기준이 아니다. */ export interface RockBoundaryControl { stepM: number; defaultOffsetM: number; /** 세션 → design 저장값 → 기본값 순으로 현재 오프셋을 돌려준다. */ offsetFor: (section: CrossSection) => number; adjust: (chainageM: number, deltaM: number) => void; reset: (chainageM: number) => void; } function isRock(ground: GroundType): boolean { return ground === "ripping_rock" || ground === "blasting_rock"; } function segment( legend: string, options: Array<[T, keyof typeof ui_locales]>, selected: T | null, onPick: (value: T) => void, disabled = false, reason = "", ): HTMLElement { const wrap = document.createElement("div"); wrap.className = `b06-design__seg${disabled ? " b06-design__seg--disabled" : ""}`; // 라벨(legend)이 빈 문자열이면 생략한다(E-7: 일부 옵션 라벨 삭제). if (legend) { const legendEl = document.createElement("span"); legendEl.className = "b06-design__seg-legend"; legendEl.textContent = legend; wrap.append(legendEl); } const group = document.createElement("div"); group.className = "b06-design__seg-buttons"; for (const [value, labelKey] of options) { const button = document.createElement("button"); button.type = "button"; button.className = `b06-design__btn${value === selected ? " b06-design__btn--active" : ""}`; button.textContent = L(labelKey); button.setAttribute("aria-pressed", value === selected ? "true" : "false"); // 선행 조건 미충족 시 비활성(상시 노출하되 클릭 불가·사유 툴팁) — E-6. button.disabled = disabled; if (disabled && reason) button.title = reason; else button.addEventListener("click", () => onPick(value)); group.append(button); } wrap.append(group); return wrap; } /** 온/오프 토글 하나(포장·2단계 경사 공용). 세그먼트와 같은 컨테이너/버튼 스타일을 쓴다. */ function toggle( legend: string, on: boolean, onLabel: string, offLabel: string, onToggle: () => void, disabled = false, reason = "", ): { wrap: HTMLElement; button: HTMLButtonElement } { const wrap = document.createElement("div"); wrap.className = `b06-design__seg${disabled ? " b06-design__seg--disabled" : ""}`; if (legend) { const legendEl = document.createElement("span"); legendEl.className = "b06-design__seg-legend"; legendEl.textContent = legend; wrap.append(legendEl); } const buttons = document.createElement("div"); buttons.className = "b06-design__seg-buttons"; const button = document.createElement("button"); button.type = "button"; button.className = `b06-design__btn${on ? " b06-design__btn--active" : ""}`; button.textContent = on ? onLabel : offLabel; button.setAttribute("aria-pressed", on ? "true" : "false"); button.disabled = disabled; if (disabled && reason) button.title = reason; else button.addEventListener("click", onToggle); buttons.append(button); wrap.append(buttons); return { wrap, button }; } /** * 길게 누르는 동안 같은 동작을 반복한다(B05 종단 선 제어 패턴 재사용). 0.5초 유지하면 * 0.1초 간격(0.1m씩) 반복이 시작된다. 버튼이 재빌드로 사라져도 반복이 끊기지 않도록 * 타이머·종료 감지를 버튼이 아니라 window 이벤트로 들고 있는다. */ function createHoldRepeater(): { start: (action: () => void) => void; stop: () => void } { let delayTimer = 0; let repeatTimer = 0; function stop(): void { window.clearTimeout(delayTimer); window.clearInterval(repeatTimer); delayTimer = 0; repeatTimer = 0; window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); window.removeEventListener("blur", stop); } function start(action: () => void): void { stop(); delayTimer = window.setTimeout(() => { repeatTimer = window.setInterval(action, 100); }, 500); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop); window.addEventListener("blur", stop); } return { start, stop }; } /** 암 경계선 상/하/리셋 컨트롤(B05 측점 선 제어 ▲/▼/↺ 버튼 패턴 재활용). E-7: X축 행 배치용 export. */ export function buildRockBoundaryControl( section: CrossSection, control: RockBoundaryControl, ): HTMLElement { const wrap = document.createElement("div"); wrap.className = "b06-design__seg b06-design__rockb"; const legendEl = document.createElement("span"); legendEl.className = "b06-design__seg-legend"; legendEl.textContent = L("B06_Design_RockBoundary_Legend"); wrap.append(legendEl); const group = document.createElement("div"); group.className = "b06-design__seg-buttons"; const readout = document.createElement("span"); readout.className = "b06-design__rockb-readout"; const currentOffset = control.offsetFor(section); readout.textContent = `${currentOffset >= 0 ? "+" : ""}${currentOffset.toFixed(1)}m`; const repeater = createHoldRepeater(); const makeButton = ( label: string, title: string, className: string, onClick: () => void, hold = false, ): HTMLButtonElement => { const button = document.createElement("button"); button.type = "button"; button.className = `b06-design__rockb-btn ${className}`; button.textContent = label; button.title = hold ? `${title}\n(길게 누르면 0.5초 뒤부터 연속 조정)` : title; if (hold) { // 포인터로 누르면 즉시 1회 반응하고 반복을 예약한다. 이어지는 click은 중복이라 삼킨다. let swallowClick = false; button.addEventListener("pointerdown", (event) => { event.stopPropagation(); swallowClick = true; onClick(); repeater.start(onClick); }); button.addEventListener("click", (event) => { event.stopPropagation(); if (swallowClick) { swallowClick = false; return; } onClick(); }); } else { button.addEventListener("click", onClick); } return button; }; group.append( makeButton( "▲", `${L("B06_Design_RockBoundary_Up")} (+${control.stepM}m)`, "is-up", () => control.adjust(section.chainage_m, control.stepM), true, ), makeButton( "▼", `${L("B06_Design_RockBoundary_Down")} (-${control.stepM}m)`, "is-down", () => control.adjust(section.chainage_m, -control.stepM), true, ), makeButton("↺", L("B06_Design_RockBoundary_Reset"), "is-reset", () => control.reset(section.chainage_m), ), readout, ); wrap.append(group); return wrap; } /** * 카드 설계 지정 컨트롤을 만든다. 지반유형 세그먼트는 제목행 배치용으로 분리 반환하고(D-6), * 나머지(단면유형·측구·2단·포장·암경계)는 본문 `bar`에 담는다. */ export function buildDesignControls( section: CrossSection, onChange: (chainageM: number, change: CrossDesignChange) => void, ): { bar: HTMLElement; groundSegment: HTMLElement } { const design = section.design; // 기본값: 토사(soil) + 상단측 절토(uphill_side, 미상이면 좌절토) + 일반측구 + 비포장. const state: { ground: GroundType; mode: SectionMode; ditch: DitchSide | null; ditchType: DitchType; paved: boolean; twoStage: boolean; ditchEnabled: boolean | null; } = { // 설계가 아직 없는 측점의 기본은 **암**이다(2026-09-07 사용자: 「기본값은 비활성화」). ground: design?.ground_type ?? GROUND_ROCK_DEFAULT, mode: design?.section_mode ?? (section.uphill_side === "right" ? "right_cut" : "left_cut"), ditch: design?.ditch_side ?? null, ditchType: design?.ditch_type ?? "standard", paved: design?.paved ?? false, // 암 design일 때만 저장값을 신뢰(토사는 two_stage=false echo가 무의미) — 암 전환 시 기본 복합경사(4번). twoStage: design && isRock(design.ground_type) ? (design.two_stage_slope ?? true) : true, // ⚠ **결과가 아니라 선택을 읽는다.** 결과를 읽으면 한 번 저장된 뒤로 // 자동 판정이 영영 안 돈다(2026-09-09에 갈라낸 자리). ditchEnabled: design?.ditch_choice ?? null, }; const bar = document.createElement("div"); bar.className = "b06-design"; // 컨트롤 상호작용이 카드 선택 클릭으로 전파되지 않게 한다. bar.addEventListener("click", (event) => event.stopPropagation()); // 경사 방향 선택이 필요한 경우 = 양절(both_cut)·양성(both_fill). 편절은 절토측 자동. // 양성은 측구가 없어도 노면 기울기 방향(생략된 측구 방향)을 여기서 지정한다(N-2-3). const needsDitch = (): boolean => state.mode === "both_cut" || state.mode === "both_fill"; const emit = (): void => { if (!state.ground || !state.mode) return; // L형 측구는 암 전용 — 토사로 되돌리면 일반측구로 강등해 서버 거부를 예방한다. if (!isRock(state.ground)) state.ditchType = "standard"; onChange(section.chainage_m, { ground_type: state.ground, section_mode: state.mode, ditch_side: needsDitch() ? (state.ditch ?? "left") : null, ditch_type: state.ditchType, paved: state.paved, two_stage_slope: state.twoStage, ditch_choice: state.ditchEnabled, }); }; // 지반유형: 제목행 배치용으로 분리 반환(D-6). 「토사」 토글 하나 — 끄면 암이다(2026-09-07). // 버튼명은 「토사」로 고정하고 **켜짐/꺼짐(색)**으로 상태를 보인다 — 측구 토글과 같은 꼴 // (사용자 원문: 「토사버튼만 존재하고 이값은 활성화/비활성화로 반영」). const groundToggle = toggle( "", state.ground === "soil", L("B06_Design_Ground_Soil"), L("B06_Design_Ground_Soil"), () => { state.ground = state.ground === "soil" ? GROUND_ROCK_DEFAULT : "soil"; emit(); }, ); groundToggle.button.title = state.ground === "soil" ? "토사 — 암반이 없어 절토는 토사 경사 하나로만 그린다. 누르면 암으로 바뀐다." : "암 — 암 경계선이 서고 그 아래는 암 절토각, 위는 토사 경사로 그린다. 누르면 토사로 바뀐다."; const groundSegment = groundToggle.wrap; groundSegment.classList.add("b06-design__seg--header"); // 단면 유형은 지형에서 자동 판정되며(D-2), 제목행 pill로 표시한다(E-3, Cross_View에서 생성). // 아래 옵션은 상시 노출하되 선행 조건 미충족 시 비활성 처리한다(E-6). const rockCut = isRock(state.ground) && state.mode !== "both_fill"; const hasDitch = state.mode !== "both_fill"; // 측구 생성 여부(자동 판정 or 사용자 override) — 측구형식은 측구가 있을 때만 의미 있다. // 화면 표시는 **결과**를 보인다 — 선택이 없으면 자동으로 선 결과가 답이다. const ditchOn = state.ditchEnabled ?? design?.ditch_enabled ?? true; // 경사 방향(좌/우): 양절·양성에서 활성. 항상 인라인 노출(오버플로 대상 아님). 라벨 삭제(E-7). const slopeDirSeg = segment( "", DITCH_OPTIONS, state.ditch, (value) => { state.ditch = value; emit(); }, !needsDitch(), L("B06_Design_Disabled_BothCutOnly"), ); // 측구 생성 토글(D-1): 측구 있는 단면에서만 활성. 버튼명 "측구" 고정, 컬러로 상태 표시(E-7). const ditchToggle = toggle( "", ditchOn, L("B06_Design_Ditch_On"), L("B06_Design_Ditch_Off"), () => { state.ditchEnabled = !ditchOn; emit(); }, !hasDitch, L("B06_Design_Disabled_NoDitch"), ); // 측구형식(일반/L형): 암 지반 + 절토 단면 + 측구가 실제 있을 때만 활성. const ditchTypeSeg = segment( L("B06_Design_DitchType_Legend"), DITCH_TYPE_OPTIONS, state.ditchType, (value) => { state.ditchType = value; emit(); }, !rockCut || !ditchOn, !ditchOn ? L("B06_Design_Disabled_NoDitchType") : L("B06_Design_Disabled_RockCut"), ); // 2단계 경사 토글: 암 지반 + 절토 단면에서만 활성. 활성="복합경사"/비활성="단경사"(E-7). const twoStage = toggle( "", state.twoStage, L("B06_Design_TwoStage_On"), L("B06_Design_TwoStage_Off"), () => { state.twoStage = !state.twoStage; emit(); }, !rockCut, L("B06_Design_Disabled_RockCut"), ); // 포장 단추는 없다(138-1) — 포장 = 노면공 · 물넘이 범위만(`pavedBySpecs`) · 「포장 권장」은 알림 줄. // `state.paved` 는 저장값 그대로 실어 보낸다(재계산이 범위로 다시 정함). // 오버플로 드롭다운(N-2-2): 컨트롤이 카드 폭에서 한 행을 넘치면 뒤쪽부터 우측 "⋯" // 드롭다운(세로 배치)으로 옮겨 다음 행으로 밀리는 것을 막는다. 경사 방향은 항상 인라인, // 이동 우선순위(뒤에서부터): 복합경사 → 측구형식 → 측구 토글. const moveable = [ditchToggle.wrap, ditchTypeSeg, twoStage.wrap]; const more = document.createElement("details"); more.className = "b06-design__more"; const moreSummary = document.createElement("summary"); moreSummary.className = "b06-design__more-summary"; moreSummary.textContent = "⋯"; moreSummary.title = L("B06_Design_More"); const morePanel = document.createElement("div"); morePanel.className = "b06-design__more-panel"; more.append(moreSummary, morePanel); bar.append(slopeDirSeg, ...moveable, more); // 넘침 정리는 **세 토막**으로 나눈다 — 쓰기(reset) → 읽기(measure) → 쓰기(apply). // 카드 안에서 한 장씩 하면 쓰기 뒤 읽기가 카드 수만큼 반복돼 브라우저가 레이아웃을 // 그때마다 강제로 다시 잰다. 게다가 한 번의 강제 레이아웃이 **그때까지 들어간 카드 // 전부**를 다시 재므로 뒤로 갈수록 비싸진다(2026-09-06 CPU 프로파일: 진입에서 자기 // 시간 1위). 그래서 `scheduleReflow` 가 67장을 모아 한 프레임에 묶어 돌린다. const card: ReflowCard = { reset() { for (const element of moveable) bar.insertBefore(element, more); morePanel.replaceChildren(); more.hidden = false; // 폭을 재려면 자리에 있어야 한다. }, measure() { const clientWidth = bar.clientWidth; if (clientWidth <= 0) return -1; // 아직 자리를 안 잡았다 — 그대로 둔다. if (barGapPx === null) barGapPx = Number.parseFloat(getComputedStyle(bar).gap) || 0; const widths = moveable.map((element) => element.offsetWidth); let overflow = bar.scrollWidth - clientWidth; let moveCount = 0; while (overflow > 1 && moveCount < moveable.length) { overflow -= widths[moveable.length - 1 - moveCount] + barGapPx; moveCount += 1; } return moveCount; }, apply(moveCount) { if (moveCount <= 0) { more.hidden = true; return; } for (let index = 0; index < moveCount; index += 1) { morePanel.insertBefore(moveable[moveable.length - 1 - index], morePanel.firstChild); } }, }; // 첫 호출은 아래 `scheduleReflow` 가 맡는다 — 관찰을 걸면 초기 크기로 곧바로 한 번 더 // 불려 카드마다 두 번 돌았다. 창 크기가 바뀔 때만 그 카드 하나를 다시 넣는다. let firstObservation = true; const overflowObserver = new ResizeObserver(() => { if (firstObservation) { firstObservation = false; return; } scheduleReflow(card); }); overflowObserver.observe(bar); scheduleReflow(card); // 암 경계선 제어는 그래프 X축 제목 행으로 이동(E-7, Cross_View에서 배치). // 절·성토 면적 readout은 그래프 중상단 오버레이로 이동(E-4, Cross_View에서 배치). return { bar, groundSegment }; } /** * 암 경계선(지면선 복사 + 상하 오프셋, 점선)을 겹쳐 그린다. * 계획선(설계선)이 아니라 **지반선(지면선)**을 복사해 이동하는 것이 규칙이다. * 리핑암·발파암 지반에서만 호출한다. offsetM 음수 = 하향. * 무효 샘플 구간은 지반선과 동일하게 선을 끊어 그린다. */