diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab.ts b/M01_MasterData/M01_MasterData_UI_LogicLab.ts index 5c78792b7..2dd75b26c 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab.ts @@ -39,7 +39,6 @@ import { setLogicOpener } from "./M01_MasterData_UI_LogicLab_Modal"; import { openCopyScreen } from "./M01_MasterData_UI_LogicLab_Copy"; import { tl } from "./M01_MasterData_UI_LogicLab_Text"; import { - buildSplit, emptyFlow, designFields, examplesOf, @@ -128,10 +127,8 @@ export async function mountM01LogicLab( .catch(() => false); let recalc: number | undefined; const editor = el("div", { className: "m01-logic__editor" }); - // 로직 상세 두 칸 — 왼쪽 지금 내용 · 오른쪽 흐름도(패널 자리) · 너비 비율 기억 - const split = buildSplit(editor); - // 오른쪽 두 패널(흐름도 · 원문) — 하나만 열림 · 흐름도는 이 칸 안에 띄움 - const panes = buildLogicSide(split); + // 로직 상세 — 왼쪽 지금 내용 · 오른쪽 접는 패널 둘(흐름도 · 원문 · 하나만 열림 · 폭 공유) + const panes = buildLogicSide(editor); const errors = el("div", { className: "m01-logic__reasons", attrs: { hidden: "" } }); const calc = el("div", { className: "m01lab__calc" }); const filterHost = el("div"); @@ -228,7 +225,7 @@ export async function mountM01LogicLab( const listing = !opened; list.root.hidden = !listing || !loaded; waiting.hidden = loaded; - split.root.hidden = !opened; + panes.root.hidden = !opened; back.hidden = listing; if (!opened) return; if (!opened.row) { @@ -570,7 +567,7 @@ export async function mountM01LogicLab( children: [ el("main", { className: "m01-logic__main", - children: [bar, errors, waiting, list.root, split.root], + children: [bar, errors, waiting, list.root, panes.root], }), ], }), diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.css index 4ef2696d4..3d2278801 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.css +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.css @@ -1,35 +1,3 @@ -/* 로직 상세 두 칸 — 왼쪽 지금 내용 · 끌기 막대 · 오른쪽 흐름도 */ -.m01lab-flow { - display: grid; - grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); - align-items: start; - gap: 0; -} - -.m01lab-flow[hidden] { - display: none; -} - -.m01lab-flow__left, -.m01lab-flow__right { - min-width: 0; -} - -.m01lab-flow__bar { - align-self: stretch; - width: 8px; - margin: 0 var(--spacing-4); - border-radius: var(--radius-sm); - background: var(--color-border); - cursor: col-resize; - touch-action: none; -} - -.m01lab-flow__bar:hover, -.m01lab-flow__bar:focus-visible { - background: var(--color-primary); -} - .m01lab-flow__wait { margin: 0; padding: var(--spacing-16); @@ -39,10 +7,6 @@ text-align: center; } -.m01lab-flow__bar[hidden] { - display: none; -} - .m01lab-flow__note { margin: 0 0 var(--spacing-8); color: var(--color-text-secondary); diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.ts index c8bb785aa..a751b64a0 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Flow.ts @@ -1,7 +1,6 @@ /* ============================================================================= * M01_MasterData_UI_LogicLab_Flow.ts - * 로직 상세 두 칸 — 왼쪽 지금 내용(보기) · 가운데 끌기 막대 · 오른쪽 흐름도 패널 - * 너비 — 패널이 없으면 두 칸 비율(끌기 막대 · localStorage) · 패널이 있으면 패널이 알린 너비(px · 패널 가장자리 끌기) + * 로직 상세 오른쪽 흐름도 — 칸 · 폭은 오른쪽 접는 패널(LogicLab_Side) 몫 * 잇기(mountLogicFlow) — 패널(M02_DF_Panel) · 왼쪽 보기(LogicLab_FlowView) · 입력 값 · 다른 로직 흐름 받기 * DataFlow 파일은 import() 로 늦게(엔진이 M01 첫 묶음에 안 들어가게). 정함 `docs/raw/M01_쉬운단가/흐름도_적용_정함.md` 2 · 5 · 6 · 7 * ========================================================================== */ @@ -14,7 +13,6 @@ import type { CfValues } from "../M02_MasterTemplete/DataFlow/M02_DF_Eval"; import "./M01_MasterData_UI_LogicLab_Flow.css"; const TEXT = { - Resize: ["두 칸 너비 — 끌어서 조절", "Drag to resize the two columns"], New: ["신규 로직", "New logic"], Waiting: ["흐름도 불러오는 중", "Loading the flow diagram"], Converted: [ @@ -27,93 +25,13 @@ const TEXT = { export const tf = (key: keyof typeof TEXT, v = ""): string => TEXT[key][currentLanguageIndex === 1 ? 1 : 0].replace("{v}", v); -const STORE = "m01.logic.flowRatio"; -const MIN = 0.25; -const MAX = 0.75; - -const clamp = (r: number): number => Math.min(MAX, Math.max(MIN, r)); - -function readRatio(): number { - try { - const r = Number(localStorage.getItem(STORE)); - return r ? clamp(r) : 0.5; - } catch { - return 0.5; - } -} - export interface SplitHandle { - root: HTMLElement; /** 오른쪽 칸 — 흐름도 패널을 붙이는 곳 */ right: HTMLElement; - /** 패널이 정한 너비(px) — 끌기 막대는 숨김(패널 가장자리로 조절) · null = 비율로 돌아감 */ + /** 패널이 알린 너비(px) · null = 패널 내림 */ setRight(px: number | null): void; } -/** 두 칸 만들기 — left 는 지금 화면 그대로 왼쪽에 둠 */ -export function buildSplit(left: HTMLElement): SplitHandle { - const right = el("div", { className: "m01lab-flow__right" }); - const bar = el("div", { - className: "m01lab-flow__bar", - attrs: { - role: "separator", - "aria-orientation": "vertical", - "aria-label": tf("Resize"), - title: tf("Resize"), - tabindex: "0", - }, - }); - const leftCol = el("div", { className: "m01lab-flow__left", children: [left] }); - const root = el("div", { className: "m01lab-flow", children: [leftCol, bar, right] }); - let ratio = readRatio(); - let panelPx: number | null = null; - const apply = (): void => { - root.style.gridTemplateColumns = - panelPx === null - ? `minmax(0, ${ratio}fr) auto minmax(0, ${1 - ratio}fr)` - : `minmax(0, 1fr) ${panelPx}px`; - }; - const keep = (): void => { - try { - localStorage.setItem(STORE, String(ratio)); - } catch { - /* 기억 못 해도 지금 화면은 그대로 */ - } - }; - bar.addEventListener("pointerdown", (ev) => { - if (ev.button !== 0) return; - ev.preventDefault(); - const box = root.getBoundingClientRect(); - const move = (m: PointerEvent): void => { - ratio = clamp((m.clientX - box.left) / box.width); - apply(); - }; - const up = (): void => { - window.removeEventListener("pointermove", move); - window.removeEventListener("pointerup", up); - keep(); - }; - window.addEventListener("pointermove", move); - window.addEventListener("pointerup", up); - }); - // 키보드 — 왼쪽 · 오른쪽 화살표로 조금씩 - bar.addEventListener("keydown", (ev) => { - const step = ev.key === "ArrowLeft" ? -0.05 : ev.key === "ArrowRight" ? 0.05 : 0; - if (!step) return; - ev.preventDefault(); - ratio = clamp(ratio + step); - apply(); - keep(); - }); - const setRight = (px: number | null): void => { - panelPx = px; - bar.hidden = px !== null; - apply(); - }; - apply(); - return { root, right, setRight }; -} - /* ── 흐름 받기 · 잇기 ─────────────────────────────────────────────────── */ export interface FlowAnswer { diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Side.css b/M01_MasterData/M01_MasterData_UI_LogicLab_Side.css index 853a55b29..38b5f9359 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Side.css +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Side.css @@ -1,15 +1,11 @@ -/* 로직 상세 오른쪽 두 패널 — 흐름도 · 원문 · 공용 접기 카드(접힌 카드 = 제목 행) */ -.m01lab-side { - min-width: 0; -} - -.m01lab-side__card, +/* 로직 상세 오른쪽 두 패널(흐름도 · 원문) — 공용 오른쪽 접는 패널 안 */ .m01lab-side__slot { min-width: 0; } -/* 카드 제목 행이 접기 단추 — 흐름도 패널 자체 접기 단추 · 테두리는 뺌 */ -.m01lab-side .m02-dfp__toggle { +/* 접기 · 폭은 공용 패널 몫 — 흐름도 패널 자체 접기 단추 · 끌기 경계 · 테두리는 뺌 */ +.m01lab-side .m02-dfp__toggle, +.m01lab-side .m02-dfp__grip { display: none; } diff --git a/M01_MasterData/M01_MasterData_UI_LogicLab_Side.ts b/M01_MasterData/M01_MasterData_UI_LogicLab_Side.ts index 3077d01bb..2eec06f9e 100644 --- a/M01_MasterData/M01_MasterData_UI_LogicLab_Side.ts +++ b/M01_MasterData/M01_MasterData_UI_LogicLab_Side.ts @@ -1,16 +1,14 @@ /* ============================================================================= * M01_MasterData_UI_LogicLab_Side.ts - * 로직 상세 오른쪽 두 패널 — 「흐름도」(다이어그램 · 상세 내용 = M02_DF_Panel) · 「원문」(품셈 본문 절) - * 공용 접기 카드(`ui-collapsible` · 제목 행 누름 · 캐럿) 두 장 — attachCollapsible 토글 위에 하나만 열림 규칙 - * 둘 다 접기 됨 · 접힌 카드 = 제목 행만 - * 열린 패널은 계정 취향(`m01-logic-panel`)으로 기억 · 원문은 출처 글로 서버가 찾음(`GET /m01/logic/source`) + * 로직 상세 — 왼쪽 지금 내용 · 오른쪽 접는 패널 둘 「흐름도」(M02_DF_Panel) · 「원문」(품셈 본문 절) + * 공용 오른쪽 접는 패널(ui_template_side_panels) — 하나만 열림 · 모두 접힘 됨 · 폭 공유 · 접힌 패널 = 세로 글 띠 + * 열린 패널 · 폭은 취향 키(`m01-logic-side`) · 원문은 출처 글로 서버가 찾음(`GET /m01/logic/source`) * ========================================================================== */ import { currentLanguageIndex } from "@ui/ui_template_locale"; -import { attachCollapsible } from "@ui/ui_template_collapsible"; +import { createSidePanels } from "@ui/ui_template_side_panels"; import { el } from "@ui/ui_template_elements"; import { API_BASE_URL } from "@config/config_frontend"; -import { readStateRaw, writeStateRaw } from "../A00_Common/b_page_state"; import type { SplitHandle } from "./M01_MasterData_UI_LogicLab_Flow"; import "../M02_MasterTemplete/DataFlow/M02_DF_Panel.css"; import "./M01_MasterData_UI_LogicLab_Side.css"; @@ -28,9 +26,6 @@ const TEXT = { const ts = (key: keyof typeof TEXT, v = ""): string => TEXT[key][currentLanguageIndex === 1 ? 1 : 0].replace("{v}", v); -/** 둘 다 접힘 — 제목 행 둘이 들어가는 칸 너비 */ -const FOLDED = 140; - export type PanelPick = "flow" | "source" | "none"; interface Block { @@ -47,7 +42,9 @@ interface Found { } export interface LogicSide { - /** 흐름도 패널에 넘길 칸 — right = 흐름도 자리 · setRight = 흐름도 패널이 알린 너비 */ + /** [왼쪽 지금 내용, 오른쪽 패널] 칸 */ + root: HTMLElement; + /** 흐름도 패널에 넘길 칸 — right = 흐름도 자리 · 폭은 오른쪽 패널 몫(setRight 안 씀) */ flowSplit: SplitHandle; flowFolded(): boolean; pick(next: PanelPick): void; @@ -57,11 +54,6 @@ export interface LogicSide { showSource(src: string): void; } -const readPick = (): PanelPick => { - const got = readStateRaw("m01-logic-panel"); - return got === "source" || got === "none" ? got : "flow"; -}; - function blockNode(b: Block): HTMLElement { if (b.table) return el("div", { @@ -83,59 +75,38 @@ function blockNode(b: Block): HTMLElement { return el("p", { className: "m01lab-src__p", text: b.p ?? "" }); } -export function buildLogicSide(split: SplitHandle): LogicSide { +export function buildLogicSide(left: HTMLElement): LogicSide { const flowSlot = el("div", { className: "m01lab-side__slot" }); const body = el("div", { className: "m01lab-src__body" }); const title = el("strong", { className: "m02-dfp__title" }); - const card = (label: string, inner: HTMLElement): HTMLElement => - el("section", { - className: "m01lab-side__card ui-collapsible ui-sidebar-section ui-sidebar-card", - children: [el("h3", { className: "ui-collapsible__title", text: label }), inner], - }); - const flowCard = card(ts("Flow"), flowSlot); - const sourceCard = card( - ts("Source"), - el("div", { className: "m01lab-src", children: [title, body] }), - ); - const side = el("div", { - className: "m01lab-side ui-sidebar-panel", - children: [flowCard, sourceCard], + const sp = createSidePanels({ + prefKey: "m01-logic-side", + defaultWidth: 520, + minWidth: 320, + panels: [ + { id: "flow", title: ts("Flow"), body: flowSlot }, + { + id: "source", + title: ts("Source"), + body: el("div", { className: "m01lab-src", children: [title, body] }), + }, + ], + onChange: () => { + flowFold?.(sp.current() !== "flow"); // 다시 펴면 흐름도 판을 폭에 맞춤 + load(); + }, }); - attachCollapsible(side); - // 공용 토글 뒤 — 연 카드만 남기고 다른 카드는 접음(접었으면 둘 다 닫힘) - side.addEventListener("click", (ev) => { - const at = (ev.target as HTMLElement).closest(".ui-collapsible__title")?.parentElement; - if (at !== flowCard && at !== sourceCard) return; - pick(at.classList.contains("is-collapsed") ? "none" : at === flowCard ? "flow" : "source"); + const root = el("div", { + className: "m01lab-side ui-side-panels-row", + children: [left, sp.root], }); - split.right.replaceChildren(side); - let now = readPick(); - let flowPx: number | null = null; let flowFold: ((on: boolean) => void) | null = null; let want = ""; let shown: string | null = null; - /** 카드 안팎 여백(좌우 안쪽 + 테두리) — 흐름도 패널 너비에 더함 */ - const pad = (): number => { - const s = getComputedStyle(flowCard); - return ["paddingLeft", "paddingRight", "borderLeftWidth", "borderRightWidth"].reduce( - (n, k) => n + (parseFloat(s[k as "paddingLeft"]) || 0), - 0, - ); - }; - /** 칸 너비 — 원문(또는 흐름도가 아직 안 뜸) = 두 칸 비율 · 흐름도 = 패널 너비 + 카드 여백 · 둘 다 접힘 = 제목 행 */ - const width = (): void => - split.setRight( - now === "source" || (now === "flow" && flowPx === null) - ? null - : now === "flow" - ? (flowPx ?? 0) + pad() - : FOLDED, - ); - const load = (): void => { - if (now !== "source" || shown === want) return; + if (sp.current() !== "source" || shown === want) return; const src = (shown = want); title.textContent = src || ts("NoSource"); body.replaceChildren(el("p", { className: "m01-logic__muted", text: ts("Loading") })); @@ -165,28 +136,11 @@ export function buildLogicSide(split: SplitHandle): LogicSide { }); }; - const pick = (next: PanelPick): void => { - if (next !== now) writeStateRaw("m01-logic-panel", next); - now = next; - flowFold?.(now !== "flow"); // 칸을 줄이기 전에 — 흐름도 패널이 접기 전 너비를 재어 둠 - flowCard.classList.toggle("is-collapsed", now !== "flow"); - sourceCard.classList.toggle("is-collapsed", now !== "source"); - width(); - load(); - }; - - pick(now); return { - flowSplit: { - root: split.root, - right: flowSlot, - setRight: (px) => { - flowPx = px; - width(); - }, - }, - flowFolded: () => now !== "flow", - pick, + root, + flowSplit: { right: flowSlot, setRight: () => undefined }, + flowFolded: () => sp.current() !== "flow", + pick: (next) => sp.open(next === "none" ? null : next), bindFlow: (f) => { flowFold = f; }, diff --git a/resources/tester/test_ui_side_panels.py b/resources/tester/test_ui_side_panels.py new file mode 100644 index 000000000..bc508ddb6 --- /dev/null +++ b/resources/tester/test_ui_side_panels.py @@ -0,0 +1,44 @@ +"""공용 오른쪽 접는 패널(`ui_template_side_panels.ts`) 시험 — 폭 자르기 · 줄 수. + +접기 · 펴기 · 기억은 화면 시나리오(`ui_checks/47-3_로직상세_오른쪽패널.js`)로 봄. +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +PART = ROOT / "ui_template" / "ui_template_side_panels.ts" + + +def test_700줄을_넘지_않음(): + for path in (PART, PART.with_suffix(".css")): + assert len(path.read_text(encoding="utf-8").splitlines()) <= 700, path.name + + +@pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없음") +def test_폭_자르기(): + """`clampSideWidth` — 가장 작게 min · 가장 크게 화면 85% · 화면이 좁아도 min.""" + found = re.search( + r"^export function clampSideWidth[\s\S]*?^}", PART.read_text(encoding="utf-8"), re.M + ) + assert found, "clampSideWidth 를 못 찾음" + script = ( + found.group(0).replace("export ", "") + + "\nconsole.log(JSON.stringify(JSON.parse(process.argv[1])" + + ".map(([p, m, v]) => clampSideWidth(p, m, v))));" + ) + cases = [[100, 280, 1600], [500.4, 280, 1600], [5000, 280, 1600], [500, 280, 200]] + result = subprocess.run( + ["node", "--experimental-strip-types", "--no-warnings", + "--input-type=module-typescript", "-e", script, json.dumps(cases)], + capture_output=True, text=True, encoding="utf-8", timeout=60, + ) # fmt: skip + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == [280, 500, 1360, 280] diff --git a/resources/tester/ui_checks/47-3_로직상세_오른쪽패널.js b/resources/tester/ui_checks/47-3_로직상세_오른쪽패널.js new file mode 100644 index 000000000..78062b155 --- /dev/null +++ b/resources/tester/ui_checks/47-3_로직상세_오른쪽패널.js @@ -0,0 +1,141 @@ +/* 47-3 M01 단가산출 로직 상세 오른쪽 패널 — `orca eval --expression "$(cat 이 파일)"` 한 번에 돎 · JSON 돌려줌. + * + * 시작 화면: M01 마스터 데이터(#/m01-master-data · 시스템 관리자 로그인) · 아무 화면이나. + * 로직 GC000277(건설품셈 토목 1-1-2 유도선 설치 및 해체)을 엶 · 고치지 않음 · 끝에 열린 패널 · 폭을 처음 값으로 되돌림. + * 기대 수치: + * panels = ["흐름도","원문"] · 패널 몸 = 공용 패널(.ui-side-panels) · 왼쪽 칸 오른쪽에 붙음(sideRight) + * flow = {open:["flow"], strips:["원문"]} · 흐름도 판 보임 · 흐름도 패널 자체 접기 단추 · 끌기 경계 안 보임(inner 0) + * source = {open:["source"], strips:["흐름도"]} · 폭 = flow 폭(공유) · srcHead 에 「1-1-2 유도선」 · srcTable true + * none = {open:[], strips:["흐름도","원문"]} · 띠 너비 < 40 + * back = {open:["flow"]}(흐름도 띠로 다시 폄) + * drag = 왼쪽 경계를 100px 왼쪽으로 끌면 폭 +100 · 원문으로 바꿔도 같은 폭 · key = 화살표 ← 한 번 +20 + * noLink = 「원문 연결 없음」 + 「출처 · …」(서버가 빈 목록을 줄 때 · fetch 를 잠시 바꿔 봄) + * restored = 처음 취향 값과 같음 + */ +(async () => { + const W = (ms) => new Promise((r) => setTimeout(r, ms)); + const $ = (s, root = document) => root.querySelector(s); + const $$ = (s, root = document) => [...root.querySelectorAll(s)]; + const until = async (f, ms = 15000) => { + for (let t = 0; t < ms; t += 200) { + const v = f(); + if (v) return v; + await W(200); + } + return null; + }; + const PREF = "aislo:pref:m01-logic-side"; + const first = localStorage.getItem(PREF); + const out = {}; + const openLogic = async (key) => { + sessionStorage.setItem("m01.logic.pending", key); + const tab = $$(".ui-collapsible__title").find((h) => h.innerText.trim() === "단가산출 로직"); + if (!tab) return false; + if (!tab.closest(".ui-collapsible").classList.contains("is-collapsed")) tab.click(); + tab.click(); + return until(() => { + const t = $(".m02-dfp__title")?.innerText ?? ""; + return !$(".m01lab-side")?.hidden && $(".m01lab-side .m02-dfp") && t; + }); + }; + if (!(await openLogic("GC000277"))) return JSON.stringify({ error: "로직 못 엶" }); + await W(800); + const shown = (n) => !!n && n.getBoundingClientRect().height > 0; + const panel = (id) => $(`.m01lab-side .ui-side-panels__panel[data-panel="${id}"]`); + const strip = (title) => + $$(".m01lab-side .ui-side-panels__strip").find((s) => s.innerText.replace(/\s/g, "") === title); + const wOf = (n) => Math.round(n.getBoundingClientRect().width); + const state = () => ({ + open: ["flow", "source"].filter((id) => shown(panel(id))), + strips: $$(".m01lab-side .ui-side-panels__strip") + .filter(shown) + .map((s) => s.innerText.replace(/\s/g, "")), + width: ["flow", "source"].filter((id) => shown(panel(id))).map((id) => wOf(panel(id)))[0] ?? 0, + }); + const pref = () => JSON.parse(localStorage.getItem(PREF) ?? "{}"); + out.panels = $$(".m01lab-side .ui-side-panels__title").map((t) => t.innerText.trim()); + const editor = $(".m01lab-side > .m01-logic__editor").getBoundingClientRect(); + const side = $(".m01lab-side .ui-side-panels").getBoundingClientRect(); + out.sideRight = Math.round(side.left - editor.right); + // 처음 = 흐름도 열림으로 맞춤 + if (!shown(panel("flow"))) { + strip("흐름도").click(); + await W(400); + } + out.flow = state(); + out.flowDiagram = shown($(".m02-dfp__open", panel("flow"))); + out.inner = $$(".m01lab-side .m02-dfp__toggle, .m01lab-side .m02-dfp__grip").filter(shown).length; + // 끌기 — 왼쪽 경계를 100px 왼쪽으로 + const grip = $(".ui-side-panels__grip", panel("flow")); + const g = grip.getBoundingClientRect(); + const x0 = g.left + g.width / 2; + const y0 = g.top + 50; + const w0 = state().width; + grip.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, button: 0, clientX: x0, clientY: y0 }), + ); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: x0 - 50, clientY: y0 })); + window.dispatchEvent(new PointerEvent("pointerup", { clientX: x0 - 100, clientY: y0 })); + await W(200); + out.drag = { before: w0, after: state().width, pref: pref().width }; + // 원문 — 폭 공유 + strip("원문").click(); + await until(() => $(".m01lab-src__head")); + out.source = state(); + out.srcHead = $(".m01lab-src__head")?.innerText; + out.srcTable = $$(".m01lab-src__table td").some((td) => td.innerText === "특별인부"); + // 키보드 — ← 한 번 = +20 · → 한 번 = 되돌림 + const sg = $(".ui-side-panels__grip", panel("source")); + sg.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true })); + const k1 = state().width; + sg.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })); + out.key = { left: k1 - out.source.width, back: state().width - out.source.width }; + // 모두 접기 — 원문 머리 ▸ + $(".ui-side-panels__fold", panel("source")).click(); + await W(300); + out.none = { ...state(), stripW: wOf(strip("흐름도")), pref: pref().open }; + strip("흐름도").click(); + await W(600); + out.back = { ...state(), pref: pref().open }; + // 원문 연결 없음 — 서버가 빈 목록을 줄 때 + strip("원문").click(); + const real = window.fetch; + window.fetch = (u, o) => + String(u).includes("/m01/logic/source") + ? Promise.resolve(new Response(JSON.stringify({ found: [] }), { status: 200 })) + : real(u, o); + try { + await openLogic("GC000338"); + await until(() => $(".m01lab-src__none")); + out.noLink = [ + $(".m01lab-src__none")?.innerText, + $(".m01lab-src__body .m01-logic__muted")?.innerText, + ]; + } finally { + window.fetch = real; + } + // 되돌림 — 폭(끈 만큼 ←→ 화살표로) · 열린 패널 + const was = JSON.parse(first ?? "{}"); + const want = was.open === undefined ? "flow" : was.open; + const now = () => ["flow", "source"].find((id) => shown(panel(id))) ?? null; + if (now() !== want) { + if (want === null) $(".ui-side-panels__fold", panel(now())).click(); + else strip(want === "flow" ? "흐름도" : "원문").click(); + await W(300); + } + const target = was.width ?? w0; + const anyGrip = $$(".m01lab-side .ui-side-panels__grip")[0]; + for (let i = 0; i < 40 && pref().width !== target; i++) { + const d = target - pref().width; + anyGrip.dispatchEvent( + new KeyboardEvent("keydown", { + key: d > 0 ? "ArrowLeft" : "ArrowRight", + shiftKey: Math.abs(d) >= 80, + bubbles: true, + }), + ); + } + out.restored = first === null ? pref() : localStorage.getItem(PREF) === first; + out.first = first; + return JSON.stringify(out); +})(); diff --git a/ui_template/ui_template_side_panels.css b/ui_template/ui_template_side_panels.css new file mode 100644 index 000000000..344f6fb1b --- /dev/null +++ b/ui_template/ui_template_side_panels.css @@ -0,0 +1,126 @@ +/* 본문 오른쪽 접는 패널 여럿 — 접힌 패널 = 세로 글 띠 · 편 패널 = 공유 폭(--ui-side-panels-width) */ + +/* 부르는 쪽 칸 — [본문, 패널 묶음] */ +.ui-side-panels-row { + display: flex; + align-items: stretch; + min-width: 0; +} + +.ui-side-panels-row[hidden] { + display: none; +} + +.ui-side-panels-row > :first-child { + flex: 1 1 auto; + min-width: 0; +} + +.ui-side-panels { + display: flex; + flex: none; + align-items: stretch; + gap: var(--spacing-4); + margin-left: var(--spacing-8); +} + +.ui-side-panels.is-resizing { + user-select: none; +} + +.ui-side-panels__strip { + flex: none; + width: 32px; + padding: var(--spacing-8) 0; + border: 1px solid var(--color-border); + border-radius: var(--radius-cards); + background: var(--color-surface); + color: var(--color-text-secondary); + font: inherit; + font-size: var(--text-body-sm); + font-weight: 600; + writing-mode: vertical-rl; + text-orientation: mixed; + text-align: start; + cursor: pointer; +} + +.ui-side-panels__strip:hover, +.ui-side-panels__strip:focus-visible { + border-color: var(--color-primary); + color: var(--color-text); +} + +.ui-side-panels__panel { + position: relative; + display: flex; + flex: none; + flex-direction: column; + width: var(--ui-side-panels-width, 420px); + min-width: 0; + border: 1px solid var(--color-border); + border-radius: var(--radius-cards); + background: var(--color-surface); +} + +.ui-side-panels__strip[hidden], +.ui-side-panels__panel[hidden] { + display: none; +} + +/* 왼쪽 경계 — 끌기 · 화살표 키 */ +.ui-side-panels__grip { + position: absolute; + top: 0; + bottom: 0; + left: -5px; + width: 8px; + cursor: col-resize; + touch-action: none; + z-index: 1; +} + +.ui-side-panels__grip:hover, +.ui-side-panels__grip:focus-visible, +.ui-side-panels.is-resizing .ui-side-panels__grip { + background: var(--color-primary); + opacity: 0.4; +} + +.ui-side-panels__head { + display: flex; + align-items: center; + gap: var(--spacing-8); + padding: var(--spacing-8) var(--spacing-12); + border-bottom: 1px solid var(--color-border); +} + +.ui-side-panels__title { + flex: 1 1 auto; + min-width: 0; + color: var(--color-text); +} + +.ui-side-panels__fold { + flex: none; + padding: 0 var(--spacing-4); + border: 0; + border-radius: var(--radius-sm); + background: none; + color: var(--color-text-secondary); + font: inherit; + cursor: pointer; +} + +.ui-side-panels__fold:hover, +.ui-side-panels__fold:focus-visible { + color: var(--color-primary); +} + +.ui-side-panels__body { + flex: 1 1 auto; + min-width: 0; + min-height: 0; + padding: var(--spacing-12); + overflow: auto; +} diff --git a/ui_template/ui_template_side_panels.ts b/ui_template/ui_template_side_panels.ts new file mode 100644 index 000000000..9198144a0 --- /dev/null +++ b/ui_template/ui_template_side_panels.ts @@ -0,0 +1,182 @@ +/* ============================================================================= + * ui_template_side_panels.ts + * 본문 오른쪽 접는 패널 여럿 — 나란히 · 하나만 열림 · 모두 접힘 됨 · 폭 공유 + * 접힌 패널 = 제목 세로 글 띠(누르면 폄) · 편 패널 = 머리(제목 · 접기 ▸) + 몸 · 왼쪽 경계 끌기(화살표 키) + * 열린 패널 · 폭 = 부르는 쪽 취향 키(`aislo:pref:{prefKey}`) + * 부르기: const sp = createSidePanels({ prefKey, panels: [{ id, title, body }] }) → + * 본문과 함께 `.ui-side-panels-row` 칸에 [본문, sp.root] 로 넣음 + * ========================================================================== */ + +import { readByKey, writeByKey } from "../A00_Common/b_page_state"; +import { el } from "./ui_template_elements"; +import { currentLanguageIndex } from "./ui_template_locale"; +import "./ui_template_side_panels.css"; + +const TEXT = { + Open: ["{v} 펴기", "Open {v}"], + Close: ["{v} 접기", "Collapse {v}"], + Grip: ["패널 너비 — 끌거나 화살표 키", "Panel width — drag or arrow keys"], +} as const; + +const ts = (key: keyof typeof TEXT, v: string): string => + TEXT[key][currentLanguageIndex === 1 ? 1 : 0].replace("{v}", v); + +export interface SidePanelDef { + id: string; + title: string; + body: HTMLElement; +} + +export interface SidePanelsOpts { + panels: SidePanelDef[]; + /** 취향 키 이름 — `aislo:pref:` 뒤에 붙음 */ + prefKey: string; + /** 기억이 없을 때 열 패널(null = 모두 접힘) · 기본 첫 패널 */ + defaultOpen?: string | null; + /** 기억이 없을 때 폭(px) · 기본 420 */ + defaultWidth?: number; + /** 가장 좁은 폭(px) · 기본 280 · 가장 넓게 = 화면의 85% */ + minWidth?: number; + /** 열린 패널이 바뀜(누름 · open 모두) */ + onChange?(open: string | null): void; + /** 폭이 바뀜(끌기 · 화살표) */ + onResize?(px: number): void; +} + +export interface SidePanels { + root: HTMLElement; + /** 열 패널(null = 모두 접음) — 기억함 */ + open(id: string | null): void; + current(): string | null; + width(): number; +} + +interface Pref { + open?: string | null; + width?: number; +} + +/** 끌어 정한 폭 — 가장 작게 min · 가장 크게 화면의 85% */ +export function clampSideWidth(px: number, min: number, viewport: number): number { + return Math.round(Math.min(Math.max(min, viewport * 0.85), Math.max(min, px))); +} + +export function createSidePanels(opts: SidePanelsOpts): SidePanels { + const key = `aislo:pref:${opts.prefKey}`; + const min = opts.minWidth ?? 280; + const ids = opts.panels.map((p) => p.id); + let pref: Pref = {}; + try { + pref = JSON.parse(readByKey(key) ?? "{}") as Pref; + } catch { + /* 깨진 기억 — 기본값 */ + } + let now: string | null = + pref.open === null || ids.includes(pref.open ?? "") + ? (pref.open ?? null) + : opts.defaultOpen === undefined + ? (ids[0] ?? null) + : opts.defaultOpen; + let width = clampSideWidth(pref.width ?? opts.defaultWidth ?? 420, min, window.innerWidth); + const save = (): void => writeByKey(key, JSON.stringify({ open: now, width })); + + const root = el("div", { className: "ui-side-panels" }); + root.style.setProperty("--ui-side-panels-width", `${width}px`); + const setWidth = (px: number, keep: boolean): void => { + width = clampSideWidth(px, min, window.innerWidth); + root.style.setProperty("--ui-side-panels-width", `${width}px`); + opts.onResize?.(width); + if (keep) save(); + }; + + const views = opts.panels.map((p) => { + const bodyId = `ui-side-panel-${opts.prefKey}-${p.id}`; + const strip = el("button", { + className: "ui-side-panels__strip", + text: p.title, + attrs: { type: "button", "aria-expanded": "false", "aria-controls": bodyId }, + }); + strip.title = ts("Open", p.title); + strip.addEventListener("click", () => { + open(p.id); + fold.focus(); + }); + const fold = el("button", { + className: "ui-side-panels__fold", + text: "▸", + attrs: { type: "button", "aria-expanded": "true", "aria-controls": bodyId }, + }); + fold.title = ts("Close", p.title); + fold.setAttribute("aria-label", fold.title); + fold.addEventListener("click", () => { + open(null); + strip.focus(); + }); + const grip = el("div", { + className: "ui-side-panels__grip", + attrs: { + role: "separator", + "aria-orientation": "vertical", + "aria-label": ts("Grip", ""), + tabindex: "0", + }, + }); + const box = el("section", { + className: "ui-side-panels__panel", + attrs: { "data-panel": p.id, "aria-label": p.title }, + children: [ + grip, + el("header", { + className: "ui-side-panels__head", + children: [el("strong", { className: "ui-side-panels__title", text: p.title }), fold], + }), + el("div", { className: "ui-side-panels__body", attrs: { id: bodyId }, children: [p.body] }), + ], + }); + grip.addEventListener("pointerdown", (ev) => { + if (ev.button !== 0) return; + ev.preventDefault(); + const start = box.getBoundingClientRect().width; + const x0 = ev.clientX; + root.classList.add("is-resizing"); + const move = (m: PointerEvent): void => setWidth(start + x0 - m.clientX, false); + const up = (u: PointerEvent): void => { + window.removeEventListener("pointermove", move); + window.removeEventListener("pointerup", up); + root.classList.remove("is-resizing"); + setWidth(start + x0 - u.clientX, true); + }; + window.addEventListener("pointermove", move); + window.addEventListener("pointerup", up); + }); + grip.addEventListener("keydown", (ev) => { + const step = ev.shiftKey ? 80 : 20; + const d = ev.key === "ArrowLeft" ? step : ev.key === "ArrowRight" ? -step : 0; + if (!d) return; + ev.preventDefault(); + setWidth(width + d, true); + }); + root.append(strip, box); + return { id: p.id, strip, box }; + }); + + const draw = (): void => { + for (const v of views) { + const on = v.id === now; + v.strip.hidden = on; + v.box.hidden = !on; + } + }; + + function open(id: string | null): void { + const next = id !== null && ids.includes(id) ? id : null; + const was = now; + now = next; + draw(); + save(); + if (next !== was) opts.onChange?.(next); + } + + draw(); + return { root, open, current: () => now, width: () => width }; +}