Files
Aislo/B03_FileInput/B03_FileInput_UI_Upload.ts
T
eomsangdonandClaude Fable 5 2ff37a6e41 feat(B03): 입력 자료 컨테이너 통합·3열 배치 + 업로드 중 화면 잠금
지형 래스터(tif)만 선택 항목이고 나머지는 모두 필수라, 계획노선과 지형 자료를
따로 묶을 이유가 없다.

- 그룹 2개(원청 계획노선/지형 분석자료)를 "입력 자료" 한 그룹으로 통합
- 계획노선 카드에만 걸려 있던 전용 서식(1열 폭·보라 배경·테두리) 제거 —
  다른 카드와 같은 템플릿으로 통일
- 카드 배치 2열 -> 3열 (1280px 이하 2열, 720px 이하 1열)
- 선택 항목(tif)은 확장자 옆에 "선택" 표시
- [파일 업로드]를 누르면 버튼을 잠그고 안에 회전 원을 넣어 진행 중임을 보이며,
  업로드·분석이 끝날 때까지 화면 조작을 막는다(중복 업로드·단계 이동 방지)

파일 분리: 업로드 실행부(청크 업로드/분석 대기/결과 표시/교체 확인 모달)를
B03_FileInput_UI_Upload.ts로 이관해 페이지 파일을 700줄 제한 안으로 되돌림(830 -> 622).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-08 14:14:46 +09:00

195 lines
6.9 KiB
TypeScript

