From e671b7739a36ac30debbd47ca6a48b93f5f6fe77 Mon Sep 17 00:00:00 2001 From: umsangdon Date: Fri, 16 Oct 2026 21:37:29 +0900 Subject: [PATCH] =?UTF-8?q?fix(=EB=90=98=EB=8F=8C=EB=A6=AC=EA=B8=B0):=2035?= =?UTF-8?q?6-4=20=EB=85=B8=EC=84=A0=20=EB=90=98=EB=8F=8C=EB=A6=AC=EA=B8=B0?= =?UTF-8?q?=20=C2=B7=20=EB=8B=A4=EC=8B=9C=ED=95=98=EA=B8=B0=20=3D=20?= =?UTF-8?q?=EA=B7=B8=20=EA=B1=B8=EC=9D=8C=20=EC=82=AC=EC=A7=84=EC=9D=98=20?= =?UTF-8?q?=EA=B3=84=ED=9A=8D=EA=B3=A0=20=ED=8E=B8=EC=A7=91=20=EA=B7=B8?= =?UTF-8?q?=EB=8C=80=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 사진첩 되살림 표시(pageReplaying) — 되살림 중 바뀐 노선은 새 조작 아님 - 묶음 follow 가 그 차례엔 계획고 편집을 옮기지 않고 세션 노선 0 칸(사진) 그대로 · 관 · 구조물도 세션 그대로 - 바뀐 구간 첫 계획선 맞춤 · 계획고 옮김은 새 조작 때만 - 시험 test_356_4 · helper_356_4(끌기 · ▲ · 다시 끌기 · 중심점 보정 · 되돌리기 · 다시하기 · 옛 동작 대조) · test_349_0q 입력 만들기 함수로 뗌 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TteK8mfYZetk5P3bEZkyVZ --- A00_Common/design/design_pipeline_page.ts | 8 + B05_Profile/B05_Profile_UI_Profile_History.ts | 8 +- resources/tester/helper_356_4_undo_grade.cjs | 448 ++++++++++++++++++ resources/tester/test_349_0q_undo_echo.py | 10 +- resources/tester/test_356_4_undo_grade.py | 88 ++++ 5 files changed, 558 insertions(+), 4 deletions(-) create mode 100644 resources/tester/helper_356_4_undo_grade.cjs create mode 100644 resources/tester/test_356_4_undo_grade.py diff --git a/A00_Common/design/design_pipeline_page.ts b/A00_Common/design/design_pipeline_page.ts index 48413bc6c..3ec3d51f0 100644 --- a/A00_Common/design/design_pipeline_page.ts +++ b/A00_Common/design/design_pipeline_page.ts @@ -55,6 +55,7 @@ import { readAlignmentDraft, } from "../../B05_Profile/B05_Profile_UI_Profile_Edit"; import { readAlignment } from "../../B05_Profile/logic/B05_Profile_UI_Profile_Data"; +import { pageReplaying } from "../../B05_Profile/B05_Profile_UI_Profile_History"; import { analysisTerrain, fetchRoutePlan, @@ -259,6 +260,9 @@ function createPagePipeline( /** 묶음이 가게에 마지막으로 쓴 관 · 구조물 · 쓰는 동안(메아리 — 다시 입력으로 안 받음). */ let written: Facilities | null = null; let echo = false; + /** 되돌리기 · 다시하기로 바뀐 노선(356-4) — follow 가 계획고 편집을 옮기지 않고 그 걸음 사진(세션 노선 0 칸) + * 그대로. 바뀐 구간 첫 계획선 맞춤 · 계획고 옮김은 새 조작 때만. */ + let replay = false; const savedLine = (): Vertex[] | null => plan ? plan.planned.map(([x, y]): Vertex => [x, y]) : null; @@ -320,6 +324,9 @@ function createPagePipeline( savedLine: () => plan && { line: savedLine()!, curves: savedCurves() }, }), follow: (ctx) => { + const kept = replay && ctx.inputs.route ? readAlignmentDraft(DRAFT_ROUTE_ID) : null; + replay = false; + if (kept) return { alignment: kept }; // 관 · 구조물도 세션 그대로(가게 · 쓰기 그대로) const line = ctx.before.route?.line ?? savedLine() ?? []; const { pipes, structures } = ctx.inputs; const inputs = { @@ -567,6 +574,7 @@ function createPagePipeline( if (stored && same({ ...stored, rev: 0 }, { ...draft, rev: 0 })) draft = stored; } if (draft && !wasDraft && !held) held = holdNow(); + replay = pageReplaying(); store.set("routeDraft", draft); if (!started) return start(); const before = pipe.output("route")?.line ?? null; diff --git a/B05_Profile/B05_Profile_UI_Profile_History.ts b/B05_Profile/B05_Profile_UI_Profile_History.ts index 932521a9d..d7c21b5f7 100644 --- a/B05_Profile/B05_Profile_UI_Profile_History.ts +++ b/B05_Profile/B05_Profile_UI_Profile_History.ts @@ -89,6 +89,10 @@ export function setPageHistory(history: ProfileHistory): void { active = history; } +/** 되돌리기 · 다시하기가 세션을 되쓰고 화면을 되살리는 중인가 — 그 사이 바뀐 노선은 새 조작이 아님(356-4). */ +let replaying = false; +export const pageReplaying = (): boolean => replaying; + export type PageHistoryEvent = "undo" | "redo"; interface PageHistoryHooks { /** 세션을 되쓴 뒤 — 자기 화면 값을 다시 읽음(사진첩이 막고 있는 동안이라 쌓이지 않음). */ @@ -193,7 +197,7 @@ export function createProfileHistory(onRestore: () => void, limit = 100): Profil if (index < 0 || index >= stack.length) return false; const kind: PageHistoryEvent = index < cursor ? "undo" : "redo"; cursor = index; - restoring = true; + restoring = replaying = true; restoreSnapshot(stack[cursor]); try { onRestore(); @@ -201,7 +205,7 @@ export function createProfileHistory(onRestore: () => void, limit = 100): Profil // 되살리며 다시 쓴 같은 값(정리된 꼴)을 이 걸음으로 — 다음 찍기가 헛걸음을 안 만듦. stack[cursor] = takeSnapshot(stack[cursor]); } finally { - restoring = false; + restoring = replaying = false; } changed(); return true; diff --git a/resources/tester/helper_356_4_undo_grade.cjs b/resources/tester/helper_356_4_undo_grade.cjs new file mode 100644 index 000000000..c72761132 --- /dev/null +++ b/resources/tester/helper_356_4_undo_grade.cjs @@ -0,0 +1,448 @@ +/* PLAN 356-4 sub7 헬퍼 — 되돌리기 · 다시하기는 그 걸음 사진(노선 + 계획고 편집)을 그대로 되살림. + * 판 = `helper_349_0q_undo_echo.cjs` 그대로(진짜 종단도 · 묶음 · 상세 가게 · 페이지 사진첩 · 서버 창구만 가짜). + * 편집기 흉내 = 사진첩 되살림 훅 안에서 세션 노선 초안을 다리에 넘김(`_RouteEdit_Draft` fromPage 꼴). + * 걸음 — 끌기 → 계획고 ▲(측점 C) → 다시 끌기(C 가 바뀐 구간 = 새 조작은 ▲ 버림) → 되돌리기 · 다시하기 → + * 중심점 좌우 꼴(끌기 + C 높이 보정 · 한 걸음) → 되돌리기 · 다시하기 → 열기까지 되돌리기. + * argv[4] = "off" 면 되살림 표시를 끔(옛 동작 대조). 결과 = 표준출력 JSON. 짝 = `test_356_4_undo_grade.py`. */ +const fs = require("fs"); +const path = require("path"); +const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript")); +const CATALOG = require("./helper_322_catalog_module.cjs"); + +const ROOT = path.join(__dirname, "..", ".."); +const job = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); + +function memoryStorage() { + const map = new Map(); + return { + getItem: (key) => (map.has(key) ? map.get(key) : null), + setItem: (key, value) => map.set(key, String(value)), + removeItem: (key) => map.delete(key), + key: (index) => [...map.keys()][index] ?? null, + get length() { + return map.size; + }, + }; +} +const winListeners = {}; +const windowBase = { + sessionStorage: memoryStorage(), + localStorage: memoryStorage(), + setTimeout, + clearTimeout, + addEventListener: (type, fn) => (winListeners[type] ??= []).push(fn), + removeEventListener: () => undefined, +}; +globalThis.window = new Proxy(windowBase, { + get: (t, key) => (key in t ? t[key] : undefined), + set: (t, key, value) => ((t[key] = value), true), +}); + +// 흙 배분 서버 — 늦게 답함 · 끊기면 버림 +globalThis.fetch = (url, init) => + new Promise((resolve, reject) => { + const timer = setTimeout( + () => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }), + 20, + ); + init.signal.addEventListener("abort", () => { + clearTimeout(timer); + reject(new Error("aborted")); + }); + }); + +const STUBS = {}; +const cache = new Map(); +function loadTs(full) { + if (cache.has(full)) return cache.get(full); + const js = ts.transpileModule(fs.readFileSync(full, "utf8"), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const box = { exports: {} }; + cache.set(full, box.exports); + const localRequire = (request) => { + if (CATALOG.isCatalogRequest(request)) return CATALOG; + const key = Object.keys(STUBS).find((name) => request.endsWith(name)); + if (key) return STUBS[key]; + if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" }; + if (request.startsWith("@ui/")) return anyModule(); + if (request.endsWith(".css")) return {}; + if (request.endsWith(".json")) return require(path.join(path.dirname(full), request)); + if (request.startsWith("@util/")) + return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`)); + if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`)); + return require(request); + }; + new Function("exports", "module", "require", js)(box.exports, box, localRequire); + return box.exports; +} +const load = (...parts) => loadTs(path.join(ROOT, ...parts)); + +const sampler = load("common_util", "common_util_surface_sampler.ts"); +const bytes = fs.readFileSync(process.argv[3]); +const grid = sampler.parseDtmGrid( + bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), +); +const local = { grid, design: "las" }; + +/** 아무 화면 부품 — 무엇을 읽든 · 부르든 또 그것(DOM · 오버레이 · 도구줄 흉내). */ +function anyNode() { + const box = { dataset: {}, style: {}, classList: { add() {}, remove() {}, toggle() {} } }; + return new Proxy(function node() {}, { + get: (_t, key) => { + if (key in box) return box[key]; + if (key === "then" || typeof key === "symbol") return undefined; + return (box[key] = anyNode()); + }, + set: (_t, key, value) => ((box[key] = value), true), + apply: () => anyNode(), + }); +} +const anyModule = (own = {}) => + new Proxy(own, { + get: (t, key) => + key in t + ? t[key] + : key === "__esModule" + ? true + : typeof key === "symbol" + ? undefined + : anyNode(), + }); +globalThis.document = anyNode(); +globalThis.HTMLElement = function HTMLElement() {}; + +STUBS["B05_Profile_Api_Replan"] = { + analysisTerrain: () => "las", + fetchRoutePlan: async () => ({ + planned: job.line, + curves: job.curves, + min_radius_m: job.minRadius, + station_snap: job.stationSnap, + }), +}; +STUBS["B05_Profile_Api_Structures"] = anyModule({ + fetchStructures: async () => ({ structures: job.structures }), + fetchStructureTypes: async () => job.types, + readPendingStructures: () => null, +}); +STUBS["B05_Profile_Api_TerrainGrid"] = { + loadDesignTerrainGrid: async () => local, + groundStageDeps: () => ({ grid: () => local, remote: async () => [] }), +}; +STUBS["B04_PreProcess_Api_Fetch"] = { + fetchDetailPipePoints: async () => ({ + pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })), + }), +}; +STUBS["B06_Section_UI_Standard_Panel"] = { + effectiveStandardCross: () => job.standard, + readRockBoundaryDefault: () => -0.5, +}; +// 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음 +STUBS["B06_Section_Section_Drafts"] = { + withDraftStations: async () => undefined, + withDraftShapes: async () => undefined, + forgetDraftStations: () => undefined, +}; +STUBS["B06_Section_Api_Fetch"] = { + fetchSectionDetail: async () => JSON.parse(JSON.stringify(job.detail)), + saveSections: async () => undefined, +}; +// 횡단 다시 셈(브라우저 · B05 crossPreview · B06 카드 같은 창구) — 부른 횟수 · 면적은 서버와 달라짐(두 배) +let refreshCalls = 0; +const doubled = (detail) => + detail.cross_sections.forEach((section) => { + if (!section.design) return; + const design = { ...section.design }; + for (const [key, value] of Object.entries(design)) + if (key.endsWith("_m2") && typeof value === "number") design[key] = value * 2; + section.design = design; + }); +STUBS["B06_Section_Cross_Refresh"] = { + refreshCrossDesigns: async ({ detail }) => { + refreshCalls += 1; + doubled(detail); + return detail.cross_sections.map((s) => s.chainage_m); + }, + // 화면 선 맡김 · 낡음 판정 = 진짜 `staleAgainstScreen` 그대로(화면 선 → 없으면 상세 자기 선) + holdScreenAlignment: (line) => { + screenLine = line; + return () => undefined; + }, + staleAgainstScreen: (detail, routeId) => { + const screen = screenLine?.(routeId); + if (!screen) return common.hasStaleDesigns(detail); + return common.hasStaleDesigns({ + longitudinal: { + design_profiles: [ + profileData.toDesignProfile(screen, detail.longitudinal.design_profiles?.[0]), + ], + }, + cross_sections: detail.cross_sections, + }); + }, + USER_TOUCHED_KEYS: [], +}; +let screenLine = null; +STUBS["B06_Section_UI_Cross_Detail"] = anyModule(); +STUBS["B06_Section_UI_Page_Common"] = anyModule({ L: (key) => key }); +// 그리기 — 진짜 `renderProfile` 의 낡음 판정 줄만(같은 함수 · 같은 인자) · SVG 는 안 그림 +const draws = []; +let opened = null; +STUBS["B05_Profile_UI_Profile_Render"] = { + renderProfile: (ctx) => { + const detail = ctx.detail(); + if (!detail) return; + const alignment = ctx.alignment(); + const longitudinal = detail.longitudinal; + const designProfiles = alignment + ? [profileData.toDesignProfile(alignment, longitudinal.design_profiles?.[0])] + : (longitudinal.design_profiles ?? []); + const key = common.staleKey({ + longitudinal: { design_profiles: designProfiles }, + cross_sections: detail.cross_sections, + }); + // 저장 상세를 그림 = 묶음 새 노선 상세(preview)가 아님 · 그린 객체(가게 것인지 견줌) + draws.push({ key, saved: !detail.cross_sections.some((s) => s.preview), ref: detail }); + ctx.onStaleDesigns?.(key); + }, +}; +STUBS["B05_Profile_UI_Profile_Tools"] = anyModule(); +STUBS["design_profile_free_view"] = anyModule(); +STUBS["B06_Section_UI_Cross_Panel_Base"] = anyModule(); +globalThis.sessionStorage = window.sessionStorage; +STUBS["common_util_view_window"] = { frameOf: (_root, fn) => fn() }; +for (const name of [ + "B05_Profile_UI_Profile_Balance", + "B05_Profile_UI_Profile_Heights", + "B05_Profile_UI_Profile_Zoom", + "B05_Profile_UI_Profile_Drag", + "B05_Profile_UI_Profile_MassHaul", + "design_profile_overlays", + "design_profile_viewport", + "design_save", + "B05_Profile_Api_Fetch", + "common_util_mass_haul_balance_view", +]) + STUBS[name] = anyModule(); + +const pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); +const storeMod = load("A00_Common", "design", "design_store.ts"); +const sectionStore = load("B06_Section", "B06_Section_Section_Store.ts"); +const common = load("B06_Section", "B06_Section_UI_Section_Common.ts"); +const layouts = load("B06_Section", "B06_Section_Structure_Layouts.ts"); +const profileData = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Data.ts"); +const alignmentMod = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts"); +const baseMod = load("A00_Common", "design", "design_profile_base.ts"); +const pageState = load("A00_Common", "b_page_state.ts"); +const massHaul = load("common_util", "common_util_mass_haul.ts"); +const historyMod = load("B05_Profile", "B05_Profile_UI_Profile_History.ts"); +const shiftMod = load("B05_Profile", "logic", "B05_Profile_RouteShift.ts"); +const profileMod = load("A00_Common", "design", "design_profile.ts"); +const designSync = load("B06_Section", "B06_Section_UI_Page_Design_Sync.ts"); +const designSession = load("B06_Section", "B06_Section_Cross_Design_Session.ts"); +const stationKeys = load("B06_Section", "B06_Section_Station_Keys.ts"); +// 진짜 다시 셈 창구(묶음 새 노선 상세를 안 고치는지만 봄 · 다른 곳은 위 가짜를 부름) +const realRefresh = loadTs(path.join(ROOT, "B06_Section", "B06_Section_Cross_Refresh.ts")); + +const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); +const runs = () => globalThis.__aisloPipeline?.runs ?? []; +/** 묶음 · 상세 가게 · 다시 셈이 조용해질 때까지. */ +async function quiet() { + let seen = -1; + for (let i = 0; i < 400; i += 1) { + await tick(30); + const last = runs()[runs().length - 1]; + const count = runs().length + refreshCalls * 1000 + draws.length * 1e6; + if (count === seen && (!last || last.outcome !== "running")) return; + seen = count; + } + throw new Error("묶음이 조용해지지 않음"); +} +const n = job.nodes.length; +const draftOf = (nodes) => ({ + nodes, + curveOn: Array(n).fill(true), + curveRadius: Array(n).fill(null), + curveLock: Array(n).fill(null), + curveArc: Array(n).fill(null), + stationSnap: job.stationSnap, +}); +const shift = (index, dx, dy) => + job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node)); +const sliceRuns = (mark) => + runs() + .slice(mark) + .map((r) => ({ + sources: r.sources, + outcome: r.outcome, + restored: r.restored ?? null, + why: r.restoreWhy ?? null, + })); +const finalOf = (detail) => { + const [series] = massHaul.computeMassHaulSeries( + detail.longitudinal, + detail.cross_sections, + job.conversion, + undefined, + ["cross"], + ); + const points = series?.result.points ?? []; + return points.length ? points[points.length - 1].cumulative_volume_m3 : null; +}; +const crossOf = (detail) => + JSON.stringify(detail.cross_sections.map((s) => [s.chainage_m, s.design, s.samples])); +/** 서버 정본 흉내 — 저장 횡단 계획고 = 열 때 종단도 계획선(낡음 0 · 서버가 낸 상세와 같음). */ +function settleDesigns(detail) { + const pa = detail.longitudinal.profile_alignment; + const base = baseMod.listedBase(alignmentMod.toAlignmentBase(pa), detail, []); + const samples = alignmentMod.buildAlignment(base, pa.edits).samples; + const at = (c) => { + const i = samples.findIndex((s) => s.chainage_m >= c); + if (i < 0) return samples[samples.length - 1].elevation_m; + if (i === 0) return samples[0].elevation_m; + const a = samples[i - 1]; + const b = samples[i]; + return ( + a.elevation_m + + ((b.elevation_m - a.elevation_m) * (c - a.chainage_m)) / (b.chainage_m - a.chainage_m) + ); + }; + detail.cross_sections.forEach((s) => (s.design.design_elevation_m = at(s.chainage_m))); +} + +async function run() { + const P = "proj-3564"; + const R = 7; + window.localStorage.setItem("frd_current_project_id", P); + opened = await sectionStore.loadSectionDetail(P, R); + settleDesigns(opened); + stationKeys.useStationKeys(P, R, opened); + const profile = profileMod.createDesignProfile({ + projectId: P, + view: "profile", + onSelectStation: () => undefined, + }); + pageMod.routeDraftBridge(P, profile, { + stationIntervalM: job.interval, + structureAreas: ({ cross_sections: rows }) => + layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)), + holdDraft: (routeId, saved) => { + const hold = saved && sectionStore.holdSectionDetail(P, routeId, saved); + return async (stations) => { + if (!hold) { + await sectionStore.swapSectionStations(P, routeId, stations); + return "no-saved"; + } + const back = await sectionStore.restoreSectionDetail(P, routeId, hold, stations); + return !back ? "no-cache" : back.same ? "saved" : "saved-diff"; + }; + }, + }); + const show = (detail) => { + profile.render(detail, job.interval, R); + profile.setIrregularStations([]); + }; + const stopListen = sectionStore.subscribeSectionDetail(P, R, (next) => show(next)); + const stopStore = storeMod.useDesignStore(P, null).subscribe("stations", (stations) => { + if (stations?.length) void sectionStore.swapSectionStations(P, R, stations); + }); + show(opened); + profile.setEarthworkContext({ conversion: job.conversion }); + await quiet(); + + if (process.argv[4] === "off") historyMod.pageReplaying = () => false; // 옛 동작 대조 + const bridge = pageMod.routeDraftBridge(P, profile); + const designStore = storeMod.useDesignStore(P, null); + // 편집기 흉내 — 되살림 훅 안에서 세션 노선 초안을 다리에 넘김(노선 편집기가 사진첩에 단 훅 꼴) + historyMod.onPageHistory({ + restore: () => { + const kept = designStore.get("routeDraft"); + bridge.edited(kept ? draftOf(kept.nodes) : null); + }, + }); + const album = () => historyMod.pageHistory(); + const pipe = () => pageMod.pagePipeline(P); + const gesture = () => (winListeners.keydown ?? []).forEach((fn) => fn({})); + /** 한 걸음 — 손길 · 사진첩 멈춤 · 조작 · 조용해짐 · 한 번 쌓음. */ + const step = async (fn) => { + gesture(); + album().pause(); + await fn(); + await quiet(); + album().resume(); + }; + const grade = async (edits) => { + pageMod.pipelineGrade(P, edits); + await quiet(); + }; + const stations = pipe().output("ground").stations; + const [nx, ny] = job.nodes[1]; + const C = stations.reduce((a, b) => + Math.hypot(b.x - nx, b.y - ny) < Math.hypot(a.x - nx, a.y - ny) ? b : a, + ).chainageM; + const state = () => ({ + route: designStore.get("routeDraft")?.nodes[1] ?? null, + z: alignmentMod.planElevationAt(pipe().output("profile"), C), + offs: JSON.stringify(pipe().input("alignment")?.station_offsets ?? {}), + session: window.sessionStorage.getItem(`aislo:draft:alignment-draft:${P}:0`), + }); + const out = { C, open: state() }; + await step(() => bridge.edited(draftOf(shift(1, 6, -4)))); + out.drag1 = state(); + await step(() => { + const p = pipe(); + return grade(alignmentMod.adjustStation(p.output("planline"), p.input("alignment"), C, 0.3)); + }); + out.lift = state(); + await step(() => bridge.edited(draftOf(shift(1, 9, -6)))); + out.drag2 = state(); + album().undo(); + await quiet(); + out.undo1 = state(); + album().redo(); + await quiet(); + out.redo1 = state(); + // 중심점 좌우 꼴 — 끌기 + C 계획고를 끌기 전 값으로(한 걸음) + const zBefore = state().z; + await step(async () => { + bridge.edited(draftOf(shift(1, 12, -8))); + await quiet(); + const p = pipe(); + const pinned = shiftMod.pinStationHeight( + p.output("planline"), + p.input("alignment"), + C, + zBefore, + ); + if (pinned) await grade(pinned); + }); + out.pinned = { ...state(), zBefore }; + album().undo(); + await quiet(); + out.undo2 = state(); + album().redo(); + await quiet(); + out.redo2 = state(); + for (let i = 0; i < 6 && album().canUndo(); i += 1) { + album().undo(); + await quiet(); + } + out.home = state(); + out.blocked = pipe().blockedWrites; + stopListen(); + stopStore(); + pageMod.disposePagePipeline(P); + return out; +} + +run() + .then((out) => { + process.stdout.write(JSON.stringify(out)); + process.exit(0); + }) + .catch((error) => { + process.stderr.write(String(error && error.stack ? error.stack : error)); + process.exit(1); + }); diff --git a/resources/tester/test_349_0q_undo_echo.py b/resources/tester/test_349_0q_undo_echo.py index 455486817..fad9cb771 100644 --- a/resources/tester/test_349_0q_undo_echo.py +++ b/resources/tester/test_349_0q_undo_echo.py @@ -60,8 +60,8 @@ def _between(sections: list[dict], index: int) -> dict: } -@pytest.fixture(scope="module") -def r() -> dict: +def build_job() -> dict: + """입력 한 벌 — 356-4 시험도 빌림.""" if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()): pytest.skip("검증_sub7 없음") curves = _json(ROUTE / "planned_route_curves.json") @@ -120,6 +120,12 @@ def r() -> dict: "cross_sections": sections, }, } + return job + + +@pytest.fixture(scope="module") +def r() -> dict: + job = build_job() with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "job.json" path.write_text(json.dumps(job), encoding="utf-8") diff --git a/resources/tester/test_356_4_undo_grade.py b/resources/tester/test_356_4_undo_grade.py new file mode 100644 index 000000000..5e1d65f18 --- /dev/null +++ b/resources/tester/test_356_4_undo_grade.py @@ -0,0 +1,88 @@ +"""PLAN 356-4 sub7 — 되돌리기 · 다시하기 = 그 걸음 사진(노선 + 계획고 편집) 그대로. + +· 노선 바뀜 규칙(바뀐 구간 첫 계획선 맞춤 · 계획고 옮김)은 새 조작 때만 — 되살림 때는 안 탐 +· 끌기 → 계획고 ▲(측점 C) → 다시 끌기(새 조작 = ▲ 버림) → 되돌리기 = ▲ 그대로 · 다시하기 = 다시 끌기 값 +· 중심점 좌우 꼴(끌기 + C 높이 보정 한 걸음) → 되돌리기 = 조작 전 계획고 · 편집 · 다시하기 = 보정 값 +· 고침을 끈 판(옛 동작)은 되돌리기에서 ▲ · 보정이 사라짐 — 시험이 흠을 실제로 잡음 +짝: `helper_356_4_undo_grade.cjs`(판 = 349-0q · 실제 TS 를 Node 로 · 화면 부품 · 서버 창구만 가짜). +""" + +from __future__ import annotations + +import json +import subprocess +import tempfile +from pathlib import Path + +import pytest + +import test_349_0q_undo_echo as base + +HERE = Path(__file__).resolve().parent + + +def _run(job: dict, mode: str) -> dict: + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "job.json" + path.write_text(json.dumps(job), encoding="utf-8") + grid = Path(folder) / "grid.bin" + grid.write_bytes(base.dtm_grid_bytes(base.GRID)) + proc = subprocess.run( # noqa: S603 — 고정 실행 파일 + ["node", str(HERE / "helper_356_4_undo_grade.cjs"), str(path), str(grid), mode], + capture_output=True, + text=True, + encoding="utf-8", + timeout=300, + ) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout) + + +@pytest.fixture(scope="module") +def job() -> dict: + return base.build_job() # 349-0q 판 입력(검증_sub7) + + +@pytest.fixture(scope="module") +def r(job) -> dict: + return _run(job, "on") + + +@pytest.fixture(scope="module") +def off(job) -> dict: + return _run(job, "off") + + +def test_새_조작은_바뀐_구간_계획고_편집을_버림(r): + c = f"{r['C']:.3f}" + assert c in json.loads(r["lift"]["offs"]) # ▲ 가 C 에 + assert c not in json.loads(r["drag2"]["offs"]) # 다시 끌기(새 조작) = 버림 + assert r["drag2"]["route"] != r["lift"]["route"] + + +def test_되돌리기_다시하기_그_걸음_사진(r): + assert r["undo1"]["route"] == r["lift"]["route"] + assert r["undo1"]["offs"] == r["lift"]["offs"] # ▲ 그대로 + assert r["undo1"]["z"] == pytest.approx(r["lift"]["z"], abs=1e-4) + assert r["redo1"]["route"] == r["drag2"]["route"] + assert r["redo1"]["offs"] == r["drag2"]["offs"] + assert r["redo1"]["z"] == pytest.approx(r["drag2"]["z"], abs=1e-4) + + +def test_중심점_좌우_보정_되돌리기(r): + pinned = r["pinned"] + assert pinned["z"] == pytest.approx(pinned["zBefore"], abs=1e-3) # 높이 보정 + assert pinned["offs"] != r["redo1"]["offs"] + assert r["undo2"]["route"] == r["redo1"]["route"] + assert r["undo2"]["offs"] == r["redo1"]["offs"] # 조작 전 편집 + assert r["undo2"]["z"] == pytest.approx(pinned["zBefore"], abs=1e-4) # 조작 전 계획고 + assert r["redo2"]["route"] == pinned["route"] + assert r["redo2"]["offs"] == pinned["offs"] # 보정 값 + assert r["home"]["route"] is None and r["home"]["offs"] == r["open"]["offs"] + assert r["blocked"] == 0 + + +def test_옛_동작은_되돌리기에서_편집이_사라짐(off): + c = f"{off['C']:.3f}" + assert c not in json.loads(off["undo1"]["offs"]) # ▲ 사라짐(고친 흠) + assert off["redo2"]["offs"] != off["pinned"]["offs"] # 다시하기에서 보정 사라짐