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/ui_template/ui_template_side_panels.css b/ui_template/ui_template_side_panels.css new file mode 100644 index 000000000..262426c46 --- /dev/null +++ b/ui_template/ui_template_side_panels.css @@ -0,0 +1,122 @@ +/* 본문 오른쪽 접는 패널 여럿 — 접힌 패널 = 세로 글 띠 · 편 패널 = 공유 폭(--ui-side-panels-width) */ + +/* 부르는 쪽 칸 — [본문, 패널 묶음] */ +.ui-side-panels-row { + display: flex; + align-items: stretch; + min-width: 0; +} + +.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 }; +}