/* =============================================================================
* B03_FileInput_UI_Upload.ts
* 파일 입력 화면의 업로드 실행부 — 청크 업로드, 분석 대기, 결과 표시, 교체 확인 모달.
*
* 화면 조립(B03_FileInput_UI_Page.ts)에서 떼어낸 부분이다. 슬롯 상태를 그대로 받아
* 갱신하고, 화면 갱신은 호출측이 넘긴 콜백으로만 한다 — 이 파일은 DOM 구조를 모른다.
* ========================================================================== */
import { PROGRESS_UPDATE_INTERVAL_MS, UPLOAD_CHUNK_SIZE_MB } from "@config/config_frontend";
import { createButton } from "@ui/ui_template_elements";
import { currentLanguageIndex, ui_locales } from "@ui/ui_template_locale";
import {
checkWF1AnalysisStatus,
createUploadSession,
finalizeUploadSession,
uploadFileChunk,
type UploadedFileResult,
} from "./B03_FileInput_Api_Fetch";
import { saveB03UploadedFile, updateB03AnalysisState } from "./B03_FileInput_State";
import {
makeSessionKey,
type FileSlotState,
type StoredUploadSession,
} from "./B03_FileInput_UI_Support";
function L(key: keyof typeof ui_locales): string {
return ui_locales[key][currentLanguageIndex];
}
/**
* 완료된 슬롯 재업로드 확인 모달 — 기존 파일·분석 결과가 교체된다는 경고에 사용자의
* 명시적 확인을 받는다(2026-08-04 사용자 지시). 확인 시에만 resolve(true).
*/
export function confirmReplaceUpload(slotLabel: string, fileName: string): Promise<boolean> {
return new Promise((resolve) => {
const backdrop = document.createElement("div");
backdrop.className = "b03-file__modal-backdrop";
const modal = document.createElement("div");
modal.className = "b03-file__modal";
modal.setAttribute("role", "alertdialog");
modal.setAttribute("aria-modal", "true");
const title = document.createElement("strong");
title.textContent = L("B03_File_Replace_Title");
const message = document.createElement("p");
message.textContent = `${slotLabel}: ${fileName}\n${L("B03_File_Replace_Message")}`;
const actions = document.createElement("div");
actions.className = "b03-file__modal-actions";
const done = (accepted: boolean): void => {
backdrop.remove();
resolve(accepted);
};
const cancel = createButton({
label: L("B03_File_Replace_Cancel"),
variant: "ghost",
onClick: () => done(false),
});
const accept = createButton({
label: L("B03_File_Replace_Confirm"),
variant: "filled",
onClick: () => done(true),
});
actions.append(cancel, accept);
modal.append(title, message, actions);
backdrop.append(modal);
backdrop.addEventListener("click", (event) => {
if (event.target === backdrop) done(false);
});
document.body.append(backdrop);
accept.focus();
});
}
/** 업로드 결과 목록(파일명 + 저장 경로)을 다시 그린다. */
export function renderUploadResults(
list: HTMLElement,
results: readonly UploadedFileResult[],
): void {
list.replaceChildren();
for (const result of results) {
const item = document.createElement("li");
const filename = document.createElement("strong");
filename.textContent = result.original_filename;
const path = document.createElement("span");
path.textContent = `${L("B03_File_Result_Path")}: ${result.relative_path}`;
item.append(filename, path);
list.append(item);
}
}
/**
* 파일 1건을 청크로 올린다. 중단된 세션이 있으면 그 지점부터 이어 올린다.
* 진행 상황은 `onProgress`로만 알린다 — 갱신 주기는 config 값으로 제한한다.
*/
export async function uploadOneFile(
projectId: string,
state: FileSlotState,
completeUpload: boolean,
onProgress: () => void,
): Promise<UploadedFileResult[]> {
const file = state.file;
if (!file) return [];
state.error = undefined;
state.uploadStatus = "uploading";
onProgress();
const chunkSizeBytes = UPLOAD_CHUNK_SIZE_MB * 1024 * 1024;
const session =
state.uploadSessionId ??
(await createUploadSession(projectId, file, chunkSizeBytes)).upload_session_id;
state.uploadSessionId = session;
const totalChunks = Math.max(1, Math.ceil(file.size / chunkSizeBytes));
const storageKey = makeSessionKey(projectId, file);
const startedAt = performance.now();
let lastPaintAt = 0;
for (
let chunkIndex = Math.floor(state.progressBytes / chunkSizeBytes);
chunkIndex < totalChunks;
chunkIndex += 1
) {
const start = chunkIndex * chunkSizeBytes;
const end = Math.min(file.size, start + chunkSizeBytes);
const chunkStartedAt = performance.now();
await uploadFileChunk(projectId, session, chunkIndex, file.slice(start, end));
const elapsedSec = Math.max(0.001, (performance.now() - chunkStartedAt) / 1000);
state.progressBytes = end;
state.speedMbs = (end - start) / 1024 / 1024 / elapsedSec;
state.etaSeconds = state.speedMbs > 0 ? (file.size - end) / 1024 / 1024 / state.speedMbs : null;
const stored: StoredUploadSession = {
key: storageKey,
projectId,
slot: state.slot,
fileName: file.name,
fileSize: file.size,
uploadSessionId: session,
chunkSizeBytes,
totalChunks,
completedChunks: chunkIndex + 1,
updatedAt: Date.now(),
};
localStorage.setItem(storageKey, JSON.stringify(stored));
const now = performance.now();
if (now - lastPaintAt > PROGRESS_UPDATE_INTERVAL_MS || chunkIndex === totalChunks - 1) {
lastPaintAt = now;
onProgress();
}
}
const response = await finalizeUploadSession(projectId, session, totalChunks, completeUpload);
localStorage.removeItem(storageKey);
saveB03UploadedFile(projectId, {
slot: state.slot,
fileName: file.name,
fileSize: file.size,
});
state.progressBytes = file.size;
state.speedMbs =
file.size / 1024 / 1024 / Math.max(0.001, (performance.now() - startedAt) / 1000);
state.etaSeconds = 0;
state.uploadStatus = "completed";
onProgress();
return response.files;
}
/**
* 지표면 분석(WF1)이 끝날 때까지 5초 간격으로 확인한다.
* 자동 확정이 보류되면 `onHold`로 사유를 넘기고 대기를 끝낸다.
*/
export async function pollWF1Analysis(
projectId: string,
onHold: (message: string) => void,
maxAttempts = 360,
): Promise<boolean> {
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
try {
const status = await checkWF1AnalysisStatus(projectId);
updateB03AnalysisState(projectId, status.status, status.progress_percent);
if (status.status === "completed") return true;
if (
status.current_stage === "awaiting_confirmation" &&
status.message.includes("자동 확정 보류")
) {
onHold(status.message);
return false;
}
} catch {
/* 일시적인 조회 실패는 다음 주기에 다시 확인한다. */
}
await new Promise((resolve) => setTimeout(resolve, 5000));
}
return false;
}