Merge remote-tracking branch 'origin/sub_laptop_7' into main_laptop_1

This commit is contained in:
2026-10-16 17:20:49 +09:00
10 changed files with 702 additions and 34 deletions
+31 -15
View File
@@ -16,8 +16,8 @@
* 출력 — 가게 stations · profile · footprint · generation · 노선 초안이 있으면 종단도가 새 첫 계획선 ·
* 옮긴 계획고 · 새 노선 상세(`pipelineDetail` — 지반 · 측점 · 횡단 면적 → 유토곡선)를 그림.
* 첫 계산 = 열 때 한 번(저장 노선 · 발자국 · 저장 안 한 노선 초안이 있으면 그 노선).
* 노선 초안을 버리면(되돌리기 · [저장 전으로]) 열 때처럼 — 측점 · 종단을 안 내고 초안 시작 때 뜬 상세 사본 ·
* 횡단 초안 칸 그대로(349-0k · 349-0o).
* 노선 초안을 버리면(되돌리기 · [저장 전으로]) 열 때처럼 — 측점 · 종단을 안 내고 초안 전 상세 · 횡단 초안 칸
* 그대로(349-0k · 349-0o) · 그 뒤 같은 측점 목록은 가게에 다시 안 냄(상세 측점이 묶음과 달라도 · 349-0q).
* [저장](sub5)이 서버 정본 — 노선을 먼저 보내고 `pendingAlignment(DRAFT_ROUTE_ID)` 를 새 노선에 보냄.
* ========================================================================== */
@@ -27,6 +27,7 @@ import { createStationsStage } from "./logic/design_pipeline_stations";
import type {
FollowPatch,
PipelineInputs,
PipelineOutputs,
PipelineRunRecord,
PipelineStation,
RouteDraft,
@@ -243,10 +244,10 @@ function createPagePipeline(
let openGeneration = -1;
/** 측점 · 종단을 가게에 안 내는 차례 — 열 때 · 노선 초안을 버린 차례(상세 = 초안 전 상세로 되돌림). */
let quietGeneration = -1;
/** 노선 초안 전 상세 사본(종단도가 그리던 것 · 초안 동안 제자리 고침이 안 닿음) · 되돌리는 함수 — 초안을
* 버리면 이것으로(다시 셈 없음 · 349-0k · 349-0o). */
/** 노선 초안 전 상세(종단도가 그리던 객체 그대로 — 횡단 초안 측점 장부가 이 객체에 묶임 · 갈아끼움은 설계를
* 사본으로 써 안 고침) · 되돌리는 함수 — 초안을 버리면 이것으로(다시 셈 없음 · 349-0k · 349-0o · 349-0q). */
let held: {
copy: SectionDetailResponse | null;
detail: SectionDetailResponse | null;
restore: ((stations: PipelineStation[]) => Promise<string>) | null;
} | null = null;
/** 초안을 버린 차례가 끝나 되돌림까지 마치는 약속(종단도는 그 뒤 저장 기준으로 — 349-0l). */
@@ -333,12 +334,28 @@ function createPagePipeline(
},
});
const publish = publishToStore(store);
/** 상세가 맞춘 측점 목록(열쇠 · 자리) — 열 때 · 되돌린 차례 측점 · 마지막으로 낸 측점. 같은 목록이면 가게에
* 다시 안 냄(되돌린 상세 측점이 묶음 측점과 달라도 · 관 · 구조물 메아리가 상세를 갈아끼우지 않게 · 349-0q). */
let stationsShown: string | null = null;
pipe.subscribe((event) => {
const saved = event.kind === "stage" && (event.stage === "ground" || event.stage === "profile");
if (!(saved && event.generation === quietGeneration)) publish(event);
const quiet = saved && event.generation === quietGeneration;
if (event.kind === "stage" && event.stage === "ground") {
const list = JSON.stringify(
(event.value as PipelineOutputs["ground"] | null)?.stations.map((station) => [
station.key,
station.chainageM,
station.x,
station.y,
]) ?? null,
);
if (!quiet && list === stationsShown) return;
stationsShown = list;
}
if (!quiet) publish(event);
});
/** 노선 초안을 버린 차례 끝 — 초안 전 상세 사본으로 되돌림(열 때와 같은 상태 · 측점이 달라도 · 다른 자리는
* 기록에) · 그 사본이 저장 정본(다시 하기도 같은 기준). 차례 끝에서 판정 — ground 를 건너뛰어도 · 사진첩
/** 노선 초안을 버린 차례 끝 — 초안 전 상세로 되돌림(열 때와 같은 상태 · 측점이 달라도 · 다른 자리는
* 기록에) · 그 상세가 저장 정본(다시 하기도 같은 기준). 차례 끝에서 판정 — ground 를 건너뛰어도 · 사진첩
* 되돌리기가 가게 초안을 먼저 비워도(349-0m). */
const finishDrop = async (record: PipelineRunRecord): Promise<string> => {
const routeId = canon?.routeId;
@@ -353,10 +370,10 @@ function createPagePipeline(
: null;
if (restore) {
held = null;
const copy = hold?.copy;
if (copy) {
canon = { routeId, samples: copy.longitudinal.samples, detail: copy };
const diff = stationDiff(copy, stations);
const detail = hold?.detail;
if (detail) {
canon = { routeId, samples: detail.longitudinal.samples, detail };
const diff = stationDiff(detail, stations);
if (diff) record.restoreDiff = diff;
}
why = await restore(stations).catch(() => "error");
@@ -365,12 +382,11 @@ function createPagePipeline(
Object.assign(record, { restored: why.startsWith("saved"), restoreWhy: why });
return why;
};
/** 노선 초안 시작 — 지금 저장 상세 사본(초안 동안 다시 셈 · 면적 얹기가 안 닿음) · 되돌리는 함수를 맡김. */
/** 노선 초안 시작 — 지금 저장 상세 · 되돌리는 함수를 맡김(횡단 초안 칸 · 측점 열쇠는 맡은 쪽이 떠 둠). */
const holdNow = (): typeof held => {
const { detail = null, routeId } = savedSource();
if (typeof routeId !== "number") return null;
const copy = detail && structuredClone(detail);
return { copy, restore: options.holdDraft?.(routeId, copy) ?? null };
return { detail, restore: options.holdDraft?.(routeId, detail) ?? null };
};
// 사용자 노선 조작 뒤 follow 가 다시 매긴 관 · 구조물 = 가게(목록 · 알약 · 횡단 보기가 바로 새 측점) ·
// 초안을 버리면 초안 전 값 · 열 때(start 차례)는 안 씀 — 알림 밖(틱 뒤)에서 씀(쓰기 고리 막음과 안 부딪힘)
+7 -7
View File
@@ -312,9 +312,12 @@ export function createDesignProfile(ctx: DesignProfileContext) {
// 판이 없는 보기는 관 자리를 되돌리기에 태우지 않는다.
drainage: drainagePanel ?? { pipeChainages: () => [], setPipeChainages: () => undefined },
restore: () => {
// 세션이 정본이므로 편집 초안을 다시 읽어 그린다.
store = createProfileEditStore(routeId, savedEdits, () => rebuild());
rebuild();
// 세션이 정본 — 편집 초안을 다시 읽음 · 노선 초안 동안은 노선 0 칸 · 계획고가 그대로면 다시 셈 예약 없음(349-0q)
const [was, draft] = [JSON.stringify(store.edits()), store === preview];
const id = draft ? pagePipeline.DRAFT_ROUTE_ID : routeId;
store = createProfileEditStore(id, draft ? store.edits() : savedEdits, () => rebuild());
if (draft) preview = store;
void (JSON.stringify(store.edits()) !== was ? rebuild() : draw());
},
restoreSaved: () => store.restoreSaved(),
canRestoreSaved: () => store.canRestoreSaved(),
@@ -344,10 +347,7 @@ export function createDesignProfile(ctx: DesignProfileContext) {
/** 계획선 측점 줄 = 측점 한 벌 — 셈은 `design_profile_base` 몫(계산 묶음 planline 도 같은 기준). */
const listed = (): AlignmentBase | null => listedBase(storedBase, detail, irregularStations);
/**
* 편집 후 다시 그린다. 길게 누르기(초당 10회)로 연속 호출되므로 한 프레임에 한 번만
* 실제 렌더링하도록 모은다.
*/
/** 편집 후 다시 그린다 — 길게 누르기(초당 10회)도 한 프레임에 한 번만 그림. */
function rebuild(): void {
if (base) alignment = buildAlignment(base, store.edits());
pagePipeline.pipelineGrade(projectId, store.edits());
+1 -1
View File
@@ -535,7 +535,7 @@ export async function mountProfileView(
onFacilitiesFollowed: followFacilities,
structureAreas: ({ cross_sections: rows }) =>
applyStructureAreaRows(rows, structureAreaRows(rows)),
// 초안 시작 — 초안 전 상태를 떠 둠 · 버리면 그대로(측점이 달라도 · 349-0o) · 사본이 없으면(초안 둔 채
// 초안 시작 — 초안 전 상태를 떠 둠 · 버리면 그대로(측점이 달라도 · 349-0o) · 상세가 없으면(초안 둔 채
// 새로고침) 묶음 측점으로 갈아끼움
holdDraft: (routeId, saved) => {
const hold = saved && holdSectionDetail(activeProjectId, routeId, saved);
+4 -4
View File
@@ -216,11 +216,11 @@ export async function refreshStaleDesigns(
* 계획선 ▲ 한 번에 값이 바뀌는 측점은 몇 개뿐 — 전부 돌려주면 카드를 다 갈아 끼워 멈춤(54-22).
*/
export async function refreshCrossDesigns(input: CrossRefreshInput): Promise<number[]> {
// 노선 초안 동안 묶음 새 노선 상세(`preview` 측점) = 묶음 cross 결과 그대로 — 브라우저 다시 셈이 다른 값을
// 안 냄(넓힌 표본 · 화면 선이 다름 · 349-0o)
if (input.detail.cross_sections.some((section) => section.preview)) return [];
useStationKeys(input.projectId, input.routeId, input.detail); // 세션 고침을 이 측점 목록으로 읽음(344-3)
// 노선 초안 동안 묶음 새 노선 상세(측점 모두 `preview`) = 묶음 cross 결과 그대로 — 브라우저 다시 셈이 다른
// 값을 안 냄(넓힌 표본 · 화면 선이 다름 · 349-0o). 관 · 구조물 초안이 미리 뜬 측점 몇 개(`preview`)는 다시 셈
const sections = input.detail.cross_sections;
if (sections.length && sections.every((section) => section.preview)) return [];
useStationKeys(input.projectId, input.routeId, input.detail); // 세션 고침을 이 측점 목록으로 읽음(344-3)
const before = new Map(sections.map((section) => [section, JSON.stringify(section.design)]));
const updated = refreshLocally(input) ?? (await refreshFromServer(input));
// 구조물이 선 측점은 폐회로 면적이 정본이다 — 설계를 갈아 끼운 **이 자리에서 한 번** 다시
+3 -3
View File
@@ -166,14 +166,14 @@ export async function swapSectionStations(
return { detail: swap.detail, moves: swap.moves };
}
/** 노선 초안 전 상태(349-0o) — 상세(사본 · 되돌리면 그대로 캐시) · 측점 열쇠 · 측점 열쇠 칸 다섯(횡단 초안). */
/** 노선 초안 전 상태(349-0o) — 상세(초안 전 객체 그대로 · 되돌리면 캐시) · 측점 열쇠 · 측점 열쇠 칸 다섯(횡단 초안). */
export interface SectionHold {
detail: SectionDetailResponse;
keys: Keyed[];
cells: Array<[KeyedState, unknown]>;
}
/** 노선 초안 시작 — 초안 전 상세(`detail` = 부르는 쪽이 뜬 사본) · 지금 측점 열쇠 · 횡단 초안 칸을 떠 둠. */
/** 노선 초안 시작 — 초안 전 상세(`detail` · 객체 그대로 — 갈아끼움은 설계를 사본으로 씀) · 지금 측점 열쇠 · 횡단 초안 칸을 떠 둠. */
export function holdSectionDetail(
projectId: string,
routeId: number,
@@ -190,7 +190,7 @@ export function holdSectionDetail(
/**
* 노선 초안을 버림(PLAN 349-0k · 349-0o) — 갈아끼운 상세를 초안 전 상태(`hold`)로 되돌림 · 다시 셈 없음.
* 상세 = 초안 시작 때 뜬 사본 · 측점 열쇠 · 횡단 초안 칸 = 그때 값(초안 동안 넘김이 버린 고침도) · 누가거리
* 상세 = 초안 전 객체 · 측점 열쇠 · 횡단 초안 칸 = 그때 값(초안 동안 넘김이 버린 고침도) · 누가거리
* 열쇠 조작값 맵은 열쇠로 옮김. 묶음 측점(`stations`)이 달라도 초안 전 상세 — `same` = 측점 목록이 같음(1 mm).
* 캐시가 없으면 null.
*/
@@ -254,8 +254,7 @@ async function run() {
runs: sliceRuns(mark),
restores,
swaps: swaps.length - swapMark,
// 되돌린 상세 = 초안 시작 때 뜬 사본(349-0o) — 열 때 객체가 아님 · 종단도가 쥔 것 = 가게 것
sameObject: back === detail && back !== opened,
sameObject: back === opened && detail === opened,
stations: back.cross_sections.map((s) => s.chainage_m),
final: finalOf(back),
cross: crossOf(back),
@@ -0,0 +1,480 @@
/* PLAN 349-0q sub7 헬퍼 — 소수 자리 구조물 측점 · 저장 상세에 없는 세월교 측점(묶음 측점 ≠ 상세 측점) 노선에서
* 열기 → 끌기 → 되돌리기 → 목록 다시 맞춤(가게 구조물 · 관 메아리 — 같은 목록 다른 꼴) = 열기 값(B05 그대로 ·
* B06 안 다녀와도). 되돌리기 · 다시 하기 = 진짜 페이지 사진첩(종단도 편집 가게 다시 읽음 → 다리 알림). 되돌린 상세 = 열 때 객체 그대로 · 같은 측점 목록은 가게에 다시 안 냄(갈아끼움 없음).
* 나머지 = `helper_349_0o_redo_same.cjs` 그대로(진짜 종단도 · 묶음 · 상세 가게 · Design_Sync 판정).
* 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0q_undo_echo.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 };
// 구조물 초안 얹기(측점 계획 · 형상) — 이 시험 밖 · 아무 일 없음
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 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-349q";
const R = 7;
window.localStorage.setItem("frd_current_project_id", P);
opened = await sectionStore.loadSectionDetail(P, R);
settleDesigns(opened);
stationKeys.useStationKeys(P, R, opened); // 상세가 측점을 얹은 뒤(Section_Drafts 몫 · 여기선 가짜)
// 횡단 초안 칸 — 열기 전에 고친 카드 선택(단면 유형은 노선이 바뀌면 안 넘김 · 349-0o)
for (const [chainage, value] of Object.entries(job.touched))
designSession.writeCrossDesignChoice(P, R, Number(chainage), value);
const profile = profileMod.createDesignProfile({
projectId: P,
view: "profile",
onSelectStation: () => undefined,
});
const live = () => sectionStore.loadSectionDetail(P, R);
pageMod.routeDraftBridge(P, profile, {
stationIntervalM: job.interval,
structureAreas: ({ cross_sections: rows }) =>
layouts.applyStructureAreaRows(rows, layouts.structureAreaRows(rows)),
// `design_view_profile` 의 holdDraft 그대로
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";
};
},
});
// 종단 보기 `renderSections` · followSwap 그대로 — 새 상세 → render · 비정규 측점 · 가게 stations → 갈아끼움
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);
});
// 횡단 보기 다시 셈 — 진짜 `B06_Section_UI_Page_Design_Sync`(낡음 · 계획고 초안이면 다시 셈) · 카드 = 그 상세
const cards = () => pageMod.pipelineDetail(P) ?? cached;
let cached = opened;
const sync = designSync.createDesignSync({
projectId: P,
routeId: () => R,
detail: () => cards(),
view: () => ({ refreshCards: () => undefined }),
});
show(opened);
profile.setEarthworkContext({ conversion: job.conversion });
await quiet();
const measure = async (mark, refreshMark) => {
const detail = await live();
const drawn = pageMod.pipelineDetail(P) ?? detail; // 종단도가 그리는 상세(초안 동안 묶음 새 상세)
return {
runs: sliceRuns(mark),
refresh: refreshCalls - refreshMark,
lastKey: draws[draws.length - 1]?.key ?? null,
drawnSaved: draws[draws.length - 1]?.saved ?? null,
drawnLive: draws[draws.length - 1]?.ref === detail,
stations: detail.cross_sections.map((s) => s.chainage_m),
final: finalOf(drawn),
cross: crossOf(drawn),
edits: JSON.stringify(profile.pipelineSource().edits),
cells: JSON.stringify(
["crossdesign", "rockb"].map((name) => pageState.readState(name, P, R) ?? null),
),
};
};
const open = await measure(0, 0);
// 페이지 사진첩(진짜 `B05_Profile_UI_Profile_History` · 종단도 패널이 세움) — 되돌리기 · 다시 하기 = 세션 되씀 →
// 종단도 편집 가게 다시 읽음(ctx.restore) → 노선 편집기가 다리에 알림(두 번 · 349-0m)
const album = () => historyMod.pageHistory();
const drag = async (redo = false) => {
const mark = runs().length;
const refreshMark = refreshCalls;
const bridge = pageMod.routeDraftBridge(P, profile);
const redone = redo ? album().redo() : null;
if (!redo) (winListeners.keydown ?? []).forEach((fn) => fn({})); // 손길 — 사진첩 「열 때」 지남
bridge.edited(draftOf(shift(1, 6, -4)));
bridge.edited(draftOf(shift(1, 6, -4)));
await quiet();
if (!redo) album().record(); // 놓은 뒤 한 걸음
// 초안 동안 횡단 카드가 갈아끼운 상세를 다시 셈(흉내 · 저장 상세 사본엔 안 닿아야)
doubled(await live());
// 횡단 보기 다시 셈 창구(진짜 `refreshCrossDesigns`)가 묶음 새 노선 상세를 부르면 — 안 고침(묶음 결과 그대로)
const shown = pageMod.pipelineDetail(P);
const before = crossOf(shown);
const updated = await realRefresh.refreshCrossDesigns({
projectId: P,
routeId: R,
detail: shown,
edits: { station_offsets: {}, curve_radii: {} },
});
return {
...(await measure(mark, refreshMark)),
draftRefresh: { updated, same: crossOf(shown) === before },
redone,
};
};
const undo = async () => {
const mark = runs().length;
const refreshMark = refreshCalls;
const bridge = pageMod.routeDraftBridge(P, profile);
const undone = album().undo();
bridge.edited(null);
bridge.edited(null);
await quiet();
return { ...(await measure(mark, refreshMark)), undone };
};
const first = await drag();
const back1 = await undo();
const back1Same = (await live()) === opened;
// 되돌린 뒤 목록 · 알약 다시 맞춤이 가게 관 · 구조물을 다시 씀(같은 목록 · 꼴만 다름) — 묶음이 한 차례 돎
const echoMark = runs().length;
const echoRefresh = refreshCalls;
const designStore = storeMod.useDesignStore(P, null);
designStore.set(
"structures",
job.structures.map((s) => ({ ...s, memo: "" })),
);
designStore.set(
"pipes",
job.pipes.map((p) => ({ ...p, memo: "" })),
);
await quiet();
const echo = { ...(await measure(echoMark, echoRefresh)), sameObject: (await live()) === opened };
const redo = await drag(true);
const back2 = await undo();
// 횡단 보기(B06) — 카드 상세 다시 받음 · 진입 다시 셈 판정 · 종단도는 횡단 보기 자리
let mark = runs().length;
let refreshMark = refreshCalls;
cached = await live();
profile.setView("cross");
show(cards());
profile.setEarthworkContext({ conversion: job.conversion });
await sync.reconcileStaleDesigns();
await quiet();
const cross = await measure(mark, refreshMark);
// 종단 보기(B05)로
mark = runs().length;
refreshMark = refreshCalls;
profile.setView("profile");
profile.setActive(true);
await quiet();
const back = await measure(mark, refreshMark);
const blocked = pageMod.pagePipeline(P).blockedWrites;
const restoreDiffs = runs()
.filter((r) => r.restoreDiff)
.map((r) => r.restoreDiff);
stopListen();
stopStore();
pageMod.disposePagePipeline(P);
return { open, first, back1, echo, redo, back2, cross, back, blocked, restoreDiffs, back1Same };
}
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);
});
+1 -1
View File
@@ -120,7 +120,7 @@ def test_되돌리기_열기_값(r):
u, o = r["undo"], r["open"]
assert [x["sources"] for x in u["runs"]] == [["route"]], u["runs"]
assert u["restores"] == [{"saved": True, "back": {"same": True}}]
assert u["sameObject"] # 가게 = 종단도 · 열 때 객체의 사본(349-0o)
assert u["sameObject"]
assert u["stations"] == o["stations"]
assert u["cross"] == o["cross"]
assert u["final"] == o["final"]
+1 -1
View File
@@ -135,7 +135,7 @@ def test_되돌리기_열기_값_다시_셈_0(r):
], u["runs"]
assert u["refresh"] == 0
assert u["lastKey"] == "" and u["drawnSaved"] and u["drawnLive"]
assert not u["sameObject"] # 초안 시작 때 뜬 사본(349-0o)
assert u["sameObject"] # 열 때 객체 그대로(횡단 초안 측점 장부가 이 객체에 묶임 · 349-0q)
assert u["stations"] == o["stations"]
assert u["cross"] == o["cross"]
assert u["final"] == o["final"]
+173
View File
@@ -0,0 +1,173 @@
"""PLAN 349-0q sub7 — 되돌린 뒤 B05 누가토량이 열기 값(B06 안 다녀와도).
· 소수 자리 구조물 측점 · 저장 상세에 없는 세월교 측점 — 묶음 저장 노선 측점 ≠ 상세 측점(saved-diff)
· 열기 → 끌기 → 되돌리기 → 목록 다시 맞춤(가게 구조물 · 관을 같은 목록 다른 꼴로 다시 씀) = 열기 값 ·
상세 = 열 때 객체 그대로 · 갈아끼움 없음 · 다시 셈 0
· 되돌리기 · 다시 하기 = 진짜 페이지 사진첩(세션 되씀 → 종단도 편집 가게 다시 읽음 → 다리 알림)
· 다시 하기 · 되돌리기 · 횡단 보기 · 종단 보기도 = 349-0o 값
짝: `helper_349_0q_undo_echo.cjs`(실제 TS 를 Node 로 · 화면 부품 · 서버 창구만 가짜).
"""
from __future__ import annotations
import csv
import json
import subprocess
import sys
import tempfile
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from B05_Profile.B05_Profile_Structures_Schema import structure_type_map # noqa: E402
from common_util.common_util_surface_sampler import dtm_grid_bytes # noqa: E402
from config.config_system_design import STANDARD_CROSS_SECTION # noqa: E402
pytestmark = pytest.mark.skipif(
not (ROOT / "config" / "node_modules" / "typescript").is_dir(),
reason="프론트엔드 의존성 미설치",
)
PROJECT = ROOT / "storage/1/3/6d3b2812-6d5a-4168-a932-40e4ae303d5a" # 검증_sub7
ROUTE = PROJECT / "B05_Profile/route"
SECTION = PROJECT / "B06_Section"
GRID = PROJECT / "B04_PreProcess/models/dtm_classification_smooth.npz"
ONES = {g: {"loose": 1.0, "compacted": 1.0} for g in ("soil", "ripping_rock", "blasting_rock")}
def _csv(path: Path) -> list[list[float]]:
with path.open(encoding="utf-8") as handle:
return [[float(r["x"]), float(r["y"])] for r in csv.DictReader(handle)]
def _json(path: Path):
return json.loads(path.read_text(encoding="utf-8"))
def _between(sections: list[dict], index: int) -> dict:
"""두 측점 사이 한 점(0.37) — 누가거리 · 좌표."""
a, b = sections[index], sections[index + 1]
k = 0.37
return {
"chainage_m": round(a["chainage_m"] + k * (b["chainage_m"] - a["chainage_m"]), 2),
"x": a["center_x"] + k * (b["center_x"] - a["center_x"]),
"y": a["center_y"] + k * (b["center_y"] - a["center_y"]),
}
@pytest.fixture(scope="module")
def r() -> dict:
if not (GRID.is_file() and (SECTION / "longitudinal/longitudinal.json").is_file()):
pytest.skip("검증_sub7 없음")
curves = _json(ROUTE / "planned_route_curves.json")
sections = sorted(
(_json(p) for p in (SECTION / "cross_sections").glob("cross_*.json")),
key=lambda s: s["chainage_m"],
)
pipes = _json(PROJECT / "B04_PreProcess/drainage/edits/pipe_points.json")["points"]
# 세월교 하나 더(측점 사이) — 저장 상세엔 그 측점이 없음 = 묶음 저장 노선 측점과 다름(검증_sub7 세월교 2 + 1)
pipes = [*pipes, {"source": "manual", "facility": "ford_bridge", **_between(sections, -6)}]
# 저장 횡단 면적 = 서버가 상세를 낼 때 셈(파일엔 없음) — 정본 대신 정한 값
for i, section in enumerate(sections):
section["design"] = {
"ground_type": "soil",
"design_elevation_m": section["center_z"],
"cut_area_m2": 4.0 + (i % 5),
"fill_area_m2": 1.5 + (i % 3),
}
job = {
"line": _csv(ROUTE / "planned_route.csv"),
"nodes": _csv(ROUTE / "planned_route_nodes.csv"),
"curves": [
{k: c[k] for k in ("start", "apex", "end", "radius_m")} for c in curves["curves"]
],
"stationSnap": bool(curves.get("station_snap")),
"minRadius": curves["min_radius_m"],
"interval": 20.0,
"types": [
{"type_id": t.type_id, "group": t.group, "placement": t.placement}
for t in structure_type_map().values()
],
"pipes": pipes,
"standard": STANDARD_CROSS_SECTION,
"conversion": ONES,
# 구조물 하나 — 첫 관 자리 횡단배수(같은 측점을 덮음)
"structures": [
{
"structure_id": "s-349o",
"type_id": "cross_drain_exposed",
"chainage_m": pipes[0]["chainage_m"],
"x": pipes[0]["x"],
"y": pipes[0]["y"],
},
# 소수 자리 측점 구조물(측점 사이 · 저장 상세엔 없음)
{"structure_id": "s-349q", "type_id": "cross_drain_exposed", **_between(sections, 8)},
],
# 열기 전에 고친 카드 선택 — 끌면 밀리는 측점(뒤쪽) · 단면 유형은 노선이 바뀌면 안 넘기는 칸
"touched": {
str(sections[-3]["chainage_m"]): {
"ground_type": "blasting_rock",
"section_mode": "right_cut",
}
},
"detail": {
"longitudinal": _json(SECTION / "longitudinal/longitudinal.json"),
"cross_sections": sections,
},
}
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(dtm_grid_bytes(GRID))
proc = subprocess.run( # noqa: S603 — 고정 실행 파일
["node", str(HERE / "helper_349_0q_undo_echo.cjs"), str(path), str(grid)],
capture_output=True,
text=True,
encoding="utf-8",
timeout=300,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def _same(a: dict, b: dict) -> None:
assert a["final"] == b["final"]
assert a["cross"] == b["cross"]
assert a["stations"] == b["stations"]
def test_되돌리기_열기_객체_그대로(r):
o, u = r["open"], r["back1"]
assert u["undone"] # 진짜 사진첩 되돌리기(종단도 편집 가게 다시 읽음)
assert [(x["restored"], x["why"]) for x in u["runs"]] == [(True, "saved-diff")], u["runs"]
assert r["back1Same"] # 열 때 상세 객체(횡단 초안 측점 장부가 묶인 것)
assert u["refresh"] == 0 and u["lastKey"] == ""
_same(u, o)
d = r["restoreDiffs"][0]
assert d["pipeline"] > d["saved"] and isinstance(d["pipelineM"], float)
def test_메아리_차례_갈아끼움_없음_열기_값(r):
o, e = r["open"], r["echo"]
assert [x["outcome"] for x in e["runs"]], e["runs"] # 묶음이 실제로 돎
assert all(x["outcome"] == "done" for x in e["runs"]), e["runs"]
assert e["sameObject"] # 같은 측점 목록 — 가게에 다시 안 냄 · 상세 그대로
assert e["refresh"] == 0 and e["lastKey"] == "" and e["drawnSaved"]
_same(e, o)
assert e["cells"] == o["cells"]
def test_다시_하기_되돌리기_횡단_보기(r):
o, f = r["open"], r["first"]
assert r["redo"]["redone"] and r["back2"]["undone"]
assert r["redo"]["final"] == f["final"] and r["redo"]["cross"] == f["cross"]
for step in (r["back2"], r["cross"], r["back"]):
assert step["refresh"] == 0
_same(step, o)
assert r["blocked"] == 0