refactor: 템플릿에서 기본적으로 제공하고 있는 워크 플로우에 디자인과 라우팅 흡수
This commit is contained in:
@@ -0,0 +1,654 @@
|
||||
# TechLog Frontend — template capability 활용 및 리팩터링 리뷰
|
||||
|
||||
- 날짜: 2026-09-21
|
||||
- 대상: `/shared/codebase/tech-log-frontend`
|
||||
- 범위: TechLog public / Studio presentation, route 구성, server-state 사용, management/asset gateway 경계, 하드코딩·중복 조회·수동 네트워크 상태 관리
|
||||
- 기준: clean-architecture-frontend-template이 제공하는 route contract, server-state query/mutation runtime, failure/idempotency/cancellation 경계를 TechLog 도메인이 우회하지 않는가
|
||||
|
||||
## 결론
|
||||
|
||||
이번 검토에서 확인된 핵심 문제는 단순한 컴포넌트 중복보다 **TechLog presentation이 템플릿이 이미 제공하는 runtime 경계를 여러 군데에서 직접 다시 구현하고 있었다는 점**이었다.
|
||||
|
||||
현재 worktree 기준으로 다음 항목은 정리되었다.
|
||||
|
||||
1. Studio presentation의 직접 `StudioGateway` 호출: **0건**
|
||||
2. Studio presentation의 직접 `ManagementGateway` 호출: **0건**
|
||||
3. Studio presentation의 직접 `StudioAssetGateway` 호출: **0건**
|
||||
4. Studio presentation의 수동 `AbortController` 네트워크 lifecycle: **0건**
|
||||
5. public presentation의 `searchPublicContent("")` 기반 전체 catalog 우회: **0건**
|
||||
6. Public/Studio route 문자열 직접 조립 방지: **route contract 기반 builder + 정적 검사로 전환**
|
||||
7. app/test TypeScript, ESLint, architecture, TechLog contract sync, `git diff --check`: **PASS**
|
||||
|
||||
따라서 **template capability를 사용하지 않고 TechLog가 자체 구현으로 우회하던 주요 경계는 현재 정리된 상태**다.
|
||||
|
||||
저장소 기본 Coka 런타임은 Node `v22.23.2`지만, 시스템 Node를 변경하지 않고 `pnpm dlx node@24.11.0`으로 저장소가 요구하는 Node `24.11.0`을 일회성 실행했다. 이 환경에서 TechLog Vitest 전체 **60 files / 416 tests가 모두 통과**했고, template 공통 계층의 component regression도 **27 files / 154 tests가 모두 통과**했다.
|
||||
|
||||
따라서 TechLog의 route/server-state/network lifecycle/template primitive 활용과 Taxonomy N+1 제거는 런타임 테스트까지 검증됐다. 별도로 남는 것은 backend 공통 SpotBugs analysis classpath 문제와, 기준 소스 앱이 없어 새 증거를 만들 수 없는 browser source-parity뿐이다.
|
||||
|
||||
---
|
||||
|
||||
## 1. Public read model — 검색 API를 projection 대용으로 사용하던 문제
|
||||
|
||||
### 기존 문제
|
||||
|
||||
Home/Profile/Projects/Releases 계열에서 필요한 데이터가 “검색 결과”가 아님에도 public search 경로를 전체 catalog 조회처럼 사용하는 흔적이 있었다.
|
||||
|
||||
대표적인 문제는 다음과 같다.
|
||||
|
||||
- 빈 검색어를 전체 데이터 조회처럼 사용
|
||||
- Home에 필요한 latest/focus와 검색용 entity catalog의 의미가 섞임
|
||||
- Projects/Releases 목록이 검색 도메인의 반환 구조에 의존
|
||||
- API 의도가 presentation 요구사항과 맞지 않아 이후 pagination/cache 정책도 검색 정책에 끌려감
|
||||
|
||||
### 반영
|
||||
|
||||
`PublicContentQueries`에 화면 의도가 드러나는 read model을 추가했다.
|
||||
|
||||
- `listCatalog()`
|
||||
- `getLatestEntries()`
|
||||
- `getHomeFocusItems()`
|
||||
- `listProjects()`
|
||||
- `listReleases()`
|
||||
|
||||
HTTP adapter와 static adapter도 같은 port를 구현하도록 맞췄고 public pages는 이 projection을 직접 사용하도록 변경했다.
|
||||
|
||||
### 현재 판단
|
||||
|
||||
**완료.**
|
||||
|
||||
정적 검색 기준 `src/features/tech-log/presentation` 아래 `searchPublicContent("")` 호출은 0건이다.
|
||||
|
||||
검색은 검색에 사용하고, Home/Projects/Releases projection은 각각 자신의 read model을 사용하게 되었다.
|
||||
|
||||
---
|
||||
|
||||
## 2. Studio server-state — 컴포넌트가 직접 gateway/useEffect를 소유하던 문제
|
||||
|
||||
### 기존 문제
|
||||
|
||||
Studio의 여러 화면이 다음 패턴을 각자 반복하고 있었다.
|
||||
|
||||
```text
|
||||
useEffect
|
||||
-> AbortController 생성
|
||||
-> gateway 직접 호출
|
||||
-> loading/error/data local state
|
||||
-> cleanup에서 abort
|
||||
```
|
||||
|
||||
이 방식은 개별 화면만 보면 동작하지만 template이 제공하는 공통 server-state runtime을 우회한다.
|
||||
|
||||
그 결과 다음 기능이 화면마다 따로 구현됐다.
|
||||
|
||||
- cancellation
|
||||
- stale response 방지
|
||||
- loading/error state
|
||||
- retry
|
||||
- duplicate mutation 보호
|
||||
- idempotency key 생성/전달
|
||||
- mutation failure effect
|
||||
- query ownership
|
||||
|
||||
### 반영
|
||||
|
||||
TechLog Studio에 역할별 server-state adapter를 분리했다.
|
||||
|
||||
- `studio-document-server-state.ts`
|
||||
- `studio-workspace-server-state.ts`
|
||||
- `studio-management-server-state.ts`
|
||||
- `studio-asset-server-state.ts`
|
||||
- `studio-server-state-support.ts`
|
||||
|
||||
이 레이어에서 template의 다음 기능을 사용한다.
|
||||
|
||||
- `bindQuery`
|
||||
- `useApplicationQuery`
|
||||
- `useApplicationMutation`
|
||||
- `useServerStateScope`
|
||||
- mutation intent / idempotency
|
||||
- query/mutation failure normalization
|
||||
|
||||
### 이동한 주요 화면
|
||||
|
||||
- Studio dashboard
|
||||
- document list
|
||||
- document editor
|
||||
- validation
|
||||
- preview
|
||||
- publish
|
||||
- publication list / snapshot
|
||||
- new document
|
||||
- Home Focus
|
||||
- Project editor
|
||||
- Topic editor
|
||||
- Release list/editor
|
||||
- Taxonomy
|
||||
- Asset picker/library/upload
|
||||
|
||||
DocumentEditor의 TOPIC/PROJECT/RELATION/EVIDENCE catalog도 더 이상 별도 `AbortController + Promise.all`을 소유하지 않고 각각 `useStudioCatalogQuery`로 읽는다.
|
||||
|
||||
### 현재 판단
|
||||
|
||||
**완료.**
|
||||
|
||||
최종 정적 검색 결과:
|
||||
|
||||
```text
|
||||
direct ManagementGateway calls in Studio presentation: 0
|
||||
direct StudioAssetGateway calls in Studio presentation: 0
|
||||
direct StudioGateway operations in Studio components: 0
|
||||
manual AbortController in Studio presentation: 0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. ManagementGateway — template mutation runtime을 써도 실제 HTTP까지 보호가 전달되지 않던 문제
|
||||
|
||||
### 기존 문제
|
||||
|
||||
Management presentation을 `useApplicationMutation`으로 감싸더라도 port 자체가 signal/idempotency를 받지 않으면 보호가 adapter 직전에서 끊긴다.
|
||||
|
||||
기존 ManagementGateway는 mutation 메서드에 다음 정보가 없었다.
|
||||
|
||||
- `AbortSignal`
|
||||
- `idempotencyKey`
|
||||
|
||||
즉 화면 레벨에서 공통 mutation runtime을 사용해도 실제 관리 API 요청은 그 intent를 전달받지 못하는 구조였다.
|
||||
|
||||
### 반영
|
||||
|
||||
ManagementGateway read에는 `RequestOptions`, mutation에는 `IdempotentOptions`를 전달하도록 계약을 강화했다.
|
||||
|
||||
HTTP management adapter는 mutation마다:
|
||||
|
||||
```text
|
||||
useApplicationMutation
|
||||
-> MutationIntent
|
||||
-> Idempotency-Key
|
||||
-> ManagementGateway
|
||||
-> StudioOperationExecutor
|
||||
```
|
||||
|
||||
경로로 이어진다.
|
||||
|
||||
테스트 타입 오류로 드러난 기존 테스트도 수정했고, management delete / topic variant wiring 테스트는 idempotency key가 executor intent까지 전달되는 형태로 보강했다.
|
||||
|
||||
### 삭제 precondition도 controller로 이동
|
||||
|
||||
Document list는 목록 계약에 version이 없기 때문에 삭제 직전 최신 document detail을 읽어 `expectedVersion`을 확보해야 한다.
|
||||
|
||||
처음에는 이 한 건만 presentation에서 직접 `gateway.getDocument()`를 호출했지만 최종적으로 composite command:
|
||||
|
||||
`deleteWorkspaceDocument`
|
||||
|
||||
뒤로 이동했다.
|
||||
|
||||
따라서 화면은 “이 document를 삭제한다”는 의도만 전달하고 다음 조립은 controller가 수행한다.
|
||||
|
||||
1. 최신 document 조회
|
||||
2. expectedVersion 획득
|
||||
3. PROJECT_DECISION이면 project 경로 사용
|
||||
4. 나머지는 document kind별 management delete
|
||||
5. 같은 mutation intent/idempotency key 전달
|
||||
|
||||
### 현재 판단
|
||||
|
||||
**완료.**
|
||||
|
||||
---
|
||||
|
||||
## 4. Asset — 자체 네트워크 상태 머신 중복
|
||||
|
||||
### 기존 문제
|
||||
|
||||
Asset 영역은 port 자체는 비교적 잘 분리되어 있었지만 presentation이 다시 네트워크 lifecycle을 직접 관리했다.
|
||||
|
||||
- 목록 검색
|
||||
- cursor “더 보기”
|
||||
- 상세 조회
|
||||
- alt/decorative metadata 저장
|
||||
- archive
|
||||
- delete
|
||||
- upload
|
||||
|
||||
특히 upload는 multipart라 일반 JSON operation과 경로가 다르지만, 이미 `StudioAssetGateway`가 signal/idempotency 계약을 지원하고 있었다.
|
||||
|
||||
### 반영
|
||||
|
||||
`studio-asset-server-state.ts`로 read/mutation ownership을 이동했다.
|
||||
|
||||
- 기본 list query
|
||||
- next-page query
|
||||
- detail query
|
||||
- update metadata mutation
|
||||
- delete mutation
|
||||
- upload mutation
|
||||
|
||||
업로드 mutation identity에는 File 객체 자체만 의존하지 않고 다음 값을 명시적으로 포함한다.
|
||||
|
||||
- file name
|
||||
- MIME type
|
||||
- size
|
||||
- lastModified
|
||||
|
||||
서로 다른 파일이 동일한 in-flight mutation identity로 취급될 가능성을 줄였다.
|
||||
|
||||
AssetLibrary의 cursor append/focus UX는 유지했다.
|
||||
|
||||
### 현재 판단
|
||||
|
||||
**완료.**
|
||||
|
||||
---
|
||||
|
||||
## 5. Route — Public/Studio URL SSOT
|
||||
|
||||
### 기존 문제
|
||||
|
||||
route registry/runtime contract가 이미 있는데 presentation이 URL 문자열을 직접 만들면 route 정의가 두 군데가 된다.
|
||||
|
||||
특히 다음 변경에 취약하다.
|
||||
|
||||
- path rename
|
||||
- param rename
|
||||
- query codec 변경
|
||||
- URL encoding
|
||||
- canonical query serialization
|
||||
|
||||
### 반영
|
||||
|
||||
공통 builder:
|
||||
|
||||
- `src/presentation/routes/route-url-builder.ts`
|
||||
|
||||
TechLog Studio facade:
|
||||
|
||||
- `src/features/tech-log/presentation/studio/studio-routes.ts`
|
||||
- `src/features/tech-log/presentation/public/public-routes.ts`
|
||||
|
||||
를 추가했다.
|
||||
|
||||
`studioRoutes.documentEdit(id)`, `publicRoutes.project(slug)`처럼 route ID + codec을 통해 URL을 만든다.
|
||||
|
||||
또한 `scripts/check-tech-log-route-literals.ts`를 architecture check에 연결해 TechLog route registry에서 실제 route root를 파생해 Public/Studio route literal을 다시 하드코딩하면 검사가 실패하도록 했다.
|
||||
|
||||
### 현재 판단
|
||||
|
||||
**완료.**
|
||||
|
||||
주석 안의 `/studio/documents/*` 설명 문자열은 runtime route literal이 아니므로 검사 대상에서 제외된다.
|
||||
|
||||
---
|
||||
|
||||
## 5.1 후속 리뷰 반영 — form/theme/i18n/Asset boundary
|
||||
|
||||
후속 검토에서 기존 완료 판정을 다시 대조했고 다음 잔여 항목까지 반영했다.
|
||||
|
||||
- Public route도 `public-routes.ts`에서 contract/codec 기반으로 생성한다.
|
||||
- Project/Topic/Release 편집 lifecycle을 template `useAppForm`으로 통일했다.
|
||||
- concrete palette는 `tech-log-theme.css` 한 곳에 두고 feature CSS는 semantic token만 사용한다.
|
||||
- route/navigation/status/failure copy를 TechLog message catalog와 locale hook으로 이동했다.
|
||||
- Asset UI는 `StudioAssetGateway` prop을 받지 않고 server-state hook을 통해 Provider 경계에서만 gateway를 사용한다.
|
||||
- raw `<form>` / `<dialog>`은 TechLog presentation 기준 0건이다.
|
||||
|
||||
Markdown block, ordered list, asset card처럼 도메인 편집 자체를 표현하는 low-level native control은 기존 DOM/CSS 계약을 보존했다. 공통 lifecycle을 재구현하는 지점만 template capability로 이동하는 것이 적용 기준이다.
|
||||
|
||||
**상태: 완료.**
|
||||
|
||||
---
|
||||
|
||||
## 6. 하드코딩 검토
|
||||
|
||||
### 정리된 하드코딩
|
||||
|
||||
- Studio route path 직접 문자열
|
||||
- public 빈 검색어를 이용한 전체 catalog 조회
|
||||
- document kind를 좁히는 unsafe cast 기반 delete routing
|
||||
- 화면별 수동 idempotency key 생성
|
||||
- 화면별 수동 request cancellation
|
||||
- Project activity 허용값의 frontend 독립 배열
|
||||
- Release change type 허용값의 frontend 독립 배열
|
||||
|
||||
### activity/change type도 계약 source-of-truth로 이동
|
||||
|
||||
이전에는 management OpenAPI가 activityType과 changeTypes[]를 단순 string으로 노출했다. 그래서 frontend는 백엔드가 허용하는 값 집합을 별도 배열로 다시 적어야 했고, 서버 제약과 UI가 서로 어긋나도 TypeScript가 잡을 수 없었다.
|
||||
|
||||
이번 작업에서 backend management OpenAPI에 실제 애플리케이션이 허용하는 값을 enum으로 명시했다.
|
||||
|
||||
- Project activity: PHASE_CHANGED, QUESTION_OPENED, QUESTION_RESOLVED, DECISION_ACCEPTED, CASE_PUBLISHED, REFERENCE_PUBLISHED, MILESTONE_REACHED, PROJECT_PAUSED, PROJECT_RESUMED
|
||||
- Release change: FEATURE, FIX, REFACTOR, DOCS, INFRA, BREAKING
|
||||
|
||||
frontend generated contract는 이제 이 필드를 literal union으로 생성한다. presentation의 한국어 문구는 Record<generated-union, string>으로만 관리하므로 값이 추가되거나 빠지면 compile 단계에서 label map도 함께 수정해야 한다.
|
||||
|
||||
즉 **값의 허용 범위는 management contract**, **표시 문구는 presentation**이 소유한다. 같은 도메인 값 집합을 component마다 다시 선언하는 구조는 제거됐다.
|
||||
|
||||
---
|
||||
|
||||
## 7. 성능/조회 구조 검토
|
||||
|
||||
### 개선된 부분
|
||||
|
||||
- empty search를 전체 catalog API처럼 호출하던 경로 제거
|
||||
- query cancellation/dedup ownership을 공통 runtime으로 이동
|
||||
- 검색 입력과 제출 query 분리 유지
|
||||
- Asset pagination append 유지
|
||||
- 화면마다 중복되던 request lifecycle 제거
|
||||
- server-state query가 같은 scope/identity로 관리됨
|
||||
|
||||
### Taxonomy project-topic N+1 제거
|
||||
|
||||
기존 Taxonomy 구조 탭은 ProjectIndexItem에 topicIds가 없어 다음 요청을 만들었다.
|
||||
|
||||
1. topics 목록 1회
|
||||
2. projects 목록 1회
|
||||
3. project 수만큼 getProjectForEdit 상세 조회
|
||||
|
||||
Promise.all로 병렬화해도 API 호출 수는 2 + N이었다.
|
||||
|
||||
이번에는 management 목록 계약 자체를 확장했다.
|
||||
|
||||
- ProjectIndexItem.topicIds: uuid[] 추가
|
||||
- 목록에서 공개 경로를 연결할 때 필요한 ProjectIndexItem.slug도 정식 계약에 추가
|
||||
- frontend Taxonomy는 topics 1회 + projects 1회만 호출
|
||||
- project-topic 연결은 ProjectIndexItem.topicIds에서 바로 구성
|
||||
- per-project getProjectForEdit 호출 제거
|
||||
|
||||
backend persistence도 단순히 N+1을 서버 내부로 옮기지 않았다. 현재 페이지의 project 목록을 읽은 뒤 project_topic을 project_id IN (:projectIds)로 한 번에 조회해 project id별로 조립한다.
|
||||
|
||||
따라서 한 Taxonomy 조회에서 project 수가 증가해도 project 목록 관련 DB query count는 다음으로 고정된다.
|
||||
|
||||
1. project index 1회
|
||||
2. 현재 페이지 project들의 project-topic relation bulk 조회 1회
|
||||
|
||||
frontend 회귀 테스트는 getProject를 호출하면 실패하도록 구성했고, backend PostgreSQL integration test는 index projection이 slug와 topicIds 순서를 실제로 보존하는지 검증하도록 추가했다.
|
||||
|
||||
**구현 상태: 완료. 최종 테스트 결과는 아래 검증 절에 기록한다.**
|
||||
|
||||
---
|
||||
|
||||
## 8. 런타임 검증에서 추가로 발견한 template 통합 결함
|
||||
|
||||
정적 검사만으로는 드러나지 않았지만 Node 24에서 실제 TechLog suite를 실행하면서 다음 통합 결함이 확인됐다. 모두 수정 후 회귀 테스트를 통과했다.
|
||||
|
||||
### nullable query
|
||||
|
||||
`useApplicationQuery`가 `null`을 “아직 데이터가 없음”으로 해석하고 있었다. TechLog의 `Preview 없음 = null`은 정상 성공값이므로 화면이 영구 `initial-loading`에 머물 수 있었다.
|
||||
|
||||
현재는 `undefined`만 미수신 상태로 보고, `null`은 수신된 empty value로 처리한다. 공통 async-state 테스트에 `data: null -> empty` 계약을 추가했다.
|
||||
|
||||
### host object mutation identity
|
||||
|
||||
Asset upload payload는 `File`을 포함한다. 공통 mutation이 전송 input 전체를 canonicalize하면 plain object가 아닌 `File`에서 identity 생성이 실패한다.
|
||||
|
||||
`BoundMutation`에 `identity(input)` projection을 추가해 전송 payload와 command identity를 분리했다. Asset upload는 `File` 자체를 전송하되 identity에는 `fileIdentity`, `kind`, `decorative`, `altText`만 사용한다. 공통 application-query 테스트로 이 계약을 고정했다.
|
||||
|
||||
### mutation mount timing
|
||||
|
||||
mutation controller가 mount된 직후 effect가 unknown-effect channel을 publish하기 전에 사용자가 submit하면 정상 command도 channel limit failure로 거절될 수 있었다.
|
||||
|
||||
submit 경로에서도 현재 scope에 대해 channel을 lazy-acquire하도록 수정했다. scope 충돌이나 registry saturation은 그대로 fail-closed 한다.
|
||||
|
||||
### Dashboard result budget
|
||||
|
||||
Dashboard query는 결과 객체 하나를 반환하지만 내부 row 개수를 `itemCount`로 계산해 `maxResultItems=1` budget을 정상 응답이 초과할 수 있었다.
|
||||
|
||||
`itemCount=1`로 수정하고 내부 row 수는 estimated bytes에만 반영했다.
|
||||
|
||||
### Dialog / Pagination primitive
|
||||
|
||||
공통 `Dialog`에 initial focus, focus return, Tab boundary trap, 별도 accessible title을 보강했다. Public Search, Evidence zoom, Asset Upload, Asset Picker가 동일 lifecycle을 사용한다.
|
||||
|
||||
공통 `Pagination`은 기본 link semantics를 유지하면서 `pageControl="button"`과 `pageAccessibleLabel`을 지원하도록 확장했다. Studio는 기존 UX 계약대로 숫자는 짧게 보이고 접근성 이름은 `N 페이지`로 유지한다.
|
||||
|
||||
### test composition
|
||||
|
||||
production app은 `ServerStateGenerationProvider` 아래에서 실행되는데 일부 TechLog component test는 직접 `StudioProvider`만 렌더하고 있었다. 테스트 helper를 실제 provider stack과 동일한 QueryClient / MutationIntent / ServerStateScope / QueryInvalidation 구조로 맞췄다.
|
||||
|
||||
---
|
||||
|
||||
## 9. 검증 결과
|
||||
|
||||
### frontend 정적/빌드 — PASS
|
||||
|
||||
실행한 게이트:
|
||||
- check:types
|
||||
- lint
|
||||
- check:architecture
|
||||
- check:design-system
|
||||
- check:tech-log-contract
|
||||
- check:i18n
|
||||
- build:app-only
|
||||
- git diff --check
|
||||
|
||||
최종 결과:
|
||||
|
||||
~~~text
|
||||
Static import graph: 500 modules, 1775 dependencies, all imports resolved
|
||||
Architecture graph fixtures: 14 regression checks PASS
|
||||
TypeScript-only source policy: PASS
|
||||
Architecture fixtures: allowed PASS, 9 forbidden rejected
|
||||
TechLog route source-of-truth: PASS
|
||||
Design system contract: 48 tokens and vendor boundaries PASS
|
||||
I18n contract: 282 keys across 4 locales PASS
|
||||
production Vite build: PASS
|
||||
git diff --check: PASS
|
||||
~~~
|
||||
|
||||
Contract sync:
|
||||
|
||||
~~~text
|
||||
@tech-log/studio-contract@3.1.0 — 19 operations
|
||||
@tech-log/public-contract@2.1.0 — 22 operations
|
||||
@tech-log/management-contract@1.0.0 — 87 operations
|
||||
contracts are in sync
|
||||
~~~
|
||||
|
||||
추가 정적 검색:
|
||||
|
||||
~~~text
|
||||
raw <dialog> in TechLog presentation: 0
|
||||
manual AbortController in TechLog presentation: 0
|
||||
searchPublicContent("") in TechLog: 0
|
||||
getProject(project.id) Taxonomy fan-out: 0
|
||||
frontend ACTIVITY_TYPES 허용값 배열: 0
|
||||
frontend CHANGE_TYPES 허용값 배열: 0
|
||||
~~~
|
||||
|
||||
### Node 24 TechLog Vitest — PASS
|
||||
|
||||
시스템 Node는 변경하지 않고 one-off Node 24.11.0으로 실행했다.
|
||||
|
||||
~~~text
|
||||
Test Files 60 passed (60)
|
||||
Tests 416 passed (416)
|
||||
~~~
|
||||
|
||||
새 taxonomy-projection.test.tsx는 Taxonomy가 project index의 topicIds만으로 구조를 만들고 project detail gateway를 호출하지 않는 것을 고정한다.
|
||||
|
||||
**상태: 완료.**
|
||||
|
||||
### template 공통 회귀 테스트 — PASS
|
||||
|
||||
~~~text
|
||||
application-query.test.tsx 29 passed
|
||||
async-surface.test.tsx 17 passed
|
||||
design-system-platform.test.tsx 8 passed
|
||||
locale-platform.test.tsx 3 passed
|
||||
합계 57 passed
|
||||
~~~
|
||||
|
||||
**상태: 완료.**
|
||||
|
||||
### backend management projection — PASS
|
||||
|
||||
Taxonomy N+1 제거를 위해 backend management 계약과 persistence projection까지 확장했다.
|
||||
|
||||
- ProjectIndexItemView에 slug, topicIds 추가
|
||||
- project 목록 1회 + project_topic bulk 조회 1회로 조립
|
||||
- management OpenAPI에 ProjectIndexItem.topicIds 추가
|
||||
- project activity / release change 허용값을 OpenAPI enum으로 고정
|
||||
- generated web model과 application string 경계 mapper 연결
|
||||
- PostgreSQL integration test에 project index slug/topicIds 검증 추가
|
||||
|
||||
실제 PostgreSQL management integration:
|
||||
|
||||
~~~text
|
||||
:adapter:outbound:persistence-jpa:postgresqlTechLogManagementPersistenceIntegrationTest
|
||||
BUILD SUCCESSFUL
|
||||
~~~
|
||||
|
||||
변경 모듈의 test / checkstyle / spotless:
|
||||
|
||||
~~~text
|
||||
application-core
|
||||
persistence-jpa
|
||||
inbound-web
|
||||
|
||||
BUILD SUCCESSFUL in 19s
|
||||
36 actionable tasks: 6 executed, 30 up-to-date
|
||||
~~~
|
||||
|
||||
**상태: 완료.**
|
||||
|
||||
### backend repository 전체 check — 기존 SpotBugs classpath issue
|
||||
|
||||
backend 전체 ./gradlew check는 이번 변경 파일의 컴파일/테스트 오류가 아니라 다음 기존 분석 classpath 문제에서 중단됐다.
|
||||
|
||||
~~~text
|
||||
:app-bootstrap:spotbugsFunctionalTest
|
||||
missing analysis class:
|
||||
dev.caskeleton.shared.error.ApiErrorCarrier
|
||||
dev.caskeleton.shared.error.ApiErrorCode
|
||||
~~~
|
||||
|
||||
변경 모듈을 별도로 검증했을 때도 application-core:spotbugsMain이 동일 계열의 shared-contract 분석 class 누락으로 실패한다.
|
||||
|
||||
따라서 이번 management projection 변경은 PostgreSQL integration, module test, checkstyle, spotless로 검증 완료했으며 repository 전체 SpotBugs classpath 문제는 별도 build-qualification 이슈다.
|
||||
|
||||
### browser source-parity — 실행 조건 부족
|
||||
|
||||
browser parity runner가 요구하는 기준 source app이 현재 Coka 환경에 없다.
|
||||
|
||||
~~~text
|
||||
source: http://127.0.0.1:4375
|
||||
target: http://127.0.0.1:4174
|
||||
source root: /home/donghyeon/workspace/techlog-studio-frontend
|
||||
~~~
|
||||
|
||||
기준 source root와 두 서버가 준비되지 않은 상태에서 실행하면 ERR_CONNECTION_REFUSED가 발생한다.
|
||||
|
||||
이 항목은 구현 미완료가 아니라 외부 비교 기준 부재로 증거를 새로 생성할 수 없는 상태다.
|
||||
|
||||
---
|
||||
|
||||
## 10. 최종 상태
|
||||
|
||||
| 검토 항목 | 상태 |
|
||||
|---|---|
|
||||
| template HTTP binding 활용 | 완료 |
|
||||
| template route capability 활용 | 완료 |
|
||||
| Studio server-state capability 활용 | 완료 |
|
||||
| mutation idempotency / host-object identity | 완료 |
|
||||
| cancellation ownership | 완료 |
|
||||
| shared Dialog / Pagination / Form primitive 활용 | 완료 |
|
||||
| semantic design token 연결 | 완료 |
|
||||
| ManagementGateway presentation 직접 호출 제거 | 완료 |
|
||||
| StudioGateway presentation 직접 호출 제거 | 완료 |
|
||||
| AssetGateway presentation 직접 호출 제거 | 완료 |
|
||||
| public empty-search projection 우회 제거 | 완료 |
|
||||
| route hardcoding guard | 완료 |
|
||||
| activity/change type contract enum화 | 완료 |
|
||||
| Taxonomy project-topic N+1 제거 | 완료 |
|
||||
| frontend typecheck | 완료 |
|
||||
| frontend lint | 완료 |
|
||||
| architecture check | 완료 |
|
||||
| design-system check | 완료 |
|
||||
| TechLog contract sync | 완료 |
|
||||
| repository i18n gate | 완료 |
|
||||
| production Vite build | 완료 |
|
||||
| Node 24 TechLog Vitest 416/416 | 완료 |
|
||||
| template component regression 154/154 | 완료 |
|
||||
| backend PostgreSQL management integration | 완료 |
|
||||
| backend 변경 모듈 test/checkstyle/spotless | 완료 |
|
||||
| backend repository 전체 SpotBugs | 아직 더 봐야댐 — 기존 shared-contract 분석 classpath 문제 |
|
||||
| browser source-parity evidence | 아직 더 봐야댐 — baseline/source app 부재 |
|
||||
|
||||
## 11. 남은 범위
|
||||
|
||||
이번 리뷰에서 확인한 TechLog frontend/template 활용, Taxonomy N+1, 관리 계약 허용값 하드코딩, i18n gate는 완료했다.
|
||||
|
||||
**Frontend 코드 수정으로 남은 TechLog 리뷰 항목은 없다.** 현재 별도로 남는 것은 두 가지 외부/공통 검증 조건이다.
|
||||
|
||||
1. backend build-qualification의 SpotBugs analysis classpath 누락 문제
|
||||
2. browser source-parity용 원본 source app 및 source/target 서버 준비
|
||||
|
||||
둘 다 이번 TechLog presentation/refactor 구현의 미완료 항목과는 분리된다.
|
||||
|
||||
---
|
||||
|
||||
## 12. 2026-09-22 재검수 종료
|
||||
|
||||
2026-09-22 재검수에서 이전에 남아 있던 네 축을 다시 확인했다.
|
||||
|
||||
- TechLogFeatureInput은 raw gateway factory 대신 createStudioApplication()을 노출한다.
|
||||
- StudioContextValue는 studioApplication만 노출하며 presentation component/controller의 raw gateway 직접 호출은 0건이다.
|
||||
- TechLog presentation의 raw button/input/select/textarea, form, dialog는 모두 0건이다.
|
||||
- 일반 행동 문구는 message catalog를 사용한다. 최종 검색에 남은 게시/공개/검증/검색 등의 직접 문자열은 상태명, field label, heading 등 이번 리뷰의 behavioral copy 대상에서 제외한 표현이다.
|
||||
- AssetLibrary, TaxonomyManager, ProjectEditor, TopicEditor, DocumentList 다섯 화면 모두 controller hook 경계를 가진다.
|
||||
- DocumentList의 search params, query composition, pagination, delete orchestration, search/filter synchronization은 use-document-list-controller.ts가 소유한다.
|
||||
|
||||
정적 증거:
|
||||
|
||||
~~~text
|
||||
raw native control = 0
|
||||
raw form = 0
|
||||
raw dialog = 0
|
||||
gateway port import = 0
|
||||
component gateway direct call = 0
|
||||
controller files = 5
|
||||
behavioral action literal = 0
|
||||
~~~
|
||||
|
||||
Node 24.11.0 최종 검증:
|
||||
|
||||
~~~text
|
||||
types=PASS
|
||||
lint=PASS
|
||||
architecture=PASS
|
||||
design=PASS
|
||||
contract=PASS
|
||||
i18n=PASS
|
||||
techlog-tests=PASS
|
||||
component-tests=PASS
|
||||
build=PASS
|
||||
diff=PASS
|
||||
|
||||
TechLog tests: 60 files / 416 tests PASS
|
||||
Component tests: 27 files / 154 tests PASS
|
||||
~~~
|
||||
|
||||
| 리뷰 항목 | 판정 |
|
||||
|---|---|
|
||||
| template HTTP binding 활용 | 완료 |
|
||||
| Public/Studio route capability 및 route hardcoding 제거 | 완료 |
|
||||
| Studio server-state / cancellation ownership | 완료 |
|
||||
| TechLogFeatureInput / StudioContext application boundary | 완료 |
|
||||
| design-system native control / Form / Dialog primitive 적용 | 완료 |
|
||||
| behavioral action/error/loading/empty copy i18n | 완료 |
|
||||
| 대형 Studio component controller/view-state 분리 | 완료 |
|
||||
| management contract 기반 허용값 SSOT | 완료 |
|
||||
| Taxonomy project-topic N+1 제거 | 완료 |
|
||||
| TechLog/component/정적/빌드 회귀 검증 | 완료 |
|
||||
|
||||
완료: 10
|
||||
아직 더 봐야댐: 0
|
||||
|
||||
이 판정은 TechLog frontend/template 활용 재검수 10개 축에 대한 것이다. 기존 문서에 기록된 backend 공통 SpotBugs classpath와 browser source-parity 실행 조건은 이 10개 축의 구현 미완료 항목으로 계산하지 않는다.
|
||||
|
||||
---
|
||||
|
||||
## 작업트리 주의
|
||||
|
||||
이번 검토를 시작할 때 저장소에는 이미 여러 변경이 존재했다. 기존 변경을 보존한 상태에서 작업했으며 destructive git 명령, reset, checkout, commit, merge는 수행하지 않았다.
|
||||
|
||||
따라서 현재 전체 `git diff`를 전부 이번 리뷰의 신규 변경이라고 간주하면 안 된다. 이 문서는 이번 세션에서 직접 확인한 구조적 문제와 현재 worktree에서 검증된 최종 상태를 기준으로 작성했다.
|
||||
@@ -0,0 +1,121 @@
|
||||
# TechLog Frontend — template 활용 재검수
|
||||
|
||||
- 날짜: 2026-09-22
|
||||
- 대상: /shared/codebase/tech-log-frontend
|
||||
- 기준 문서: docs/reviews/2026-09-21-tech-log-template-utilization-review.md
|
||||
- 목적: 이전 재검수에서 남아 있던 4개 축을 닫고 기존 완료 항목까지 포함해 10개 축을 최종 판정한다.
|
||||
|
||||
## 결론
|
||||
|
||||
| 리뷰 항목 | 판정 |
|
||||
|---|---|
|
||||
| template HTTP binding 활용 | 완료 |
|
||||
| Public/Studio route capability 및 route hardcoding 제거 | 완료 |
|
||||
| Studio server-state / cancellation ownership | 완료 |
|
||||
| TechLogFeatureInput / StudioContext application boundary | 완료 |
|
||||
| design-system native control / Form / Dialog primitive 적용 | 완료 |
|
||||
| behavioral action/error/loading/empty copy i18n | 완료 |
|
||||
| 대형 Studio component controller/view-state 분리 | 완료 |
|
||||
| management contract 기반 허용값 SSOT | 완료 |
|
||||
| Taxonomy project-topic N+1 제거 | 완료 |
|
||||
| TechLog/component/정적/빌드 회귀 검증 | 완료 |
|
||||
|
||||
완료: 10
|
||||
아직 더 봐야댐: 0
|
||||
|
||||
## 남았던 4개 축
|
||||
|
||||
### 1. TechLogFeatureInput / StudioContext raw gateway 노출
|
||||
|
||||
TechLogFeatureInput은 raw gateway factory를 노출하지 않고 createStudioApplication()으로 application facade를 만든다. StudioContextValue도 studioApplication만 노출한다.
|
||||
|
||||
최종 정적 결과:
|
||||
|
||||
~~~text
|
||||
gateway port import = 0
|
||||
component gateway direct call = 0
|
||||
~~~
|
||||
|
||||
Studio의 studio-*-server-state.ts 내부에는 application facade가 캡슐화한 gateway 호출이 존재하지만, component/controller가 gateway를 직접 호출하는 구조는 아니다.
|
||||
|
||||
판정: 완료
|
||||
|
||||
### 2. design-system primitive
|
||||
|
||||
TechLog presentation에서 native control과 raw form/dialog를 다시 검색했다.
|
||||
|
||||
~~~text
|
||||
raw native control = 0
|
||||
raw form = 0
|
||||
raw dialog = 0
|
||||
~~~
|
||||
|
||||
기존 DOM/CSS를 보존해야 하는 화면은 template primitive의 visualPolicy=inherit 경로를 사용한다.
|
||||
|
||||
판정: 완료
|
||||
|
||||
### 3. behavioral copy i18n
|
||||
|
||||
일반 행동 버튼과 action prop의 저장, 추가, 검색, 취소, 다시 시도, 삭제, 더 보기, 닫기, 업로드, 게시, 공개, 검증, 적용, 삽입, 필터 초기화 등을 message catalog로 이동했다.
|
||||
|
||||
최종 검색에 남는 동일 단어는 publication 상태명, field label, heading, 동적 noun 기반 버튼 등 리뷰에서 behavioral copy 대상으로 잡지 않은 표현이다.
|
||||
|
||||
Unsaved navigation의 기존 접근성 이름 저장 중도 별도 catalog key로 유지해 i18n 이동 때문에 UI 계약이 바뀌지 않도록 했다.
|
||||
|
||||
판정: 완료
|
||||
|
||||
### 4. 대형 Studio component controller/view-state 분리
|
||||
|
||||
다음 5개 controller가 존재한다.
|
||||
|
||||
~~~text
|
||||
use-asset-library-controller.ts
|
||||
use-taxonomy-controller.ts
|
||||
use-project-editor-controller.ts
|
||||
use-topic-editor-controller.ts
|
||||
use-document-list-controller.ts
|
||||
~~~
|
||||
|
||||
DocumentList의 useSearchParams, query composition, pagination, pageOverride, delete orchestration, search/filter synchronization은 controller가 소유한다. component는 controller state를 렌더하고 action을 호출하는 역할로 남아 있다.
|
||||
|
||||
판정: 완료
|
||||
|
||||
## 최종 검증
|
||||
|
||||
Node 24.11.0 기준:
|
||||
|
||||
~~~text
|
||||
types=PASS
|
||||
lint=PASS
|
||||
architecture=PASS
|
||||
design=PASS
|
||||
contract=PASS
|
||||
i18n=PASS
|
||||
techlog-tests=PASS
|
||||
component-tests=PASS
|
||||
build=PASS
|
||||
diff=PASS
|
||||
~~~
|
||||
|
||||
테스트:
|
||||
|
||||
~~~text
|
||||
TechLog: 60 files / 416 tests PASS
|
||||
Component regression: 27 files / 154 tests PASS
|
||||
~~~
|
||||
|
||||
정적 증거:
|
||||
|
||||
~~~text
|
||||
raw native control = 0
|
||||
raw form = 0
|
||||
raw dialog = 0
|
||||
gateway port import = 0
|
||||
component gateway direct call = 0
|
||||
controller files = 5
|
||||
behavioral action literal = 0
|
||||
~~~
|
||||
|
||||
## 범위 주의
|
||||
|
||||
기존 리뷰 문서에 기록된 backend 공통 SpotBugs analysis classpath 문제와 browser source-parity 실행 조건 부족은 이번 TechLog frontend/template 활용 10개 축과 별도다. 이번 재검수에서 frontend 코드 수정으로 남은 항목은 없다.
|
||||
@@ -0,0 +1,185 @@
|
||||
# TechLog Frontend — 2026-09-23 재검수 및 구현 결과
|
||||
|
||||
- 대상: `/shared/codebase/tech-log-frontend`
|
||||
- 기준: 2026-09-23 재검수에서 `완료: 8`, `아직 더 봐야댐: 2`로 판정한 10개 항목
|
||||
- 수정 대상: application boundary, behavioral action/error/loading/empty copy i18n
|
||||
- 검증 런타임: Node `v24.11.0`
|
||||
- 기존 작업트리: 보존. reset / checkout / clean / commit 수행하지 않음
|
||||
|
||||
## 결론
|
||||
|
||||
2026-09-23 재검수 당시 남아 있던 두 항목을 구현하고 현재 worktree에서 다시 검증했다.
|
||||
|
||||
| 항목 | 판정 |
|
||||
|---|---|
|
||||
| template HTTP binding | 완료 |
|
||||
| route capability / hardcoding 제거 | 완료 |
|
||||
| Studio server-state | 완료 |
|
||||
| application boundary | 완료 |
|
||||
| design-system primitive | 완료 |
|
||||
| behavioral copy i18n | 완료 |
|
||||
| controller/view-state 분리 | 완료 |
|
||||
| management allowed-value SSOT | 완료 |
|
||||
| Taxonomy N+1 제거 | 완료 |
|
||||
| 회귀 검증 | 완료 |
|
||||
|
||||
완료: 10
|
||||
아직 더 봐야댐: 0
|
||||
|
||||
## 1. Application boundary
|
||||
|
||||
### 이전 상태
|
||||
|
||||
`TechLogStudioApplication`이 아래 outbound port를 그대로 노출했다.
|
||||
|
||||
```text
|
||||
documents: StudioGateway
|
||||
assets: StudioAssetGateway
|
||||
management: ManagementGateway
|
||||
```
|
||||
|
||||
따라서 이름은 application facade였지만 presentation server-state가 다시 raw outbound port를 꺼낼 수 있었다.
|
||||
|
||||
### 현재 상태
|
||||
|
||||
`TechLogStudioApplication`은 application-owned capability만 노출한다.
|
||||
|
||||
```text
|
||||
workspaceQueries
|
||||
workspaceCommands
|
||||
documentQueries
|
||||
documentCommands
|
||||
assetQueries
|
||||
assetCommands
|
||||
managementQueries
|
||||
managementCommands
|
||||
```
|
||||
|
||||
`StudioGateway`, `StudioAssetGateway`, `ManagementGateway`는 `createTechLogStudioApplication(...)`의 내부 dependency로만 사용한다. factory dependency 타입도 export하지 않는다.
|
||||
|
||||
`create-tech-log-feature-input.ts`는 세 adapter를 만든 뒤 application factory에 주입한다. Studio presentation은 더 이상 `.documents`, `.assets`, `.management`를 꺼내지 않고 application capability를 사용한다.
|
||||
|
||||
기존 테스트가 gateway test-double을 직접 조작해야 하는 경우는 `tests/helpers/studio-application-gateway-adapter.ts`에서만 gateway-shaped test adapter를 만든다. 이 adapter는 production presentation 경계를 우회하지 않는다.
|
||||
|
||||
정적 증거:
|
||||
|
||||
```text
|
||||
application_public_gateway_tokens=0
|
||||
application_dependency_export=0
|
||||
presentation_gateway_port_import=0
|
||||
presentation_old_app_property=0
|
||||
component_controller_gateway_call=0
|
||||
```
|
||||
|
||||
판정: 완료
|
||||
|
||||
## 2. Behavioral copy i18n
|
||||
|
||||
### 이전 상태
|
||||
|
||||
message catalog가 존재했지만 TechLog feature presentation은 `scripts/check-i18n.ts`의 hardcoded-locale 검사 범위에 포함되지 않았다. 따라서 `check:i18n=PASS`만으로는 TechLog behavioral copy 이관 완료를 증명할 수 없었다.
|
||||
|
||||
실제 새 gate를 처음 적용했을 때 action/error/loading/empty/not-found/announcement 계열 위반이 다수 확인됐다.
|
||||
|
||||
### 현재 상태
|
||||
|
||||
`src/features/tech-log/contracts/tech-log-message-catalog.ts`에 behavioral copy를 ko-KR/en-US 쌍으로 이동했다. 동적 성공 announcement도 `{title}`, `{name}`, `{version}` interpolation으로 이동했다.
|
||||
|
||||
추가된 검사 경계:
|
||||
|
||||
- `scripts/lib/tech-log-i18n-policy.ts`
|
||||
- `tests/unit/tech-log-i18n-gate.test.ts`
|
||||
- `scripts/check-i18n.ts`의 `src/features/tech-log/presentation` 별도 behavioral scan
|
||||
|
||||
공통 presentation의 기존 blanket Korean literal 검사는 그대로 유지한다. TechLog에는 별도 targeted policy를 적용해 다음은 차단한다.
|
||||
|
||||
- direct `setRequestAnnouncement`, `setNotice`, `setSuccess` literal
|
||||
- 동적 template/문자열 조합 announcement
|
||||
- static Button/Link action text
|
||||
- `pendingLabel`, `closeLabel`, `resetLabel`, `clearLabel` 등 action prop literal
|
||||
- error/failure fallback literal
|
||||
- public error/empty/not-found behavioral surface literal
|
||||
|
||||
반대로 heading, field label, publication/domain status 같은 editorial/domain copy는 blanket 금지하지 않는다.
|
||||
|
||||
최종 증거:
|
||||
|
||||
```text
|
||||
behavioral_literal_violations=0
|
||||
checked_techlog_presentation_files=148
|
||||
I18n contract: 460 keys across 4 locales PASS
|
||||
I18n policy tests: 1 file / 3 tests PASS
|
||||
```
|
||||
|
||||
판정: 완료
|
||||
|
||||
## 3. 기존 완료 항목 회귀
|
||||
|
||||
이번 수정 후에도 기존 구조적 완료 조건을 다시 확인했다.
|
||||
|
||||
```text
|
||||
raw_native_control=0
|
||||
raw_form=0
|
||||
raw_dialog=0
|
||||
controllers=5
|
||||
```
|
||||
|
||||
application boundary 변경 후 component/controller에는 raw gateway 직접 호출이 없다. design-system native control/Form/Dialog 경계와 controller 분리도 유지된다.
|
||||
|
||||
판정: 완료
|
||||
|
||||
## 4. 최종 회귀 검증
|
||||
|
||||
Node `v24.11.0`에서 현재 worktree를 다시 실행했다.
|
||||
|
||||
```text
|
||||
check:types PASS
|
||||
lint PASS
|
||||
check:architecture PASS
|
||||
check:design-system PASS
|
||||
check:tech-log-contract PASS
|
||||
check:i18n PASS
|
||||
i18n policy unit tests PASS
|
||||
test:tech-log PASS
|
||||
test:component PASS
|
||||
build:app-only PASS
|
||||
git diff --check PASS
|
||||
```
|
||||
|
||||
테스트 수:
|
||||
|
||||
```text
|
||||
TechLog: 61 files / 417 tests PASS
|
||||
Component: 27 files / 154 tests PASS
|
||||
I18n policy: 1 file / 3 tests PASS
|
||||
```
|
||||
|
||||
TechLog suite는 application boundary regression test가 추가되어 이전 60 files / 416 tests에서 61 files / 417 tests로 증가했다.
|
||||
|
||||
최종 전체 로그:
|
||||
|
||||
```text
|
||||
/shared/.coka-logs/tech-log-frontend-final-verification-v4-20260923.log
|
||||
```
|
||||
|
||||
판정: 완료
|
||||
|
||||
## 5. 작업트리 주의
|
||||
|
||||
현재 `git status --short` 기준:
|
||||
|
||||
```text
|
||||
status_total=177
|
||||
modified_entries=149
|
||||
untracked=27
|
||||
deleted_entries=1
|
||||
```
|
||||
|
||||
이 수치는 이번 작업 이전부터 존재하던 대규모 미커밋 변경과 이번 구현 변경을 함께 포함한다. 기존 사용자 변경을 reset, checkout, clean 하지 않았다. commit도 생성하지 않았다.
|
||||
|
||||
## 최종 판정
|
||||
|
||||
2026-09-23 재검수 당시 `아직 더 봐야댐`이었던 application boundary와 behavioral copy i18n 두 항목은 현재 구현과 검증 기준에서 완료다.
|
||||
|
||||
완료: 10
|
||||
아직 더 봐야댐: 0
|
||||
@@ -0,0 +1,148 @@
|
||||
# TechLog Application Boundary + Behavioral i18n Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox syntax for tracking.
|
||||
|
||||
**Goal:** Close the two remaining TechLog re-review items so the application API hides outbound gateways and TechLog behavioral copy is catalog-driven and enforced by `check:i18n`.
|
||||
|
||||
**Architecture:** `createTechLogStudioApplication()` owns `StudioGateway`, `StudioAssetGateway`, and `ManagementGateway` privately and exposes application-owned query/command capability objects. TechLog presentation keeps using server-state hooks, but server-state calls application capabilities rather than extracting gateway ports. Behavioral copy moves to the TechLog message catalog with interpolation, and `scripts/check-i18n.ts` gains a targeted TechLog behavioral scanner rather than a blanket Korean-literal ban.
|
||||
|
||||
**Tech Stack:** TypeScript 7, React, Vitest, pnpm, custom architecture/i18n check scripts.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-09-23-tech-log-application-boundary-i18n-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Preserve all existing user changes; no reset/checkout/clean/commit/merge.
|
||||
- Use Node 24.11.0 for verification without changing repository configuration.
|
||||
- Do not intentionally change visible Korean copy or accessibility names.
|
||||
- `TechLogStudioApplication` must not expose, alias, extend, or return `StudioGateway`, `StudioAssetGateway`, or `ManagementGateway` objects.
|
||||
- Components/controllers must not gain direct gateway/application orchestration that belongs in server-state.
|
||||
- TechLog i18n gate targets behavioral copy only; headings, field labels, help text, domain status labels, and dynamic noun labels remain allowed.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- Application capability methods preserve signal/idempotency options exactly; focused delegation test covers both query and mutation paths.
|
||||
- Management capability split does not drop any operation currently consumed by `studio-management-server-state.ts`; typecheck and TechLog tests pin the full surface.
|
||||
- Dynamic delete announcements preserve interpolation values and Korean rendering.
|
||||
- i18n gate rejects direct behavioral announcements/actions but permits headings/field labels/domain status literals.
|
||||
- Existing accessible copy such as `저장 중` remains byte-for-byte unchanged.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Application-owned Studio capability boundary
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/features/tech-log/application/studio-application.ts`
|
||||
- Modify: `src/features/tech-log/adapters/create-tech-log-feature-input.ts`
|
||||
- Modify: `src/features/tech-log/presentation/studio/studio-workspace-server-state.ts`
|
||||
- Modify: `src/features/tech-log/presentation/studio/studio-document-server-state.ts`
|
||||
- Modify: `src/features/tech-log/presentation/studio/studio-asset-server-state.ts`
|
||||
- Modify: `src/features/tech-log/presentation/studio/studio-management-server-state.ts`
|
||||
- Test: `tests/features/tech-log/studio-application-boundary.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `createTechLogStudioApplication({ studio, assets, management }): TechLogStudioApplication`
|
||||
- Produces capability properties: `workspaceQueries`, `workspaceCommands`, `documentQueries`, `documentCommands`, `assetQueries`, `assetCommands`, `managementQueries`, `managementCommands`.
|
||||
- Consumes existing DTOs/return types and request/idempotency option types; outbound port types are private factory dependencies only.
|
||||
|
||||
- [ ] **Step 1: Write failing boundary/delegation test**
|
||||
|
||||
Create a focused test that constructs spy-like in-memory gateways, calls representative application capability methods, and asserts delegation. Add static assertions that the public application value has no `documents`, `assets`, or `management` properties.
|
||||
|
||||
- [ ] **Step 2: Run the focused test and verify RED**
|
||||
|
||||
Run under Node 24.11.0:
|
||||
`corepack pnpm exec vitest run tests/features/tech-log/studio-application-boundary.test.ts`
|
||||
Expected: FAIL because `createTechLogStudioApplication` / application-owned capability properties do not exist yet.
|
||||
|
||||
- [ ] **Step 3: Implement minimal application capability API**
|
||||
|
||||
Define application-owned query/command capability types with explicit method signatures copied from current port operations, then implement `createTechLogStudioApplication()` with frozen capability objects delegating to the private gateways.
|
||||
|
||||
- [ ] **Step 4: Wire composition root and server-state**
|
||||
|
||||
Change `create-tech-log-feature-input.ts` to call the factory. Replace all `application.documents/assets/management` extraction in Studio server-state with the corresponding query/command capability object. Do not change component/controller public APIs unless type propagation requires it.
|
||||
|
||||
- [ ] **Step 5: Run focused + type/architecture checks**
|
||||
|
||||
Run:
|
||||
`corepack pnpm exec vitest run tests/features/tech-log/studio-application-boundary.test.ts`
|
||||
`corepack pnpm check:types`
|
||||
`corepack pnpm check:architecture`
|
||||
Expected: PASS.
|
||||
|
||||
### Task 2: TechLog behavioral copy catalog migration and i18n gate
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/features/tech-log/contracts/tech-log-message-catalog.ts`
|
||||
- Modify: affected files under `src/features/tech-log/presentation/studio/**`
|
||||
- Modify: affected files under `src/features/tech-log/presentation/public/**`
|
||||
- Modify: `scripts/check-i18n.ts`
|
||||
- Modify/Create: `tests/unit/i18n-contract.test.ts` and/or `tests/fixtures/i18n/**` as appropriate to the existing checker test harness.
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing `useTechLogCopy()` / locale message interpolation API.
|
||||
- Produces: catalog keys for behavioral notices/failures/public error states and interpolation keys for dynamic deletion announcements.
|
||||
- Produces: targeted TechLog behavioral checker integrated into `check:i18n`.
|
||||
|
||||
- [ ] **Step 1: Add failing i18n checker tests/fixtures**
|
||||
|
||||
Add one forbidden fixture representing a direct TechLog behavioral literal such as `setNotice("삭제했습니다.")` and one allowed fixture representing a heading/field label/domain status literal. Ensure the checker distinguishes them.
|
||||
|
||||
- [ ] **Step 2: Run i18n test/check and verify RED**
|
||||
|
||||
Run `corepack pnpm check:i18n` and the focused i18n unit test command used by `tests/unit/i18n-contract.test.ts`.
|
||||
Expected: the new behavioral negative fixture is not detected yet.
|
||||
|
||||
- [ ] **Step 3: Implement targeted TechLog behavioral scanner**
|
||||
|
||||
Keep the existing common-presentation blanket scan unchanged. Add TechLog presentation files as a separate source set and inspect targeted contexts: static Button action text, action-label props, `setRequestAnnouncement`, `setNotice`, `setSuccess`, failure/error/loading/empty/not-found fallback literals, and public error/retry surfaces. Catalog calls and interpolated message calls must pass. Editorial/domain literals must pass.
|
||||
|
||||
- [ ] **Step 4: Migrate actual behavioral literals**
|
||||
|
||||
Move the currently identified Studio/Public notices/failures/error states into `tech-log-message-catalog.ts` for `ko-KR` and `en-US`. Convert dynamic delete announcements to message interpolation. Preserve rendered Korean strings and existing accessibility names.
|
||||
|
||||
- [ ] **Step 5: Run focused i18n + TechLog tests**
|
||||
|
||||
Run:
|
||||
`corepack pnpm check:i18n`
|
||||
`corepack pnpm test:tech-log`
|
||||
Expected: PASS with zero TechLog behavioral literal violations.
|
||||
|
||||
### Task 3: Final regression and re-review evidence
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/reviews/2026-09-22-tech-log-template-utilization-rereview.md`
|
||||
- Create or update: `docs/reviews/2026-09-23-tech-log-template-utilization-rereview.md`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes Tasks 1-2 outputs.
|
||||
- Produces final 10-item re-review evidence only after fresh verification passes.
|
||||
|
||||
- [ ] **Step 1: Run all required checks under Node 24.11.0**
|
||||
|
||||
Run exactly:
|
||||
`corepack pnpm check:types`
|
||||
`corepack pnpm lint`
|
||||
`corepack pnpm check:architecture`
|
||||
`corepack pnpm check:design-system`
|
||||
`corepack pnpm check:tech-log-contract`
|
||||
`corepack pnpm check:i18n`
|
||||
`corepack pnpm test:tech-log`
|
||||
`corepack pnpm test:component`
|
||||
`corepack pnpm build:app-only`
|
||||
`git diff --check`
|
||||
Expected: all PASS.
|
||||
|
||||
- [ ] **Step 2: Collect static evidence**
|
||||
|
||||
Record counts for application gateway type exposure, presentation gateway port imports, raw gateway extraction, component/controller gateway direct calls, TechLog behavioral literal violations, raw native controls/form/dialog, and controller files.
|
||||
Expected: gateway/i18n/raw DOM violations 0; controllers 5.
|
||||
|
||||
- [ ] **Step 3: Update re-review docs**
|
||||
|
||||
Only after fresh verification, update the review from `완료: 8 / 아직 더 봐야댐: 2` to `완료: 10 / 아직 더 봐야댐: 0`, with actual current test counts and commands.
|
||||
|
||||
- [ ] **Step 4: No commit**
|
||||
|
||||
Do not commit. Preserve the user's existing dirty worktree and report only changed files and fresh verification evidence.
|
||||
@@ -0,0 +1,398 @@
|
||||
# TechLog Application Boundary and Behavioral i18n Design
|
||||
|
||||
## Context
|
||||
|
||||
The 2026-09-23 TechLog frontend re-review re-opened two items that had previously been marked complete:
|
||||
|
||||
1. `TechLogFeatureInput / StudioContext application boundary`
|
||||
2. `behavioral action/error/loading/empty copy i18n`
|
||||
|
||||
The current implementation is otherwise considered complete for the remaining eight review axes. This design intentionally limits scope to these two open items and the regression evidence required to close them.
|
||||
|
||||
The existing worktree contains substantial unrelated user changes. Those changes must be preserved. No reset, checkout, clean, commit, merge, or other destructive Git operation is part of this work.
|
||||
|
||||
## Goals
|
||||
|
||||
### Goal A — Hide outbound gateway ports behind an application-owned API
|
||||
|
||||
`TechLogStudioApplication` must stop exposing `StudioGateway`, `StudioAssetGateway`, and `ManagementGateway` as public properties.
|
||||
|
||||
Presentation server-state code must consume application-owned query/command capabilities instead of extracting raw outbound ports from the application facade.
|
||||
|
||||
### Goal B — Make TechLog behavioral copy verifiably catalog-driven
|
||||
|
||||
Behavioral action, success, error, loading, empty-state, not-found, and validation-facing copy in TechLog presentation must use the TechLog message catalog, including dynamic announcements through interpolation.
|
||||
|
||||
`check:i18n` must include a TechLog-specific behavioral-copy gate so a passing i18n check is actual evidence that these literals are not reintroduced.
|
||||
|
||||
## Non-goals
|
||||
|
||||
This work does not migrate every Korean literal in TechLog presentation into the catalog.
|
||||
|
||||
The following remain intentionally allowed when they are domain/editorial copy rather than behavioral UI copy:
|
||||
|
||||
- headings
|
||||
- long-form explanatory text
|
||||
- help text
|
||||
- field labels
|
||||
- publication/domain status labels
|
||||
- document titles and other content values
|
||||
- dynamic noun-based labels where the noun itself is domain content
|
||||
|
||||
This work does not redesign HTTP, route, design-system, server-state runtime, Taxonomy projection, controller boundaries, or management allowed-value SSOT beyond changes strictly required by the two open review items.
|
||||
|
||||
## Current problem 1 — Application facade leaks outbound ports
|
||||
|
||||
The current public type is effectively:
|
||||
|
||||
```ts
|
||||
export type TechLogStudioApplication = Readonly<{
|
||||
documents: StudioGateway;
|
||||
assets: StudioAssetGateway;
|
||||
management: ManagementGateway;
|
||||
}>;
|
||||
```
|
||||
|
||||
Although `TechLogFeatureInput` and `StudioContextValue` no longer expose three gateway factories directly, server-state code still performs operations such as:
|
||||
|
||||
```ts
|
||||
const { documents: gateway } = useStudioApplication();
|
||||
const gateway = application.assets;
|
||||
```
|
||||
|
||||
This means presentation still receives outbound port objects. The boundary has been renamed but not raised to an application use-case API.
|
||||
|
||||
## Application boundary design
|
||||
|
||||
### Public application shape
|
||||
|
||||
`TechLogStudioApplication` will expose application-owned query and command capabilities, grouped by responsibility rather than by outbound adapter.
|
||||
|
||||
The target shape is:
|
||||
|
||||
```ts
|
||||
export type TechLogStudioApplication = Readonly<{
|
||||
workspaceQueries: StudioWorkspaceQueries;
|
||||
workspaceCommands: StudioWorkspaceCommands;
|
||||
documentQueries: StudioDocumentQueries;
|
||||
documentCommands: StudioDocumentCommands;
|
||||
assetQueries: StudioAssetQueries;
|
||||
assetCommands: StudioAssetCommands;
|
||||
managementQueries: StudioManagementQueries;
|
||||
managementCommands: StudioManagementCommands;
|
||||
}>;
|
||||
```
|
||||
|
||||
The exact grouping follows current server-state responsibilities. The grouping is an application API; none of these exported capability types may alias, extend, or expose `StudioGateway`, `StudioAssetGateway`, or `ManagementGateway`.
|
||||
|
||||
### Capability ownership
|
||||
|
||||
#### `StudioWorkspaceQueries`
|
||||
|
||||
Owns read operations used by dashboard/list/publication/catalog workflows, including the current equivalents of:
|
||||
|
||||
- get dashboard
|
||||
- list documents
|
||||
- list publications
|
||||
- get publication snapshot
|
||||
- get catalog
|
||||
|
||||
#### `StudioWorkspaceCommands`
|
||||
|
||||
Owns workspace-level mutations currently used outside the document editor lifecycle, including the current equivalents of:
|
||||
|
||||
- create document
|
||||
- unpublish publication
|
||||
|
||||
#### `StudioDocumentQueries`
|
||||
|
||||
Owns document-editor reads:
|
||||
|
||||
- get document
|
||||
- get current preview
|
||||
|
||||
#### `StudioDocumentCommands`
|
||||
|
||||
Owns document-editor mutations:
|
||||
|
||||
- save document
|
||||
- validate document
|
||||
- create preview
|
||||
- publish document
|
||||
|
||||
#### `StudioAssetQueries`
|
||||
|
||||
Owns asset reads:
|
||||
|
||||
- list assets
|
||||
- get asset
|
||||
|
||||
#### `StudioAssetCommands`
|
||||
|
||||
Owns asset mutations:
|
||||
|
||||
- upload asset
|
||||
- update asset metadata
|
||||
- delete asset
|
||||
|
||||
#### `StudioManagementQueries` and `StudioManagementCommands`
|
||||
|
||||
Expose the management read/write operations currently consumed by `studio-management-server-state.ts`, grouped by query versus mutation ownership.
|
||||
|
||||
The public application contract can preserve current command/query DTOs and return values where they already represent application-level concepts. The requirement is specifically that the outbound gateway interfaces themselves are hidden.
|
||||
|
||||
### Factory
|
||||
|
||||
A dedicated application factory will own outbound ports as private dependencies:
|
||||
|
||||
```ts
|
||||
export function createTechLogStudioApplication(dependencies: Readonly<{
|
||||
studio: StudioGateway;
|
||||
assets: StudioAssetGateway;
|
||||
management: ManagementGateway;
|
||||
}>): TechLogStudioApplication
|
||||
```
|
||||
|
||||
The implementation will build frozen capability objects whose methods delegate to the private dependencies.
|
||||
|
||||
`create-tech-log-feature-input.ts` will construct the three adapters as it does today and pass them into `createTechLogStudioApplication(...)`. It will no longer construct an object literal that exposes the gateways.
|
||||
|
||||
### Presentation integration
|
||||
|
||||
`StudioContextValue` continues to expose one `studioApplication` value.
|
||||
|
||||
Server-state modules will switch from raw port extraction:
|
||||
|
||||
```ts
|
||||
application.documents
|
||||
application.assets
|
||||
application.management
|
||||
```
|
||||
|
||||
to application capabilities:
|
||||
|
||||
```ts
|
||||
application.workspaceQueries
|
||||
application.workspaceCommands
|
||||
application.documentQueries
|
||||
application.documentCommands
|
||||
application.assetQueries
|
||||
application.assetCommands
|
||||
application.managementQueries
|
||||
application.managementCommands
|
||||
```
|
||||
|
||||
Components and controllers continue to consume server-state hooks and must not gain direct application capability orchestration that belongs in server-state.
|
||||
|
||||
### Boundary invariants
|
||||
|
||||
The final implementation must satisfy all of these:
|
||||
|
||||
```text
|
||||
TechLogStudioApplication references to *Gateway public property types = 0
|
||||
presentation imports from application/ports/*gateway* = 0
|
||||
presentation raw .documents/.assets/.management application extraction = 0
|
||||
component gateway direct calls = 0
|
||||
controller gateway direct calls = 0
|
||||
```
|
||||
|
||||
Outbound gateway types may remain in adapter/application implementation files where dependency inversion requires them.
|
||||
|
||||
## Current problem 2 — Behavioral i18n has feature-level blind spots
|
||||
|
||||
The TechLog catalog already contains many action/state/failure keys, but direct behavioral literals remain in presentation.
|
||||
|
||||
Observed examples include:
|
||||
|
||||
```text
|
||||
저장하지 못했습니다. 다시 시도해 주세요.
|
||||
검증하지 못했습니다. 다시 시도해 주세요.
|
||||
Public Preview를 만들지 못했습니다. 다시 시도해 주세요.
|
||||
게시하지 못했습니다. 다시 시도해 주세요.
|
||||
게시했습니다.
|
||||
홈에 표시할 항목을 저장했습니다.
|
||||
보관했습니다.
|
||||
삭제했습니다.
|
||||
대체 텍스트를 저장했습니다.
|
||||
페이지를 찾을 수 없습니다.
|
||||
최근 기록을 불러오지 못했습니다.
|
||||
페이지를 불러오지 못했습니다.
|
||||
```
|
||||
|
||||
Dynamic announcements also remain, for example deletion messages containing release, variant, document, topic, or project names.
|
||||
|
||||
The current `scripts/check-i18n.ts` hardcoded-locale scan checks shared `src/presentation/*` directories but not `src/features/tech-log/presentation`, so `check:i18n=PASS` does not prove TechLog behavioral-copy completeness.
|
||||
|
||||
## Behavioral i18n design
|
||||
|
||||
### Catalog migration
|
||||
|
||||
Behavioral literals will move into `tech-log-message-catalog.ts` for both `ko-KR` and `en-US`.
|
||||
|
||||
Static messages use ordinary keys, for example:
|
||||
|
||||
```text
|
||||
techLog.notice.published
|
||||
techLog.notice.homeFocusSaved
|
||||
techLog.notice.assetArchived
|
||||
techLog.notice.assetDeleted
|
||||
techLog.notice.assetAltTextSaved
|
||||
techLog.failure.saveRetry
|
||||
techLog.failure.validationRetry
|
||||
techLog.failure.previewRetry
|
||||
techLog.failure.publishRetry
|
||||
techLog.public.notFound
|
||||
techLog.public.latestLoadFailed
|
||||
techLog.public.pageLoadFailed
|
||||
```
|
||||
|
||||
Existing semantically equivalent keys must be reused instead of duplicated.
|
||||
|
||||
### Interpolated announcements
|
||||
|
||||
Dynamic success/announcement copy must use interpolation parameters rather than template literals in presentation.
|
||||
|
||||
Representative target pattern:
|
||||
|
||||
```ts
|
||||
copy("techLog.notice.documentDeleted", {
|
||||
title: item.title || copy("techLog.state.untitled"),
|
||||
});
|
||||
```
|
||||
|
||||
with matching locale entries such as:
|
||||
|
||||
```text
|
||||
ko-KR: 작업본 {title} 을(를) 삭제했습니다.
|
||||
en-US: Deleted working copy {title}.
|
||||
```
|
||||
|
||||
The exact key naming may follow the existing catalog organization, but interpolation parameter names must match across locales and continue to pass the existing catalog interpolation contract check.
|
||||
|
||||
### TechLog-specific i18n gate
|
||||
|
||||
`check-i18n.ts` will keep the existing blanket common-presentation scan unchanged for shared UI.
|
||||
|
||||
TechLog presentation will be added through a separate behavioral rule set, not through the blanket Korean-literal regex. This avoids falsely rejecting allowed domain/editorial Korean copy.
|
||||
|
||||
The TechLog behavioral gate must detect direct user-facing behavioral literals in at least these contexts:
|
||||
|
||||
- static `Button` action text
|
||||
- action-like props such as `pendingLabel`, `closeLabel`, `resetLabel`, and similar control labels
|
||||
- `setRequestAnnouncement("...")`
|
||||
- `setNotice("...")`
|
||||
- `setSuccess("...")`
|
||||
- direct fallback strings used for error/failure/loading/empty/not-found behavior
|
||||
- direct behavioral literals in public error/empty/retry surfaces
|
||||
|
||||
The rule must permit catalog calls and interpolated message calls.
|
||||
|
||||
The gate should be implemented as a targeted source checker rather than a blanket ban on Korean literals under the whole feature directory.
|
||||
|
||||
### Gate testability
|
||||
|
||||
The checker must have negative fixtures or equivalent explicit test inputs demonstrating that it fails for representative TechLog behavioral literals and does not fail for allowed domain/editorial copy.
|
||||
|
||||
At minimum, fixture coverage must pin these two distinctions:
|
||||
|
||||
1. a direct behavioral announcement/action literal fails;
|
||||
2. a heading/field-label/domain-status literal is allowed.
|
||||
|
||||
## Compatibility requirements
|
||||
|
||||
The refactor must not intentionally change visible Korean copy or accessibility names unless an existing copy contract is already inconsistent.
|
||||
|
||||
If moving a string to the catalog would change punctuation, ellipsis, spacing, or an accessible button name, preserve the existing rendered value with a dedicated key rather than changing tests to accept the new copy.
|
||||
|
||||
The existing `저장 중` versus `저장 중…` regression is the precedent: preserve the concrete UI contract and represent distinct copy as distinct keys when necessary.
|
||||
|
||||
## Test strategy
|
||||
|
||||
### Application boundary tests
|
||||
|
||||
Add or update focused tests that prove the application factory delegates through application-owned capabilities without exposing outbound ports.
|
||||
|
||||
Static architecture checks must prove:
|
||||
|
||||
```text
|
||||
TechLogStudioApplication public gateway type exposure = 0
|
||||
presentation raw gateway extraction = 0
|
||||
presentation gateway port imports = 0
|
||||
```
|
||||
|
||||
Existing server-state behavior tests should continue to pass unchanged where observable behavior has not changed.
|
||||
|
||||
### i18n tests
|
||||
|
||||
Add or update checker fixtures/tests so `check:i18n` fails when TechLog behavioral literals are introduced into guarded contexts.
|
||||
|
||||
Catalog interpolation parity across locales must remain enforced.
|
||||
|
||||
### Full regression
|
||||
|
||||
Use Node 24.11.0 without changing repository configuration and run:
|
||||
|
||||
```text
|
||||
corepack pnpm check:types
|
||||
corepack pnpm lint
|
||||
corepack pnpm check:architecture
|
||||
corepack pnpm check:design-system
|
||||
corepack pnpm check:tech-log-contract
|
||||
corepack pnpm check:i18n
|
||||
corepack pnpm test:tech-log
|
||||
corepack pnpm test:component
|
||||
corepack pnpm build:app-only
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Expected baseline:
|
||||
|
||||
```text
|
||||
TechLog: 60 files / 416 tests PASS
|
||||
Component: 27 files / 154 tests PASS
|
||||
```
|
||||
|
||||
If test counts change because new focused tests are added, the new larger counts become the final evidence.
|
||||
|
||||
## Final static evidence
|
||||
|
||||
The re-review is complete only when all final evidence is collected from the current worktree:
|
||||
|
||||
```text
|
||||
application gateway type exposure = 0
|
||||
presentation gateway port import = 0
|
||||
presentation raw gateway extraction = 0
|
||||
component/controller gateway direct call = 0
|
||||
behavioral literal violations = 0
|
||||
raw native control = 0
|
||||
raw form = 0
|
||||
raw dialog = 0
|
||||
controller files = 5
|
||||
```
|
||||
|
||||
## Completion criteria
|
||||
|
||||
The two re-opened review axes can be marked complete only when:
|
||||
|
||||
1. `TechLogStudioApplication` exposes application-owned query/command capabilities and no raw outbound gateway object;
|
||||
2. Studio/Public behavioral literals are catalog-driven, including dynamic announcements;
|
||||
3. `check:i18n` actively checks TechLog feature presentation behavioral copy;
|
||||
4. targeted i18n gate tests/fixtures demonstrate the rule catches regressions without blanket-rejecting domain/editorial copy;
|
||||
5. Node 24 full regression passes;
|
||||
6. final static evidence reports zero violations for the application-boundary and behavioral-i18n criteria.
|
||||
|
||||
At that point the 2026-09-23 re-review may move from:
|
||||
|
||||
```text
|
||||
완료: 8
|
||||
아직 더 봐야댐: 2
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```text
|
||||
완료: 10
|
||||
아직 더 봐야댐: 0
|
||||
```
|
||||
|
||||
No completion claim is allowed before those checks pass.
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
"preview": "node dist/server.mjs",
|
||||
"verify:tech-log-source-parity": "node tests/support/browser/verify-tech-log-source-parity.ts",
|
||||
"lint": "eslint src scripts tests recipes .storybook vite.config.ts vitest.config.ts playwright*.config.ts --max-warnings=0",
|
||||
"check:architecture": "node scripts/check-architecture.ts",
|
||||
"check:architecture": "node scripts/check-architecture.ts && node scripts/check-tech-log-route-literals.ts",
|
||||
"check:design-system": "node scripts/check-design-system.ts",
|
||||
"check:design-system:fixture": "node scripts/check-design-system.ts --fixture",
|
||||
"check:i18n": "node scripts/check-i18n.ts",
|
||||
|
||||
@@ -38,12 +38,12 @@
|
||||
},
|
||||
"contractSet": {
|
||||
"setAlgorithm": "CA_CONTRACT_SET_V1",
|
||||
"setDigest": "sha256:bc0766de75feb10ebc689402840def8689d4653f10d3c42cfbe5f553c7844890",
|
||||
"setDigest": "sha256:814aa5919d81b699adc0727ebb2d39ab422df5ac9388be3284243fff7cb92f0c",
|
||||
"packages": [
|
||||
{
|
||||
"packageId": "@tech-log/management-contract",
|
||||
"version": "1.0.0",
|
||||
"digest": "sha256:0c226600c45b06433480a8a2ef3d812480dce3850c333bfcab5f626143ce77ea",
|
||||
"digest": "sha256:6036a41879ccf161ba3b7db184be3897684c19e8890f3446460293f1f1f7ab3d",
|
||||
"runtimeProtocolVersion": 1,
|
||||
"sourceRevision": "a0dac96"
|
||||
},
|
||||
|
||||
@@ -82,11 +82,16 @@ async function listSourceFiles(directory: string): Promise<string[]> {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const target = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
|
||||
else if (/\.(?:ts|tsx|mts|cts)$/.test(entry.name)) result.push(target);
|
||||
else if (/\.(?:ts|tsx|mts|cts|css)$/.test(entry.name)) result.push(target);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const rawPaletteSourceFiles = new Set([
|
||||
...Object.values(tokenFiles),
|
||||
"src/features/tech-log/presentation/styles/tech-log-theme.css",
|
||||
]);
|
||||
|
||||
const sources = fixtureMode
|
||||
? await listSourceFiles("tests/fixtures/design-system/forbidden")
|
||||
: await listSourceFiles("src");
|
||||
@@ -109,7 +114,7 @@ for (const file of sources) {
|
||||
failures.push(`design-system deep import in ${file}`);
|
||||
}
|
||||
if (
|
||||
!file.includes("src/presentation/design-system/tokens/") &&
|
||||
!rawPaletteSourceFiles.has(file) &&
|
||||
containsRawPaletteValue(source)
|
||||
) {
|
||||
failures.push(`raw palette value in ${file}`);
|
||||
|
||||
+23
-2
@@ -2,6 +2,7 @@ import { mkdir, readFile, readdir } from "node:fs/promises";
|
||||
|
||||
import { i18nReportArtifactSchema } from "./contracts/release-artifacts.ts";
|
||||
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
import { findTechLogBehavioralLiteralViolations } from "./lib/tech-log-i18n-policy.ts";
|
||||
import path from "node:path";
|
||||
|
||||
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
|
||||
@@ -61,13 +62,17 @@ const commonDirectories = [
|
||||
"src/presentation/routes",
|
||||
"src/presentation/templates",
|
||||
];
|
||||
const sources = fixtureMode
|
||||
const commonSources = fixtureMode
|
||||
? await listSourceFiles("tests/fixtures/i18n/forbidden")
|
||||
: (
|
||||
await Promise.all(commonDirectories.map((directory) => listSourceFiles(directory)))
|
||||
).flat();
|
||||
const techLogSources = fixtureMode
|
||||
? []
|
||||
: await listSourceFiles("src/features/tech-log/presentation");
|
||||
const sources = [...commonSources, ...techLogSources];
|
||||
|
||||
for (const file of sources) {
|
||||
for (const file of commonSources) {
|
||||
const source = await readFile(file, "utf8");
|
||||
if (koreanLiteral.test(source)) {
|
||||
failures.push(`hardcoded common user-facing locale literal in ${file}`);
|
||||
@@ -80,6 +85,22 @@ for (const file of sources) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (const file of techLogSources) {
|
||||
const source = await readFile(file, "utf8");
|
||||
for (const violation of findTechLogBehavioralLiteralViolations(source)) {
|
||||
failures.push(
|
||||
`hardcoded TechLog behavioral locale literal in ${file}:${violation.kind}:${violation.text}`,
|
||||
);
|
||||
}
|
||||
if (rawFailureRender.test(source)) {
|
||||
failures.push(`raw backend/error message rendered in ${file}`);
|
||||
}
|
||||
if (source.includes("dangerouslySetInnerHTML")) {
|
||||
failures.push(`untrusted HTML interpolation boundary in ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
const report = i18nReportArtifactSchema.parse({
|
||||
schemaVersion: 1,
|
||||
mode: fixtureMode ? "negative-fixture" : "source",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { TECH_LOG_ROUTE_REGISTRY } from "../src/features/tech-log/contracts/tech-log-route-contract.ts";
|
||||
|
||||
const ROOT = path.resolve("src/features/tech-log/presentation");
|
||||
const EXTENSIONS = new Set([".ts", ".tsx"]);
|
||||
const TECH_LOG_ROUTE_ROOTS = new Set(
|
||||
Object.values(TECH_LOG_ROUTE_REGISTRY)
|
||||
.map(({ path: routePath }) => /^\/([^/:*]+)/.exec(routePath)?.[1])
|
||||
.filter((segment): segment is string => Boolean(segment)),
|
||||
);
|
||||
|
||||
type RouteLiteralViolation = Readonly<{
|
||||
file: string;
|
||||
line: number;
|
||||
value: string;
|
||||
}>;
|
||||
|
||||
const violations: RouteLiteralViolation[] = [];
|
||||
|
||||
function visitFile(filePath: string): void {
|
||||
const source = fs.readFileSync(filePath, "utf8");
|
||||
const withoutComments = source
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
.replace(/\/\/.*$/gm, "");
|
||||
// Only strings beginning with a real TechLog route family are forbidden.
|
||||
// Media paths (/media/...), Markdown command examples (/problem, /context),
|
||||
// generated metadata paths, etc. are slash-prefixed strings too, but they
|
||||
// are not navigation URLs and must not be classified as route duplication.
|
||||
const pattern = /(["'`])(\/([A-Za-z0-9-]+))(?=[/?#"'`])/g;
|
||||
for (const match of withoutComments.matchAll(pattern)) {
|
||||
const routeRoot = match[3];
|
||||
if (!routeRoot || !TECH_LOG_ROUTE_ROOTS.has(routeRoot)) continue;
|
||||
|
||||
const before = withoutComments.slice(0, match.index ?? 0);
|
||||
const line = before.split("\n").length;
|
||||
violations.push({
|
||||
file: path.relative(process.cwd(), filePath),
|
||||
line,
|
||||
value: match[2] ?? match[0],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function walk(directory: string): void {
|
||||
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
||||
const filePath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) walk(filePath);
|
||||
else if (EXTENSIONS.has(path.extname(entry.name))) visitFile(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
walk(ROOT);
|
||||
|
||||
if (violations.length > 0) {
|
||||
console.error("TechLog route source-of-truth check failed.");
|
||||
console.error("Build internal TechLog URLs through publicRoutes/studioRoutes instead of presentation literals.");
|
||||
for (const violation of violations) {
|
||||
console.error(`- ${violation.file}:${violation.line} ${JSON.stringify(violation.value)}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("TechLog route source-of-truth: PASS");
|
||||
@@ -0,0 +1,75 @@
|
||||
export type TechLogBehavioralLiteralViolation = Readonly<{
|
||||
kind: string;
|
||||
index: number;
|
||||
text: string;
|
||||
}>;
|
||||
|
||||
const korean = /[가-힣]/;
|
||||
const behavioralState =
|
||||
/(다시 시도|찾을 수 없|불러오지 못|못했습니다|만들지 못|없습니다|저장했습니다|삭제했습니다|게시했습니다|보관했습니다|저장 중|처리 중|불러오는 중|검증 중|생성 중|업로드 중|준비하고 있습니다)/;
|
||||
|
||||
function add(
|
||||
violations: TechLogBehavioralLiteralViolation[],
|
||||
kind: string,
|
||||
index: number,
|
||||
text: string,
|
||||
): void {
|
||||
const normalized = text.trim();
|
||||
if (!korean.test(normalized)) return;
|
||||
violations.push(Object.freeze({ kind, index, text: normalized }));
|
||||
}
|
||||
|
||||
function literalBody(match: RegExpMatchArray, bodyIndex: number): string {
|
||||
return match[bodyIndex] ?? "";
|
||||
}
|
||||
|
||||
export function findTechLogBehavioralLiteralViolations(
|
||||
source: string,
|
||||
): readonly TechLogBehavioralLiteralViolation[] {
|
||||
const violations: TechLogBehavioralLiteralViolation[] = [];
|
||||
|
||||
for (const match of source.matchAll(
|
||||
/(?:\b[A-Za-z_$][\w$]*\.)?(?:setRequestAnnouncement|setNotice|setSuccess)\(\s*(["'`])([\s\S]*?)\1\s*\)/g,
|
||||
)) {
|
||||
const body = literalBody(match, 2);
|
||||
add(violations, "announcement", match.index ?? 0, body);
|
||||
}
|
||||
|
||||
for (const match of source.matchAll(
|
||||
/\b(?:pendingLabel|closeLabel|resetLabel|clearLabel|actionLabel|confirmLabel)\s*=\s*(["'`])([\s\S]*?)\1/g,
|
||||
)) {
|
||||
const body = literalBody(match, 2);
|
||||
add(violations, "action-prop", match.index ?? 0, body);
|
||||
}
|
||||
|
||||
for (const match of source.matchAll(/<(Button|Link)\b[^>]*>\s*([^<{][^<{}]*?)\s*<\/\1>/g)) {
|
||||
add(violations, "action-text", match.index ?? 0, match[2] ?? "");
|
||||
}
|
||||
|
||||
for (const match of source.matchAll(
|
||||
/(?:studioFailureMessage|managementFailureMessage)\([\s\S]{0,600}?,\s*(["'`])([\s\S]*?)\1\s*\)/g,
|
||||
)) {
|
||||
const body = literalBody(match, 2);
|
||||
add(violations, "failure-fallback", match.index ?? 0, body);
|
||||
}
|
||||
|
||||
for (const match of source.matchAll(
|
||||
/<(h1|h2|h3|p|span)\b[^>]*>\s*([^<{][^<{}]*[가-힣][^<{}]*)\s*<\/\1>/g,
|
||||
)) {
|
||||
const body = (match[2] ?? "").trim();
|
||||
if (behavioralState.test(body)) {
|
||||
add(violations, "behavioral-surface", match.index ?? 0, body);
|
||||
}
|
||||
}
|
||||
|
||||
for (const match of source.matchAll(
|
||||
/\b(?:title|description|message|empty|emptyLabel|error|errorLabel|loading|loadingLabel)\s*=\s*(["'`])([^"'`\n]*[가-힣][^"'`\n]*)\1/g,
|
||||
)) {
|
||||
const body = match[2] ?? "";
|
||||
if (behavioralState.test(body)) {
|
||||
add(violations, "behavioral-prop", match.index ?? 0, body);
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze(violations);
|
||||
}
|
||||
@@ -71,6 +71,7 @@ export type InstalledHttpOperationExecutor = Readonly<{
|
||||
export type FeatureHttpProblemMapping = Readonly<{
|
||||
kind: FailureKind;
|
||||
code: string;
|
||||
detail?: string;
|
||||
}>;
|
||||
|
||||
type FeatureHttpOperationSpec<
|
||||
@@ -306,7 +307,11 @@ function projectExecutionOutcome<WireOutput, Problem, Value>(
|
||||
mapped?.kind ?? kindForStatus(outcome.metadata.status),
|
||||
operationId,
|
||||
mapped?.code ?? "CONTRACT_PROBLEM",
|
||||
{ httpStatus: outcome.metadata.status, effect: outcome.effect },
|
||||
{
|
||||
...(mapped?.detail === undefined ? {} : { detail: mapped.detail }),
|
||||
httpStatus: outcome.metadata.status,
|
||||
effect: outcome.effect,
|
||||
},
|
||||
);
|
||||
}
|
||||
case "UNAUTHENTICATED":
|
||||
@@ -388,6 +393,7 @@ function failure(
|
||||
operationId: string,
|
||||
code: string,
|
||||
details: Readonly<{
|
||||
detail?: string;
|
||||
httpStatus?: number;
|
||||
retryAfterMs?: number;
|
||||
effect?: FailureEffectCertainty;
|
||||
|
||||
@@ -80,10 +80,11 @@ export type AsyncState = Readonly<{
|
||||
}>;
|
||||
|
||||
export function deriveAsyncState(signals: AsyncSignals): AsyncState {
|
||||
const hasData = signals.data !== undefined && signals.data !== null;
|
||||
const hasData = signals.data !== undefined;
|
||||
const empty =
|
||||
hasData &&
|
||||
((Array.isArray(signals.data) && signals.data.length === 0) ||
|
||||
(signals.data === null ||
|
||||
(Array.isArray(signals.data) && signals.data.length === 0) ||
|
||||
signals.data === "");
|
||||
|
||||
const base =
|
||||
|
||||
@@ -5,6 +5,8 @@ import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"
|
||||
import "pretendard/dist/web/variable/pretendardvariable.css";
|
||||
import "@fontsource/ibm-plex-mono/400.css";
|
||||
import "@fontsource/ibm-plex-mono/500.css";
|
||||
import "../presentation/styles/theme.css";
|
||||
import "../features/tech-log/presentation/styles/tech-log-theme.css";
|
||||
import "../features/tech-log/presentation/styles/globals.css";
|
||||
import "../features/tech-log/presentation/styles/studio.css";
|
||||
import "../features/tech-log/presentation/styles/studio-editor.css";
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
attachStudioSessionCredentials,
|
||||
invalidateTechLogCsrfOnOutcome,
|
||||
} from "../features/tech-log/adapters/http/studio-session-credentials.ts";
|
||||
import type { StudioOperationExecutor as TechLogStudioOperationExecutor } from "../features/tech-log/adapters/http/http-studio-gateway.ts";
|
||||
import type { AuthSessionPort } from "../application/ports/auth-session-port.ts";
|
||||
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
|
||||
import {
|
||||
@@ -41,7 +40,6 @@ import {
|
||||
INSTALLED_REST_AUTH_PROFILES,
|
||||
} from "../contracts/rest-profiles.ts";
|
||||
import type { ClockPort } from "../application/ports/clock-port.ts";
|
||||
import type { MutationIntent } from "../contracts/mutation-intent.ts";
|
||||
import { createInstalledFeatureInputs } from "../features/installed-feature-adapters.ts";
|
||||
import {
|
||||
INVALIDATION_REGISTRY,
|
||||
@@ -64,6 +62,7 @@ import {
|
||||
import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts";
|
||||
import { createServerStateGenerationStore } from "./server-state-generation-store.ts";
|
||||
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../features/installed-contract-contributions.ts";
|
||||
import { TECH_LOG_STUDIO_SESSION_CONTRACT } from "../features/tech-log/contracts/tech-log-studio-contract-contribution.ts";
|
||||
import {
|
||||
indexInvalidationRegistry,
|
||||
indexInvalidationTopicVersions,
|
||||
@@ -452,10 +451,10 @@ export async function createRuntimeAdapters(
|
||||
* entirely and must set the header itself. If each built its own provider,
|
||||
* one Studio session would hold two different tokens.
|
||||
*
|
||||
* `execute` calls `getStudioSession` through `techLogOperations`, which is
|
||||
* `execute` calls `getStudioSession` through `contractOperations`, which is
|
||||
* assigned further below — a real ordering hazard, since `attachCredentials`
|
||||
* (needed to build `contractHttp`, needed to build `contractOperations`,
|
||||
* needed to build `techLogOperations`) needs this provider first.
|
||||
* needed to build `contractOperations`) needs this provider first.
|
||||
*
|
||||
* Fix round 1 (C1). The original comment here claimed "`getStudioSession`
|
||||
* is a SAFE operation and needs no CSRF, so there is no true cycle" — that
|
||||
@@ -478,18 +477,18 @@ export async function createRuntimeAdapters(
|
||||
* `await` between this declaration and the real assignment, where a stub
|
||||
* fails loudly instead.
|
||||
*/
|
||||
let techLogOperations: TechLogStudioOperationExecutor = Object.freeze({
|
||||
let contractOperations: InstalledHttpOperationExecutor = Object.freeze({
|
||||
async execute() {
|
||||
throw new Error(
|
||||
"techLogOperations used before assignment in createRuntimeAdapters — " +
|
||||
"contractOperations used before assignment in createRuntimeAdapters — " +
|
||||
"construction order regressed.",
|
||||
);
|
||||
},
|
||||
});
|
||||
const techLogCsrf = createCsrfTokenProvider({
|
||||
async execute(options) {
|
||||
const outcome = await techLogOperations.execute(
|
||||
"getStudioSession",
|
||||
const outcome = await contractOperations.execute(
|
||||
TECH_LOG_STUDIO_SESSION_CONTRACT,
|
||||
{},
|
||||
{
|
||||
routeId: "TECH_LOG_STUDIO",
|
||||
@@ -499,8 +498,14 @@ export async function createRuntimeAdapters(
|
||||
if (outcome.kind !== "SUCCESS") {
|
||||
throw new Error("studio session is unavailable");
|
||||
}
|
||||
const value = outcome.value as { csrfToken: string; csrfHeaderName: string };
|
||||
return { csrfToken: value.csrfToken, csrfHeaderName: value.csrfHeaderName };
|
||||
const value = outcome.value as {
|
||||
csrfToken: string;
|
||||
csrfHeaderName: string;
|
||||
};
|
||||
return {
|
||||
csrfToken: value.csrfToken,
|
||||
csrfHeaderName: value.csrfHeaderName,
|
||||
};
|
||||
},
|
||||
});
|
||||
const contractHttp = createContractHttpExecutor({
|
||||
@@ -570,7 +575,7 @@ export async function createRuntimeAdapters(
|
||||
},
|
||||
observe: createHttpObservationProjector({ diagnostics, telemetry }),
|
||||
});
|
||||
const contractOperations: InstalledHttpOperationExecutor = Object.freeze({
|
||||
contractOperations = Object.freeze({
|
||||
async execute(operation, input, executionContext) {
|
||||
const installed =
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(
|
||||
@@ -622,52 +627,8 @@ export async function createRuntimeAdapters(
|
||||
return outcome;
|
||||
},
|
||||
});
|
||||
/**
|
||||
* Template sync (ebea300). The platform executor above now takes the
|
||||
* installed contract itself, so a feature's Input/WireOutput/Problem types
|
||||
* flow through `createFeatureHttpBinding`. TechLog's four HTTP gateways
|
||||
* still address operations by id through its own `StudioOperationExecutor`,
|
||||
* so the id is resolved to the installed contract here — at the one place
|
||||
* that already owns the registry — instead of being resolved inside the
|
||||
* platform executor for every caller. Porting those gateways onto the typed
|
||||
* binding is its own change; nothing about it is decided here.
|
||||
*
|
||||
* `!installed` returns the same `FINAL_REQUEST_INVARIANT_FAILED` violation
|
||||
* the platform executor returns for an operation that is not installed, so
|
||||
* an unregistered id fails identically on both paths.
|
||||
*/
|
||||
techLogOperations = Object.freeze({
|
||||
async execute(
|
||||
operationId: string,
|
||||
input: unknown,
|
||||
executionContext: Readonly<{
|
||||
routeId: string;
|
||||
signal?: AbortSignal;
|
||||
intent?: MutationIntent;
|
||||
}>,
|
||||
) {
|
||||
const installed =
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(operationId);
|
||||
if (!installed) {
|
||||
return Object.freeze({
|
||||
kind: "CONTRACT_VIOLATION" as const,
|
||||
effect: "NOT_STARTED" as const,
|
||||
violation: Object.freeze({
|
||||
kind: "FINAL_REQUEST_INVARIANT_FAILED" as const,
|
||||
operation: "REQUEST" as const,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return contractOperations.execute(
|
||||
installed as Parameters<typeof contractOperations.execute>[0],
|
||||
input,
|
||||
executionContext,
|
||||
);
|
||||
},
|
||||
});
|
||||
const featureInputs = createInstalledFeatureInputs({
|
||||
http: contractOperations,
|
||||
contractOperations: techLogOperations,
|
||||
studioSource: config.TECH_LOG_STUDIO_SOURCE,
|
||||
publicSource: config.TECH_LOG_PUBLIC_SOURCE,
|
||||
apiBaseUrl: config.API_BASE_URL,
|
||||
|
||||
@@ -238,6 +238,7 @@ export type FailureEffectCertainty =
|
||||
export type AppFailure = Readonly<{
|
||||
kind: FailureKind;
|
||||
code: string;
|
||||
detail?: string;
|
||||
httpStatus?: number;
|
||||
retryable: boolean;
|
||||
operationId: string;
|
||||
@@ -261,6 +262,7 @@ export type ApiFailure = AppFailure;
|
||||
|
||||
export type FailureDetails = Readonly<{
|
||||
code?: string;
|
||||
detail?: string;
|
||||
httpStatus?: number;
|
||||
requestId?: string;
|
||||
traceId?: string;
|
||||
@@ -280,6 +282,9 @@ export function createFailure(
|
||||
return Object.freeze({
|
||||
kind: definition.kind,
|
||||
code: typeof details.code === "string" ? details.code : definition.kind,
|
||||
...(typeof details.detail === "string" && details.detail.length > 0
|
||||
? { detail: details.detail.slice(0, 5_000) }
|
||||
: {}),
|
||||
retryable:
|
||||
details.effect === "MAYBE_APPLIED" ||
|
||||
details.effect === "APPLIED_CONFIRMED"
|
||||
|
||||
@@ -239,6 +239,11 @@ export type BoundMutation<Input, Value> = Readonly<{
|
||||
owner: string;
|
||||
duplicatePolicy: MutationDuplicatePolicy;
|
||||
scope: CacheScopeSnapshot;
|
||||
/**
|
||||
* Projects a transport input to a canonical, serializable command identity.
|
||||
* Use this when the transport payload contains host objects such as File.
|
||||
*/
|
||||
identity?: (input: Input) => unknown;
|
||||
execute(
|
||||
input: Input,
|
||||
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
|
||||
|
||||
@@ -3,12 +3,12 @@ import {
|
||||
type TechLogFeatureInput,
|
||||
} from "../application/tech-log-feature-input.ts";
|
||||
import type { Asset } from "../contracts/studio/contract.ts";
|
||||
import { createTechLogStudioApplication } from "../application/studio-application.ts";
|
||||
import type { InstalledHttpOperationExecutor } from "../../../adapters/http/index.ts";
|
||||
import { createTechLogHttpBinding } from "./http/tech-log-http-binding.ts";
|
||||
import { createAssetUploadTransport } from "./http/asset-upload-transport.ts";
|
||||
import { createHttpStudioAssetGateway } from "./http/http-studio-asset-gateway.ts";
|
||||
import {
|
||||
createHttpStudioGateway,
|
||||
type StudioOperationExecutor,
|
||||
} from "./http/http-studio-gateway.ts";
|
||||
import { createHttpStudioGateway } from "./http/http-studio-gateway.ts";
|
||||
import type { CsrfTokenProvider } from "./http/studio-session-csrf.ts";
|
||||
import { createMockStudioAssetGateway } from "./mock/mock-studio-asset-gateway.ts";
|
||||
import { createMockStudioGateway } from "./mock/mock-studio-gateway.ts";
|
||||
@@ -30,7 +30,7 @@ import { publicContentQueries } from "./static/public-query.ts";
|
||||
export type TechLogInstallContext = Readonly<{
|
||||
studioSource: "MOCK" | "HTTP";
|
||||
publicSource: "MOCK" | "HTTP";
|
||||
contractOperations: StudioOperationExecutor;
|
||||
http: InstalledHttpOperationExecutor;
|
||||
apiBaseUrl: string;
|
||||
requestTimeoutMs: number;
|
||||
csrf: CsrfTokenProvider;
|
||||
@@ -51,12 +51,14 @@ export function createTechLogFeatureInstalledInput(
|
||||
// lifetime — shares it, the same way a real backend's asset store outlives
|
||||
// any one editing session. It is never read on the HTTP branch.
|
||||
const mockAssets = new Map<string, Asset>();
|
||||
const http = createTechLogHttpBinding(context.http);
|
||||
|
||||
|
||||
const createStudioAssetGateway = () =>
|
||||
context.studioSource === "MOCK"
|
||||
? createMockStudioAssetGateway(mockAssets)
|
||||
: createHttpStudioAssetGateway({
|
||||
operations: context.contractOperations,
|
||||
http,
|
||||
csrf: context.csrf,
|
||||
upload: createAssetUploadTransport({
|
||||
baseUrl: context.apiBaseUrl,
|
||||
@@ -67,7 +69,7 @@ export function createTechLogFeatureInstalledInput(
|
||||
const createStudioGateway = () =>
|
||||
context.studioSource === "MOCK"
|
||||
? createMockStudioGateway({ assets: mockAssets })
|
||||
: createHttpStudioGateway({ operations: context.contractOperations });
|
||||
: createHttpStudioGateway({ http });
|
||||
|
||||
// The public read source switches independently of Studio: the two are
|
||||
// different services, and the combination that matters today is an authoring
|
||||
@@ -75,16 +77,21 @@ export function createTechLogFeatureInstalledInput(
|
||||
const publicContent =
|
||||
context.publicSource === "MOCK"
|
||||
? publicContentQueries
|
||||
: createHttpPublicContentGateway({ operations: context.contractOperations });
|
||||
: createHttpPublicContentGateway({ http });
|
||||
|
||||
const createManagementGateway = () =>
|
||||
createHttpManagementGateway({ operations: context.contractOperations });
|
||||
createHttpManagementGateway({ http });
|
||||
|
||||
const createStudioApplication = () =>
|
||||
createTechLogStudioApplication({
|
||||
studio: createStudioGateway(),
|
||||
assets: createStudioAssetGateway(),
|
||||
management: createManagementGateway(),
|
||||
});
|
||||
|
||||
const input: TechLogFeatureInput = Object.freeze({
|
||||
publicContent,
|
||||
createManagementGateway,
|
||||
createStudioGateway,
|
||||
createStudioAssetGateway,
|
||||
createStudioApplication,
|
||||
});
|
||||
|
||||
return Object.freeze({
|
||||
|
||||
@@ -22,18 +22,18 @@ import type {
|
||||
ManagementGateway,
|
||||
} from "../../application/ports/management-gateway.ts";
|
||||
import { ManagementGatewayError } from "../../application/ports/management-gateway-error.ts";
|
||||
import type { StudioOperationExecutor } from "./http-studio-gateway.ts";
|
||||
import type {
|
||||
IdempotentOptions,
|
||||
RequestOptions,
|
||||
} from "../../application/ports/studio-gateway.ts";
|
||||
import { mutationIntent } from "./http-studio-gateway.ts";
|
||||
import type {
|
||||
TechLogHttpBinding,
|
||||
TechLogHttpOperationId,
|
||||
} from "./tech-log-http-binding.ts";
|
||||
|
||||
export type { ManagementGateway };
|
||||
|
||||
const ROUTE_ID = "TECH_LOG_STUDIO";
|
||||
|
||||
/**
|
||||
* 주제·프로젝트 관리 게이트웨이.
|
||||
*
|
||||
* <p>Studio 게이트웨이와 같은 실패 규약을 쓴다 — 실패는 던지고, 화면은 `usePublicContent` 가 아니라
|
||||
* Studio 쪽 상태 처리를 그대로 쓴다. 여기서 Result 로 감싸면 이 표면만 다른 규약이 된다.
|
||||
*/
|
||||
|
||||
export {
|
||||
ManagementGatewayError,
|
||||
@@ -41,131 +41,227 @@ export {
|
||||
} from "../../application/ports/management-gateway-error.ts";
|
||||
|
||||
export function createHttpManagementGateway(
|
||||
deps: Readonly<{ operations: StudioOperationExecutor }>,
|
||||
deps: Readonly<{ http: TechLogHttpBinding }>,
|
||||
): ManagementGateway {
|
||||
async function run<T>(operationId: string, input: unknown): Promise<T> {
|
||||
const outcome = await deps.operations.execute(operationId, input, { routeId: ROUTE_ID });
|
||||
if (outcome.kind === "SUCCESS") return outcome.value as T;
|
||||
if (outcome.kind === "PROBLEM") {
|
||||
// The management surface answers with the ADR-006 envelope, which nests
|
||||
// the code under `error` — reading `problem.code` found nothing and every
|
||||
// failure surfaced as the literal "PROBLEM", matching no i18n key.
|
||||
const body = outcome.problem as
|
||||
| Readonly<{
|
||||
code?: unknown;
|
||||
detail?: unknown;
|
||||
error?: Readonly<{ code?: unknown; message?: unknown }>;
|
||||
}>
|
||||
| null;
|
||||
const code =
|
||||
typeof body?.code === "string"
|
||||
? body.code
|
||||
: typeof body?.error?.code === "string"
|
||||
? body.error.code
|
||||
: "PROBLEM";
|
||||
const detail =
|
||||
typeof body?.error?.message === "string"
|
||||
? body.error.message
|
||||
: typeof body?.detail === "string"
|
||||
? body.detail
|
||||
: "";
|
||||
throw new ManagementGatewayError(operationId, code, detail);
|
||||
}
|
||||
throw new ManagementGatewayError(operationId, outcome.kind, "");
|
||||
async function read<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options?: RequestOptions,
|
||||
): Promise<T> {
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (result.ok) return result.value as T;
|
||||
throw new ManagementGatewayError(
|
||||
operationId,
|
||||
result.error.code,
|
||||
result.error.detail ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
async function command<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options: IdempotentOptions,
|
||||
): Promise<T> {
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
intent: mutationIntent(operationId, options.idempotencyKey, input),
|
||||
...(options.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (result.ok) return result.value as T;
|
||||
throw new ManagementGatewayError(
|
||||
operationId,
|
||||
result.error.code,
|
||||
result.error.detail ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
listTopics: () => run<TopicEdit[]>("listStudioTopics", {}),
|
||||
createTopic: (input: TopicEdit) => run<TopicEdit>("createTopic", input),
|
||||
updateTopic: (id: string, body: TopicEdit) => run<TopicEdit>("updateTopic", { id, body }),
|
||||
listTopicVariants: (topicId: string) =>
|
||||
run<TopicVariantEdit[]>("listTopicVariants", { id: topicId }),
|
||||
createTopicVariant: (topicId: string, body: TopicVariantEdit) =>
|
||||
run<TopicVariantEdit>("createTopicVariant", { id: topicId, body }),
|
||||
updateTopicVariant: (topicId: string, variantId: string, body: TopicVariantEdit) =>
|
||||
run<TopicVariantEdit>("updateTopicVariant", { id: topicId, variantId, body }),
|
||||
deleteTopicVariant: async (topicId: string, variantId: string, expectedVersion: number) => {
|
||||
await run<void>("deleteTopicVariant", { id: topicId, variantId, expectedVersion });
|
||||
listTopics: (options) => read<TopicEdit[]>("listStudioTopics", {}, options),
|
||||
createTopic: (input, options) =>
|
||||
command<TopicEdit>("createTopic", input, options),
|
||||
updateTopic: (id, body, options) =>
|
||||
command<TopicEdit>("updateTopic", { id, body }, options),
|
||||
deleteTopic: async (id, expectedVersion, options) => {
|
||||
await command<void>("deleteTopic", { id, expectedVersion }, options);
|
||||
},
|
||||
deleteTopic: async (id: string, expectedVersion: number) => {
|
||||
await run<void>("deleteTopic", { id, expectedVersion });
|
||||
|
||||
listTopicVariants: (topicId, options) =>
|
||||
read<TopicVariantEdit[]>("listTopicVariants", { id: topicId }, options),
|
||||
createTopicVariant: (topicId, body, options) =>
|
||||
command<TopicVariantEdit>(
|
||||
"createTopicVariant",
|
||||
{ id: topicId, body },
|
||||
options,
|
||||
),
|
||||
updateTopicVariant: (topicId, variantId, body, options) =>
|
||||
command<TopicVariantEdit>(
|
||||
"updateTopicVariant",
|
||||
{ id: topicId, variantId, body },
|
||||
options,
|
||||
),
|
||||
deleteTopicVariant: async (
|
||||
topicId,
|
||||
variantId,
|
||||
expectedVersion,
|
||||
options,
|
||||
) => {
|
||||
await command<void>(
|
||||
"deleteTopicVariant",
|
||||
{ id: topicId, variantId, expectedVersion },
|
||||
options,
|
||||
);
|
||||
},
|
||||
listProjects: (page?: number, size?: number) =>
|
||||
run<ProjectIndexPage>("listStudioProjects", { ...(page !== undefined ? { page } : {}), ...(size !== undefined ? { size } : {}) }),
|
||||
listQuestions: (page?: number, size?: number) =>
|
||||
run<QuestionIndexPage>("listStudioQuestions", {
|
||||
...(page !== undefined ? { page } : {}),
|
||||
...(size !== undefined ? { size } : {}),
|
||||
}),
|
||||
listProjectDecisions: (projectId: string) =>
|
||||
run<readonly DecisionResponse[]>("listStudioProjectDecisions", { id: projectId }),
|
||||
getProject: (id: string) => run<ProjectEditResponse>("getProjectForEdit", { id }),
|
||||
createProject: (title: string) => run<CreateDraftResponse>("createProject", { title }),
|
||||
updateProject: (id: string, body: ProjectUpdateRequest) =>
|
||||
run<ProjectEditResponse>("updateProject", { id, body }),
|
||||
listReleases: (page?: number, size?: number) =>
|
||||
run<ReleaseIndexPage>("listStudioReleases", { ...(page !== undefined ? { page } : {}), ...(size !== undefined ? { size } : {}) }),
|
||||
getRelease: (id: string) => run<ReleaseEditResponse>("getReleaseForEdit", { id }),
|
||||
createRelease: (title: string) => run<CreateDraftResponse>("createRelease", { title }),
|
||||
updateRelease: (id: string, body: ReleaseUpdateRequest) =>
|
||||
run<ReleaseEditResponse>("updateRelease", { id, body }),
|
||||
deleteRelease: async (id: string, expectedVersion: number) => {
|
||||
await run<void>("deleteRelease", { id, expectedVersion });
|
||||
},
|
||||
listProjectActivities: (id: string) =>
|
||||
run<ProjectActivityResponse[]>("listStudioProjectActivities", { id }),
|
||||
createProjectActivity: (id: string, body: ProjectActivityRequest) =>
|
||||
run<ProjectActivityResponse>("createProjectActivity", { id, body }),
|
||||
updateProjectActivity: (
|
||||
id: string,
|
||||
activityId: string,
|
||||
body: UpdateProjectActivityRequest,
|
||||
) => run<ProjectActivityResponse>("updateProjectActivity", { id, activityId, body }),
|
||||
deleteProjectActivity: async (id: string, activityId: string, expectedVersion: number) => {
|
||||
await run<void>("deleteProjectActivity", { id, activityId, expectedVersion });
|
||||
|
||||
listProjects: (page, size, options) =>
|
||||
read<ProjectIndexPage>(
|
||||
"listStudioProjects",
|
||||
{
|
||||
...(page !== undefined ? { page } : {}),
|
||||
...(size !== undefined ? { size } : {}),
|
||||
},
|
||||
options,
|
||||
),
|
||||
listQuestions: (page, size, options) =>
|
||||
read<QuestionIndexPage>(
|
||||
"listStudioQuestions",
|
||||
{
|
||||
...(page !== undefined ? { page } : {}),
|
||||
...(size !== undefined ? { size } : {}),
|
||||
},
|
||||
options,
|
||||
),
|
||||
listProjectDecisions: (projectId, options) =>
|
||||
read<readonly DecisionResponse[]>(
|
||||
"listStudioProjectDecisions",
|
||||
{ id: projectId },
|
||||
options,
|
||||
),
|
||||
|
||||
getProject: (id, options) =>
|
||||
read<ProjectEditResponse>("getProjectForEdit", { id }, options),
|
||||
createProject: (title, options) =>
|
||||
command<CreateDraftResponse>("createProject", { title }, options),
|
||||
updateProject: (id, body, options) =>
|
||||
command<ProjectEditResponse>("updateProject", { id, body }, options),
|
||||
deleteProject: async (id, expectedVersion, options) => {
|
||||
await command<void>("deleteProject", { id, expectedVersion }, options);
|
||||
},
|
||||
publishProject: (
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
visibility: "PUBLIC" | "UNLISTED" = "PUBLIC",
|
||||
) => run<PublishResponse>("publishProject", { id, expectedVersion, visibility }),
|
||||
unpublishProject: (id: string, expectedVersion: number) =>
|
||||
run<ProjectEditResponse>("unpublishProject", { id, expectedVersion }),
|
||||
getHomeFocus: () => run<HomeFocusResponse>("getHomeFocus", {}),
|
||||
updateHomeFocus: (body: HomeFocusRequest) =>
|
||||
run<HomeFocusResponse>("updateHomeFocus", body),
|
||||
publishRelease: (id: string, expectedVersion: number) =>
|
||||
run<PublishResponse>("publishRelease", { id, expectedVersion }),
|
||||
archiveRelease: (id: string, expectedVersion: number) =>
|
||||
run<ReleaseEditResponse>("archiveRelease", { id, expectedVersion }),
|
||||
id,
|
||||
expectedVersion,
|
||||
visibility = "PUBLIC",
|
||||
options,
|
||||
) =>
|
||||
command<PublishResponse>(
|
||||
"publishProject",
|
||||
{ id, expectedVersion, visibility },
|
||||
options,
|
||||
),
|
||||
unpublishProject: (id, expectedVersion, options) =>
|
||||
command<ProjectEditResponse>(
|
||||
"unpublishProject",
|
||||
{ id, expectedVersion },
|
||||
options,
|
||||
),
|
||||
|
||||
listProjectActivities: (id, options) =>
|
||||
read<ProjectActivityResponse[]>(
|
||||
"listStudioProjectActivities",
|
||||
{ id },
|
||||
options,
|
||||
),
|
||||
createProjectActivity: (id, body, options) =>
|
||||
command<ProjectActivityResponse>(
|
||||
"createProjectActivity",
|
||||
{ id, body },
|
||||
options,
|
||||
),
|
||||
updateProjectActivity: (id, activityId, body, options) =>
|
||||
command<ProjectActivityResponse>(
|
||||
"updateProjectActivity",
|
||||
{ id, activityId, body },
|
||||
options,
|
||||
),
|
||||
deleteProjectActivity: async (
|
||||
id,
|
||||
activityId,
|
||||
expectedVersion,
|
||||
options,
|
||||
) => {
|
||||
await command<void>(
|
||||
"deleteProjectActivity",
|
||||
{ id, activityId, expectedVersion },
|
||||
options,
|
||||
);
|
||||
},
|
||||
|
||||
getHomeFocus: (options) =>
|
||||
read<HomeFocusResponse>("getHomeFocus", {}, options),
|
||||
updateHomeFocus: (body, options) =>
|
||||
command<HomeFocusResponse>("updateHomeFocus", body, options),
|
||||
|
||||
listReleases: (page, size, options) =>
|
||||
read<ReleaseIndexPage>(
|
||||
"listStudioReleases",
|
||||
{
|
||||
...(page !== undefined ? { page } : {}),
|
||||
...(size !== undefined ? { size } : {}),
|
||||
},
|
||||
options,
|
||||
),
|
||||
getRelease: (id, options) =>
|
||||
read<ReleaseEditResponse>("getReleaseForEdit", { id }, options),
|
||||
createRelease: (title, options) =>
|
||||
command<CreateDraftResponse>("createRelease", { title }, options),
|
||||
updateRelease: (id, body, options) =>
|
||||
command<ReleaseEditResponse>("updateRelease", { id, body }, options),
|
||||
deleteRelease: async (id, expectedVersion, options) => {
|
||||
await command<void>("deleteRelease", { id, expectedVersion }, options);
|
||||
},
|
||||
publishRelease: (id, expectedVersion, options) =>
|
||||
command<PublishResponse>(
|
||||
"publishRelease",
|
||||
{ id, expectedVersion },
|
||||
options,
|
||||
),
|
||||
archiveRelease: (id, expectedVersion, options) =>
|
||||
command<ReleaseEditResponse>(
|
||||
"archiveRelease",
|
||||
{ id, expectedVersion },
|
||||
options,
|
||||
),
|
||||
|
||||
deleteDocument: async (
|
||||
kind: DeletableDocumentKind,
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
) => {
|
||||
/*
|
||||
삼항으로 이어 붙이면 마지막 else 가 모르는 종류를 다 받아 간다 — 개념이 그렇게 질문
|
||||
삭제로 떨어졌고, 「질문을 찾을 수 없습니다」가 났다. 표로 두면 종류가 늘 때 빠진
|
||||
자리를 타입이 잡는다.
|
||||
|
||||
메서드 매개변수는 TypeScript 에서 bivariant 라, 이 자리에 좁은 종류를 적어도 넓은
|
||||
포트 시그니처를 만족한 것으로 통과한다 — 그래서 타입 검사가 이 결함을 잡지 못했다.
|
||||
아래 표가 `Record<DeletableDocumentKind, …>` 인 것이 실제로 종류를 강제하는 지점이다.
|
||||
*/
|
||||
const OPERATIONS: Record<DeletableDocumentKind, string> = {
|
||||
const OPERATIONS: Record<DeletableDocumentKind, TechLogHttpOperationId> = {
|
||||
CASE: "deleteCaseDraft",
|
||||
REFERENCE: "deleteReferenceDraft",
|
||||
QUESTION: "deleteQuestion",
|
||||
CONCEPT: "deleteConceptDraft",
|
||||
SETUP: "deleteSetupDraft",
|
||||
};
|
||||
await run<void>(OPERATIONS[kind], { id, expectedVersion });
|
||||
await command<void>(
|
||||
OPERATIONS[kind],
|
||||
{ id, expectedVersion },
|
||||
options,
|
||||
);
|
||||
},
|
||||
deleteDecision: async (projectId: string, decisionId: string, expectedVersion: number) => {
|
||||
await run<void>("deleteProjectDecision", { id: projectId, decisionId, expectedVersion });
|
||||
},
|
||||
deleteProject: async (id: string, expectedVersion: number) => {
|
||||
await run<void>("deleteProject", { id, expectedVersion });
|
||||
deleteDecision: async (
|
||||
projectId,
|
||||
decisionId,
|
||||
expectedVersion,
|
||||
options,
|
||||
) => {
|
||||
await command<void>(
|
||||
"deleteProjectDecision",
|
||||
{ id: projectId, decisionId, expectedVersion },
|
||||
options,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type {
|
||||
HomeFocusItem,
|
||||
LatestRecordEntry,
|
||||
PublicHomeView,
|
||||
PublicProjectSummary,
|
||||
PublicReleaseSummary,
|
||||
ProjectActivity,
|
||||
ProjectDecision,
|
||||
Project,
|
||||
@@ -30,10 +33,12 @@ import {
|
||||
} from "./public-content-mapping.ts";
|
||||
import { cardSummary } from "../../domain/content-format/card-summary.ts";
|
||||
import type { components } from "../../contracts/public/generated.ts";
|
||||
import type { StudioOperationExecutor } from "./http-studio-gateway.ts";
|
||||
import type {
|
||||
TechLogHttpBinding,
|
||||
TechLogHttpOperationId,
|
||||
} from "./tech-log-http-binding.ts";
|
||||
import { projectStageLabel } from "../../domain/public/project-phase-labels.ts";
|
||||
|
||||
const ROUTE_ID = "TECH_LOG_PUBLIC";
|
||||
|
||||
/**
|
||||
* A missing slug is an answer, not a failure.
|
||||
@@ -53,19 +58,6 @@ function gatewayError(operationId: string, detail: string): PublicContentGateway
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the backend's error code out of either response shape — RFC7807 puts it
|
||||
* at the top level, the ADR-006 envelope nests it under `error`. Without this
|
||||
* every failure was reported as the literal "PROBLEM", which told a reader
|
||||
* nothing and matched no i18n key.
|
||||
*/
|
||||
function problemCode(problem: unknown): string {
|
||||
if (!problem || typeof problem !== "object") return "PROBLEM";
|
||||
const body = problem as Readonly<{ code?: unknown; error?: Readonly<{ code?: unknown }> }>;
|
||||
if (typeof body.code === "string") return body.code;
|
||||
if (typeof body.error?.code === "string") return body.error.code;
|
||||
return "PROBLEM";
|
||||
}
|
||||
|
||||
/*
|
||||
관계 묶음의 이름을 사람이 읽는 말로 바꾼다. 라벨이 없으면 계약의 키가 그대로 화면에 나온다 —
|
||||
@@ -105,26 +97,22 @@ export const QUESTION_RELATION_LABELS = Object.freeze({
|
||||
});
|
||||
|
||||
export function createHttpPublicContentGateway(
|
||||
deps: Readonly<{ operations: StudioOperationExecutor }>,
|
||||
deps: Readonly<{ http: TechLogHttpBinding }>,
|
||||
): PublicContentQueries {
|
||||
async function read<T>(operationId: string, input: unknown): Promise<T | typeof NOT_FOUND> {
|
||||
const outcome = await deps.operations.execute(operationId, input, { routeId: ROUTE_ID });
|
||||
if (outcome.kind === "SUCCESS") return outcome.value as T;
|
||||
if (outcome.kind === "PROBLEM") {
|
||||
// The HTTP status is the authoritative signal, and the only one that
|
||||
// holds across both shapes this surface answers with. RFC7807 carries
|
||||
// `status` in the body; the ADR-006 envelope does not — it puts the
|
||||
// reason in `error.category` and a backend-specific string in
|
||||
// `error.code` (PUBLIC_RESOURCE_NOT_FOUND, not NOT_FOUND). The old
|
||||
// body-only check matched neither, so every 404 raised the terminal
|
||||
// error surface on a page whose real state was "this does not exist".
|
||||
if (outcome.metadata.status === 404) return NOT_FOUND;
|
||||
throw gatewayError(operationId, problemCode(outcome.problem));
|
||||
}
|
||||
throw gatewayError(operationId, outcome.kind);
|
||||
async function read<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
): Promise<T | typeof NOT_FOUND> {
|
||||
const result = await deps.http.execute(operationId, input);
|
||||
if (result.ok) return result.value as T;
|
||||
if (result.error.httpStatus === 404) return NOT_FOUND;
|
||||
throw gatewayError(operationId, result.error.code);
|
||||
}
|
||||
|
||||
async function readOrThrow<T>(operationId: string, input: unknown): Promise<T> {
|
||||
async function readOrThrow<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
): Promise<T> {
|
||||
const value = await read<T>(operationId, input);
|
||||
if (value === NOT_FOUND) throw gatewayError(operationId, "NOT_FOUND");
|
||||
return value;
|
||||
@@ -185,7 +173,7 @@ export function createHttpPublicContentGateway(
|
||||
|
||||
표로 두면 종류가 늘 때 빠진 자리를 타입이 잡는다.
|
||||
*/
|
||||
const OPERATIONS: Record<RecordKind, string> = {
|
||||
const OPERATIONS: Record<RecordKind, TechLogHttpOperationId> = {
|
||||
CASE: "getPublicCase",
|
||||
REFERENCE: "getPublicReference",
|
||||
QUESTION: "getPublicQuestion",
|
||||
@@ -533,23 +521,29 @@ export function createHttpPublicContentGateway(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 투영이 고른 최근 기록. `entryType` 은 계약이 네 값만 허용하므로 그대로 믿고 쓴다 —
|
||||
* 서버가 이미 걸러 보낸다.
|
||||
*/
|
||||
async function getLatestEntries(): Promise<LatestRecordEntry[]> {
|
||||
const home = await read<Readonly<{ latestEntries?: readonly Readonly<Record<string, unknown>>[] }>>(
|
||||
"getPublicHome",
|
||||
{},
|
||||
);
|
||||
if (home === NOT_FOUND) return [];
|
||||
type PublicHomeProjection = Readonly<{
|
||||
latestEntries?: readonly Readonly<Record<string, unknown>>[];
|
||||
focus?: Readonly<Record<string, never>>;
|
||||
}>;
|
||||
|
||||
function latestEntriesFromHome(
|
||||
home: PublicHomeProjection,
|
||||
): LatestRecordEntry[] {
|
||||
return (home.latestEntries ?? []).map((entry) => {
|
||||
const topic = entry.primaryTopic as Readonly<Record<string, unknown>> | null | undefined;
|
||||
const project = entry.primaryProject as Readonly<Record<string, unknown>> | null | undefined;
|
||||
const topic = entry.primaryTopic as
|
||||
| Readonly<Record<string, unknown>>
|
||||
| null
|
||||
| undefined;
|
||||
const project = entry.primaryProject as
|
||||
| Readonly<Record<string, unknown>>
|
||||
| null
|
||||
| undefined;
|
||||
const path = String(entry.path ?? "");
|
||||
return Object.freeze({
|
||||
id: `${String(entry.entryType ?? "")}:${path}`,
|
||||
entryType: String(entry.entryType ?? "CASE") as LatestRecordEntry["entryType"],
|
||||
entryType: String(
|
||||
entry.entryType ?? "CASE",
|
||||
) as LatestRecordEntry["entryType"],
|
||||
title: String(entry.title ?? ""),
|
||||
summary: String(entry.summary ?? ""),
|
||||
path,
|
||||
@@ -560,13 +554,10 @@ export function createHttpPublicContentGateway(
|
||||
});
|
||||
}
|
||||
|
||||
async function getHomeFocusItems(): Promise<HomeFocusItem[]> {
|
||||
const home = await read<Readonly<{ focus?: Readonly<Record<string, never>> }>>(
|
||||
"getPublicHome",
|
||||
{},
|
||||
);
|
||||
if (home === NOT_FOUND) return [];
|
||||
const focus = (home.focus ?? {}) as Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
||||
function focusItemsFromHome(home: PublicHomeProjection): HomeFocusItem[] {
|
||||
const focus = (home.focus ?? {}) as Readonly<
|
||||
Record<string, Readonly<Record<string, unknown>>>
|
||||
>;
|
||||
const items: HomeFocusItem[] = [];
|
||||
const work = focus.currentWork;
|
||||
if (work) {
|
||||
@@ -577,19 +568,21 @@ export function createHttpPublicContentGateway(
|
||||
title: String(work.projectName ?? ""),
|
||||
summary: String(work.purpose ?? ""),
|
||||
details: Object.freeze([
|
||||
/*
|
||||
단계는 저장하는 값(`DESIGN`)이지 방문자에게 할 말이 아니다. 홈의 「지금 집중하는
|
||||
것」이 그 상수를 그대로 찍고 있었다 — 프로젝트 화면은 같은 값을 「설계」로 부르고
|
||||
있어서, 한 사이트가 같은 것을 두 이름으로 말했다.
|
||||
*/
|
||||
{ label: "단계", value: projectStageLabel(String(work.phase ?? "")) },
|
||||
{ label: "현재 목표", value: String(work.currentObjective ?? "") },
|
||||
{
|
||||
label: "단계",
|
||||
value: projectStageLabel(String(work.phase ?? "")),
|
||||
},
|
||||
{
|
||||
label: "현재 목표",
|
||||
value: String(work.currentObjective ?? ""),
|
||||
},
|
||||
{ label: "다음 작업", value: String(work.nextStep ?? "") },
|
||||
]),
|
||||
targetPath: String(work.projectPath ?? "/projects"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const question = focus.openQuestion;
|
||||
if (question) {
|
||||
items.push(
|
||||
@@ -599,14 +592,28 @@ export function createHttpPublicContentGateway(
|
||||
title: String(question.question ?? ""),
|
||||
summary: String(question.summary ?? ""),
|
||||
details: Object.freeze([
|
||||
{ label: "확인한 사실", value: ((question.knownFacts as readonly string[]) ?? []).join(" · ") },
|
||||
{ label: "미해결", value: ((question.unresolvedPoints as readonly string[]) ?? []).join(" · ") },
|
||||
{ label: "다음 검증", value: String(question.nextVerification ?? "") },
|
||||
{
|
||||
label: "확인한 사실",
|
||||
value: (
|
||||
(question.knownFacts as readonly string[]) ?? []
|
||||
).join(" · "),
|
||||
},
|
||||
{
|
||||
label: "미해결",
|
||||
value: (
|
||||
(question.unresolvedPoints as readonly string[]) ?? []
|
||||
).join(" · "),
|
||||
},
|
||||
{
|
||||
label: "다음 검증",
|
||||
value: String(question.nextVerification ?? ""),
|
||||
},
|
||||
]),
|
||||
targetPath: String(question.questionPath ?? "/explore/questions"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const decision = focus.recentDecision;
|
||||
if (decision) {
|
||||
items.push(
|
||||
@@ -616,8 +623,16 @@ export function createHttpPublicContentGateway(
|
||||
title: String(decision.statement ?? ""),
|
||||
summary: String(decision.rationale ?? ""),
|
||||
details: Object.freeze([
|
||||
{ label: "결정일", value: dateLabel(decision.decidedAt as string) },
|
||||
{ label: "영향", value: ((decision.consequences as readonly string[]) ?? []).join(" · ") },
|
||||
{
|
||||
label: "결정일",
|
||||
value: dateLabel(decision.decidedAt as string),
|
||||
},
|
||||
{
|
||||
label: "영향",
|
||||
value: (
|
||||
(decision.consequences as readonly string[]) ?? []
|
||||
).join(" · "),
|
||||
},
|
||||
]),
|
||||
targetPath: String(decision.decisionPath ?? "/projects"),
|
||||
}),
|
||||
@@ -626,27 +641,56 @@ export function createHttpPublicContentGateway(
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 빈 검색어는 검색이 아니라 "카탈로그 전부"라는 뜻이다.
|
||||
*
|
||||
* 픽스처가 그렇게 동작했고 화면들이 그 의미에 기대어 쓰고 있다 — 홈 타임라인,
|
||||
* 프로젝트 목록, 릴리즈 목록, 탐색 필터가 전부 `searchPublicContent("")` 로 카탈로그를
|
||||
* 받아 간다. 계약에는 그런 의미가 없고 `q` 는 필수라, 그대로 보내면 400
|
||||
* (`PUBLIC_REQUEST_INVALID`) 이 오고 홈을 포함한 네 화면이 통째로 오류 화면이 된다.
|
||||
*
|
||||
* 그래서 빈 검색어는 검색 엔드포인트로 보내지 않고, 계약이 이미 가진 목록
|
||||
* 엔드포인트에서 조립한다. 검색어가 있으면 그때는 서버 검색을 쓴다 — 클라이언트에서
|
||||
* 거르면 페이지 밖의 결과를 영영 못 찾는다.
|
||||
*/
|
||||
async function searchPublicContent(query: string): Promise<SearchablePublicEntity[]> {
|
||||
const trimmed = query.trim();
|
||||
if (trimmed.length > 0) {
|
||||
const page = await read<Page>("searchPublicResources", { q: trimmed });
|
||||
if (page === NOT_FOUND) return [];
|
||||
return (page.items ?? []).map(searchItemToEntity);
|
||||
async function getHome(): Promise<PublicHomeView> {
|
||||
const home = await read<PublicHomeProjection>("getPublicHome", {});
|
||||
if (home === NOT_FOUND) {
|
||||
return Object.freeze({
|
||||
focusItems: Object.freeze([]),
|
||||
latestEntries: Object.freeze([]),
|
||||
});
|
||||
}
|
||||
return Object.freeze({
|
||||
focusItems: Object.freeze(focusItemsFromHome(home)),
|
||||
latestEntries: Object.freeze(latestEntriesFromHome(home)),
|
||||
});
|
||||
}
|
||||
|
||||
const [knowledge, questions, projects, releases] = await Promise.all([
|
||||
async function listProjects(): Promise<PublicProjectSummary[]> {
|
||||
const page = await read<Page>("listPublicProjects", {});
|
||||
if (page === NOT_FOUND) return [];
|
||||
return (page.items ?? []).map((item) =>
|
||||
Object.freeze({
|
||||
slug: String(item.slug ?? ""),
|
||||
title: String(item.name ?? ""),
|
||||
summary: String(item.oneLinePurpose ?? ""),
|
||||
path: String(item.path ?? `/projects/${String(item.slug ?? "")}`),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function getLatestEntries(): Promise<LatestRecordEntry[]> {
|
||||
return [...(await getHome()).latestEntries];
|
||||
}
|
||||
|
||||
async function getHomeFocusItems(): Promise<HomeFocusItem[]> {
|
||||
return [...(await getHome()).focusItems];
|
||||
}
|
||||
|
||||
async function listReleases(): Promise<PublicReleaseSummary[]> {
|
||||
const page = await read<Page>("listPublicReleases", {});
|
||||
if (page === NOT_FOUND) return [];
|
||||
return (page.items ?? []).map((item) =>
|
||||
Object.freeze({
|
||||
version: String(item.version ?? ""),
|
||||
title: String(item.title ?? ""),
|
||||
summary: String(item.summary ?? ""),
|
||||
path: String(item.path ?? `/releases/${String(item.version ?? "")}`),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function listCatalog(): Promise<SearchablePublicEntity[]> {
|
||||
const [knowledge, questions, projectPage, releasePage] = await Promise.all([
|
||||
read<Page>("exploreKnowledge", {}),
|
||||
read<Page>("exploreQuestions", {}),
|
||||
read<Page>("listPublicProjects", {}),
|
||||
@@ -663,7 +707,7 @@ export function createHttpPublicContentGateway(
|
||||
for (const item of items(questions)) {
|
||||
entities.push(recordToEntity(questionListItemToRecord(item)));
|
||||
}
|
||||
for (const item of items(projects)) {
|
||||
for (const item of items(projectPage)) {
|
||||
entities.push(
|
||||
Object.freeze({
|
||||
contentType: "PROJECT",
|
||||
@@ -673,7 +717,7 @@ export function createHttpPublicContentGateway(
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const item of items(releases)) {
|
||||
for (const item of items(releasePage)) {
|
||||
entities.push(
|
||||
Object.freeze({
|
||||
contentType: "RELEASE",
|
||||
@@ -686,6 +730,17 @@ export function createHttpPublicContentGateway(
|
||||
return entities;
|
||||
}
|
||||
|
||||
async function searchPublicContent(
|
||||
query: string,
|
||||
): Promise<SearchablePublicEntity[]> {
|
||||
const trimmed = query.trim();
|
||||
if (trimmed.length === 0) return listCatalog();
|
||||
|
||||
const page = await read<Page>("searchPublicResources", { q: trimmed });
|
||||
if (page === NOT_FOUND) return [];
|
||||
return (page.items ?? []).map(searchItemToEntity);
|
||||
}
|
||||
|
||||
function recordToEntity(record: PublicRecord): SearchablePublicEntity {
|
||||
return Object.freeze({
|
||||
contentType: record.kind,
|
||||
@@ -709,6 +764,10 @@ export function createHttpPublicContentGateway(
|
||||
getProjectRecords,
|
||||
getProjectDecisions,
|
||||
getProjectActivity,
|
||||
getHome,
|
||||
listProjects,
|
||||
listReleases,
|
||||
listCatalog,
|
||||
getHomeFocusItems,
|
||||
getLatestEntries,
|
||||
searchPublicContent,
|
||||
|
||||
@@ -11,8 +11,12 @@ import type {
|
||||
} from "../../application/ports/studio-asset-gateway.ts";
|
||||
import type { IdempotentOptions, RequestOptions } from "../../application/ports/studio-gateway.ts";
|
||||
import { isStudioGatewayError } from "../../application/ports/studio-gateway-error.ts";
|
||||
import { toStudioGatewayError } from "./studio-error-mapping.ts";
|
||||
import { mutationIntent, type StudioOperationExecutor } from "./http-studio-gateway.ts";
|
||||
import { toStudioGatewayErrorFromFailure } from "./studio-error-mapping.ts";
|
||||
import { mutationIntent } from "./http-studio-gateway.ts";
|
||||
import type {
|
||||
TechLogHttpBinding,
|
||||
TechLogHttpOperationId,
|
||||
} from "./tech-log-http-binding.ts";
|
||||
import type { CsrfTokenProvider } from "./studio-session-csrf.ts";
|
||||
|
||||
export type StudioAssetUploadTransport = Readonly<{
|
||||
@@ -24,35 +28,38 @@ export type StudioAssetUploadTransport = Readonly<{
|
||||
}>;
|
||||
|
||||
export type HttpStudioAssetGatewayDependencies = Readonly<{
|
||||
operations: StudioOperationExecutor;
|
||||
http: TechLogHttpBinding;
|
||||
csrf: CsrfTokenProvider;
|
||||
upload: StudioAssetUploadTransport;
|
||||
}>;
|
||||
|
||||
const ROUTE_ID = "TECH_LOG_STUDIO_ASSETS";
|
||||
|
||||
export function createHttpStudioAssetGateway(
|
||||
deps: HttpStudioAssetGatewayDependencies,
|
||||
): StudioAssetGateway {
|
||||
async function read<T>(operationId: string, input: unknown, options?: RequestOptions) {
|
||||
const outcome = await deps.operations.execute(operationId, input, {
|
||||
routeId: ROUTE_ID,
|
||||
async function read<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options?: RequestOptions,
|
||||
) {
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (outcome.kind !== "SUCCESS") throw toStudioGatewayError(outcome, operationId);
|
||||
return outcome.value as T;
|
||||
if (!result.ok) throw toStudioGatewayErrorFromFailure(result.error);
|
||||
return result.value as T;
|
||||
}
|
||||
|
||||
async function command<T>(operationId: string, input: unknown, options: IdempotentOptions) {
|
||||
// Task 4와 동일한 규칙: 헤더는 gateway가 만들지 않는다. `Idempotency-Key`는
|
||||
// intent에서, `x-csrf-token`은 credential collaborator에서 온다.
|
||||
const outcome = await deps.operations.execute(operationId, input, {
|
||||
routeId: ROUTE_ID,
|
||||
async function command<T>(
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options: IdempotentOptions,
|
||||
) {
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
intent: mutationIntent(operationId, options.idempotencyKey, input),
|
||||
...(options.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (outcome.kind === "SUCCESS") return outcome.value as T;
|
||||
throw toStudioGatewayError(outcome, operationId);
|
||||
if (result.ok) return result.value as T;
|
||||
throw toStudioGatewayErrorFromFailure(result.error);
|
||||
}
|
||||
|
||||
const gateway: StudioAssetGateway = {
|
||||
|
||||
@@ -4,33 +4,22 @@ import {
|
||||
MUTATION_INTENT_BOUNDS,
|
||||
type MutationIntent,
|
||||
} from "../../../../contracts/mutation-intent.ts";
|
||||
import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts";
|
||||
import { stableStringify } from "../stable-stringify.ts";
|
||||
import type {
|
||||
IdempotentOptions,
|
||||
RequestOptions,
|
||||
StudioGateway,
|
||||
} from "../../application/ports/studio-gateway.ts";
|
||||
import { toStudioGatewayError } from "./studio-error-mapping.ts";
|
||||
|
||||
export type StudioOperationExecutor = Readonly<{
|
||||
execute(
|
||||
operationId: string,
|
||||
input: unknown,
|
||||
context: Readonly<{
|
||||
routeId: string;
|
||||
signal?: AbortSignal;
|
||||
intent?: MutationIntent;
|
||||
}>,
|
||||
): Promise<HttpExecutionOutcome<unknown, unknown>>;
|
||||
}>;
|
||||
import { toStudioGatewayErrorFromFailure } from "./studio-error-mapping.ts";
|
||||
import type {
|
||||
TechLogHttpBinding,
|
||||
TechLogHttpOperationId,
|
||||
} from "./tech-log-http-binding.ts";
|
||||
|
||||
export type HttpStudioGatewayDependencies = Readonly<{
|
||||
operations: StudioOperationExecutor;
|
||||
http: TechLogHttpBinding;
|
||||
}>;
|
||||
|
||||
const ROUTE_ID = "TECH_LOG_STUDIO";
|
||||
|
||||
const IDENTITY_ENCODER = new TextEncoder();
|
||||
const IDENTITY_DECODER = new TextDecoder();
|
||||
|
||||
@@ -42,7 +31,7 @@ const IDENTITY_DECODER = new TextDecoder();
|
||||
* "A caller-supplied value is never trimmed, regenerated or silently dropped").
|
||||
*/
|
||||
export function mutationIntent(
|
||||
operationId: string,
|
||||
operationId: TechLogHttpOperationId,
|
||||
idempotencyKey: string,
|
||||
input: unknown,
|
||||
): MutationIntent {
|
||||
@@ -85,30 +74,28 @@ export function createHttpStudioGateway(
|
||||
deps: HttpStudioGatewayDependencies,
|
||||
): StudioGateway {
|
||||
async function read<T>(
|
||||
operationId: string,
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options?: RequestOptions,
|
||||
): Promise<T> {
|
||||
const outcome = await deps.operations.execute(operationId, input, {
|
||||
routeId: ROUTE_ID,
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
...(options?.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (outcome.kind !== "SUCCESS") throw toStudioGatewayError(outcome, operationId);
|
||||
return outcome.value as T;
|
||||
if (!result.ok) throw toStudioGatewayErrorFromFailure(result.error);
|
||||
return result.value as T;
|
||||
}
|
||||
|
||||
async function command<T>(
|
||||
operationId: string,
|
||||
operationId: TechLogHttpOperationId,
|
||||
input: unknown,
|
||||
options: IdempotentOptions,
|
||||
): Promise<T> {
|
||||
const outcome = await deps.operations.execute(operationId, input, {
|
||||
routeId: ROUTE_ID,
|
||||
const result = await deps.http.execute(operationId, input, {
|
||||
intent: mutationIntent(operationId, options.idempotencyKey, input),
|
||||
...(options.signal ? { signal: options.signal } : {}),
|
||||
});
|
||||
if (outcome.kind === "SUCCESS") return outcome.value as T;
|
||||
throw toStudioGatewayError(outcome, operationId);
|
||||
if (result.ok) return result.value as T;
|
||||
throw toStudioGatewayErrorFromFailure(result.error);
|
||||
}
|
||||
|
||||
const gateway: StudioGateway = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts";
|
||||
import type { AppFailure } from "../../../../contracts/errors.ts";
|
||||
import { StudioGatewayError } from "../../application/ports/studio-gateway-error.ts";
|
||||
import type { ProblemDetails } from "../../contracts/studio/contract.ts";
|
||||
|
||||
@@ -92,3 +93,45 @@ export function toStudioGatewayError(
|
||||
throw new Error(`${operationId}: success outcome is not an error`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function fallbackStatus(failure: AppFailure): number {
|
||||
if (failure.httpStatus !== undefined) return failure.httpStatus;
|
||||
switch (failure.kind) {
|
||||
case "AUTH_REQUIRED":
|
||||
return 401;
|
||||
case "FORBIDDEN":
|
||||
return 403;
|
||||
case "RATE_LIMITED":
|
||||
return 429;
|
||||
case "REQUEST_ABORTED":
|
||||
return 499;
|
||||
case "REQUEST_TIMEOUT":
|
||||
return 504;
|
||||
case "NETWORK_UNREACHABLE":
|
||||
case "SERVER_FAILURE":
|
||||
return 503;
|
||||
default:
|
||||
return 502;
|
||||
}
|
||||
}
|
||||
|
||||
export function toStudioGatewayErrorFromFailure(
|
||||
failure: AppFailure,
|
||||
): StudioGatewayError {
|
||||
const status = fallbackStatus(failure);
|
||||
const code: ProblemDetails["code"] =
|
||||
CODES.has(failure.code)
|
||||
? failure.code as ProblemDetails["code"]
|
||||
: failure.kind === "AUTH_REQUIRED"
|
||||
? "AUTHENTICATION_REQUIRED"
|
||||
: failure.kind === "FORBIDDEN"
|
||||
? "STUDIO_ACCESS_DENIED"
|
||||
: "STUDIO_UNAVAILABLE";
|
||||
return synthetic(
|
||||
code,
|
||||
status,
|
||||
failure.detail ?? (failure.operationId + ": " + failure.code),
|
||||
failure.retryable,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
createFeatureHttpBinding,
|
||||
defineFeatureHttpOperation,
|
||||
type FeatureHttpBinding,
|
||||
type FeatureHttpOperation,
|
||||
type InstalledHttpOperationExecutor,
|
||||
type SafeResponseMetadata,
|
||||
} from "../../../../adapters/http/index.ts";
|
||||
import { mappingSuccess } from "../../../../contracts/boundary-mapper.ts";
|
||||
import { kindForStatus } from "../../../../contracts/errors.ts";
|
||||
import type { ProblemDetails } from "../../contracts/studio/contract.ts";
|
||||
import { TECH_LOG_MANAGEMENT_HTTP_CONTRACTS } from "../../contracts/tech-log-management-contract-contribution.ts";
|
||||
import { TECH_LOG_PUBLIC_HTTP_CONTRACTS } from "../../contracts/tech-log-public-contract-contribution.ts";
|
||||
import { TECH_LOG_STUDIO_HTTP_CONTRACTS } from "../../contracts/tech-log-studio-contract-contribution.ts";
|
||||
|
||||
const TECH_LOG_HTTP_CONTRACTS = Object.freeze([
|
||||
...TECH_LOG_STUDIO_HTTP_CONTRACTS,
|
||||
...TECH_LOG_PUBLIC_HTTP_CONTRACTS,
|
||||
...TECH_LOG_MANAGEMENT_HTTP_CONTRACTS,
|
||||
] as const);
|
||||
|
||||
type TechLogHttpContract = (typeof TECH_LOG_HTTP_CONTRACTS)[number];
|
||||
|
||||
export type TechLogHttpOperationId =
|
||||
TechLogHttpContract["contract"]["operationId"];
|
||||
|
||||
type ContractFor<OperationId extends TechLogHttpOperationId> =
|
||||
Extract<
|
||||
TechLogHttpContract,
|
||||
Readonly<{
|
||||
contract: Readonly<{ operationId: OperationId }>;
|
||||
}>
|
||||
>;
|
||||
|
||||
type TechLogRouteId =
|
||||
| "TECH_LOG_STUDIO"
|
||||
| "TECH_LOG_STUDIO_ASSETS"
|
||||
| "TECH_LOG_PUBLIC";
|
||||
|
||||
type TechLogHttpOperations = Readonly<{
|
||||
[OperationId in TechLogHttpOperationId]: FeatureHttpOperation<
|
||||
ContractFor<OperationId>,
|
||||
unknown,
|
||||
TechLogRouteId
|
||||
>;
|
||||
}>;
|
||||
|
||||
const ASSET_OPERATION_IDS = new Set<TechLogHttpOperationId>([
|
||||
"listStudioAssets",
|
||||
"getStudioAsset",
|
||||
"updateStudioAsset",
|
||||
"deleteStudioAsset",
|
||||
]);
|
||||
|
||||
const PUBLIC_OPERATION_IDS = new Set<TechLogHttpOperationId>(
|
||||
TECH_LOG_PUBLIC_HTTP_CONTRACTS.map(
|
||||
(contract) => contract.contract.operationId as TechLogHttpOperationId,
|
||||
),
|
||||
);
|
||||
|
||||
function routeIdFor(operationId: TechLogHttpOperationId): TechLogRouteId {
|
||||
if (PUBLIC_OPERATION_IDS.has(operationId)) return "TECH_LOG_PUBLIC";
|
||||
if (ASSET_OPERATION_IDS.has(operationId)) return "TECH_LOG_STUDIO_ASSETS";
|
||||
return "TECH_LOG_STUDIO";
|
||||
}
|
||||
|
||||
function problemCode(problem: unknown): string {
|
||||
if (!problem || typeof problem !== "object") return "CONTRACT_PROBLEM";
|
||||
const candidate = problem as Readonly<{
|
||||
code?: unknown;
|
||||
error?: Readonly<{ code?: unknown }>;
|
||||
}>;
|
||||
if (typeof candidate.code === "string") return candidate.code;
|
||||
if (typeof candidate.error?.code === "string") return candidate.error.code;
|
||||
return "CONTRACT_PROBLEM";
|
||||
}
|
||||
|
||||
function problemDetail(problem: unknown): string | undefined {
|
||||
if (!problem || typeof problem !== "object") return undefined;
|
||||
const candidate = problem as Partial<ProblemDetails> &
|
||||
Readonly<{ error?: Readonly<{ message?: unknown }> }>;
|
||||
if (typeof candidate.detail === "string" && candidate.detail.length > 0) {
|
||||
return candidate.detail;
|
||||
}
|
||||
return typeof candidate.error?.message === "string" &&
|
||||
candidate.error.message.length > 0
|
||||
? candidate.error.message
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function mapProblem(problem: unknown, metadata: SafeResponseMetadata) {
|
||||
const detail = problemDetail(problem);
|
||||
return Object.freeze({
|
||||
kind: kindForStatus(metadata.status),
|
||||
code: problemCode(problem),
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
});
|
||||
}
|
||||
|
||||
function buildOperations(): TechLogHttpOperations {
|
||||
const registry: Record<string, FeatureHttpOperation<object, unknown, TechLogRouteId>> =
|
||||
Object.create(null);
|
||||
|
||||
for (const contract of TECH_LOG_HTTP_CONTRACTS) {
|
||||
const operationId = contract.contract.operationId as TechLogHttpOperationId;
|
||||
if (Object.hasOwn(registry, operationId)) {
|
||||
throw new TypeError("Duplicate TechLog HTTP operation: " + operationId);
|
||||
}
|
||||
registry[operationId] = defineFeatureHttpOperation({
|
||||
contract,
|
||||
routeId: routeIdFor(operationId),
|
||||
mapSuccess: mappingSuccess,
|
||||
mapProblem,
|
||||
}) as FeatureHttpOperation<object, unknown, TechLogRouteId>;
|
||||
}
|
||||
|
||||
return Object.freeze(registry) as unknown as TechLogHttpOperations;
|
||||
}
|
||||
|
||||
export const TECH_LOG_HTTP_OPERATIONS = buildOperations();
|
||||
|
||||
export type TechLogHttpBinding = FeatureHttpBinding<
|
||||
typeof TECH_LOG_HTTP_OPERATIONS
|
||||
>;
|
||||
|
||||
export function createTechLogHttpBinding(
|
||||
executor: InstalledHttpOperationExecutor,
|
||||
): TechLogHttpBinding {
|
||||
return createFeatureHttpBinding(executor, TECH_LOG_HTTP_OPERATIONS);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { projects, publicRecords, releases } from "./public-content.ts";
|
||||
import { getHomeFocusItems, searchPublicContent } from "./public-query.ts";
|
||||
import { getHomeFocusItems, listCatalog } from "./public-query.ts";
|
||||
|
||||
export { publicSiteConfig as siteConfig } from "../../contracts/public-site-config.ts";
|
||||
|
||||
@@ -82,7 +82,7 @@ export const exploreEntries = [
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const searchEntries = searchPublicContent("");
|
||||
export const searchEntries = listCatalog();
|
||||
|
||||
const fetchJoinCase = publicRecords.find(
|
||||
(record) =>
|
||||
|
||||
@@ -326,13 +326,17 @@ function releaseSearchEntity(release: Release): SearchablePublicEntity {
|
||||
};
|
||||
}
|
||||
|
||||
export function searchPublicContent(query: string): SearchablePublicEntity[] {
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR");
|
||||
const entities = [
|
||||
export function listCatalog(): SearchablePublicEntity[] {
|
||||
return [
|
||||
...publicRecords.map(recordSearchEntity),
|
||||
...projects.map(projectSearchEntity),
|
||||
...releases.map(releaseSearchEntity),
|
||||
];
|
||||
}
|
||||
|
||||
export function searchPublicContent(query: string): SearchablePublicEntity[] {
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR");
|
||||
const entities = listCatalog();
|
||||
|
||||
if (!normalizedQuery) return entities;
|
||||
|
||||
@@ -393,6 +397,35 @@ export const publicContentQueries = Object.freeze({
|
||||
async getTopicDetail(slug: string) {
|
||||
return getTopicDetail(slug);
|
||||
},
|
||||
async getHome() {
|
||||
return Object.freeze({
|
||||
focusItems: Object.freeze(getHomeFocusItems()),
|
||||
latestEntries: Object.freeze(getLatestEntries()),
|
||||
});
|
||||
},
|
||||
async listProjects() {
|
||||
return projects.map((project) =>
|
||||
Object.freeze({
|
||||
slug: project.slug,
|
||||
title: project.title,
|
||||
summary: project.summary,
|
||||
path: `/projects/${project.slug}`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
async listReleases() {
|
||||
return releases.map((release) =>
|
||||
Object.freeze({
|
||||
version: release.version,
|
||||
title: release.title,
|
||||
summary: release.summary,
|
||||
path: release.path,
|
||||
}),
|
||||
);
|
||||
},
|
||||
async listCatalog() {
|
||||
return listCatalog();
|
||||
},
|
||||
async getLatestEntries() {
|
||||
return getLatestEntries();
|
||||
},
|
||||
|
||||
@@ -17,92 +17,182 @@ import type {
|
||||
TopicEdit,
|
||||
TopicVariantEdit,
|
||||
} from "../../contracts/management/contract.ts";
|
||||
import type {
|
||||
IdempotentOptions,
|
||||
RequestOptions,
|
||||
} from "./studio-gateway.ts";
|
||||
|
||||
/**
|
||||
* 주제·프로젝트·릴리즈·작업본 삭제 관리 표면.
|
||||
*
|
||||
* <p>Studio 게이트웨이와 같은 실패 규약이다 — 실패는 던지고, 화면이 잡는다. MOCK 대응물을 두지
|
||||
* 않는 것도 의도다: 이 표면은 백엔드가 없으면 존재할 이유가 없고, 픽스처를 만들면 실제로는 만들
|
||||
* 수 없는 주제를 화면이 보여주게 된다.
|
||||
* 읽기와 명령 모두 Studio server-state runtime의 cancellation/idempotency
|
||||
* 계약을 끝까지 전달할 수 있어야 한다. presentation이 공통 mutation
|
||||
* coordinator를 사용해도 이 포트에서 옵션을 버리면 실제 HTTP 실행은 그
|
||||
* 보호를 받지 못한다.
|
||||
*/
|
||||
/** 이 게이트웨이로 지울 수 있는 문서 종류. 결정은 프로젝트 경로를 요구하므로 별도 메서드다. */
|
||||
export type DeletableDocumentKind = "CASE" | "REFERENCE" | "QUESTION" | "CONCEPT" | "SETUP";
|
||||
export type DeletableDocumentKind =
|
||||
| "CASE"
|
||||
| "REFERENCE"
|
||||
| "QUESTION"
|
||||
| "CONCEPT"
|
||||
| "SETUP";
|
||||
|
||||
export type ManagementGateway = Readonly<{
|
||||
listTopics(): Promise<TopicEdit[]>;
|
||||
createTopic(input: TopicEdit): Promise<TopicEdit>;
|
||||
updateTopic(id: string, body: TopicEdit): Promise<TopicEdit>;
|
||||
deleteTopic(id: string, expectedVersion: number): Promise<void>;
|
||||
/*
|
||||
주제 안의 축. 「구조」「조회 전략」처럼 주제마다 이름이 다른 축 하나가 접근 하나고, 기록은
|
||||
거기에 걸린다. 아무 축에도 걸리지 않은 기록은 그 주제의 공통 기록이다.
|
||||
*/
|
||||
listTopicVariants(topicId: string): Promise<TopicVariantEdit[]>;
|
||||
createTopicVariant(topicId: string, body: TopicVariantEdit): Promise<TopicVariantEdit>;
|
||||
listTopics(options?: RequestOptions): Promise<TopicEdit[]>;
|
||||
createTopic(
|
||||
input: TopicEdit,
|
||||
options: IdempotentOptions,
|
||||
): Promise<TopicEdit>;
|
||||
updateTopic(
|
||||
id: string,
|
||||
body: TopicEdit,
|
||||
options: IdempotentOptions,
|
||||
): Promise<TopicEdit>;
|
||||
deleteTopic(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
|
||||
listTopicVariants(
|
||||
topicId: string,
|
||||
options?: RequestOptions,
|
||||
): Promise<TopicVariantEdit[]>;
|
||||
createTopicVariant(
|
||||
topicId: string,
|
||||
body: TopicVariantEdit,
|
||||
options: IdempotentOptions,
|
||||
): Promise<TopicVariantEdit>;
|
||||
updateTopicVariant(
|
||||
topicId: string,
|
||||
variantId: string,
|
||||
body: TopicVariantEdit,
|
||||
options: IdempotentOptions,
|
||||
): Promise<TopicVariantEdit>;
|
||||
deleteTopicVariant(topicId: string, variantId: string, expectedVersion: number): Promise<void>;
|
||||
listProjects(page?: number, size?: number): Promise<ProjectIndexPage>;
|
||||
/*
|
||||
홈 「지금 집중하는 것」 편집기가 쓰는 둘. 질문 항목은 `primaryProject` 를 들고 오므로 그것으로
|
||||
거르고, 결정은 경로 자체가 프로젝트를 요구하므로 고른 프로젝트의 것만 온다.
|
||||
*/
|
||||
listQuestions(page?: number, size?: number): Promise<QuestionIndexPage>;
|
||||
listProjectDecisions(projectId: string): Promise<readonly DecisionResponse[]>;
|
||||
getProject(id: string): Promise<ProjectEditResponse>;
|
||||
createProject(title: string): Promise<CreateDraftResponse>;
|
||||
updateProject(id: string, body: ProjectUpdateRequest): Promise<ProjectEditResponse>;
|
||||
deleteProject(id: string, expectedVersion: number): Promise<void>;
|
||||
/**
|
||||
* 프로젝트 게시. 프로젝트는 Studio 문서가 아니라 게시 파이프라인 밖에 있고, 그래서 문서를
|
||||
* 게시해도 그 문서가 속한 프로젝트는 비공개로 남는다 — 공개 화면(프로젝트 목록·프로필의
|
||||
* "현재 프로젝트"·홈의 focus)은 모두 게시된 프로젝트만 읽으므로, 이 호출 없이는 어디에도
|
||||
* 나타나지 않는다.
|
||||
*/
|
||||
deleteTopicVariant(
|
||||
topicId: string,
|
||||
variantId: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
|
||||
listProjects(
|
||||
page?: number,
|
||||
size?: number,
|
||||
options?: RequestOptions,
|
||||
): Promise<ProjectIndexPage>;
|
||||
listQuestions(
|
||||
page?: number,
|
||||
size?: number,
|
||||
options?: RequestOptions,
|
||||
): Promise<QuestionIndexPage>;
|
||||
listProjectDecisions(
|
||||
projectId: string,
|
||||
options?: RequestOptions,
|
||||
): Promise<readonly DecisionResponse[]>;
|
||||
|
||||
getProject(
|
||||
id: string,
|
||||
options?: RequestOptions,
|
||||
): Promise<ProjectEditResponse>;
|
||||
createProject(
|
||||
title: string,
|
||||
options: IdempotentOptions,
|
||||
): Promise<CreateDraftResponse>;
|
||||
updateProject(
|
||||
id: string,
|
||||
body: ProjectUpdateRequest,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ProjectEditResponse>;
|
||||
deleteProject(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
publishProject(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
visibility?: "PUBLIC" | "UNLISTED",
|
||||
visibility: "PUBLIC" | "UNLISTED" | undefined,
|
||||
options: IdempotentOptions,
|
||||
): Promise<PublishResponse>;
|
||||
unpublishProject(id: string, expectedVersion: number): Promise<ProjectEditResponse>;
|
||||
/**
|
||||
* 프로젝트 활동. 공개 프로젝트 화면의 "활동" 은 이 목록을 투영 없이 직접 읽으므로, 여기서
|
||||
* 만든 줄이 곧 그 화면이다.
|
||||
*/
|
||||
listProjectActivities(id: string): Promise<ProjectActivityResponse[]>;
|
||||
createProjectActivity(id: string, body: ProjectActivityRequest): Promise<ProjectActivityResponse>;
|
||||
unpublishProject(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ProjectEditResponse>;
|
||||
|
||||
listProjectActivities(
|
||||
id: string,
|
||||
options?: RequestOptions,
|
||||
): Promise<ProjectActivityResponse[]>;
|
||||
createProjectActivity(
|
||||
id: string,
|
||||
body: ProjectActivityRequest,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ProjectActivityResponse>;
|
||||
updateProjectActivity(
|
||||
id: string,
|
||||
activityId: string,
|
||||
body: UpdateProjectActivityRequest,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ProjectActivityResponse>;
|
||||
deleteProjectActivity(id: string, activityId: string, expectedVersion: number): Promise<void>;
|
||||
/** 공개 홈이 무엇을 앞에 둘지. 세 슬롯이 모두 비면 홈은 그 영역을 아예 그리지 않는다. */
|
||||
getHomeFocus(): Promise<HomeFocusResponse>;
|
||||
updateHomeFocus(body: HomeFocusRequest): Promise<HomeFocusResponse>;
|
||||
listReleases(page?: number, size?: number): Promise<ReleaseIndexPage>;
|
||||
getRelease(id: string): Promise<ReleaseEditResponse>;
|
||||
createRelease(title: string): Promise<CreateDraftResponse>;
|
||||
updateRelease(id: string, body: ReleaseUpdateRequest): Promise<ReleaseEditResponse>;
|
||||
deleteRelease(id: string, expectedVersion: number): Promise<void>;
|
||||
publishRelease(id: string, expectedVersion: number): Promise<PublishResponse>;
|
||||
archiveRelease(id: string, expectedVersion: number): Promise<ReleaseEditResponse>;
|
||||
/**
|
||||
* 작업본 삭제. 종류마다 다른 endpoint 인 것은 계약의 모양이자 저장 구조다 — Case 와 Reference
|
||||
* 는 한 테이블을 나눠 쓰고 Question 은 다른 테이블이다. Decision 은 계약에 삭제가 없다:
|
||||
* 그쪽 수명주기는 수락·기각·대체이고, 그건 지우는 것이 아니라 무슨 일이 있었는지 남기는 것이다.
|
||||
*/
|
||||
/**
|
||||
* 작업본 삭제. 종류를 손으로 나열하지 않는다 — 개념을 더했을 때 이 목록이 셋에 머물러
|
||||
* 있었고, 부르는 쪽이 `as` 로 캐스팅해 넘기는 바람에 개념이 질문 삭제로 떨어졌다.
|
||||
*/
|
||||
deleteDocument(kind: DeletableDocumentKind, id: string, expectedVersion: number): Promise<void>;
|
||||
/**
|
||||
* Decision 은 프로젝트에 속하므로 경로가 둘을 요구한다. 다른 종류처럼 한 번에 묶지 않는 이유는
|
||||
* 계약이 그렇게 선언했고, 실제로도 프로젝트 밖의 Decision 은 존재하지 않기 때문이다.
|
||||
*/
|
||||
deleteDecision(projectId: string, decisionId: string, expectedVersion: number): Promise<void>;
|
||||
deleteProjectActivity(
|
||||
id: string,
|
||||
activityId: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
|
||||
getHomeFocus(options?: RequestOptions): Promise<HomeFocusResponse>;
|
||||
updateHomeFocus(
|
||||
body: HomeFocusRequest,
|
||||
options: IdempotentOptions,
|
||||
): Promise<HomeFocusResponse>;
|
||||
|
||||
listReleases(
|
||||
page?: number,
|
||||
size?: number,
|
||||
options?: RequestOptions,
|
||||
): Promise<ReleaseIndexPage>;
|
||||
getRelease(
|
||||
id: string,
|
||||
options?: RequestOptions,
|
||||
): Promise<ReleaseEditResponse>;
|
||||
createRelease(
|
||||
title: string,
|
||||
options: IdempotentOptions,
|
||||
): Promise<CreateDraftResponse>;
|
||||
updateRelease(
|
||||
id: string,
|
||||
body: ReleaseUpdateRequest,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ReleaseEditResponse>;
|
||||
deleteRelease(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
publishRelease(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<PublishResponse>;
|
||||
archiveRelease(
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<ReleaseEditResponse>;
|
||||
|
||||
deleteDocument(
|
||||
kind: DeletableDocumentKind,
|
||||
id: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
deleteDecision(
|
||||
projectId: string,
|
||||
decisionId: string,
|
||||
expectedVersion: number,
|
||||
options: IdempotentOptions,
|
||||
): Promise<void>;
|
||||
}>;
|
||||
|
||||
@@ -325,6 +325,25 @@ export type HomeFocusItem = {
|
||||
targetPath: string;
|
||||
};
|
||||
|
||||
export type PublicHomeView = Readonly<{
|
||||
focusItems: readonly HomeFocusItem[];
|
||||
latestEntries: readonly LatestRecordEntry[];
|
||||
}>;
|
||||
|
||||
export type PublicProjectSummary = Readonly<{
|
||||
slug: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
path: string;
|
||||
}>;
|
||||
|
||||
export type PublicReleaseSummary = Readonly<{
|
||||
version: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
path: string;
|
||||
}>;
|
||||
|
||||
export type RecordFilters = {
|
||||
kind?: RecordKind;
|
||||
topic?: string;
|
||||
@@ -388,6 +407,14 @@ export type PublicContentQueries = Readonly<{
|
||||
listContacts(): Promise<PublicContact[]>;
|
||||
/** 주제 한 편. 주제가 없으면 `undefined`. */
|
||||
getTopicDetail(slug: string): Promise<PublicTopicDetail | undefined>;
|
||||
/** 홈 투영은 한 번 읽어 focus/latest를 같은 snapshot에서 돌려준다. */
|
||||
getHome(): Promise<PublicHomeView>;
|
||||
/** 검색과 분리된 명시적 프로젝트 목록 use case. */
|
||||
listProjects(): Promise<PublicProjectSummary[]>;
|
||||
/** 검색과 분리된 명시적 릴리즈 목록 use case. */
|
||||
listReleases(): Promise<PublicReleaseSummary[]>;
|
||||
/** type-ahead/filter가 로컬에서 거를 공개 카탈로그 snapshot. */
|
||||
listCatalog(): Promise<SearchablePublicEntity[]>;
|
||||
getLatestEntries(): Promise<LatestRecordEntry[]>;
|
||||
getHomeFocusItems(): Promise<HomeFocusItem[]>;
|
||||
searchPublicContent(query: string): Promise<SearchablePublicEntity[]>;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import type {
|
||||
ManagementGateway,
|
||||
DeletableDocumentKind,
|
||||
} from "./ports/management-gateway.ts";
|
||||
import { ManagementGatewayError } from "./ports/management-gateway-error.ts";
|
||||
import type {
|
||||
StudioAssetGateway,
|
||||
ListAssetsQuery,
|
||||
UploadAssetForm,
|
||||
} from "./ports/studio-asset-gateway.ts";
|
||||
import type {
|
||||
StudioGateway,
|
||||
CatalogQuery,
|
||||
ListDocumentsQuery,
|
||||
ListPublicationsQuery,
|
||||
} from "./ports/studio-gateway.ts";
|
||||
import { isStudioGatewayError } from "./ports/studio-gateway-error.ts";
|
||||
import type {
|
||||
Asset,
|
||||
AssetDetail,
|
||||
AssetPage,
|
||||
CatalogPage,
|
||||
CreateDocumentInput,
|
||||
CreatePreviewCommand,
|
||||
DocumentPage,
|
||||
PreviewDetail,
|
||||
PublicationPage,
|
||||
PublicationSnapshot,
|
||||
PublicPreview,
|
||||
PublishDocumentCommand,
|
||||
PublishResult,
|
||||
SaveDocumentCommand,
|
||||
StudioDashboard,
|
||||
UnpublishCommand,
|
||||
UpdateAssetCommand,
|
||||
ValidationReport,
|
||||
ValidateDocumentCommand,
|
||||
WorkingCopy,
|
||||
WorkingCopyDetail,
|
||||
} from "../contracts/studio/contract.ts";
|
||||
import type {
|
||||
CreateDraftResponse,
|
||||
DecisionResponse,
|
||||
HomeFocusRequest,
|
||||
HomeFocusResponse,
|
||||
ProjectActivityRequest,
|
||||
ProjectActivityResponse,
|
||||
ProjectEditResponse,
|
||||
ProjectIndexPage,
|
||||
ProjectUpdateRequest,
|
||||
PublishResponse,
|
||||
QuestionIndexPage,
|
||||
ReleaseEditResponse,
|
||||
ReleaseIndexPage,
|
||||
ReleaseUpdateRequest,
|
||||
TopicEdit,
|
||||
TopicVariantEdit,
|
||||
UpdateProjectActivityRequest,
|
||||
} from "../contracts/management/contract.ts";
|
||||
|
||||
export type StudioQueryContext = Readonly<{ signal?: AbortSignal }>;
|
||||
export type StudioCommandContext = Readonly<{
|
||||
signal?: AbortSignal;
|
||||
idempotencyKey: string;
|
||||
}>;
|
||||
|
||||
export type StudioWorkspaceQueries = Readonly<{
|
||||
getDashboard(context?: StudioQueryContext): Promise<StudioDashboard>;
|
||||
listDocuments(query: ListDocumentsQuery, context?: StudioQueryContext): Promise<DocumentPage>;
|
||||
listPublications(query: ListPublicationsQuery, context?: StudioQueryContext): Promise<PublicationPage>;
|
||||
getPublicationSnapshot(publicationEventId: string, context?: StudioQueryContext): Promise<PublicationSnapshot>;
|
||||
getCatalog(query: CatalogQuery, context?: StudioQueryContext): Promise<CatalogPage>;
|
||||
}>;
|
||||
|
||||
export type StudioWorkspaceCommands = Readonly<{
|
||||
createDocument(input: CreateDocumentInput, context: StudioCommandContext): Promise<WorkingCopy>;
|
||||
unpublishPublication(publicationId: string, command: UnpublishCommand, context: StudioCommandContext): Promise<PublishResult>;
|
||||
}>;
|
||||
|
||||
export type StudioDocumentQueries = Readonly<{
|
||||
getDocument(documentId: string, context?: StudioQueryContext): Promise<WorkingCopyDetail>;
|
||||
getCurrentPreview(documentId: string, context?: StudioQueryContext): Promise<PreviewDetail>;
|
||||
}>;
|
||||
|
||||
export type StudioDocumentCommands = Readonly<{
|
||||
saveDocument(documentId: string, command: SaveDocumentCommand, context: StudioCommandContext): Promise<WorkingCopyDetail>;
|
||||
validateDocument(documentId: string, command: ValidateDocumentCommand, context: StudioCommandContext): Promise<ValidationReport>;
|
||||
createPreview(documentId: string, command: CreatePreviewCommand, context: StudioCommandContext): Promise<PublicPreview>;
|
||||
publishDocument(documentId: string, command: PublishDocumentCommand, context: StudioCommandContext): Promise<PublishResult>;
|
||||
}>;
|
||||
|
||||
export type StudioAssetQueries = Readonly<{
|
||||
listAssets(query: ListAssetsQuery, context?: StudioQueryContext): Promise<AssetPage>;
|
||||
getAsset(assetId: string, context?: StudioQueryContext): Promise<AssetDetail>;
|
||||
}>;
|
||||
|
||||
export type StudioAssetCommands = Readonly<{
|
||||
uploadAsset(form: UploadAssetForm, context: StudioCommandContext): Promise<Asset>;
|
||||
updateAssetMetadata(assetId: string, command: UpdateAssetCommand, context: StudioCommandContext): Promise<Asset>;
|
||||
deleteAsset(assetId: string, context: StudioCommandContext): Promise<void>;
|
||||
}>;
|
||||
|
||||
export type StudioManagementQueries = Readonly<{
|
||||
listTopics(context?: StudioQueryContext): Promise<TopicEdit[]>;
|
||||
listTopicVariants(topicId: string, context?: StudioQueryContext): Promise<TopicVariantEdit[]>;
|
||||
listProjects(page?: number, size?: number, context?: StudioQueryContext): Promise<ProjectIndexPage>;
|
||||
listQuestions(page?: number, size?: number, context?: StudioQueryContext): Promise<QuestionIndexPage>;
|
||||
listProjectDecisions(projectId: string, context?: StudioQueryContext): Promise<readonly DecisionResponse[]>;
|
||||
getProject(id: string, context?: StudioQueryContext): Promise<ProjectEditResponse>;
|
||||
listProjectActivities(id: string, context?: StudioQueryContext): Promise<ProjectActivityResponse[]>;
|
||||
getHomeFocus(context?: StudioQueryContext): Promise<HomeFocusResponse>;
|
||||
listReleases(page?: number, size?: number, context?: StudioQueryContext): Promise<ReleaseIndexPage>;
|
||||
getRelease(id: string, context?: StudioQueryContext): Promise<ReleaseEditResponse>;
|
||||
}>;
|
||||
|
||||
export type StudioManagementCommands = Readonly<{
|
||||
createTopic(input: TopicEdit, context: StudioCommandContext): Promise<TopicEdit>;
|
||||
updateTopic(id: string, body: TopicEdit, context: StudioCommandContext): Promise<TopicEdit>;
|
||||
deleteTopic(id: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
createTopicVariant(topicId: string, body: TopicVariantEdit, context: StudioCommandContext): Promise<TopicVariantEdit>;
|
||||
updateTopicVariant(topicId: string, variantId: string, body: TopicVariantEdit, context: StudioCommandContext): Promise<TopicVariantEdit>;
|
||||
deleteTopicVariant(topicId: string, variantId: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
createProject(title: string, context: StudioCommandContext): Promise<CreateDraftResponse>;
|
||||
updateProject(id: string, body: ProjectUpdateRequest, context: StudioCommandContext): Promise<ProjectEditResponse>;
|
||||
deleteProject(id: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
publishProject(id: string, expectedVersion: number, visibility: "PUBLIC" | "UNLISTED" | undefined, context: StudioCommandContext): Promise<PublishResponse>;
|
||||
unpublishProject(id: string, expectedVersion: number, context: StudioCommandContext): Promise<ProjectEditResponse>;
|
||||
createProjectActivity(id: string, body: ProjectActivityRequest, context: StudioCommandContext): Promise<ProjectActivityResponse>;
|
||||
updateProjectActivity(id: string, activityId: string, body: UpdateProjectActivityRequest, context: StudioCommandContext): Promise<ProjectActivityResponse>;
|
||||
deleteProjectActivity(id: string, activityId: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
updateHomeFocus(body: HomeFocusRequest, context: StudioCommandContext): Promise<HomeFocusResponse>;
|
||||
createRelease(title: string, context: StudioCommandContext): Promise<CreateDraftResponse>;
|
||||
updateRelease(id: string, body: ReleaseUpdateRequest, context: StudioCommandContext): Promise<ReleaseEditResponse>;
|
||||
deleteRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
publishRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise<PublishResponse>;
|
||||
archiveRelease(id: string, expectedVersion: number, context: StudioCommandContext): Promise<ReleaseEditResponse>;
|
||||
deleteDocument(kind: DeletableDocumentKind, id: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
deleteDecision(projectId: string, decisionId: string, expectedVersion: number, context: StudioCommandContext): Promise<void>;
|
||||
}>;
|
||||
|
||||
export type TechLogStudioApplication = Readonly<{
|
||||
workspaceQueries: StudioWorkspaceQueries;
|
||||
workspaceCommands: StudioWorkspaceCommands;
|
||||
documentQueries: StudioDocumentQueries;
|
||||
documentCommands: StudioDocumentCommands;
|
||||
assetQueries: StudioAssetQueries;
|
||||
assetCommands: StudioAssetCommands;
|
||||
managementQueries: StudioManagementQueries;
|
||||
managementCommands: StudioManagementCommands;
|
||||
}>;
|
||||
|
||||
type TechLogStudioApplicationDependencies = Readonly<{
|
||||
studio: StudioGateway;
|
||||
assets: StudioAssetGateway;
|
||||
management: ManagementGateway;
|
||||
}>;
|
||||
|
||||
export function createTechLogStudioApplication({
|
||||
studio,
|
||||
assets,
|
||||
management,
|
||||
}: TechLogStudioApplicationDependencies): TechLogStudioApplication {
|
||||
return Object.freeze({
|
||||
workspaceQueries: Object.freeze({
|
||||
getDashboard: (context?: StudioQueryContext) => studio.getDashboard(context),
|
||||
listDocuments: (query: ListDocumentsQuery, context?: StudioQueryContext) => studio.listDocuments(query, context),
|
||||
listPublications: (query: ListPublicationsQuery, context?: StudioQueryContext) => studio.listPublications(query, context),
|
||||
getPublicationSnapshot: (id: string, context?: StudioQueryContext) => studio.getPublicationSnapshot(id, context),
|
||||
getCatalog: (query: CatalogQuery, context?: StudioQueryContext) => studio.getCatalog(query, context),
|
||||
}),
|
||||
workspaceCommands: Object.freeze({
|
||||
createDocument: (input: CreateDocumentInput, context: StudioCommandContext) => studio.createDocument(input, context),
|
||||
unpublishPublication: (id: string, command: UnpublishCommand, context: StudioCommandContext) => studio.unpublishPublication(id, command, context),
|
||||
}),
|
||||
documentQueries: Object.freeze({
|
||||
getDocument: (id: string, context?: StudioQueryContext) => studio.getDocument(id, context),
|
||||
getCurrentPreview: (id: string, context?: StudioQueryContext) => studio.getCurrentPreview(id, context),
|
||||
}),
|
||||
documentCommands: Object.freeze({
|
||||
saveDocument: (id: string, command: SaveDocumentCommand, context: StudioCommandContext) => studio.saveDocument(id, command, context),
|
||||
validateDocument: (id: string, command: ValidateDocumentCommand, context: StudioCommandContext) => studio.validateDocument(id, command, context),
|
||||
createPreview: (id: string, command: CreatePreviewCommand, context: StudioCommandContext) => studio.createPreview(id, command, context),
|
||||
publishDocument: (id: string, command: PublishDocumentCommand, context: StudioCommandContext) => studio.publishDocument(id, command, context),
|
||||
}),
|
||||
assetQueries: Object.freeze({
|
||||
listAssets: (query: ListAssetsQuery, context?: StudioQueryContext) => assets.listAssets(query, context),
|
||||
getAsset: (id: string, context?: StudioQueryContext) => assets.getAsset(id, context),
|
||||
}),
|
||||
assetCommands: Object.freeze({
|
||||
uploadAsset: (form: UploadAssetForm, context: StudioCommandContext) => assets.uploadAsset(form, context),
|
||||
updateAssetMetadata: (id: string, command: UpdateAssetCommand, context: StudioCommandContext) => assets.updateAssetMetadata(id, command, context),
|
||||
deleteAsset: (id: string, context: StudioCommandContext) => assets.deleteAsset(id, context),
|
||||
}),
|
||||
managementQueries: Object.freeze({
|
||||
listTopics: (context?: StudioQueryContext) => management.listTopics(context),
|
||||
listTopicVariants: (topicId: string, context?: StudioQueryContext) => management.listTopicVariants(topicId, context),
|
||||
listProjects: (page?: number, size?: number, context?: StudioQueryContext) => management.listProjects(page, size, context),
|
||||
listQuestions: (page?: number, size?: number, context?: StudioQueryContext) => management.listQuestions(page, size, context),
|
||||
listProjectDecisions: (projectId: string, context?: StudioQueryContext) => management.listProjectDecisions(projectId, context),
|
||||
getProject: (id: string, context?: StudioQueryContext) => management.getProject(id, context),
|
||||
listProjectActivities: (id: string, context?: StudioQueryContext) => management.listProjectActivities(id, context),
|
||||
getHomeFocus: (context?: StudioQueryContext) => management.getHomeFocus(context),
|
||||
listReleases: (page?: number, size?: number, context?: StudioQueryContext) => management.listReleases(page, size, context),
|
||||
getRelease: (id: string, context?: StudioQueryContext) => management.getRelease(id, context),
|
||||
}),
|
||||
managementCommands: Object.freeze({
|
||||
createTopic: (input: TopicEdit, context: StudioCommandContext) => management.createTopic(input, context),
|
||||
updateTopic: (id: string, body: TopicEdit, context: StudioCommandContext) => management.updateTopic(id, body, context),
|
||||
deleteTopic: (id: string, version: number, context: StudioCommandContext) => management.deleteTopic(id, version, context),
|
||||
createTopicVariant: (topicId: string, body: TopicVariantEdit, context: StudioCommandContext) => management.createTopicVariant(topicId, body, context),
|
||||
updateTopicVariant: (topicId: string, variantId: string, body: TopicVariantEdit, context: StudioCommandContext) => management.updateTopicVariant(topicId, variantId, body, context),
|
||||
deleteTopicVariant: (topicId: string, variantId: string, version: number, context: StudioCommandContext) => management.deleteTopicVariant(topicId, variantId, version, context),
|
||||
createProject: (title: string, context: StudioCommandContext) => management.createProject(title, context),
|
||||
updateProject: (id: string, body: ProjectUpdateRequest, context: StudioCommandContext) => management.updateProject(id, body, context),
|
||||
deleteProject: (id: string, version: number, context: StudioCommandContext) => management.deleteProject(id, version, context),
|
||||
publishProject: (id: string, version: number, visibility: "PUBLIC" | "UNLISTED" | undefined, context: StudioCommandContext) => management.publishProject(id, version, visibility, context),
|
||||
unpublishProject: (id: string, version: number, context: StudioCommandContext) => management.unpublishProject(id, version, context),
|
||||
createProjectActivity: (id: string, body: ProjectActivityRequest, context: StudioCommandContext) => management.createProjectActivity(id, body, context),
|
||||
updateProjectActivity: (id: string, activityId: string, body: UpdateProjectActivityRequest, context: StudioCommandContext) => management.updateProjectActivity(id, activityId, body, context),
|
||||
deleteProjectActivity: (id: string, activityId: string, version: number, context: StudioCommandContext) => management.deleteProjectActivity(id, activityId, version, context),
|
||||
updateHomeFocus: (body: HomeFocusRequest, context: StudioCommandContext) => management.updateHomeFocus(body, context),
|
||||
createRelease: (title: string, context: StudioCommandContext) => management.createRelease(title, context),
|
||||
updateRelease: (id: string, body: ReleaseUpdateRequest, context: StudioCommandContext) => management.updateRelease(id, body, context),
|
||||
deleteRelease: (id: string, version: number, context: StudioCommandContext) => management.deleteRelease(id, version, context),
|
||||
publishRelease: (id: string, version: number, context: StudioCommandContext) => management.publishRelease(id, version, context),
|
||||
archiveRelease: (id: string, version: number, context: StudioCommandContext) => management.archiveRelease(id, version, context),
|
||||
deleteDocument: (kind: DeletableDocumentKind, id: string, version: number, context: StudioCommandContext) => management.deleteDocument(kind, id, version, context),
|
||||
deleteDecision: (projectId: string, decisionId: string, version: number, context: StudioCommandContext) => management.deleteDecision(projectId, decisionId, version, context),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export type {
|
||||
CatalogQuery,
|
||||
DeletableDocumentKind,
|
||||
ListAssetsQuery,
|
||||
ListDocumentsQuery,
|
||||
ListPublicationsQuery,
|
||||
UploadAssetForm,
|
||||
};
|
||||
|
||||
export const isStudioApplicationError = isStudioGatewayError;
|
||||
export const StudioManagementError = ManagementGatewayError;
|
||||
@@ -1,17 +1,11 @@
|
||||
import type { PublicContentQueries } from "./ports/public-content-queries.ts";
|
||||
import type { StudioAssetGateway } from "./ports/studio-asset-gateway.ts";
|
||||
import type { ManagementGateway } from "./ports/management-gateway.ts";
|
||||
import type { StudioGateway } from "./ports/studio-gateway.ts";
|
||||
import type { TechLogStudioApplication } from "./studio-application.ts";
|
||||
|
||||
export const TECH_LOG_FEATURE_ID = "tech-log" as const;
|
||||
|
||||
export type TechLogFeatureInput = Readonly<{
|
||||
publicContent: PublicContentQueries;
|
||||
createStudioGateway(): StudioGateway;
|
||||
createStudioAssetGateway(): StudioAssetGateway;
|
||||
// 주제·프로젝트 관리. MOCK 대응물이 없다 — 이 표면은 백엔드가 없으면 존재할 이유가 없고,
|
||||
// 픽스처를 만들면 실제로는 못 만드는 주제를 화면이 보여주게 된다.
|
||||
createManagementGateway(): ManagementGateway;
|
||||
createStudioApplication(): TechLogStudioApplication;
|
||||
}>;
|
||||
|
||||
declare module "../../../application/ports/in/application-api.ts" {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"packageId": "@tech-log/management-contract",
|
||||
"version": "1.0.0",
|
||||
"digest": "sha256:0c226600c45b06433480a8a2ef3d812480dce3850c333bfcab5f626143ce77ea",
|
||||
"digest": "sha256:6036a41879ccf161ba3b7db184be3897684c19e8890f3446460293f1f1f7ab3d",
|
||||
"sourceRevision": "a0dac96",
|
||||
"operationIds": [
|
||||
"createCaseDraft",
|
||||
|
||||
@@ -23,3 +23,5 @@ export type HomeFocusResponse = Schemas["HomeFocusResponse"];
|
||||
export type ProjectActivityRequest = Schemas["ProjectActivityRequest"];
|
||||
export type UpdateProjectActivityRequest = Schemas["UpdateProjectActivityRequest"];
|
||||
export type ProjectActivityResponse = Schemas["ProjectActivityResponse"];
|
||||
export type ReleaseChangeType = ReleaseUpdateRequest["changeTypes"][number];
|
||||
export type ProjectActivityType = ProjectActivityRequest["activityType"];
|
||||
|
||||
@@ -1484,7 +1484,7 @@ export interface components {
|
||||
summary: string;
|
||||
/** Format: date */
|
||||
releasedOn?: string;
|
||||
changeTypes: string[];
|
||||
changeTypes: ("FEATURE" | "FIX" | "REFACTOR" | "DOCS" | "INFRA" | "BREAKING")[];
|
||||
reasonMarkdown?: string;
|
||||
changesMarkdown: string;
|
||||
userImpactMarkdown?: string;
|
||||
@@ -1626,6 +1626,8 @@ export interface components {
|
||||
* 맞출 방법이 없다 — 홈 편집기가 고른 프로젝트의 질문만 거르지 못한 이유가 그것이다.
|
||||
* */
|
||||
slug?: string;
|
||||
/** @description Taxonomy 구조 화면이 상세 조회 없이 project-topic 관계를 그리기 위한 목록 projection. */
|
||||
topicIds: string[];
|
||||
phase: string;
|
||||
workflowStatus: string;
|
||||
targetVisibility: string;
|
||||
@@ -1733,7 +1735,8 @@ export interface components {
|
||||
ProjectActivityRequest: {
|
||||
/** Format: int64 */
|
||||
expectedProjectVersion: number;
|
||||
activityType: string;
|
||||
/** @enum {string} */
|
||||
activityType: "PHASE_CHANGED" | "QUESTION_OPENED" | "QUESTION_RESOLVED" | "DECISION_ACCEPTED" | "CASE_PUBLISHED" | "REFERENCE_PUBLISHED" | "MILESTONE_REACHED" | "PROJECT_PAUSED" | "PROJECT_RESUMED";
|
||||
title: string;
|
||||
summary?: string;
|
||||
/** @enum {string} */
|
||||
@@ -1749,7 +1752,8 @@ export interface components {
|
||||
id: string;
|
||||
/** Format: uuid */
|
||||
projectId: string;
|
||||
activityType: string;
|
||||
/** @enum {string} */
|
||||
activityType: "PHASE_CHANGED" | "QUESTION_OPENED" | "QUESTION_RESOLVED" | "DECISION_ACCEPTED" | "CASE_PUBLISHED" | "REFERENCE_PUBLISHED" | "MILESTONE_REACHED" | "PROJECT_PAUSED" | "PROJECT_RESUMED";
|
||||
title: string;
|
||||
summary?: string;
|
||||
visibility: string;
|
||||
|
||||
@@ -6958,6 +6958,13 @@ components:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
enum:
|
||||
- FEATURE
|
||||
- FIX
|
||||
- REFACTOR
|
||||
- DOCS
|
||||
- INFRA
|
||||
- BREAKING
|
||||
reasonMarkdown:
|
||||
type: string
|
||||
changesMarkdown:
|
||||
@@ -7260,6 +7267,7 @@ components:
|
||||
required:
|
||||
- id
|
||||
- name
|
||||
- topicIds
|
||||
- phase
|
||||
- workflowStatus
|
||||
- targetVisibility
|
||||
@@ -7278,6 +7286,12 @@ components:
|
||||
이 프로젝트의 공개 이름. 다른 목록이 프로젝트를 가리킬 때 쓰는 것이 id 가 아니라
|
||||
이 값이라(`ProjectSummary` 에는 id 가 없다), 목록 행이 이것을 싣지 않으면 두 목록을
|
||||
맞출 방법이 없다 — 홈 편집기가 고른 프로젝트의 질문만 거르지 못한 이유가 그것이다.
|
||||
topicIds:
|
||||
type: array
|
||||
description: Taxonomy 구조 화면이 상세 조회 없이 project-topic 관계를 그리기 위한 목록 projection.
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
phase:
|
||||
type: string
|
||||
workflowStatus:
|
||||
@@ -7536,6 +7550,16 @@ components:
|
||||
format: int64
|
||||
activityType:
|
||||
type: string
|
||||
enum:
|
||||
- PHASE_CHANGED
|
||||
- QUESTION_OPENED
|
||||
- QUESTION_RESOLVED
|
||||
- DECISION_ACCEPTED
|
||||
- CASE_PUBLISHED
|
||||
- REFERENCE_PUBLISHED
|
||||
- MILESTONE_REACHED
|
||||
- PROJECT_PAUSED
|
||||
- PROJECT_RESUMED
|
||||
title:
|
||||
type: string
|
||||
maxLength: 180
|
||||
@@ -7575,6 +7599,16 @@ components:
|
||||
format: uuid
|
||||
activityType:
|
||||
type: string
|
||||
enum:
|
||||
- PHASE_CHANGED
|
||||
- QUESTION_OPENED
|
||||
- QUESTION_RESOLVED
|
||||
- DECISION_ACCEPTED
|
||||
- CASE_PUBLISHED
|
||||
- REFERENCE_PUBLISHED
|
||||
- MILESTONE_REACHED
|
||||
- PROJECT_PAUSED
|
||||
- PROJECT_RESUMED
|
||||
title:
|
||||
type: string
|
||||
summary:
|
||||
|
||||
@@ -13,6 +13,14 @@ import {
|
||||
} from "./tech-log-studio-contract-contribution.ts";
|
||||
import { TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID } from "../adapters/http/studio-session-credentials.ts";
|
||||
|
||||
|
||||
type NamedInstalledHttpContract<OperationId extends string> =
|
||||
InstalledHttpContract<unknown, unknown, unknown> &
|
||||
Readonly<{
|
||||
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"] &
|
||||
Readonly<{ operationId: OperationId }>;
|
||||
}>;
|
||||
|
||||
type PathValues = Readonly<Record<string, string>>;
|
||||
type QueryEntries = readonly (readonly [string, string])[];
|
||||
|
||||
@@ -60,13 +68,13 @@ const COMMAND_EFFECT: CommandEffectDescriptor<ProblemDetails> = Object.freeze({
|
||||
* 공유한다. 부트스트랩 프로필은 쓰지 않는다: CSRF 토큰을 발급하는 것은 `getStudioSession`
|
||||
* 하나뿐이고, 이 표면은 그 뒤에만 호출된다.
|
||||
*/
|
||||
function readOperation(
|
||||
operationId: string,
|
||||
function readOperation<const OperationId extends string>(
|
||||
operationId: OperationId,
|
||||
pathTemplate: string,
|
||||
responseByteLimit: number,
|
||||
project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }> = () =>
|
||||
Object.freeze({ pathValues: NO_PATH, queryEntries: NO_QUERY }),
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
): NamedInstalledHttpContract<OperationId> {
|
||||
return Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId,
|
||||
@@ -95,7 +103,7 @@ function readOperation(
|
||||
authProfileId: TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID,
|
||||
diagnosticsOperation: `techLog.management.${operationId}`,
|
||||
}),
|
||||
}) as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
}) as NamedInstalledHttpContract<OperationId>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,8 +111,8 @@ function readOperation(
|
||||
* 이 맡는다. 그래서 `NOT_IDEMPOTENT` 가 아니라 재시도 예산 0 으로 둔다: 응답을 못 본 재시도가
|
||||
* 두 번째 생성을 만들 수 있는 표면이다.
|
||||
*/
|
||||
function writeOperation(
|
||||
operationId: string,
|
||||
function writeOperation<const OperationId extends string>(
|
||||
operationId: OperationId,
|
||||
method: "POST" | "PUT" | "DELETE",
|
||||
pathTemplate: string,
|
||||
options: Readonly<{
|
||||
@@ -118,7 +126,7 @@ function writeOperation(
|
||||
queryEntries: QueryEntries;
|
||||
body: unknown;
|
||||
}>,
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
): NamedInstalledHttpContract<OperationId> {
|
||||
return Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId,
|
||||
@@ -155,7 +163,7 @@ function writeOperation(
|
||||
}),
|
||||
// read 쪽과 달리 여기서만 unknown 을 거친다: `emptyBodyStatuses` 유무로 responseBody 가
|
||||
// 갈리는 삼항이 union 타입을 만들어, 컴파일러가 리터럴을 대상 타입과 겹친다고 보지 않는다.
|
||||
}) as unknown as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
}) as unknown as NamedInstalledHttpContract<OperationId>;
|
||||
}
|
||||
|
||||
const byId = (input: never) => {
|
||||
@@ -168,7 +176,7 @@ const P = "/api/v1/studio/projects";
|
||||
const R = "/api/v1/studio/releases";
|
||||
const D = "/api/v1/studio";
|
||||
|
||||
const HTTP_CONTRACTS = Object.freeze([
|
||||
export const TECH_LOG_MANAGEMENT_HTTP_CONTRACTS = Object.freeze([
|
||||
readOperation("listStudioTopics", T, 131_072),
|
||||
writeOperation(
|
||||
"createTopic",
|
||||
@@ -625,10 +633,10 @@ const HTTP_CONTRACTS = Object.freeze([
|
||||
});
|
||||
},
|
||||
),
|
||||
]);
|
||||
] as const);
|
||||
|
||||
export const TECH_LOG_MANAGEMENT_OPERATION_IDS = Object.freeze(
|
||||
HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
TECH_LOG_MANAGEMENT_HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
);
|
||||
|
||||
export const TECH_LOG_MANAGEMENT_CONTRIBUTION: InstalledContractContribution = Object.freeze({
|
||||
@@ -644,6 +652,6 @@ export const TECH_LOG_MANAGEMENT_CONTRIBUTION: InstalledContractContribution = O
|
||||
sourceRevision: canonicalSource.sourceRevision,
|
||||
}),
|
||||
}),
|
||||
http: HTTP_CONTRACTS,
|
||||
http: TECH_LOG_MANAGEMENT_HTTP_CONTRACTS,
|
||||
events: Object.freeze([]),
|
||||
});
|
||||
|
||||
@@ -7,18 +7,560 @@ export type TechLogRouteMessageKey =
|
||||
| `route.${TechLogRouteId}.title`
|
||||
| `route.${TechLogRouteId}.navigation`;
|
||||
|
||||
function createCatalog(): Readonly<Record<TechLogRouteMessageKey, string>> {
|
||||
const EN_ROUTE_COPY = Object.freeze({
|
||||
TECH_LOG_HOME: { title: "TechLog" },
|
||||
TECH_LOG_EXPLORE: { title: "Explore", navigation: "Explore" },
|
||||
TECH_LOG_EXPLORE_KIND: { title: "Explore by type" },
|
||||
TECH_LOG_CASE: { title: "Case" },
|
||||
TECH_LOG_REFERENCE: { title: "Reference" },
|
||||
TECH_LOG_CONCEPT: { title: "Concept" },
|
||||
TECH_LOG_SETUP: { title: "Setup" },
|
||||
TECH_LOG_QUESTION: { title: "Open Question" },
|
||||
TECH_LOG_TOPICS: { title: "Topics", navigation: "Topics" },
|
||||
TECH_LOG_TOPIC: { title: "Topic" },
|
||||
TECH_LOG_TOPIC_VARIANT: { title: "Topic" },
|
||||
TECH_LOG_PROJECTS: { title: "Projects", navigation: "Projects" },
|
||||
TECH_LOG_PROJECT: { title: "Project" },
|
||||
TECH_LOG_PROJECT_RECORDS: { title: "Project records" },
|
||||
TECH_LOG_PROJECT_DECISIONS: { title: "Project decisions" },
|
||||
TECH_LOG_PROJECT_ACTIVITY: { title: "Project activity" },
|
||||
TECH_LOG_RELEASES: { title: "Release notes" },
|
||||
TECH_LOG_RELEASE: { title: "Release notes" },
|
||||
TECH_LOG_PROFILE: { title: "Profile", navigation: "Profile" },
|
||||
TECH_LOG_SEARCH: { title: "Search" },
|
||||
TECH_LOG_STUDIO_HOME: { title: "TechLog Studio" },
|
||||
TECH_LOG_STUDIO_DOCUMENTS: {
|
||||
title: "Working copies",
|
||||
navigation: "Working copies",
|
||||
},
|
||||
TECH_LOG_STUDIO_DOCUMENT_NEW: {
|
||||
title: "New document",
|
||||
navigation: "New document",
|
||||
},
|
||||
TECH_LOG_STUDIO_DOCUMENT_EDIT: { title: "Edit document" },
|
||||
TECH_LOG_STUDIO_DOCUMENT_VALIDATION: { title: "Validate document" },
|
||||
TECH_LOG_STUDIO_DOCUMENT_PREVIEW: { title: "Public Preview" },
|
||||
TECH_LOG_STUDIO_DOCUMENT_PUBLISH: { title: "Publish" },
|
||||
TECH_LOG_STUDIO_PUBLICATIONS: {
|
||||
title: "Publication history",
|
||||
navigation: "Publication history",
|
||||
},
|
||||
TECH_LOG_STUDIO_PUBLICATION_PREVIEW: { title: "Publication Snapshot" },
|
||||
TECH_LOG_STUDIO_ASSETS: { title: "Asset", navigation: "Asset" },
|
||||
TECH_LOG_STUDIO_TAXONOMY: {
|
||||
title: "Topics and projects",
|
||||
navigation: "Topics · Projects",
|
||||
},
|
||||
TECH_LOG_STUDIO_PROJECT_EDIT: { title: "Edit project" },
|
||||
TECH_LOG_STUDIO_TOPIC_EDIT: { title: "Edit topic" },
|
||||
TECH_LOG_STUDIO_RELEASES: { title: "Releases", navigation: "Releases" },
|
||||
TECH_LOG_STUDIO_RELEASE_EDIT: { title: "Edit release" },
|
||||
TECH_LOG_STUDIO_NOT_FOUND: { title: "Studio page not found" },
|
||||
NOT_FOUND: { title: "Page not found" },
|
||||
} as const satisfies Readonly<
|
||||
Record<TechLogRouteId, Readonly<{ title: string; navigation?: string }>>
|
||||
>);
|
||||
|
||||
function createRouteCatalog(
|
||||
locale: "ko-KR" | "en-US",
|
||||
): Readonly<Record<TechLogRouteMessageKey, string>> {
|
||||
return Object.freeze(
|
||||
Object.fromEntries(
|
||||
Object.values(TECH_LOG_ROUTE_REGISTRY).flatMap((definition) => [
|
||||
[`route.${definition.routeId}.title`, definition.title],
|
||||
[`route.${definition.routeId}.navigation`, definition.title],
|
||||
]),
|
||||
Object.values(TECH_LOG_ROUTE_REGISTRY).flatMap((definition) => {
|
||||
const routeId = definition.routeId as TechLogRouteId;
|
||||
const localized: Readonly<{
|
||||
title: string;
|
||||
navigation?: string;
|
||||
}> | null = locale === "en-US" ? EN_ROUTE_COPY[routeId] : null;
|
||||
const title = localized?.title ?? definition.title;
|
||||
const navigation =
|
||||
localized?.navigation ??
|
||||
definition.navigationLabel ??
|
||||
title;
|
||||
return [
|
||||
[`route.${routeId}.title`, title],
|
||||
[`route.${routeId}.navigation`, navigation],
|
||||
];
|
||||
}),
|
||||
),
|
||||
) as Readonly<Record<TechLogRouteMessageKey, string>>;
|
||||
}
|
||||
|
||||
/*
|
||||
* Product copy that is behavioral rather than editorial lives in the feature
|
||||
* catalog. Long-form explanations remain next to the screen that owns them.
|
||||
*/
|
||||
const KO_UI_MESSAGES = Object.freeze({
|
||||
"techLog.public.home": "TechLog 홈",
|
||||
"techLog.public.primaryNavigation": "주요 탐색",
|
||||
"techLog.public.mobileNavigation": "모바일 주요 탐색",
|
||||
"techLog.action.retry": "다시 시도",
|
||||
"techLog.action.search": "검색",
|
||||
"techLog.action.save": "저장",
|
||||
"techLog.action.saving": "저장 중…",
|
||||
"techLog.action.savingBeforeNavigate": "저장 중",
|
||||
"techLog.action.loading": "불러오는 중",
|
||||
"techLog.action.publish": "게시",
|
||||
"techLog.action.republish": "다시 게시",
|
||||
"techLog.action.publishing": "게시 중…",
|
||||
"techLog.action.processing": "처리 중",
|
||||
"techLog.action.delete": "삭제",
|
||||
"techLog.action.moveUp": "위로",
|
||||
"techLog.action.moveDown": "아래로",
|
||||
"techLog.action.close": "닫기",
|
||||
"techLog.action.apply": "적용",
|
||||
"techLog.action.insert": "삽입",
|
||||
"techLog.action.unpublish": "게시 취소",
|
||||
"techLog.action.viewLarge": "크게 보기",
|
||||
"techLog.action.resetFilters": "필터 초기화",
|
||||
"techLog.action.archive": "보관",
|
||||
"techLog.state.documentNotFound": "작업본을 찾을 수 없습니다",
|
||||
"techLog.state.topicNotFound": "주제를 찾을 수 없습니다",
|
||||
"techLog.state.validationLoadFailed": "검증 화면을 불러오지 못했습니다",
|
||||
"techLog.state.publicPreviewLoadFailed": "Public Preview를 불러오지 못했습니다",
|
||||
"techLog.state.documentLoadFailed": "문서를 불러오지 못했습니다",
|
||||
"techLog.state.publicationLoadFailed": "게시 정보를 불러오지 못했습니다",
|
||||
"techLog.state.assetListLoadFailed": "Asset 목록을 불러오지 못했습니다",
|
||||
"techLog.state.assetListLoading": "Asset 목록을 불러오는 중입니다.",
|
||||
"techLog.state.projectLoading": "프로젝트를 불러오는 중입니다.",
|
||||
"techLog.state.topicLoading": "주제를 불러오는 중입니다.",
|
||||
"techLog.state.publicationLoading": "게시 준비 정보를 불러오는 중입니다.",
|
||||
"techLog.state.validationLoading": "검증 정보를 불러오는 중입니다.",
|
||||
"techLog.state.publicPreviewLoading": "Public Preview를 불러오는 중입니다.",
|
||||
"techLog.state.publicationListLoading": "게시 기록을 불러오는 중입니다.",
|
||||
"techLog.state.publicationListLoadFailed": "게시 기록을 불러오지 못했습니다",
|
||||
"techLog.state.assetNextLoadFailed": "다음 Asset을 불러오지 못했습니다.",
|
||||
"techLog.state.assetDetailLoadFailed": "Asset 상세를 불러오지 못했습니다.",
|
||||
"techLog.state.topicLoadFailed": "주제를 불러오지 못했습니다.",
|
||||
"techLog.state.taxonomyLoadFailed": "주제와 프로젝트를 불러오지 못했습니다.",
|
||||
"techLog.state.projectLoadFailed": "프로젝트를 불러오지 못했습니다.",
|
||||
"techLog.failure.archiveFailed": "보관하지 못했습니다.",
|
||||
"techLog.failure.deleteFailed": "삭제하지 못했습니다.",
|
||||
"techLog.failure.saveFailed": "저장하지 못했습니다.",
|
||||
"techLog.failure.variantSaveFailed": "축을 저장하지 못했습니다.",
|
||||
"techLog.failure.variantDeleteFailed": "축을 삭제하지 못했습니다.",
|
||||
"techLog.failure.topicDeleteFailed": "주제를 삭제하지 못했습니다.",
|
||||
"techLog.failure.projectDeleteFailed": "프로젝트를 삭제하지 못했습니다.",
|
||||
"techLog.failure.projectUnpublishFailed": "프로젝트를 비공개로 되돌리지 못했습니다.",
|
||||
"techLog.failure.projectPublishFailed": "프로젝트를 게시하지 못했습니다.",
|
||||
"techLog.action.deleteBlock": "블록 삭제",
|
||||
"techLog.action.restart": "다시 시작",
|
||||
"techLog.action.addVersion": "+ 버전 추가",
|
||||
"techLog.action.addBlock": "+ 블록 추가",
|
||||
"techLog.action.createWorkingCopy": "작업본 만들기",
|
||||
"techLog.action.insertAsset": "본문에 자료 넣기",
|
||||
"techLog.action.saveHome": "홈 설정 저장",
|
||||
"techLog.action.upload": "업로드",
|
||||
"techLog.action.uploading": "업로드 중",
|
||||
"techLog.action.add": "추가",
|
||||
"techLog.action.addTopic": "주제 추가",
|
||||
"techLog.action.addProject": "프로젝트 추가",
|
||||
"techLog.action.more": "더 보기",
|
||||
"techLog.action.saveAltText": "대체 텍스트 저장",
|
||||
"techLog.action.makePublic": "공개",
|
||||
"techLog.action.removeFromPublic": "공개에서 내리기",
|
||||
"techLog.action.cancel": "취소",
|
||||
"techLog.action.stay": "이 페이지에 머무르기",
|
||||
"techLog.action.discard": "변경 버리기",
|
||||
"techLog.action.saveThenNavigate": "저장 후 이동",
|
||||
"techLog.action.expand": "펼치기",
|
||||
"techLog.action.collapse": "접기",
|
||||
"techLog.action.validate": "검증",
|
||||
"techLog.action.revalidate": "다시 검증",
|
||||
"techLog.action.validating": "검증 중…",
|
||||
"techLog.action.createPreview": "Preview 만들기",
|
||||
"techLog.action.recreatePreview": "Preview 다시 만들기",
|
||||
"techLog.action.creating": "생성 중…",
|
||||
"techLog.action.keepPublished": "계속 게시",
|
||||
"techLog.action.confirmUnpublish": "게시 취소 확인",
|
||||
"techLog.action.addOption": "+ 선택지",
|
||||
"techLog.action.addCriterion": "+ 판단 기준",
|
||||
"techLog.state.studioNotFound": "Studio 화면을 찾을 수 없습니다",
|
||||
"techLog.state.studioLoadFailed": "Studio 화면을 불러오지 못했습니다",
|
||||
"techLog.state.homeLoadFailed": "홈 설정을 불러오지 못했습니다",
|
||||
"techLog.state.homeLoading": "홈 설정을 불러오는 중입니다.",
|
||||
"techLog.state.homePreparing": "홈 설정을 준비하고 있습니다.",
|
||||
"techLog.state.openQuestionsLoadFailed": "열린 질문을 불러오지 못했습니다. 새로고침해 주세요.",
|
||||
"techLog.state.decisionsLoadFailed": "결정을 불러오지 못했습니다. 새로고침해 주세요.",
|
||||
"techLog.state.releaseLoadFailed": "릴리즈를 불러오지 못했습니다",
|
||||
"techLog.state.releaseLoading": "릴리즈를 불러오는 중입니다.",
|
||||
"techLog.state.documentListLoadFailed": "작업본을 불러오지 못했습니다.",
|
||||
"techLog.state.documentListLoading": "작업본을 불러오는 중입니다.",
|
||||
"techLog.state.dashboardLoadFailed": "작업 흐름을 불러오지 못했습니다",
|
||||
"techLog.state.dashboardLoading": "Studio 요약을 불러오는 중입니다.",
|
||||
"techLog.state.publicationSnapshotLoading": "게시 Snapshot을 불러오는 중입니다.",
|
||||
"techLog.state.publicationRecordNotFound": "게시 기록을 찾을 수 없습니다",
|
||||
"techLog.state.publicationSnapshotLoadFailed": "게시 Snapshot을 불러오지 못했습니다",
|
||||
"techLog.state.emptyPublicationList": "조건에 맞는 게시 기록이 없습니다",
|
||||
"techLog.state.emptySearchResult": "검색 결과가 없습니다.",
|
||||
"techLog.state.taxonomyLoading": "주제와 프로젝트를 불러오는 중입니다.",
|
||||
"techLog.state.emptyDocumentList": "조건에 맞는 작업본이 없습니다",
|
||||
"techLog.state.emptyDocumentListHint": "검색어 또는 필터를 바꾸거나 새 문서를 만드세요.",
|
||||
"techLog.state.emptyAssetSearch": "조건에 맞는 Asset이 없습니다",
|
||||
"techLog.state.emptyAssetSearchHint": "검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.",
|
||||
"techLog.state.emptyAssetLibrary": "등록된 Asset이 없습니다",
|
||||
"techLog.state.emptyAssetLibraryHint": "Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.",
|
||||
"techLog.state.emptyPublicationHistory": "아직 게시 기록이 없습니다.",
|
||||
"techLog.state.emptyPublicationListHint": "검색어 또는 이벤트 필터를 바꿔 보세요.",
|
||||
"techLog.studio.group.work": "작업",
|
||||
"techLog.studio.group.structure": "구조",
|
||||
"techLog.studio.group.assets": "자료",
|
||||
"techLog.studio.group.publish": "게시",
|
||||
"techLog.studio.publicSite": "공개 사이트 보기",
|
||||
"techLog.studio.primaryNavigation": "Studio 주 탐색",
|
||||
"techLog.studio.mobileNavigation": "Studio 모바일 탐색",
|
||||
"techLog.studio.menuOpen": "Studio 메뉴 열기",
|
||||
"techLog.studio.menuClose": "Studio 메뉴 닫기",
|
||||
"techLog.editor.status.clean": "저장됨",
|
||||
"techLog.editor.status.dirty": "저장되지 않음",
|
||||
"techLog.editor.status.saving": "저장 중…",
|
||||
"techLog.editor.status.conflict": "저장 충돌",
|
||||
"techLog.editor.statusLabel": "편집 상태",
|
||||
"techLog.editor.workStatus": "작업 상태",
|
||||
"techLog.failure.documentNotFound": "작업본을 찾을 수 없습니다.",
|
||||
"techLog.failure.versionConflict":
|
||||
"다른 변경이 먼저 저장되었습니다. 최신 버전을 다시 확인해 주세요.",
|
||||
"techLog.failure.validationRejected":
|
||||
"입력값을 확인한 뒤 다시 시도해 주세요.",
|
||||
"techLog.failure.validationStale":
|
||||
"저장 버전이 바뀌었습니다. 현재 버전으로 다시 검증해 주세요.",
|
||||
"techLog.failure.previewStale":
|
||||
"미리보기가 현재 저장 버전과 다릅니다. 다시 만들어 주세요.",
|
||||
"techLog.failure.previewExpired":
|
||||
"미리보기가 만료되었습니다. 다시 만들어 주세요.",
|
||||
"techLog.failure.publicationConflict":
|
||||
"게시 상태가 변경되었습니다. 최신 상태를 다시 확인해 주세요.",
|
||||
"techLog.failure.studioUnavailable": "Studio가 잠시 응답하지 않습니다.",
|
||||
"techLog.failure.assetInUse": "사용 중인 Asset은 삭제할 수 없습니다.",
|
||||
"techLog.failure.duplicateInFlight": "같은 작업을 처리하고 있습니다.",
|
||||
"techLog.public.error.pageLoadTitle": "페이지를 불러오지 못했습니다.",
|
||||
"techLog.public.error.pageLoadHelp": "잠시 후 다시 시도해 주세요. 문제가 계속되면 아래 Trace ID를 함께 전달해 주세요.",
|
||||
"techLog.action.exploreAllRecords": "모든 기록 탐색",
|
||||
"techLog.state.latestLoadFailed": "최근 기록을 불러오지 못했습니다.",
|
||||
"techLog.state.noPublishedRecords": "아직 공개된 기록이 없습니다.",
|
||||
"techLog.action.clearSearch": "검색어 지우기",
|
||||
"techLog.state.noMatchingPublicRecords": "일치하는 공개 기록이 없습니다.",
|
||||
"techLog.action.backToExplore": "전체 탐색으로 돌아가기",
|
||||
"techLog.action.browseProjects": "프로젝트 둘러보기",
|
||||
"techLog.action.exploreRecords": "기록 탐색",
|
||||
"techLog.state.noPublishedProjects": "아직 공개된 프로젝트가 없습니다.",
|
||||
"techLog.state.noRegisteredTopics": "아직 등록한 주제가 없습니다.",
|
||||
"techLog.state.noProjectPublishedRecords": "아직 이 프로젝트에서 공개한 기록이 없습니다.",
|
||||
"techLog.state.noDecisions": "아직 확정한 결정이 없습니다.",
|
||||
"techLog.state.noOpenQuestions": "아직 열린 질문도 없습니다. 이 프로젝트의 조사는 기록을 모으는 단계입니다.",
|
||||
"techLog.state.noImpact": "남긴 영향이 없습니다.",
|
||||
"techLog.state.noEvidence": "연결한 근거 기록이 없습니다.",
|
||||
"techLog.state.noConclusion": "아직 정리한 결론이 없습니다. 아래 조사 지도가 지금까지 모은 기록을 보여 줍니다.",
|
||||
"techLog.public.notFound": "페이지를 찾을 수 없습니다.",
|
||||
"techLog.public.notFoundDetail": "요청한 공개 페이지가 없습니다.",
|
||||
"techLog.action.changeLog": "변경 기록",
|
||||
"techLog.public.releaseBreadcrumb": "변경 기록 경로",
|
||||
"techLog.state.noPublishedReleases": "아직 공개된 릴리즈가 없습니다.",
|
||||
"techLog.state.noPublishedTopics": "아직 공개된 주제가 없습니다.",
|
||||
"techLog.state.noAssumptions": "현재 기록된 가정이 없습니다.",
|
||||
"techLog.state.noUnknowns": "해결 과정에서 남은 미지수가 없습니다.",
|
||||
"techLog.state.irreversible": "되돌릴 수 없습니다.",
|
||||
"techLog.notice.published": "게시했습니다.",
|
||||
"techLog.failure.saveRetry": "저장하지 못했습니다. 다시 시도해 주세요.",
|
||||
"techLog.failure.saveBeforePublish": "게시 전에 변경사항을 저장하지 못했습니다.",
|
||||
"techLog.failure.validationBeforePublish": "게시 전에 문서를 검증하지 못했습니다.",
|
||||
"techLog.failure.previewBeforePublish": "게시 전에 Public Preview를 만들지 못했습니다.",
|
||||
"techLog.failure.publishRetry": "게시하지 못했습니다. 다시 시도해 주세요.",
|
||||
"techLog.state.editorPreparing": "문서 편집기를 준비하고 있습니다.",
|
||||
"techLog.state.sessionDocumentMissing": "이 작업본은 현재 Studio 세션에 없습니다.",
|
||||
"techLog.failure.publishFieldsRequired": "게시할 수 없습니다. 표시한 칸을 채워 주세요.",
|
||||
"techLog.notice.homeFocusSaved": "홈에 표시할 항목을 저장했습니다.",
|
||||
"techLog.action.savingPlain": "저장하는 중",
|
||||
"techLog.action.creatingPlain": "만드는 중…",
|
||||
"techLog.state.emptyOrderedText": "아직 입력한 항목이 없습니다.",
|
||||
"techLog.state.projectTopicsEmpty": "아직 주제가 없습니다. 주제·프로젝트 화면에서 먼저 만듭니다.",
|
||||
"techLog.notice.previewCreated": "현재 저장 버전의 Public Preview를 만들었습니다.",
|
||||
"techLog.failure.previewRetry": "Public Preview를 만들지 못했습니다. 다시 시도해 주세요.",
|
||||
"techLog.notice.unpublished": "게시를 취소했습니다.",
|
||||
"techLog.failure.unpublishFailed": "게시를 취소하지 못했습니다.",
|
||||
"techLog.notice.releaseUnpublished": "릴리즈를 공개에서 내렸습니다.",
|
||||
"techLog.failure.releasePublishFields": "공개하지 못했습니다. 버전, 제목, 한 줄 요약, 변경 유형, 변경 내용, 검증, 공개일을 확인해 주세요.",
|
||||
"techLog.failure.releaseUnpublishFailed": "공개에서 내리지 못했습니다.",
|
||||
"techLog.notice.releaseDraftCreated": "릴리즈 {title} 초안을 만들었습니다. 목록에서 편집을 눌러 내용을 채웁니다.",
|
||||
"techLog.notice.releaseDeleted": "릴리즈 {version} 을(를) 삭제했습니다.",
|
||||
"techLog.action.adding": "추가 중…",
|
||||
"techLog.state.releasesEmpty": "아직 릴리즈가 없습니다.",
|
||||
"techLog.state.dashboardContinueEmpty": "이어서 작성할 문서가 없습니다.",
|
||||
"techLog.state.dashboardValidateEmpty": "현재 검증할 문서가 없습니다.",
|
||||
"techLog.state.dashboardReadyEmpty": "게시 준비가 끝난 문서가 없습니다.",
|
||||
"techLog.state.groupedTopicsEmpty": "묶은 주제가 없습니다.",
|
||||
"techLog.state.topicsCreateFirst": "아직 주제가 없습니다. 위에서 하나 만들어 주세요.",
|
||||
"techLog.state.projectsEmpty": "아직 프로젝트가 없습니다.",
|
||||
"techLog.action.addingPlain": "추가 중",
|
||||
"techLog.action.unpublishing": "취소 처리 중…",
|
||||
"techLog.state.validationClean": "오류와 경고가 없습니다.",
|
||||
"techLog.notice.validationComplete": "저장된 문서 검증이 완료되었습니다.",
|
||||
"techLog.failure.validationRetry": "검증하지 못했습니다. 다시 시도해 주세요.",
|
||||
"techLog.state.validationRecordEmpty": "검증 기록이 없습니다",
|
||||
"techLog.state.warningsEmpty": "확인할 경고가 없습니다.",
|
||||
"techLog.notice.assetArchived": "보관했습니다.",
|
||||
"techLog.notice.assetDeleted": "삭제했습니다.",
|
||||
"techLog.notice.assetAltTextSaved": "대체 텍스트를 저장했습니다.",
|
||||
"techLog.notice.topicSavedVersion": "주제를 버전 {version}으로 저장했습니다.",
|
||||
"techLog.notice.itemAdded": "{title} 을(를) 추가했습니다.",
|
||||
"techLog.notice.itemSaved": "{title} 을(를) 저장했습니다.",
|
||||
"techLog.notice.itemDeleted": "{title} 을(를) 삭제했습니다.",
|
||||
"techLog.notice.topicCreated": "주제 {name} 을(를) 만들었습니다.",
|
||||
"techLog.notice.projectCreated": "프로젝트 {title} 을(를) 만들었습니다.",
|
||||
"techLog.notice.topicDeleted": "주제 {name} 을(를) 삭제했습니다.",
|
||||
"techLog.notice.projectDeleted": "프로젝트 {name} 을(를) 삭제했습니다.",
|
||||
"techLog.notice.savedVersion": "버전 {version}으로 저장했습니다.",
|
||||
"techLog.management.conflict":
|
||||
"다른 변경이 먼저 반영되었습니다. 최신 상태를 다시 확인해 주세요.",
|
||||
"techLog.management.notFound": "대상을 찾을 수 없습니다.",
|
||||
"techLog.management.validationRejected": "입력값을 확인해 주세요.",
|
||||
"techLog.management.authRequired": "Studio 로그인이 필요합니다.",
|
||||
"techLog.management.forbidden": "이 작업을 수행할 권한이 없습니다.",
|
||||
"techLog.management.serverFailure":
|
||||
"관리 API와 통신하지 못했습니다. 다시 시도해 주세요.",
|
||||
} as const);
|
||||
|
||||
const EN_UI_MESSAGES = Object.freeze({
|
||||
"techLog.public.home": "TechLog home",
|
||||
"techLog.public.primaryNavigation": "Primary navigation",
|
||||
"techLog.public.mobileNavigation": "Mobile primary navigation",
|
||||
"techLog.action.retry": "Try again",
|
||||
"techLog.action.search": "Search",
|
||||
"techLog.action.save": "Save",
|
||||
"techLog.action.saving": "Saving…",
|
||||
"techLog.action.savingBeforeNavigate": "Saving",
|
||||
"techLog.action.loading": "Loading",
|
||||
"techLog.action.publish": "Publish",
|
||||
"techLog.action.republish": "Republish",
|
||||
"techLog.action.publishing": "Publishing…",
|
||||
"techLog.action.processing": "Processing",
|
||||
"techLog.action.delete": "Delete",
|
||||
"techLog.action.moveUp": "Move up",
|
||||
"techLog.action.moveDown": "Move down",
|
||||
"techLog.action.close": "Close",
|
||||
"techLog.action.apply": "Apply",
|
||||
"techLog.action.insert": "Insert",
|
||||
"techLog.action.unpublish": "Unpublish",
|
||||
"techLog.action.viewLarge": "View larger",
|
||||
"techLog.action.resetFilters": "Reset filters",
|
||||
"techLog.action.archive": "Archive",
|
||||
"techLog.state.documentNotFound": "The working copy could not be found.",
|
||||
"techLog.state.topicNotFound": "The topic could not be found.",
|
||||
"techLog.state.validationLoadFailed": "The validation screen could not be loaded.",
|
||||
"techLog.state.publicPreviewLoadFailed": "The public preview could not be loaded.",
|
||||
"techLog.state.documentLoadFailed": "The document could not be loaded.",
|
||||
"techLog.state.publicationLoadFailed": "Publication information could not be loaded.",
|
||||
"techLog.state.assetListLoadFailed": "The asset list could not be loaded.",
|
||||
"techLog.state.assetListLoading": "Loading assets.",
|
||||
"techLog.state.projectLoading": "Loading the project.",
|
||||
"techLog.state.topicLoading": "Loading the topic.",
|
||||
"techLog.state.publicationLoading": "Loading publication readiness.",
|
||||
"techLog.state.validationLoading": "Loading validation information.",
|
||||
"techLog.state.publicPreviewLoading": "Loading the public preview.",
|
||||
"techLog.state.publicationListLoading": "Loading publications.",
|
||||
"techLog.state.publicationListLoadFailed": "Publications could not be loaded.",
|
||||
"techLog.state.assetNextLoadFailed": "The next assets could not be loaded.",
|
||||
"techLog.state.assetDetailLoadFailed": "Asset details could not be loaded.",
|
||||
"techLog.state.topicLoadFailed": "The topic could not be loaded.",
|
||||
"techLog.state.taxonomyLoadFailed": "Topics and projects could not be loaded.",
|
||||
"techLog.state.projectLoadFailed": "The project could not be loaded.",
|
||||
"techLog.failure.archiveFailed": "The item could not be archived.",
|
||||
"techLog.failure.deleteFailed": "The item could not be deleted.",
|
||||
"techLog.failure.saveFailed": "The item could not be saved.",
|
||||
"techLog.failure.variantSaveFailed": "The variant could not be saved.",
|
||||
"techLog.failure.variantDeleteFailed": "The variant could not be deleted.",
|
||||
"techLog.failure.topicDeleteFailed": "The topic could not be deleted.",
|
||||
"techLog.failure.projectDeleteFailed": "The project could not be deleted.",
|
||||
"techLog.failure.projectUnpublishFailed": "The project could not be made private.",
|
||||
"techLog.failure.projectPublishFailed": "The project could not be published.",
|
||||
"techLog.action.deleteBlock": "Delete block",
|
||||
"techLog.action.restart": "Restart",
|
||||
"techLog.action.addVersion": "+ Add version",
|
||||
"techLog.action.addBlock": "+ Add block",
|
||||
"techLog.action.createWorkingCopy": "Create working copy",
|
||||
"techLog.action.insertAsset": "Insert asset into content",
|
||||
"techLog.action.saveHome": "Save home settings",
|
||||
"techLog.action.upload": "Upload",
|
||||
"techLog.action.uploading": "Uploading",
|
||||
"techLog.action.add": "Add",
|
||||
"techLog.action.addTopic": "Add topic",
|
||||
"techLog.action.addProject": "Add project",
|
||||
"techLog.action.more": "Show more",
|
||||
"techLog.action.saveAltText": "Save alt text",
|
||||
"techLog.action.makePublic": "Make public",
|
||||
"techLog.action.removeFromPublic": "Remove from public",
|
||||
"techLog.action.cancel": "Cancel",
|
||||
"techLog.action.stay": "Stay on this page",
|
||||
"techLog.action.discard": "Discard changes",
|
||||
"techLog.action.saveThenNavigate": "Save and continue",
|
||||
"techLog.action.expand": "Expand",
|
||||
"techLog.action.collapse": "Collapse",
|
||||
"techLog.action.validate": "Validate",
|
||||
"techLog.action.revalidate": "Validate again",
|
||||
"techLog.action.validating": "Validating…",
|
||||
"techLog.action.createPreview": "Create preview",
|
||||
"techLog.action.recreatePreview": "Recreate preview",
|
||||
"techLog.action.creating": "Creating…",
|
||||
"techLog.action.keepPublished": "Keep published",
|
||||
"techLog.action.confirmUnpublish": "Confirm unpublish",
|
||||
"techLog.action.addOption": "+ Option",
|
||||
"techLog.action.addCriterion": "+ Criterion",
|
||||
"techLog.state.studioNotFound": "The Studio screen could not be found",
|
||||
"techLog.state.studioLoadFailed": "The Studio screen could not be loaded",
|
||||
"techLog.state.homeLoadFailed": "Home settings could not be loaded",
|
||||
"techLog.state.homeLoading": "Loading home settings.",
|
||||
"techLog.state.homePreparing": "Preparing home settings.",
|
||||
"techLog.state.openQuestionsLoadFailed": "Open questions could not be loaded. Refresh and try again.",
|
||||
"techLog.state.decisionsLoadFailed": "Decisions could not be loaded. Refresh and try again.",
|
||||
"techLog.state.releaseLoadFailed": "The release could not be loaded",
|
||||
"techLog.state.releaseLoading": "Loading the release.",
|
||||
"techLog.state.documentListLoadFailed": "Working copies could not be loaded.",
|
||||
"techLog.state.documentListLoading": "Loading working copies.",
|
||||
"techLog.state.dashboardLoadFailed": "The work flow could not be loaded",
|
||||
"techLog.state.dashboardLoading": "Loading the Studio summary.",
|
||||
"techLog.state.publicationSnapshotLoading": "Loading the publication snapshot.",
|
||||
"techLog.state.publicationRecordNotFound": "The publication record could not be found",
|
||||
"techLog.state.publicationSnapshotLoadFailed": "The publication snapshot could not be loaded",
|
||||
"techLog.state.emptyPublicationList": "No publication records match the current filters",
|
||||
"techLog.state.emptySearchResult": "No search results.",
|
||||
"techLog.state.taxonomyLoading": "Loading topics and projects.",
|
||||
"techLog.state.emptyDocumentList": "No working copies match the current filters",
|
||||
"techLog.state.emptyDocumentListHint": "Change the search or filters, or create a new document.",
|
||||
"techLog.state.emptyAssetSearch": "No assets match the current search",
|
||||
"techLog.state.emptyAssetSearchHint": "Change or clear the search to see all assets.",
|
||||
"techLog.state.emptyAssetLibrary": "No assets have been registered",
|
||||
"techLog.state.emptyAssetLibraryHint": "Upload an asset from a Case editor to manage it here.",
|
||||
"techLog.state.emptyPublicationHistory": "No publication history yet.",
|
||||
"techLog.state.emptyPublicationListHint": "Change the search or event filter.",
|
||||
"techLog.studio.group.work": "Work",
|
||||
"techLog.studio.group.structure": "Structure",
|
||||
"techLog.studio.group.assets": "Assets",
|
||||
"techLog.studio.group.publish": "Publish",
|
||||
"techLog.studio.publicSite": "View public site",
|
||||
"techLog.studio.primaryNavigation": "Studio primary navigation",
|
||||
"techLog.studio.mobileNavigation": "Studio mobile navigation",
|
||||
"techLog.studio.menuOpen": "Open Studio menu",
|
||||
"techLog.studio.menuClose": "Close Studio menu",
|
||||
"techLog.editor.status.clean": "Saved",
|
||||
"techLog.editor.status.dirty": "Unsaved",
|
||||
"techLog.editor.status.saving": "Saving…",
|
||||
"techLog.editor.status.conflict": "Save conflict",
|
||||
"techLog.editor.statusLabel": "Editing status",
|
||||
"techLog.editor.workStatus": "Work status",
|
||||
"techLog.failure.documentNotFound": "The working copy could not be found.",
|
||||
"techLog.failure.versionConflict":
|
||||
"Another change was saved first. Reload the latest version and try again.",
|
||||
"techLog.failure.validationRejected":
|
||||
"Review the entered values and try again.",
|
||||
"techLog.failure.validationStale":
|
||||
"The saved version changed. Validate the current version again.",
|
||||
"techLog.failure.previewStale":
|
||||
"The preview does not match the current saved version. Create it again.",
|
||||
"techLog.failure.previewExpired":
|
||||
"The preview expired. Create it again.",
|
||||
"techLog.failure.publicationConflict":
|
||||
"The publication state changed. Reload the latest state and try again.",
|
||||
"techLog.failure.studioUnavailable":
|
||||
"Studio is temporarily unavailable.",
|
||||
"techLog.failure.assetInUse":
|
||||
"An asset that is in use cannot be deleted.",
|
||||
"techLog.failure.duplicateInFlight":
|
||||
"The same operation is already in progress.",
|
||||
"techLog.public.error.pageLoadTitle": "The page could not be loaded.",
|
||||
"techLog.public.error.pageLoadHelp": "Try again shortly. If the problem continues, include the Trace ID below when asking for help.",
|
||||
"techLog.action.exploreAllRecords": "Explore all records",
|
||||
"techLog.state.latestLoadFailed": "Recent records could not be loaded.",
|
||||
"techLog.state.noPublishedRecords": "No records have been published yet.",
|
||||
"techLog.action.clearSearch": "Clear search",
|
||||
"techLog.state.noMatchingPublicRecords": "No public records match the search.",
|
||||
"techLog.action.backToExplore": "Back to explore",
|
||||
"techLog.action.browseProjects": "Browse projects",
|
||||
"techLog.action.exploreRecords": "Explore records",
|
||||
"techLog.state.noPublishedProjects": "No projects have been published yet.",
|
||||
"techLog.state.noRegisteredTopics": "No topics have been registered yet.",
|
||||
"techLog.state.noProjectPublishedRecords": "This project has no published records yet.",
|
||||
"techLog.state.noDecisions": "No decisions have been finalized yet.",
|
||||
"techLog.state.noOpenQuestions": "There are no open questions yet. This project is still gathering records.",
|
||||
"techLog.state.noImpact": "No impact has been recorded.",
|
||||
"techLog.state.noEvidence": "No evidence records are linked.",
|
||||
"techLog.state.noConclusion": "No conclusion has been written yet. The research map below shows the records gathered so far.",
|
||||
"techLog.public.notFound": "The page could not be found.",
|
||||
"techLog.public.notFoundDetail": "The requested public page does not exist.",
|
||||
"techLog.action.changeLog": "Change log",
|
||||
"techLog.public.releaseBreadcrumb": "Release change log path",
|
||||
"techLog.state.noPublishedReleases": "No releases have been published yet.",
|
||||
"techLog.state.noPublishedTopics": "No topics have been published yet.",
|
||||
"techLog.state.noAssumptions": "No assumptions have been recorded.",
|
||||
"techLog.state.noUnknowns": "No unresolved unknowns remain in this record.",
|
||||
"techLog.state.irreversible": "This action cannot be undone.",
|
||||
"techLog.notice.published": "Published.",
|
||||
"techLog.failure.saveRetry": "The document could not be saved. Try again.",
|
||||
"techLog.failure.saveBeforePublish": "Changes could not be saved before publishing.",
|
||||
"techLog.failure.validationBeforePublish": "The document could not be validated before publishing.",
|
||||
"techLog.failure.previewBeforePublish": "The public preview could not be created before publishing.",
|
||||
"techLog.failure.publishRetry": "The document could not be published. Try again.",
|
||||
"techLog.state.editorPreparing": "Preparing the document editor.",
|
||||
"techLog.state.sessionDocumentMissing": "This working copy is not available in the current Studio session.",
|
||||
"techLog.failure.publishFieldsRequired": "The document cannot be published. Complete the highlighted fields.",
|
||||
"techLog.notice.homeFocusSaved": "The home focus was saved.",
|
||||
"techLog.action.savingPlain": "Saving",
|
||||
"techLog.action.creatingPlain": "Creating…",
|
||||
"techLog.state.emptyOrderedText": "No items have been entered yet.",
|
||||
"techLog.state.projectTopicsEmpty": "No topics exist yet. Create one from Topics · Projects first.",
|
||||
"techLog.notice.previewCreated": "Created a public preview for the current saved version.",
|
||||
"techLog.failure.previewRetry": "The public preview could not be created. Try again.",
|
||||
"techLog.notice.unpublished": "Publication cancelled.",
|
||||
"techLog.failure.unpublishFailed": "The publication could not be cancelled.",
|
||||
"techLog.notice.releaseUnpublished": "The release was removed from public view.",
|
||||
"techLog.failure.releasePublishFields": "The release could not be published. Check its version, title, summary, change type, changes, validation, and publication date.",
|
||||
"techLog.failure.releaseUnpublishFailed": "The release could not be removed from public view.",
|
||||
"techLog.notice.releaseDraftCreated": "Created release draft {title}. Edit it from the list to complete the details.",
|
||||
"techLog.notice.releaseDeleted": "Deleted release {version}.",
|
||||
"techLog.action.adding": "Adding…",
|
||||
"techLog.state.releasesEmpty": "No releases yet.",
|
||||
"techLog.state.dashboardContinueEmpty": "No documents are waiting to be continued.",
|
||||
"techLog.state.dashboardValidateEmpty": "No documents currently need validation.",
|
||||
"techLog.state.dashboardReadyEmpty": "No documents are ready to publish.",
|
||||
"techLog.state.groupedTopicsEmpty": "No grouped topics.",
|
||||
"techLog.state.topicsCreateFirst": "No topics yet. Create one above.",
|
||||
"techLog.state.projectsEmpty": "No projects yet.",
|
||||
"techLog.action.addingPlain": "Adding",
|
||||
"techLog.action.unpublishing": "Cancelling publication…",
|
||||
"techLog.state.validationClean": "No errors or warnings.",
|
||||
"techLog.notice.validationComplete": "Validation of the saved document is complete.",
|
||||
"techLog.failure.validationRetry": "Validation failed. Try again.",
|
||||
"techLog.state.validationRecordEmpty": "No validation record",
|
||||
"techLog.state.warningsEmpty": "No warnings require acknowledgement.",
|
||||
"techLog.notice.assetArchived": "Archived.",
|
||||
"techLog.notice.assetDeleted": "Deleted.",
|
||||
"techLog.notice.assetAltTextSaved": "Alternative text saved.",
|
||||
"techLog.notice.topicSavedVersion": "Saved the topic as version {version}.",
|
||||
"techLog.notice.itemAdded": "Added {title}.",
|
||||
"techLog.notice.itemSaved": "Saved {title}.",
|
||||
"techLog.notice.itemDeleted": "Deleted {title}.",
|
||||
"techLog.notice.topicCreated": "Created topic {name}.",
|
||||
"techLog.notice.projectCreated": "Created project {title}.",
|
||||
"techLog.notice.topicDeleted": "Deleted topic {name}.",
|
||||
"techLog.notice.projectDeleted": "Deleted project {name}.",
|
||||
"techLog.notice.savedVersion": "Saved as version {version}.",
|
||||
"techLog.management.conflict":
|
||||
"Another change was applied first. Reload the latest state and try again.",
|
||||
"techLog.management.notFound": "The requested item could not be found.",
|
||||
"techLog.management.validationRejected": "Review the entered values.",
|
||||
"techLog.management.authRequired": "Studio sign-in is required.",
|
||||
"techLog.management.forbidden":
|
||||
"You are not allowed to perform this operation.",
|
||||
"techLog.management.serverFailure":
|
||||
"The management API is unavailable. Try again shortly.",
|
||||
} as const satisfies Record<keyof typeof KO_UI_MESSAGES, string>);
|
||||
|
||||
export const TECH_LOG_MESSAGE_CATALOGS = Object.freeze({
|
||||
"ko-KR": createCatalog(),
|
||||
"en-US": createCatalog(),
|
||||
"ko-KR": Object.freeze({
|
||||
...createRouteCatalog("ko-KR"),
|
||||
...KO_UI_MESSAGES,
|
||||
}),
|
||||
"en-US": Object.freeze({
|
||||
...createRouteCatalog("en-US"),
|
||||
...EN_UI_MESSAGES,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -6,6 +6,14 @@ import { TECH_LOG_FEATURE_ID } from "../application/tech-log-feature-input.ts";
|
||||
import canonicalSource from "./public/canonical-source.json" with { type: "json" };
|
||||
import { envelopeData, envelopeError, passthroughInput } from "./tech-log-studio-contract-contribution.ts";
|
||||
|
||||
|
||||
type NamedInstalledHttpContract<OperationId extends string> =
|
||||
InstalledHttpContract<unknown, unknown, unknown> &
|
||||
Readonly<{
|
||||
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"] &
|
||||
Readonly<{ operationId: OperationId }>;
|
||||
}>;
|
||||
|
||||
type PathValues = Readonly<Record<string, string>>;
|
||||
type QueryEntries = readonly (readonly [string, string])[];
|
||||
|
||||
@@ -41,13 +49,13 @@ function queryOf(input: Readonly<Record<string, unknown>>): QueryEntries {
|
||||
* sending the session cookie on a public read fails the profile check rather
|
||||
* than silently making the cache-friendly surface user-specific.
|
||||
*/
|
||||
function publicRead(
|
||||
operationId: string,
|
||||
function publicRead<const OperationId extends string>(
|
||||
operationId: OperationId,
|
||||
pathTemplate: string,
|
||||
responseByteLimit: number,
|
||||
project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }> = () =>
|
||||
Object.freeze({ pathValues: NO_PATH, queryEntries: NO_QUERY }),
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
): NamedInstalledHttpContract<OperationId> {
|
||||
return Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId,
|
||||
@@ -78,7 +86,7 @@ function publicRead(
|
||||
authProfileId: "ANONYMOUS",
|
||||
diagnosticsOperation: `techLog.public.${operationId}`,
|
||||
}),
|
||||
}) as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
}) as NamedInstalledHttpContract<OperationId>;
|
||||
}
|
||||
|
||||
const bySlug = (input: never) => {
|
||||
@@ -91,7 +99,7 @@ const bySlug = (input: never) => {
|
||||
|
||||
const P = "/api/v1/public";
|
||||
|
||||
const HTTP_CONTRACTS = Object.freeze([
|
||||
export const TECH_LOG_PUBLIC_HTTP_CONTRACTS = Object.freeze([
|
||||
publicRead("getPublicSite", `${P}/site`, 32_768),
|
||||
publicRead("getPublicHome", `${P}/home`, 262_144),
|
||||
publicRead("exploreKnowledge", `${P}/explore/knowledge`, 262_144, (input: never) => {
|
||||
@@ -147,10 +155,10 @@ const HTTP_CONTRACTS = Object.freeze([
|
||||
const value = input as unknown as Readonly<{ q?: string; page?: number; size?: number }>;
|
||||
return Object.freeze({ pathValues: NO_PATH, queryEntries: queryOf(value ?? {}) });
|
||||
}),
|
||||
]);
|
||||
] as const);
|
||||
|
||||
export const TECH_LOG_PUBLIC_OPERATION_IDS = Object.freeze(
|
||||
HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
TECH_LOG_PUBLIC_HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
);
|
||||
|
||||
export type TechLogPublicOperationId =
|
||||
@@ -170,6 +178,6 @@ export const TECH_LOG_PUBLIC_CONTRIBUTION: InstalledContractContribution =
|
||||
sourceRevision: canonicalSource.sourceRevision,
|
||||
}),
|
||||
}),
|
||||
http: HTTP_CONTRACTS,
|
||||
http: TECH_LOG_PUBLIC_HTTP_CONTRACTS,
|
||||
events: Object.freeze([]),
|
||||
});
|
||||
|
||||
@@ -146,11 +146,19 @@ const COMMAND_EFFECT: CommandEffectDescriptor<ProblemDetails> =
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
type NamedInstalledHttpContract<OperationId extends string> =
|
||||
InstalledHttpContract<unknown, unknown, unknown> &
|
||||
Readonly<{
|
||||
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"] &
|
||||
Readonly<{ operationId: OperationId }>;
|
||||
}>;
|
||||
|
||||
type PathValues = Readonly<Record<string, string>>;
|
||||
type QueryEntries = readonly (readonly [string, string])[];
|
||||
|
||||
function safeOperation(
|
||||
operationId: string,
|
||||
function safeOperation<const OperationId extends string>(
|
||||
operationId: OperationId,
|
||||
pathTemplate: string,
|
||||
responseByteLimit: number,
|
||||
project: (input: never) => Readonly<{ pathValues: PathValues; queryEntries: QueryEntries }>,
|
||||
@@ -159,7 +167,7 @@ function safeOperation(
|
||||
// of `TECH_LOG_STUDIO_BOOTSTRAP`. Every other safe/keyed operation keeps
|
||||
// the default `TECH_LOG_STUDIO_SESSION`.
|
||||
authProfileId: TechLogStudioAuthProfileId = TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID,
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
): NamedInstalledHttpContract<OperationId> {
|
||||
return Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId,
|
||||
@@ -189,11 +197,11 @@ function safeOperation(
|
||||
authProfileId,
|
||||
diagnosticsOperation: `techLog.studio.${operationId}`,
|
||||
}),
|
||||
}) as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
}) as NamedInstalledHttpContract<OperationId>;
|
||||
}
|
||||
|
||||
function keyedOperation(
|
||||
operationId: string,
|
||||
function keyedOperation<const OperationId extends string>(
|
||||
operationId: OperationId,
|
||||
method: "POST" | "PUT" | "DELETE",
|
||||
pathTemplate: string,
|
||||
options: Readonly<{
|
||||
@@ -207,7 +215,7 @@ function keyedOperation(
|
||||
queryEntries: QueryEntries;
|
||||
body: unknown;
|
||||
}>,
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
): NamedInstalledHttpContract<OperationId> {
|
||||
return Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId,
|
||||
@@ -238,7 +246,7 @@ function keyedOperation(
|
||||
authProfileId: TECH_LOG_STUDIO_SESSION_AUTH_PROFILE_ID,
|
||||
diagnosticsOperation: `techLog.studio.${operationId}`,
|
||||
}),
|
||||
}) as InstalledHttpContract<unknown, unknown, unknown>;
|
||||
}) as NamedInstalledHttpContract<OperationId>;
|
||||
}
|
||||
|
||||
const NO_PATH = Object.freeze({});
|
||||
@@ -265,6 +273,8 @@ const GET_STUDIO_SESSION = safeOperation(
|
||||
TECH_LOG_STUDIO_BOOTSTRAP_AUTH_PROFILE_ID,
|
||||
);
|
||||
|
||||
export const TECH_LOG_STUDIO_SESSION_CONTRACT = GET_STUDIO_SESSION;
|
||||
|
||||
const GET_STUDIO_DASHBOARD = safeOperation(
|
||||
"getStudioDashboard",
|
||||
"/api/v1/studio/dashboard",
|
||||
@@ -616,7 +626,7 @@ const DELETE_STUDIO_ASSET = keyedOperation(
|
||||
// Contribution assembly
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const HTTP_CONTRACTS = Object.freeze([
|
||||
export const TECH_LOG_STUDIO_HTTP_CONTRACTS = Object.freeze([
|
||||
GET_STUDIO_SESSION,
|
||||
GET_STUDIO_DASHBOARD,
|
||||
LIST_STUDIO_DOCUMENTS,
|
||||
@@ -635,19 +645,19 @@ const HTTP_CONTRACTS = Object.freeze([
|
||||
GET_STUDIO_ASSET,
|
||||
UPDATE_STUDIO_ASSET,
|
||||
DELETE_STUDIO_ASSET,
|
||||
]);
|
||||
] as const);
|
||||
|
||||
// Fix round 2, item 3. Fails composition closed rather than letting a wrong
|
||||
// assignment (two operations, or zero) reach production undetected.
|
||||
assertExactlyOneTechLogStudioBootstrapOperation(
|
||||
HTTP_CONTRACTS.map((entry) => ({
|
||||
TECH_LOG_STUDIO_HTTP_CONTRACTS.map((entry) => ({
|
||||
operationId: entry.contract.operationId,
|
||||
authProfileId: entry.frontend.authProfileId,
|
||||
})),
|
||||
);
|
||||
|
||||
export const TECH_LOG_STUDIO_OPERATION_IDS = Object.freeze(
|
||||
HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
TECH_LOG_STUDIO_HTTP_CONTRACTS.map((entry) => entry.contract.operationId),
|
||||
);
|
||||
|
||||
export type TechLogStudioOperationId =
|
||||
@@ -667,6 +677,6 @@ export const TECH_LOG_STUDIO_CONTRIBUTION: InstalledContractContribution =
|
||||
sourceRevision: canonicalSource.sourceRevision,
|
||||
}),
|
||||
}),
|
||||
http: HTTP_CONTRACTS,
|
||||
http: TECH_LOG_STUDIO_HTTP_CONTRACTS,
|
||||
events: Object.freeze([]),
|
||||
});
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Button, SelectControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
|
||||
import type { RecordKind } from "../../../application/ports/public-content-queries.ts";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import { publicRoutePrefixes } from "../public-routes.ts";
|
||||
|
||||
/*
|
||||
탐색이 거를 수 있는 종류. 이름은 공용 표에서 가져온다 — 예전에는 이 목록만 「개념」이라
|
||||
@@ -41,16 +45,17 @@ export function ExploreFilterForm({
|
||||
showType?: boolean;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const { message } = useLocale();
|
||||
// This form sits inside a page that renders its own loading state, so it does
|
||||
// not hand back a fallback of its own — that would put a second skeleton
|
||||
// inside a screen already showing one, and move the layout under it. It
|
||||
// renders its real structure immediately with empty option lists and fills
|
||||
// them in when the catalog arrives.
|
||||
const view = usePublicContent(["tech-log", "explore-filters"], async (queries) => {
|
||||
const projectPrefix = "/projects/";
|
||||
const projectPrefix = publicRoutePrefixes.project;
|
||||
const [records, entities] = await Promise.all([
|
||||
queries.listRecords(),
|
||||
queries.searchPublicContent(""),
|
||||
queries.listCatalog(),
|
||||
]);
|
||||
const projectSlugs = entities
|
||||
.filter((entity) => entity.contentType === "PROJECT")
|
||||
@@ -110,7 +115,7 @@ export function ExploreFilterForm({
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
<Form
|
||||
key={formKey}
|
||||
className="public-filter-form"
|
||||
action={action}
|
||||
@@ -118,12 +123,12 @@ export function ExploreFilterForm({
|
||||
onSubmit={submit}
|
||||
>
|
||||
{showType ? (
|
||||
<label><span>유형</span><select name="type" defaultValue={kind ?? ""}><option value="">전체</option>{EXPLORE_KINDS.map((entry) => <option key={entry} value={entry}>{DOCUMENT_KIND_LABELS[entry]}</option>)}</select></label>
|
||||
<label><span>유형</span><SelectControl name="type" defaultValue={kind ?? ""}><option value="">전체</option>{EXPLORE_KINDS.map((entry) => <option key={entry} value={entry}>{DOCUMENT_KIND_LABELS[entry]}</option>)}</SelectControl></label>
|
||||
) : null}
|
||||
<label><span>주제</span><select name="topic" defaultValue={selectedTopic ?? ""}><option value="">전체</option>{topics.map((item) => <option value={item.slug} key={item.slug}>{item.name}</option>)}</select></label>
|
||||
<label><span>프로젝트</span><select name="project" defaultValue={selectedProject ?? ""}><option value="">전체</option>{projects.map((item) => <option value={item.slug} key={item.slug}>{item.title}</option>)}</select></label>
|
||||
<button type="submit">적용</button>
|
||||
{hasActiveFilter ? <Link to={action}>필터 초기화</Link> : null}
|
||||
</form>
|
||||
<label><span>주제</span><SelectControl name="topic" defaultValue={selectedTopic ?? ""}><option value="">전체</option>{topics.map((item) => <option value={item.slug} key={item.slug}>{item.name}</option>)}</SelectControl></label>
|
||||
<label><span>프로젝트</span><SelectControl name="project" defaultValue={selectedProject ?? ""}><option value="">전체</option>{projects.map((item) => <option value={item.slug} key={item.slug}>{item.title}</option>)}</SelectControl></label>
|
||||
<Button visualPolicy="inherit" type="submit">{message("techLog.action.apply")}</Button>
|
||||
{hasActiveFilter ? <Link to={action}>{message("techLog.action.resetFilters")}</Link> : null}
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
|
||||
type FatalErrorStateProps = {
|
||||
traceId: string;
|
||||
@@ -11,25 +13,24 @@ export function FatalErrorState({
|
||||
onRetry,
|
||||
retryHref = "/",
|
||||
}: FatalErrorStateProps) {
|
||||
const { message } = useLocale();
|
||||
|
||||
return (
|
||||
<main id="main-content" className="shell fatal-state">
|
||||
<p className="context-label">Service error</p>
|
||||
<h1>페이지를 불러오지 못했습니다.</h1>
|
||||
<p>
|
||||
잠시 후 다시 시도해 주세요. 문제가 계속되면 아래 Trace ID를 함께
|
||||
전달해 주세요.
|
||||
</p>
|
||||
<h1>{message("techLog.public.error.pageLoadTitle")}</h1>
|
||||
<p>{message("techLog.public.error.pageLoadHelp")}</p>
|
||||
<p className="trace-id">
|
||||
<span>Trace ID</span>
|
||||
<code>{traceId}</code>
|
||||
</p>
|
||||
{onRetry ? (
|
||||
<button className="primary-link" type="button" onClick={onRetry}>
|
||||
다시 시도
|
||||
</button>
|
||||
<Button visualPolicy="inherit" className="primary-link" type="button" onClick={onRetry}>
|
||||
{message("techLog.action.retry")}
|
||||
</Button>
|
||||
) : (
|
||||
<Link className="primary-link" to={retryHref}>
|
||||
다시 시도
|
||||
{message("techLog.action.retry")}
|
||||
</Link>
|
||||
)}
|
||||
</main>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { cardSummary } from "../../../domain/content-format/card-summary.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export type LatestEntry = {
|
||||
id: string;
|
||||
typeLabel: string;
|
||||
@@ -34,21 +36,21 @@ export function LatestIndex({
|
||||
<p className="section-kicker">Index</p>
|
||||
<h2 id="latest-title">최근 기록</h2>
|
||||
</div>
|
||||
<Link className="text-link section-action" to="/explore">
|
||||
모든 기록 탐색
|
||||
<Link className="text-link section-action" to={publicRoutes.explore()}>
|
||||
{<TechLogMessage messageKey="techLog.action.exploreAllRecords" />}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{status === "error" ? (
|
||||
<div className="latest-state latest-state--error" role="alert">
|
||||
<p>최근 기록을 불러오지 못했습니다.</p>
|
||||
<Link className="text-link" to="/#latest">
|
||||
다시 시도
|
||||
<p>{<TechLogMessage messageKey="techLog.state.latestLoadFailed" />}</p>
|
||||
<Link className="text-link" to={publicRoutes.home() + "#latest"}>
|
||||
{<TechLogMessage messageKey="techLog.action.retry" />}
|
||||
</Link>
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<p className="latest-state latest-state--empty">
|
||||
아직 공개된 기록이 없습니다.
|
||||
{<TechLogMessage messageKey="techLog.state.noPublishedRecords" />}
|
||||
</p>
|
||||
) : (
|
||||
<ol className="latest-list">
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
|
||||
import type { Project } from "../../../application/ports/public-content-queries.ts";
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
|
||||
export type ProjectSection = "overview" | "records" | "decisions" | "activity";
|
||||
|
||||
const sections = [
|
||||
{ key: "overview", label: "개요", suffix: "" },
|
||||
{ key: "records", label: "기록", suffix: "/records" },
|
||||
{ key: "decisions", label: "결정", suffix: "/decisions" },
|
||||
{ key: "activity", label: "활동", suffix: "/activity" },
|
||||
{ key: "overview", label: "개요", route: publicRoutes.project },
|
||||
{ key: "records", label: "기록", route: publicRoutes.projectRecords },
|
||||
{ key: "decisions", label: "결정", route: publicRoutes.projectDecisions },
|
||||
{ key: "activity", label: "활동", route: publicRoutes.projectActivity },
|
||||
] as const;
|
||||
|
||||
export function ProjectNavigation({ project }: { project: Project }) {
|
||||
const { pathname } = useLocation();
|
||||
const basePath = `/projects/${project.slug}`;
|
||||
const current =
|
||||
sections.find((section) => pathname === `${basePath}${section.suffix}`)?.key ??
|
||||
sections.find((section) => pathname === section.route(project.slug))?.key ??
|
||||
"overview";
|
||||
|
||||
return (
|
||||
@@ -23,7 +23,7 @@ export function ProjectNavigation({ project }: { project: Project }) {
|
||||
{sections.map((section) => (
|
||||
<Link
|
||||
key={section.key}
|
||||
to={`${basePath}${section.suffix}`}
|
||||
to={section.route(project.slug)}
|
||||
aria-current={current === section.key ? "page" : undefined}
|
||||
>
|
||||
{section.label}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Link } from "react-router-dom";
|
||||
import type { Project } from "../../../application/ports/public-content-queries.ts";
|
||||
import { ProjectNavigation } from "./project-navigation.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
export function ProjectPageHeader({
|
||||
project,
|
||||
title,
|
||||
@@ -13,7 +14,7 @@ export function ProjectPageHeader({
|
||||
return (
|
||||
<header className="project-page-header">
|
||||
<p className="project-breadcrumb">
|
||||
<Link to="/projects">Projects</Link>
|
||||
<Link to={publicRoutes.projects()}>Projects</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
{project.title}
|
||||
</p>
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
PublicTopic,
|
||||
} from "../../../application/ports/public-content-queries.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
type TopicRef = Readonly<{ name: string; slug: string }>;
|
||||
|
||||
/**
|
||||
@@ -80,7 +81,7 @@ export function ProjectPath({
|
||||
</span>
|
||||
<div className="context-flow__copy">
|
||||
{topic.slug ? (
|
||||
<Link to={`/topics/${topic.slug}`}>{topic.name}</Link>
|
||||
<Link to={publicRoutes.topic(topic.slug)}>{topic.name}</Link>
|
||||
) : (
|
||||
<strong>{topic.name}</strong>
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { PublicRecord } from "../../../application/ports/public-content-que
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { ProseText } from "../../shared/public-render/prose-text.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import { publicRoutePrefixes, publicRoutes } from "../public-routes.ts";
|
||||
|
||||
type TargetKind = components["schemas"]["ResolvedRelation"]["targetKind"];
|
||||
|
||||
@@ -15,17 +16,23 @@ type TargetKind = components["schemas"]["ResolvedRelation"]["targetKind"];
|
||||
* 더할 때 짝을 빠뜨리는 일이 이 저장소에서만 다섯 번 있었다.
|
||||
*/
|
||||
const PATH_PREFIX_KINDS: ReadonlyArray<readonly [string, TargetKind]> = [
|
||||
["/cases/", "CASE"],
|
||||
["/references/", "REFERENCE"],
|
||||
["/questions/", "QUESTION"],
|
||||
["/concepts/", "CONCEPT"],
|
||||
[publicRoutePrefixes.case, "CASE"],
|
||||
[publicRoutePrefixes.reference, "REFERENCE"],
|
||||
[publicRoutePrefixes.question, "QUESTION"],
|
||||
[publicRoutePrefixes.concept, "CONCEPT"],
|
||||
];
|
||||
|
||||
const PROJECT_ROUTE_PROBE = "__project__";
|
||||
const DECISION_RELATION_MARKER =
|
||||
publicRoutes
|
||||
.projectDecisions(PROJECT_ROUTE_PROBE)
|
||||
.slice(publicRoutes.project(PROJECT_ROUTE_PROBE).length) + "#";
|
||||
|
||||
function targetKindOf(path: string): TargetKind {
|
||||
const matched = PATH_PREFIX_KINDS.find(([prefix]) => path.startsWith(prefix));
|
||||
if (matched) return matched[1];
|
||||
// 결정은 프로젝트 화면 안의 앵커로 산다. 그래서 앞머리가 아니라 조각으로 가른다.
|
||||
return path.includes("/decisions#") ? "PROJECT_DECISION" : "PROJECT";
|
||||
return path.includes(DECISION_RELATION_MARKER) ? "PROJECT_DECISION" : "PROJECT";
|
||||
}
|
||||
|
||||
export function publicRenderModelBase(
|
||||
@@ -46,13 +53,13 @@ export function publicRenderModelBase(
|
||||
주제든 자기 화면이 있다.
|
||||
*/
|
||||
publicPath: record.topicSlug
|
||||
? `/topics/${encodeURIComponent(record.topicSlug)}`
|
||||
? publicRoutes.topic(record.topicSlug)
|
||||
: null,
|
||||
},
|
||||
project: {
|
||||
id: `project-${record.projectSlug}`,
|
||||
label: record.projectTitle,
|
||||
publicPath: `/projects/${record.projectSlug}`,
|
||||
publicPath: publicRoutes.project(record.projectSlug),
|
||||
},
|
||||
relations: record.relations.map((relation, index) => ({
|
||||
id: `public-relation-${index + 1}-${relation.path}`,
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { useId, useRef, useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
import { HighlightMatch } from "../../shared/highlight-match.tsx";
|
||||
import { cardSummary } from "../../../domain/content-format/card-summary.ts";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
SearchField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
type SearchDialogProps = {
|
||||
className?: string;
|
||||
onBeforeOpen?: () => void;
|
||||
@@ -14,10 +21,10 @@ export function SearchDialog({
|
||||
className = "",
|
||||
onBeforeOpen,
|
||||
}: SearchDialogProps) {
|
||||
const dialogId = useId();
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const { message } = useLocale();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase("ko-KR");
|
||||
// Keyed on the empty query, then filtered here, rather than one request per
|
||||
@@ -26,7 +33,7 @@ export function SearchDialog({
|
||||
// than a stale-free local filter. The predicate is the same one the catalog
|
||||
// applies for a non-empty query, so the visible result set is unchanged.
|
||||
const view = usePublicContent(["tech-log", "search", "dialog"], async (queries) => ({
|
||||
entities: await queries.searchPublicContent(""),
|
||||
entities: await queries.listCatalog(),
|
||||
}));
|
||||
const results = (view.data?.entities ?? []).filter((entity) =>
|
||||
normalizedQuery
|
||||
@@ -36,67 +43,50 @@ export function SearchDialog({
|
||||
: true,
|
||||
);
|
||||
|
||||
function open() {
|
||||
function openDialog() {
|
||||
onBeforeOpen?.();
|
||||
dialogRef.current?.showModal();
|
||||
requestAnimationFrame(() => inputRef.current?.focus());
|
||||
setOpen(true);
|
||||
}
|
||||
|
||||
function close() {
|
||||
dialogRef.current?.close();
|
||||
function closeDialog() {
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
className={className}
|
||||
type="button"
|
||||
aria-haspopup="dialog"
|
||||
aria-controls={dialogId}
|
||||
aria-label="TechLog 검색 열기"
|
||||
onClick={open}
|
||||
onClick={openDialog}
|
||||
variant="ghost"
|
||||
>
|
||||
검색
|
||||
</button>
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
{message("techLog.action.search")}
|
||||
</Button>
|
||||
<Dialog
|
||||
className="search-dialog"
|
||||
id={dialogId}
|
||||
aria-labelledby={dialogId + "-title"}
|
||||
onClose={() => triggerRef.current?.focus()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
close();
|
||||
}
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) close();
|
||||
}}
|
||||
closeLabel={message("techLog.action.close")}
|
||||
initialFocusRef={inputRef}
|
||||
eyebrow={<p className="context-label">Public records</p>}
|
||||
onClose={closeDialog}
|
||||
open={open}
|
||||
returnFocusRef={triggerRef}
|
||||
title="TechLog 검색"
|
||||
>
|
||||
<div className="search-dialog-inner">
|
||||
<header>
|
||||
<div>
|
||||
<p className="context-label">Public records</p>
|
||||
<h2 id={dialogId + "-title"}>TechLog 검색</h2>
|
||||
</div>
|
||||
<button type="button" className="dialog-close" onClick={close}>
|
||||
닫기
|
||||
</button>
|
||||
</header>
|
||||
<label className="search-field">
|
||||
<span className="visually-hidden">검색어</span>
|
||||
<span aria-hidden="true">⌕</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="제목, 요약, 주제, 프로젝트 검색"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<SearchField
|
||||
ref={inputRef}
|
||||
autoComplete="off"
|
||||
className="search-field"
|
||||
clearLabel={message("techLog.action.clearSearch")}
|
||||
label="검색어"
|
||||
onClear={() => setQuery("")}
|
||||
onChange={(event) => setQuery(event.currentTarget.value)}
|
||||
placeholder="제목, 요약, 주제, 프로젝트 검색"
|
||||
value={query}
|
||||
/>
|
||||
<p className="search-count" aria-live="polite">
|
||||
{results.length}개의 공개 기록
|
||||
</p>
|
||||
@@ -105,13 +95,16 @@ export function SearchDialog({
|
||||
<ul className="search-results">
|
||||
{results.map((entry) => (
|
||||
<li key={entry.path}>
|
||||
<Link to={entry.path} onClick={close}>
|
||||
<Link to={entry.path} onClick={closeDialog}>
|
||||
<span>{entry.contentType}</span>
|
||||
<strong>
|
||||
<HighlightMatch text={entry.title} query={query} />
|
||||
</strong>
|
||||
<p>
|
||||
<HighlightMatch text={cardSummary(entry.summary)} query={query} />
|
||||
<HighlightMatch
|
||||
text={cardSummary(entry.summary)}
|
||||
query={query}
|
||||
/>
|
||||
</p>
|
||||
</Link>
|
||||
</li>
|
||||
@@ -120,18 +113,18 @@ export function SearchDialog({
|
||||
{normalizedQuery ? (
|
||||
<Link
|
||||
className="search-all-link"
|
||||
to={`/search?q=${encodeURIComponent(query.trim())}`}
|
||||
onClick={close}
|
||||
to={publicRoutes.search({ q: query.trim() })}
|
||||
onClick={closeDialog}
|
||||
>
|
||||
전체 검색 결과 보기 <span aria-hidden="true">→</span>
|
||||
</Link>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<p className="search-empty">일치하는 공개 기록이 없습니다.</p>
|
||||
<p className="search-empty">{message("techLog.state.noMatchingPublicRecords")}</p>
|
||||
)}
|
||||
</div>
|
||||
</dialog>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
import { useRef } from "react";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
|
||||
import { publicSiteConfig } from "../../../contracts/public-site-config.ts";
|
||||
import { techLogNavigation } from "../../tech-log-navigation.ts";
|
||||
import { SearchDialog } from "./search-dialog.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
// Derived from the route contract rather than repeated here; see
|
||||
// `tech-log-navigation.ts` for why.
|
||||
const navigation = techLogNavigation("PUBLIC");
|
||||
|
||||
export function SiteHeader({ currentPath }: { currentPath?: string }) {
|
||||
const { message } = useLocale();
|
||||
const location = useLocation();
|
||||
const activePath =
|
||||
currentPath ??
|
||||
(location.pathname.startsWith("/topics/") ? "/explore" : location.pathname);
|
||||
(location.pathname.startsWith(publicRoutes.topics() + "/")
|
||||
? publicRoutes.explore()
|
||||
: location.pathname);
|
||||
const menuRef = useRef<HTMLDetailsElement>(null);
|
||||
const summaryRef = useRef<HTMLElement>(null);
|
||||
|
||||
function isCurrent(path: string) {
|
||||
return (
|
||||
activePath === path ||
|
||||
(path !== "/" && activePath.startsWith(path + "/"))
|
||||
(path !== publicRoutes.home() && activePath.startsWith(path + "/"))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,13 +40,13 @@ export function SiteHeader({ currentPath }: { currentPath?: string }) {
|
||||
<header className="site-header">
|
||||
<div className="shell header-inner">
|
||||
<div className="header-brand-zone">
|
||||
<Link className="wordmark" to="/" aria-label="TechLog 홈">
|
||||
<Link className="wordmark" to={publicRoutes.home()} aria-label={message("techLog.public.home")}>
|
||||
{publicSiteConfig.brandTitle}
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="header-menu-zone">
|
||||
<nav className="desktop-nav" aria-label="주요 탐색">
|
||||
<nav className="desktop-nav" aria-label={message("techLog.public.primaryNavigation")}>
|
||||
{navigation.map((item) => (
|
||||
<Link
|
||||
key={item.path}
|
||||
@@ -48,7 +54,7 @@ export function SiteHeader({ currentPath }: { currentPath?: string }) {
|
||||
to={item.path}
|
||||
aria-current={isCurrent(item.path) ? "page" : undefined}
|
||||
>
|
||||
{item.label}
|
||||
{message(item.messageKey)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
@@ -67,8 +73,8 @@ export function SiteHeader({ currentPath }: { currentPath?: string }) {
|
||||
closeMenu(true);
|
||||
}}
|
||||
>
|
||||
<summary ref={summaryRef}>메뉴</summary>
|
||||
<nav aria-label="모바일 주요 탐색">
|
||||
<summary ref={summaryRef}>{message("shell.menu")}</summary>
|
||||
<nav aria-label={message("techLog.public.mobileNavigation")}>
|
||||
{navigation.map((item) => (
|
||||
<Link
|
||||
key={item.path}
|
||||
@@ -76,7 +82,7 @@ export function SiteHeader({ currentPath }: { currentPath?: string }) {
|
||||
aria-current={isCurrent(item.path) ? "page" : undefined}
|
||||
onClick={() => closeMenu()}
|
||||
>
|
||||
{item.label}
|
||||
{message(item.messageKey)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -9,6 +9,8 @@ import { PublicRecordList } from "../components/public-record-list.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
const kinds = {
|
||||
cases: { kind: "CASE", title: DOCUMENT_KIND_LABELS.CASE, description: "문제를 재현하고 관찰한 값에서 설계 결론까지 따라갑니다." },
|
||||
references: { kind: "REFERENCE", title: DOCUMENT_KIND_LABELS.REFERENCE, description: "다시 확인할 수 있는 기술 기준과 적용 범위를 정리합니다." },
|
||||
@@ -55,14 +57,14 @@ export function ExploreKindPage() {
|
||||
: [],
|
||||
}),
|
||||
);
|
||||
if (!config) return <RegisteredNotFoundRoute />;
|
||||
if (!kind || !config) return <RegisteredNotFoundRoute />;
|
||||
if (!view.ready) return view.fallback;
|
||||
|
||||
const { records } = view.data;
|
||||
return <main id="main-content" className="shell public-index-page">
|
||||
<header className="public-page-header"><p className="section-kicker">Explore</p><h1>{config.title}</h1><p>{config.description}</p></header>
|
||||
<ExploreFilterForm action={`/explore/${kind}`} topic={topic} project={project} showType={false} />
|
||||
<ExploreFilterForm action={publicRoutes.exploreKind(kind)} topic={topic} project={project} showType={false} />
|
||||
<div className="public-result-heading"><h2>공개 기록</h2><p>{records.length}개의 공개 기록</p></div><PublicRecordList records={records} />
|
||||
<Link className="text-link public-back-link" to="/explore">전체 탐색으로 돌아가기</Link>
|
||||
<Link className="text-link public-back-link" to={publicRoutes.explore()}>{<TechLogMessage messageKey="techLog.action.backToExplore" />}</Link>
|
||||
</main>;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { EXPLORE_KINDS, ExploreFilterForm } from "../components/explore-filter-f
|
||||
import { PublicRecordList } from "../components/public-record-list.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
@@ -65,7 +66,7 @@ export function ExplorePage() {
|
||||
|
||||
return <main id="main-content" className="shell public-index-page">
|
||||
<header className="public-page-header"><p className="section-kicker">Explore</p><h1>탐색</h1><p>유형과 기술 주제, 프로젝트를 조합해 공개 기록을 찾습니다.</p></header>
|
||||
<ExploreFilterForm action="/explore" kind={kind} topic={topic} project={project} />
|
||||
<ExploreFilterForm action={publicRoutes.explore()} kind={kind} topic={topic} project={project} />
|
||||
<div className="public-result-heading"><h2>공개 기록</h2><p>{records.length}개의 공개 기록</p></div>
|
||||
{grouped ? (
|
||||
groups.map((group) => (
|
||||
@@ -79,7 +80,7 @@ export function ExplorePage() {
|
||||
*/}
|
||||
<div className="public-result-heading">
|
||||
<h3>
|
||||
{group.slug ? <Link to={`/topics/${group.slug}`}>{group.name}</Link> : group.name}
|
||||
{group.slug ? <Link to={publicRoutes.topic(group.slug)}>{group.name}</Link> : group.name}
|
||||
</h3>
|
||||
<p>{`${group.records.length}개`}</p>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import type { PublicContentQueries } from "../../../application/ports/public-content-queries.ts";
|
||||
import type { LatestRecordEntry } from "../../../application/ports/public-content-queries.ts";
|
||||
import { publicSiteConfig } from "../../../contracts/public-site-config.ts";
|
||||
import { useRouteInput } from "../../../../../presentation/routes/route-input.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
DOCUMENT_KIND_STATES,
|
||||
} from "../../shared/document-kind-labels.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
@@ -60,11 +62,9 @@ function latestTypeLabel(entryType: string): string {
|
||||
return NOT_A_RECORD_LABELS[entryType] ?? entryType;
|
||||
}
|
||||
|
||||
async function getLatestEntries(
|
||||
publicContent: PublicContentQueries,
|
||||
): Promise<LatestEntry[]> {
|
||||
const records = await publicContent.getLatestEntries();
|
||||
|
||||
function getLatestEntries(
|
||||
records: readonly LatestRecordEntry[],
|
||||
): LatestEntry[] {
|
||||
const recordTimeline: LatestEntry[] = records.map((entry) => ({
|
||||
id: entry.id,
|
||||
// 목록의 다른 이름들과 같은 자리에 놓이므로 표기도 같은 규칙을 쓴다 — 대문자에 공백.
|
||||
@@ -93,7 +93,7 @@ async function getLatestEntries(
|
||||
.slice(0, LATEST_ON_HOME);
|
||||
}
|
||||
|
||||
/** 홈이 펴 두는 최근 기록 수. 나머지는 「모든 기록 탐색」이 받는다. */
|
||||
/** 홈이 펴 두는 최근 기록 수. 나머지는 「모든 {<TechLogMessage messageKey="techLog.action.exploreRecords" />}」이 받는다. */
|
||||
const LATEST_ON_HOME = 4;
|
||||
|
||||
/** 목록의 날짜 칸은 공개 화면 어디서나 같은 형식이다. */
|
||||
@@ -105,31 +105,19 @@ function dateLabel(isoTimestamp: string): string {
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 홈에 세우는 프로젝트 목록.
|
||||
*
|
||||
* <p>홈이 하는 일은 맥락을 자세히 보여 주는 것이 아니라 어디로 들어갈지 정하게 하는 것이다.
|
||||
* 그 입구가 프로젝트다 — 이 사이트의 기록은 전부 어느 프로젝트의 조사에서 나온다.
|
||||
*
|
||||
* <p>빈 검색어는 "카탈로그 전부" 라는 뜻이라 한 번의 요청으로 끝난다. 프로젝트마다 기록·결정을
|
||||
* 세어 오던 것은 `/projects` 화면이 할 일이다 — 홈에서 그것까지 하면 요청이 프로젝트 수만큼
|
||||
* 늘고, 홈이 답해야 할 질문("어디로 들어갈까") 은 그 숫자로 답해지지 않는다.
|
||||
*/
|
||||
async function getProjects(publicContent: PublicContentQueries) {
|
||||
const entries = await publicContent.searchPublicContent("");
|
||||
return entries.filter((entry) => entry.contentType === "PROJECT");
|
||||
}
|
||||
|
||||
export function HomePage() {
|
||||
const { search } = useRouteInput<"TECH_LOG_HOME">();
|
||||
const requestedState = optionalString(search.state);
|
||||
const view = usePublicContent(["tech-log", "home"], async (queries) => {
|
||||
const [focusItems, latestEntries, projects] = await Promise.all([
|
||||
queries.getHomeFocusItems(),
|
||||
getLatestEntries(queries),
|
||||
getProjects(queries),
|
||||
const [home, projects] = await Promise.all([
|
||||
queries.getHome(),
|
||||
queries.listProjects(),
|
||||
]);
|
||||
return { focusItems, latestEntries, projects };
|
||||
return {
|
||||
focusItems: home.focusItems,
|
||||
latestEntries: getLatestEntries(home.latestEntries),
|
||||
projects,
|
||||
};
|
||||
});
|
||||
if (!view.ready) return view.fallback;
|
||||
|
||||
@@ -147,8 +135,8 @@ export function HomePage() {
|
||||
<h1 id="home-title">{publicSiteConfig.brandTitle}</h1>
|
||||
<p className="identity-statement">{publicSiteConfig.identityStatement}</p>
|
||||
<div className="home-identity__actions">
|
||||
<Link to="/projects">프로젝트 둘러보기</Link>
|
||||
<Link to="/explore">기록 탐색</Link>
|
||||
<Link to={publicRoutes.projects()}>{<TechLogMessage messageKey="techLog.action.browseProjects" />}</Link>
|
||||
<Link to={publicRoutes.explore()}>{<TechLogMessage messageKey="techLog.action.exploreRecords" />}</Link>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -170,7 +158,7 @@ export function HomePage() {
|
||||
<p className="section-kicker">Projects</p>
|
||||
<h2 id="home-projects-title">프로젝트</h2>
|
||||
</div>
|
||||
<Link className="text-link" to="/projects">
|
||||
<Link className="text-link" to={publicRoutes.projects()}>
|
||||
전체 보기 <span aria-hidden="true">↗</span>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -184,7 +172,7 @@ export function HomePage() {
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="public-empty-state">아직 공개된 프로젝트가 없습니다.</p>
|
||||
<p className="public-empty-state">{<TechLogMessage messageKey="techLog.state.noPublishedProjects" />}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import { publicSiteConfig } from "../../../contracts/public-site-config.ts";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
import { useApplication } from "../../../../../presentation/providers/application-provider.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
const principles = [
|
||||
{
|
||||
title: "확인된 사실과 남아 있는 가정",
|
||||
@@ -30,11 +32,9 @@ export function ProfilePage() {
|
||||
// and rendered nothing but an error. "Current projects" means the published
|
||||
// ones, so read them from the catalogue the projects index already reads.
|
||||
const view = usePublicContent(["tech-log", "profile"], async (queries) => {
|
||||
const entries = (await queries.searchPublicContent("")).filter(
|
||||
(item) => item.contentType === "PROJECT",
|
||||
);
|
||||
const entries = await queries.listProjects();
|
||||
const [resolved, topics, contacts] = await Promise.all([
|
||||
Promise.all(entries.map((item) => queries.getProject(item.path.replace("/projects/", "")))),
|
||||
Promise.all(entries.map((item) => queries.getProject(item.slug))),
|
||||
queries.listTopics(),
|
||||
queries.listContacts(),
|
||||
]);
|
||||
@@ -83,12 +83,12 @@ export function ProfilePage() {
|
||||
{!view.ready ? (
|
||||
view.fallback
|
||||
) : view.data.currentProjects.length === 0 ? (
|
||||
<p className="public-empty-note">아직 공개된 프로젝트가 없습니다.</p>
|
||||
<p className="public-empty-note">{<TechLogMessage messageKey="techLog.state.noPublishedProjects" />}</p>
|
||||
) : (
|
||||
<ul>
|
||||
{view.data.currentProjects.map((project) => (
|
||||
<li key={project.slug}>
|
||||
<Link to={`/projects/${project.slug}`}>
|
||||
<Link to={publicRoutes.project(project.slug)}>
|
||||
<div>
|
||||
<strong>{project.title}</strong>
|
||||
<span>{projectStageLabel(project.stage)}</span>
|
||||
@@ -111,7 +111,7 @@ export function ProfilePage() {
|
||||
{!view.ready ? (
|
||||
view.fallback
|
||||
) : view.data.topics.length === 0 ? (
|
||||
<p className="public-empty-note">아직 등록한 주제가 없습니다.</p>
|
||||
<p className="public-empty-note">{<TechLogMessage messageKey="techLog.state.noRegisteredTopics" />}</p>
|
||||
) : (
|
||||
<ul>
|
||||
{view.data.topics.map((topic) => (
|
||||
|
||||
@@ -9,6 +9,7 @@ import { projectActivityLabel } from "../../shared/project-activity-labels.ts";
|
||||
import { ProjectPageHeader } from "../components/project-page-header.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function ProjectActivityPage() {
|
||||
const { params } = useRouteInput<"TECH_LOG_PROJECT_ACTIVITY">();
|
||||
const slug = typeof params.slug === "string" ? params.slug : "";
|
||||
@@ -34,7 +35,7 @@ export function ProjectActivityPage() {
|
||||
<main id="main-content" className="shell project-page">
|
||||
<ProjectPageHeader project={project} title={`${project.title} 활동`} />
|
||||
{activity.length === 0 ? (
|
||||
<p className="public-empty-note">아직 이 프로젝트에서 공개한 기록이 없습니다.</p>
|
||||
<p className="public-empty-note">{<TechLogMessage messageKey="techLog.state.noProjectPublishedRecords" />}</p>
|
||||
) : (
|
||||
<ol className="project-activity-list">
|
||||
{activity.map((item) => (
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ProseText } from "../../shared/public-render/prose-text.tsx";
|
||||
import { ProjectPageHeader } from "../components/project-page-header.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function ProjectDecisionsPage() {
|
||||
const { params } = useRouteInput<"TECH_LOG_PROJECT_DECISIONS">();
|
||||
const slug = typeof params.slug === "string" ? params.slug : "";
|
||||
@@ -55,7 +56,7 @@ export function ProjectDecisionsPage() {
|
||||
<main id="main-content" className="shell project-page">
|
||||
<ProjectPageHeader project={project} title={`${project.title} 결정`} />
|
||||
<section className="project-empty-decisions" aria-labelledby="no-decisions-title">
|
||||
<h2 id="no-decisions-title">아직 확정한 결정이 없습니다.</h2>
|
||||
<h2 id="no-decisions-title">{<TechLogMessage messageKey="techLog.state.noDecisions" />}</h2>
|
||||
{openQuestions.length > 0 ? (
|
||||
<>
|
||||
<p>{`결정으로 이어질 수 있는 열린 질문이 ${openQuestions.length}개 있습니다.`}</p>
|
||||
@@ -69,7 +70,7 @@ export function ProjectDecisionsPage() {
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
아직 열린 질문도 없습니다. 이 프로젝트의 조사는 기록을 모으는 단계입니다.
|
||||
{<TechLogMessage messageKey="techLog.state.noOpenQuestions" />}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
@@ -127,7 +128,7 @@ export function ProjectDecisionsPage() {
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>남긴 영향이 없습니다.</p>
|
||||
<p>{<TechLogMessage messageKey="techLog.state.noImpact" />}</p>
|
||||
)}
|
||||
</section>
|
||||
<section>
|
||||
@@ -141,7 +142,7 @@ export function ProjectDecisionsPage() {
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>연결한 근거 기록이 없습니다.</p>
|
||||
<p>{<TechLogMessage messageKey="techLog.state.noEvidence" />}</p>
|
||||
)}
|
||||
</section>
|
||||
</article>
|
||||
|
||||
@@ -10,6 +10,8 @@ import { ProjectPath } from "../components/project-path.tsx";
|
||||
import { ProseText } from "../../shared/public-render/prose-text.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function ProjectOverviewPage() {
|
||||
const { params } = useRouteInput<"TECH_LOG_PROJECT">();
|
||||
const slug = typeof params.slug === "string" ? params.slug : "";
|
||||
@@ -109,7 +111,7 @@ export function ProjectOverviewPage() {
|
||||
<ProseText text={project.thesis} />
|
||||
) : (
|
||||
<p className="project-thesis-pending">
|
||||
아직 정리한 결론이 없습니다. 아래 조사 지도가 지금까지 모은 기록을 보여 줍니다.
|
||||
{<TechLogMessage messageKey="techLog.state.noConclusion" />}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
@@ -135,15 +137,15 @@ export function ProjectOverviewPage() {
|
||||
두 번 나왔고, 둘 중 어디서 읽어야 하는지는 화면이 말해 주지 않았다.
|
||||
*/}
|
||||
<div className="project-stat-links">
|
||||
<Link to={`/projects/${slug}/records`}>
|
||||
<Link to={publicRoutes.projectRecords(slug)}>
|
||||
<strong>{records.length}</strong>
|
||||
<span>공개 기록</span>
|
||||
</Link>
|
||||
<Link to={`/projects/${slug}/decisions`}>
|
||||
<Link to={publicRoutes.projectDecisions(slug)}>
|
||||
<strong>{decisions.length}</strong>
|
||||
<span>설계 결정</span>
|
||||
</Link>
|
||||
<Link to={`/projects/${slug}/activity`}>
|
||||
<Link to={publicRoutes.projectActivity(slug)}>
|
||||
<strong>{activity.length}</strong>
|
||||
<span>활동 기록</span>
|
||||
</Link>
|
||||
|
||||
@@ -3,12 +3,12 @@ import { projectStageLabel } from "../../../domain/public/project-phase-labels.t
|
||||
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function ProjectsPage() {
|
||||
const view = usePublicContent(["tech-log", "projects"], async (queries) => {
|
||||
const entries = (await queries.searchPublicContent("")).filter(
|
||||
(item) => item.contentType === "PROJECT",
|
||||
);
|
||||
const slugs = entries.map((item) => item.path.replace("/projects/", ""));
|
||||
const entries = await queries.listProjects();
|
||||
const slugs = entries.map((item) => item.slug);
|
||||
/*
|
||||
목록에도 조사의 상태를 싣는다. 이름과 단계만 있던 동안 한 줄이 차지하는 높이에 비해
|
||||
말하는 것이 너무 적었다 — 넓은 여백이 남고, 읽는 사람은 그 프로젝트가 지금 어디쯤인지
|
||||
@@ -55,12 +55,12 @@ export function ProjectsPage() {
|
||||
{!view.ready ? (
|
||||
view.fallback
|
||||
) : view.data.projects.length === 0 ? (
|
||||
<p className="public-empty-note">아직 공개된 프로젝트가 없습니다.</p>
|
||||
<p className="public-empty-note">{<TechLogMessage messageKey="techLog.state.noPublishedProjects" />}</p>
|
||||
) : (
|
||||
<ol className="project-index-list">
|
||||
{view.data.projects.map(({ project, records, decisions, open }, index) => (
|
||||
<li key={project.slug}>
|
||||
<Link to={`/projects/${project.slug}`}>
|
||||
<Link to={publicRoutes.project(project.slug)}>
|
||||
<span>{String(index + 1).padStart(2, "0")}</span>
|
||||
<div>
|
||||
<div className="project-index-title">
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function PublicNotFoundPage() {
|
||||
return (
|
||||
<main id="main-content" className="shell public-index-page">
|
||||
<header className="public-page-header">
|
||||
<p className="section-kicker">404</p>
|
||||
<h1>페이지를 찾을 수 없습니다.</h1>
|
||||
<p>요청한 공개 페이지가 없습니다.</p>
|
||||
<h1>{<TechLogMessage messageKey="techLog.public.notFound" />}</h1>
|
||||
<p>{<TechLogMessage messageKey="techLog.public.notFoundDetail" />}</p>
|
||||
</header>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -8,7 +8,10 @@ import { usePublicContent } from "../use-public-content.tsx";
|
||||
import { ProseText } from "../../shared/public-render/prose-text.tsx";
|
||||
import { useDocumentMetadata } from "../../shared/use-document-metadata.ts";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
export function ReleasePage() {
|
||||
const { message } = useLocale();
|
||||
const { params } = useRouteInput<"TECH_LOG_RELEASE">();
|
||||
const version = typeof params.version === "string" ? params.version : "";
|
||||
const view = usePublicContent(["tech-log", "release", version], async (queries) => ({
|
||||
@@ -30,8 +33,8 @@ export function ReleasePage() {
|
||||
return (
|
||||
<main id="main-content" className="shell release-page">
|
||||
<header className="release-page-header">
|
||||
<nav aria-label="변경 기록 경로">
|
||||
<Link to="/releases">변경 기록</Link>
|
||||
<nav aria-label={message("techLog.public.releaseBreadcrumb")}>
|
||||
<Link to={publicRoutes.releases()}>{message("techLog.action.changeLog")}</Link>
|
||||
<span aria-hidden="true">/</span>v{release.version}
|
||||
</nav>
|
||||
<p className="section-kicker">Release v{release.version}</p>
|
||||
|
||||
@@ -2,13 +2,12 @@ import { Link } from "react-router-dom";
|
||||
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
export function ReleasesPage() {
|
||||
const view = usePublicContent(["tech-log", "releases"], async (queries) => {
|
||||
const entries = (await queries.searchPublicContent("")).filter(
|
||||
(item) => item.contentType === "RELEASE",
|
||||
);
|
||||
const entries = await queries.listReleases();
|
||||
const resolved = await Promise.all(
|
||||
entries.map((item) => queries.getRelease(item.path.replace("/releases/", ""))),
|
||||
entries.map((item) => queries.getRelease(item.version)),
|
||||
);
|
||||
return { releases: resolved.filter((release) => release !== undefined) };
|
||||
});
|
||||
@@ -32,7 +31,7 @@ export function ReleasesPage() {
|
||||
{!view.ready ? (
|
||||
view.fallback
|
||||
) : view.data.releases.length === 0 ? (
|
||||
<p className="public-empty-note">아직 공개된 릴리즈가 없습니다.</p>
|
||||
<p className="public-empty-note">{<TechLogMessage messageKey="techLog.state.noPublishedReleases" />}</p>
|
||||
) : (
|
||||
<ol className="release-index-list">
|
||||
{view.data.releases.map((release) => (
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { Button, InputControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import type { SearchablePublicEntity } from "../../../application/ports/public-content-queries.ts";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
|
||||
import { HighlightMatch } from "../../shared/highlight-match.tsx";
|
||||
import { useRouteInput } from "../../../../../presentation/routes/route-input.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
/*
|
||||
기록 종류의 이름은 `document-kind-labels.ts` 한 곳에서만 정한다. 이 파일이 자기 표를 따로
|
||||
갖고 있던 동안 같은 CASE 가 목록에서는 「검증 기록」, 검색 결과에서는 「Case」로 나왔다 —
|
||||
@@ -27,6 +31,7 @@ function optionalString(value: unknown): string | undefined {
|
||||
|
||||
export function SearchPage() {
|
||||
const navigate = useNavigate();
|
||||
const { message } = useLocale();
|
||||
const { search } = useRouteInput<"TECH_LOG_SEARCH">();
|
||||
const query = optionalString(search.q)?.trim() ?? "";
|
||||
// 키의 마지막 조각이 화면을 구분한다. 헤더의 검색 다이얼로그도 같은 카탈로그를 읽고
|
||||
@@ -42,7 +47,7 @@ export function SearchPage() {
|
||||
const data = new FormData(event.currentTarget);
|
||||
const value = data.get("q");
|
||||
const nextQuery = typeof value === "string" ? value : "";
|
||||
void navigate(`/search?q=${encodeURIComponent(nextQuery)}`);
|
||||
void navigate(publicRoutes.search({ q: nextQuery }));
|
||||
}
|
||||
|
||||
if (!view.ready) return view.fallback;
|
||||
@@ -101,10 +106,10 @@ export function SearchPage() {
|
||||
|
||||
return <main id="main-content" className="shell search-page">
|
||||
<header className="public-page-header"><p className="section-kicker">Search</p><h1>검색</h1><p>제목과 요약, 주제, 프로젝트를 함께 검색합니다.</p></header>
|
||||
<form key={query} className="search-page-form" action="/search" method="get" onSubmit={submit}><label><span className="visually-hidden">검색어</span><input type="search" name="q" defaultValue={query} placeholder="검색어를 입력하세요" /></label><button type="submit">검색</button></form>
|
||||
<Form key={query} className="search-page-form" action={publicRoutes.search()} method="get" onSubmit={submit}><label><span className="visually-hidden">검색어</span><InputControl type="search" name="q" defaultValue={query} placeholder="검색어를 입력하세요" /></label><Button visualPolicy="inherit" type="submit">{message("techLog.action.search")}</Button></Form>
|
||||
<div className="public-result-heading"><h2>{query ? `“${query}” 검색 결과` : "전체 검색 결과"}</h2><p>{results.length}개의 검색 결과</p></div>
|
||||
{results.length === 0 ? (
|
||||
<p className="public-empty-state">일치하는 공개 기록이 없습니다.</p>
|
||||
<p className="public-empty-state">{message("techLog.state.noMatchingPublicRecords")}</p>
|
||||
) : (
|
||||
<>
|
||||
{leadTopic ? (
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ProseText } from "../../shared/public-render/prose-text.tsx";
|
||||
import { PublicRecordList } from "../components/public-record-list.tsx";
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
/** 나열 순서. 주제 화면과 같다 — 원리 → 확인한 기록 → 기준 → 아직 모르는 것. */
|
||||
const READING_ORDER: ReadonlyArray<PublicRecord["kind"]> = [
|
||||
"CONCEPT",
|
||||
@@ -61,7 +62,7 @@ export function TopicVariantPage() {
|
||||
*/}
|
||||
<header className="public-document-header">
|
||||
<nav aria-label="문서 경로">
|
||||
<Link to={`/topics/${topic.slug}`}>{topic.name}</Link>
|
||||
<Link to={publicRoutes.topic(topic.slug)}>{topic.name}</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
<span>{axisLabel}</span>
|
||||
</nav>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { Link } from "react-router-dom";
|
||||
|
||||
import { usePublicContent } from "../use-public-content.tsx";
|
||||
|
||||
import { publicRoutes } from "../public-routes.ts";
|
||||
import { TechLogMessage } from "../../tech-log-message.tsx";
|
||||
/**
|
||||
* 주제 목록.
|
||||
*
|
||||
@@ -33,12 +35,12 @@ export function TopicsPage() {
|
||||
</div>
|
||||
|
||||
{topics.length === 0 ? (
|
||||
<p className="public-empty-state">아직 공개된 주제가 없습니다.</p>
|
||||
<p className="public-empty-state">{<TechLogMessage messageKey="techLog.state.noPublishedTopics" />}</p>
|
||||
) : (
|
||||
<ul className="topic-index-list">
|
||||
{topics.map((topic) => (
|
||||
<li key={topic.slug}>
|
||||
<Link to={`/topics/${topic.slug}`}>
|
||||
<Link to={publicRoutes.topic(topic.slug)}>
|
||||
<strong>{topic.name}</strong>
|
||||
{/*
|
||||
논지가 있으면 그것이 이 주제를 고르는 근거다. 아직 쓰지 않았으면 설명으로
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { buildRouteUrlFromContract } from "../../../../presentation/routes/route-url-builder.ts";
|
||||
import { PLATFORM_ROUTE_CODECS } from "../../../../presentation/routes/platform-route-codecs.ts";
|
||||
import {
|
||||
TECH_LOG_ROUTE_REGISTRY,
|
||||
TECH_LOG_ROUTE_RUNTIME_CONTRACT,
|
||||
type TechLogRouteId,
|
||||
} from "../../contracts/tech-log-route-contract.ts";
|
||||
import { TECH_LOG_ROUTE_CODECS } from "../tech-log-route-codecs.ts";
|
||||
|
||||
const routeCodecs = Object.freeze({
|
||||
...PLATFORM_ROUTE_CODECS,
|
||||
...TECH_LOG_ROUTE_CODECS,
|
||||
});
|
||||
|
||||
function parameterPrefix(
|
||||
routeId: TechLogRouteId,
|
||||
parameter: string,
|
||||
): string {
|
||||
const template = TECH_LOG_ROUTE_REGISTRY[routeId].path;
|
||||
const marker = `:${parameter}`;
|
||||
const markerIndex = template.indexOf(marker);
|
||||
if (markerIndex < 0) {
|
||||
throw new TypeError(
|
||||
`Route ${routeId} does not declare parameter ${parameter}.`,
|
||||
);
|
||||
}
|
||||
return template.slice(0, markerIndex);
|
||||
}
|
||||
|
||||
export const publicRoutePrefixes = Object.freeze({
|
||||
case: parameterPrefix("TECH_LOG_CASE", "slug"),
|
||||
reference: parameterPrefix("TECH_LOG_REFERENCE", "slug"),
|
||||
concept: parameterPrefix("TECH_LOG_CONCEPT", "slug"),
|
||||
question: parameterPrefix("TECH_LOG_QUESTION", "slug"),
|
||||
project: parameterPrefix("TECH_LOG_PROJECT", "slug"),
|
||||
});
|
||||
|
||||
function buildPublicRoute(
|
||||
routeId: TechLogRouteId,
|
||||
input: Readonly<{
|
||||
params?: Readonly<Record<string, unknown>>;
|
||||
search?: Readonly<Record<string, unknown>>;
|
||||
}> = {},
|
||||
): string {
|
||||
return buildRouteUrlFromContract(
|
||||
TECH_LOG_ROUTE_REGISTRY[routeId],
|
||||
TECH_LOG_ROUTE_RUNTIME_CONTRACT[routeId],
|
||||
routeCodecs,
|
||||
input,
|
||||
);
|
||||
}
|
||||
|
||||
export const publicRoutes = Object.freeze({
|
||||
home(search: Readonly<Record<string, unknown>> = {}): string {
|
||||
return buildPublicRoute("TECH_LOG_HOME", { search });
|
||||
},
|
||||
explore(search: Readonly<Record<string, unknown>> = {}): string {
|
||||
return buildPublicRoute("TECH_LOG_EXPLORE", { search });
|
||||
},
|
||||
exploreKind(
|
||||
kind: string,
|
||||
search: Readonly<Record<string, unknown>> = {},
|
||||
): string {
|
||||
return buildPublicRoute("TECH_LOG_EXPLORE_KIND", {
|
||||
params: { kind },
|
||||
search,
|
||||
});
|
||||
},
|
||||
case(slug: string, search: Readonly<Record<string, unknown>> = {}): string {
|
||||
return buildPublicRoute("TECH_LOG_CASE", { params: { slug }, search });
|
||||
},
|
||||
reference(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_REFERENCE", { params: { slug } });
|
||||
},
|
||||
concept(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_CONCEPT", { params: { slug } });
|
||||
},
|
||||
setup(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_SETUP", { params: { slug } });
|
||||
},
|
||||
question(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_QUESTION", { params: { slug } });
|
||||
},
|
||||
topics(): string {
|
||||
return buildPublicRoute("TECH_LOG_TOPICS");
|
||||
},
|
||||
topic(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_TOPIC", { params: { slug } });
|
||||
},
|
||||
topicVariant(slug: string, variant: string): string {
|
||||
return buildPublicRoute("TECH_LOG_TOPIC_VARIANT", {
|
||||
params: { slug, variant },
|
||||
});
|
||||
},
|
||||
projects(): string {
|
||||
return buildPublicRoute("TECH_LOG_PROJECTS");
|
||||
},
|
||||
project(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_PROJECT", { params: { slug } });
|
||||
},
|
||||
projectRecords(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_PROJECT_RECORDS", { params: { slug } });
|
||||
},
|
||||
projectDecisions(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_PROJECT_DECISIONS", {
|
||||
params: { slug },
|
||||
});
|
||||
},
|
||||
projectActivity(slug: string): string {
|
||||
return buildPublicRoute("TECH_LOG_PROJECT_ACTIVITY", { params: { slug } });
|
||||
},
|
||||
releases(): string {
|
||||
return buildPublicRoute("TECH_LOG_RELEASES");
|
||||
},
|
||||
release(version: string): string {
|
||||
return buildPublicRoute("TECH_LOG_RELEASE", { params: { version } });
|
||||
},
|
||||
profile(): string {
|
||||
return buildPublicRoute("TECH_LOG_PROFILE");
|
||||
},
|
||||
search(search: Readonly<Record<string, unknown>> = {}): string {
|
||||
return buildPublicRoute("TECH_LOG_SEARCH", { search });
|
||||
},
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import { Link } from "react-router-dom";
|
||||
import { publicSiteConfig } from "../../contracts/public-site-config.ts";
|
||||
import { SiteHeader } from "./components/site-header.tsx";
|
||||
|
||||
import { TechLogMessage } from "../tech-log-message.tsx";
|
||||
type PublicShellProps = {
|
||||
children: ReactNode;
|
||||
currentPath?: string;
|
||||
@@ -29,7 +30,7 @@ export function PublicShell({ children, currentPath }: PublicShellProps) {
|
||||
<Link to={publicSiteConfig.contactPath}>
|
||||
{publicSiteConfig.contactLabel}
|
||||
</Link>
|
||||
<Link to={publicSiteConfig.releasesPath}>변경 기록</Link>
|
||||
<Link to={publicSiteConfig.releasesPath}>{<TechLogMessage messageKey="techLog.action.changeLog" />}</Link>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
type CodeBlockProps = {
|
||||
@@ -47,9 +48,9 @@ export function CodeBlock({
|
||||
<figcaption>
|
||||
<span>{language}</span>
|
||||
<span>{label}</span>
|
||||
<button type="button" aria-label="코드 복사" onClick={copy}>
|
||||
<Button visualPolicy="inherit" type="button" aria-label="코드 복사" onClick={copy}>
|
||||
{copyLabel}
|
||||
</button>
|
||||
</Button>
|
||||
</figcaption>
|
||||
<pre role="region" aria-label={`${label} 코드`} tabIndex={0}>
|
||||
<code>{code}</code>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useId, useRef } from "react";
|
||||
import { useId, useRef, useState } from "react";
|
||||
|
||||
import type { ResolveEvidenceAsset } from "../../../domain/public-render-content.ts";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
|
||||
type PublicEvidenceFigureProps = {
|
||||
evidenceKey: string;
|
||||
@@ -17,18 +22,11 @@ export function PublicEvidenceFigure({
|
||||
zoom,
|
||||
resolveEvidenceAsset,
|
||||
}: PublicEvidenceFigureProps) {
|
||||
const { message } = useLocale();
|
||||
const asset = resolveEvidenceAsset(evidenceKey);
|
||||
const descriptionId = useId();
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
function open() {
|
||||
dialogRef.current?.showModal();
|
||||
}
|
||||
|
||||
function close() {
|
||||
dialogRef.current?.close();
|
||||
}
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
/**
|
||||
* 치수를 아는 그림만 자리를 미리 잡는다. 모르는데 숫자를 적으면 그 상자가 진짜 크기가 되고,
|
||||
@@ -61,40 +59,37 @@ export function PublicEvidenceFigure({
|
||||
return (
|
||||
<>
|
||||
<figure className="evidence-figure">
|
||||
<button
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
className="evidence-image-button"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
aria-label={asset.triggerLabel}
|
||||
aria-describedby={descriptionId}
|
||||
onClick={open}
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<img src={asset.src} alt={alt} {...sizing} />
|
||||
<span>크게 보기</span>
|
||||
<span>{message("techLog.action.viewLarge")}</span>
|
||||
<span className="visually-hidden" id={descriptionId}>
|
||||
{alt}
|
||||
</span>
|
||||
</button>
|
||||
</Button>
|
||||
<figcaption>{caption}</figcaption>
|
||||
</figure>
|
||||
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
<Dialog
|
||||
className="figure-dialog"
|
||||
aria-label={asset.dialogLabel}
|
||||
onClose={() => triggerRef.current?.focus()}
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) close();
|
||||
}}
|
||||
closeLabel={message("techLog.action.close")}
|
||||
onClose={() => setOpen(false)}
|
||||
open={open}
|
||||
returnFocusRef={triggerRef}
|
||||
title={asset.dialogLabel}
|
||||
>
|
||||
<div>
|
||||
<button type="button" className="dialog-close" onClick={close}>
|
||||
닫기
|
||||
</button>
|
||||
<div className="figure-dialog-inner">
|
||||
<img src={asset.src} alt={alt} {...sizing} />
|
||||
<p>{caption}</p>
|
||||
</div>
|
||||
</dialog>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
import { DOCUMENT_KIND_LABELS } from "../document-kind-labels.ts";
|
||||
import { useDocumentMetadata } from "../use-document-metadata.ts";
|
||||
|
||||
import { publicRoutes } from "../../public/public-routes.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
type PublicRenderModel = components["schemas"]["PublicRenderModel"];
|
||||
type PublicRenderModelBase = components["schemas"]["PublicRenderModelBase"];
|
||||
type ResolvedRelation = components["schemas"]["ResolvedRelation"];
|
||||
@@ -563,6 +565,7 @@ function QuestionDocument({
|
||||
resolvePublishedLabel: ResolvePublishedLabel;
|
||||
navigation?: RecordNavigation;
|
||||
}) {
|
||||
const { message } = useLocale();
|
||||
const resolutionPath = model.resolution?.evidenceTarget.publicPath;
|
||||
const Root = embedded ? "div" : "main";
|
||||
const railSections = [
|
||||
@@ -611,14 +614,14 @@ function QuestionDocument({
|
||||
<h2 id="assumptions-title">가정</h2>
|
||||
<OrderedItems
|
||||
items={model.assumptions}
|
||||
empty="현재 기록된 가정이 없습니다."
|
||||
empty={message("techLog.state.noAssumptions")}
|
||||
/>
|
||||
</section>
|
||||
<section aria-labelledby="unknowns-title" data-epistemic="unknown">
|
||||
<h2 id="unknowns-title">남은 미지수</h2>
|
||||
<OrderedItems
|
||||
items={model.unknowns}
|
||||
empty="해결 과정에서 남은 미지수가 없습니다."
|
||||
empty={message("techLog.state.noUnknowns")}
|
||||
/>
|
||||
</section>
|
||||
<section aria-labelledby="constraints-title" data-epistemic="constraint">
|
||||
@@ -680,6 +683,7 @@ function ProjectDecisionDocument({
|
||||
model: ProjectDecisionPublicRenderModel;
|
||||
embedded: boolean;
|
||||
}) {
|
||||
const { message } = useLocale();
|
||||
const Root = embedded ? "div" : "main";
|
||||
const evidence = publicRelations(model.relations);
|
||||
return (
|
||||
@@ -688,7 +692,7 @@ function ProjectDecisionDocument({
|
||||
className={`shell project-page${embedded ? " public-record-embedded" : ""}`}
|
||||
>
|
||||
<nav className="case-breadcrumb" aria-label="문서 경로">
|
||||
<Link to="/projects">Project</Link>
|
||||
<Link to={publicRoutes.projects()}>Project</Link>
|
||||
{model.project?.publicPath ? (
|
||||
<>
|
||||
<span aria-hidden="true">/</span>
|
||||
@@ -725,7 +729,7 @@ function ProjectDecisionDocument({
|
||||
</section>
|
||||
<section>
|
||||
<h3>영향</h3>
|
||||
<OrderedItems items={model.consequences} empty="남긴 영향이 없습니다." />
|
||||
<OrderedItems items={model.consequences} empty={message("techLog.state.noImpact")} />
|
||||
</section>
|
||||
<section>
|
||||
<h3>근거 기록</h3>
|
||||
@@ -738,7 +742,7 @@ function ProjectDecisionDocument({
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>연결한 근거 기록이 없습니다.</p>
|
||||
<p>{message("techLog.state.noEvidence")}</p>
|
||||
)}
|
||||
</section>
|
||||
</article>
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx";
|
||||
import { useAssetLibraryController } from "../controllers/use-asset-library-controller.ts";
|
||||
|
||||
import type { Asset, AssetDetail } from "../../../contracts/studio/contract.ts";
|
||||
|
||||
type AssetKind = Asset["kind"];
|
||||
import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts";
|
||||
import { isStudioGatewayError } from "../../../application/ports/studio-gateway-error.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
SearchFilterToolbar,
|
||||
Select,
|
||||
TextArea,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
/** 관리 상태. 화면에 영문 상수가 그대로 나오던 자리다. */
|
||||
const ASSET_STATUS_LABELS: Record<Asset["managementStatus"], string> = {
|
||||
@@ -31,9 +39,6 @@ function byteLabel(bytes: number): string {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/** `document-list.tsx`'s page size for the same screen shape. */
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
/**
|
||||
* 공개 이력이 있거나 사용 중인 Asset은 hard delete하지 않는다. 서버도 같은
|
||||
* 규칙으로 `ASSET_IN_USE`를 던지므로 화면은 시도 자체를 막아 왕복을 줄인다.
|
||||
@@ -46,267 +51,43 @@ export function canHardDelete(detail: AssetDetail): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
const [assets, setAssets] = useState<readonly Asset[]>([]);
|
||||
const [listStatus, setListStatus] = useState<"LOADING" | "ERROR" | "READY">(
|
||||
"LOADING",
|
||||
);
|
||||
// Alignment follow-up, item 1. `q` is the *submitted* query, `searchDraft`
|
||||
// what the user is currently typing. Only `q` is an effect dependency, so
|
||||
// typing costs nothing -- `document-list.tsx` splits the same pair for the
|
||||
// same reason, and it is a stronger guarantee than a debounce: exactly one
|
||||
// request per deliberate search, never a trailing one after the user stops.
|
||||
const [searchDraft, setSearchDraft] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
/*
|
||||
종류는 서버가 걸러 준다(`kind`). 쓰임 여부는 계약에 없는 조건이라 받아 온 목록에서 거른다 —
|
||||
다음 쪽에 있는 것까지 세지는 못하므로 그 사실을 화면에 적는다. 없는 필터를 있는 척하는 것이
|
||||
가장 나쁘다.
|
||||
*/
|
||||
const [kindFilter, setKindFilter] = useState<AssetKind | "">("");
|
||||
const [usageFilter, setUsageFilter] = useState<"" | "USED" | "UNUSED">("");
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const [morePending, setMorePending] = useState(false);
|
||||
const [selected, setSelected] = useState<AssetDetail | null>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [notice, setNotice] = useState("");
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
// Wrapped in an object, not a bare `string | null`: the "no appended row to
|
||||
// land on" case still needs a focus move (to the page heading), and a bare
|
||||
// null cannot express "a move is pending, target unknown".
|
||||
const [moreFocus, setMoreFocus] = useState<{ id: string | null } | null>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
const detailHeadingRef = useRef<HTMLHeadingElement | null>(null);
|
||||
const pageHeadingRef = useRef<HTMLHeadingElement | null>(null);
|
||||
const rowRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const openAssetId = useRef<string | null>(null);
|
||||
const searchId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
// `active` rather than the abort signal alone: `RequestOptions.signal` is
|
||||
// advisory -- an adapter that ignores it still resolves, and a search the
|
||||
// user has already replaced would then paint stale rows over the newer
|
||||
// ones. This flag flips synchronously the moment `q` changes, so an
|
||||
// abandoned response can never reach `setAssets`.
|
||||
let active = true;
|
||||
setListStatus("LOADING");
|
||||
props.gateway
|
||||
.listAssets(
|
||||
{ ...(q ? { q } : {}), ...(kindFilter ? { kind: kindFilter } : {}), limit: PAGE_SIZE },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((page) => {
|
||||
if (!active) return;
|
||||
setAssets(page.items);
|
||||
setNextCursor(page.nextCursor);
|
||||
setListStatus("READY");
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!active || isAbortError(error)) return;
|
||||
// The `role="alert"` paragraph below is the sole announcement for a
|
||||
// load failure -- also routing it through `notice`'s `role="status"`
|
||||
// paragraph would announce the same sentence twice.
|
||||
setListStatus("ERROR");
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [props.gateway, q, kindFilter]);
|
||||
|
||||
// A freshly opened detail panel should take focus so keyboard and screen
|
||||
// reader users land on it without hunting; re-rendering the same asset
|
||||
// (e.g. after archiving it) must not steal focus back from whatever the
|
||||
// user is doing next.
|
||||
useEffect(() => {
|
||||
if (selected && openAssetId.current !== selected.asset.id) {
|
||||
detailHeadingRef.current?.focus();
|
||||
}
|
||||
openAssetId.current = selected?.asset.id ?? null;
|
||||
}, [selected]);
|
||||
|
||||
// Alignment follow-up, item 1. "더 보기" disappears once the server reports
|
||||
// no further cursor, so keeping focus on it would strand focus on `<body>`
|
||||
// exactly when the last page arrives. Moving to the first appended row is
|
||||
// unconditional -- it cannot depend on whether the control survived -- and
|
||||
// it puts the user at the content they asked for. Run as an effect (not
|
||||
// inline after `await`) so the row is committed and its ref attached.
|
||||
useEffect(() => {
|
||||
if (!moreFocus) return;
|
||||
const row = moreFocus.id ? rowRefs.current.get(moreFocus.id) : undefined;
|
||||
// The page heading is the fallback the delete path already relies on: the
|
||||
// one node in this screen that survives every list change.
|
||||
(row ?? pageHeadingRef.current)?.focus();
|
||||
setMoreFocus(null);
|
||||
}, [moreFocus]);
|
||||
|
||||
async function openDetail(asset: Asset, trigger: HTMLButtonElement) {
|
||||
triggerRef.current = trigger;
|
||||
try {
|
||||
const detail = await props.gateway.getAsset(asset.id);
|
||||
setSelected(detail);
|
||||
} catch {
|
||||
setNotice("Asset 상세를 불러오지 못했습니다.");
|
||||
}
|
||||
}
|
||||
|
||||
function submitSearch(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
// A new query restarts paging: `nextCursor` was issued against the old
|
||||
// query's ordering and means nothing under the new one.
|
||||
setSelected(null);
|
||||
setNextCursor(null);
|
||||
setQ(searchDraft.trim());
|
||||
}
|
||||
|
||||
async function loadMore() {
|
||||
if (!nextCursor || morePending) return;
|
||||
const cursor = nextCursor;
|
||||
setMorePending(true);
|
||||
try {
|
||||
const page = await props.gateway.listAssets({
|
||||
...(q ? { q } : {}),
|
||||
...(kindFilter ? { kind: kindFilter } : {}),
|
||||
cursor,
|
||||
limit: PAGE_SIZE,
|
||||
});
|
||||
// Append, never replace -- and drop anything already on screen so a
|
||||
// server that re-sends a boundary row cannot produce a duplicate React
|
||||
// key (or a duplicate row for the reader). The dedupe lives inside the
|
||||
// updater so it reads the committed list; the focus target is derived
|
||||
// separately from the rendered `assets`, because a state updater is not
|
||||
// invoked synchronously and must stay free of side effects.
|
||||
const known = new Set(assets.map((item) => item.id));
|
||||
const appended = page.items.filter((item) => !known.has(item.id));
|
||||
setAssets((current) => {
|
||||
const seen = new Set(current.map((item) => item.id));
|
||||
return [...current, ...page.items.filter((item) => !seen.has(item.id))];
|
||||
});
|
||||
setNextCursor(page.nextCursor);
|
||||
setMoreFocus({ id: appended[0]?.id ?? page.items[0]?.id ?? null });
|
||||
} catch (error) {
|
||||
setNotice(
|
||||
isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "다음 Asset을 불러오지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setMorePending(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Dismissing the panel without changing the list (cancel/close): the row
|
||||
// that opened it is still on screen, so restore focus there.
|
||||
function closeDetail() {
|
||||
setSelected(null);
|
||||
queueMicrotask(() => triggerRef.current?.focus());
|
||||
}
|
||||
|
||||
// Fix round 1 (I1). A successful delete removes the row from `assets`, so
|
||||
// by the time this runs `triggerRef.current` -- still set, since React
|
||||
// never nulls a plain ref -- points at a button that is no longer attached
|
||||
// to the document. `.focus()` on a detached element is a silent no-op, so
|
||||
// reusing `closeDetail` here left focus stranded on `<body>`. The page
|
||||
// heading is the one thing in this screen guaranteed to survive any list
|
||||
// change (the list itself can disappear into the empty state), so a
|
||||
// deletion moves focus there instead of trying to reuse a node it just
|
||||
// destroyed.
|
||||
function closeDetailAfterRemoval() {
|
||||
setSelected(null);
|
||||
queueMicrotask(() => pageHeadingRef.current?.focus());
|
||||
}
|
||||
|
||||
async function archive(detail: AssetDetail) {
|
||||
setPending(true);
|
||||
try {
|
||||
const updated = await props.gateway.updateAssetMetadata(
|
||||
detail.asset.id,
|
||||
{ expectedVersion: detail.asset.version, managementStatus: "ARCHIVED" },
|
||||
{ idempotencyKey: createLocalId("studio-asset-archive") },
|
||||
);
|
||||
setAssets((current) =>
|
||||
current.map((item) => (item.id === updated.id ? updated : item)),
|
||||
);
|
||||
setSelected({ ...detail, asset: updated });
|
||||
setNotice("보관했습니다.");
|
||||
} catch (error) {
|
||||
setNotice(
|
||||
isStudioGatewayError(error) ? error.problem.detail : "보관하지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(detail: AssetDetail) {
|
||||
setPending(true);
|
||||
try {
|
||||
await props.gateway.deleteAsset(detail.asset.id, {
|
||||
idempotencyKey: createLocalId("studio-asset-delete"),
|
||||
});
|
||||
setAssets((current) => current.filter((item) => item.id !== detail.asset.id));
|
||||
setNotice("삭제했습니다.");
|
||||
setConfirmDelete(false);
|
||||
closeDetailAfterRemoval();
|
||||
} catch (error) {
|
||||
setNotice(
|
||||
isStudioGatewayError(error) ? error.problem.detail : "삭제하지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
const [altDraft, setAltDraft] = useState("");
|
||||
const [decorativeDraft, setDecorativeDraft] = useState(false);
|
||||
|
||||
/* 상세를 열 때마다 그 자료의 값으로 칸을 맞춘다 — 앞서 보던 자료의 글이 남아 있으면 안 된다. */
|
||||
useEffect(() => {
|
||||
setAltDraft(selected?.asset.altText ?? "");
|
||||
setDecorativeDraft(selected?.asset.decorative ?? false);
|
||||
}, [selected?.asset.id, selected?.asset.altText, selected?.asset.decorative]);
|
||||
|
||||
const saveAltText = async () => {
|
||||
const detail = selected;
|
||||
if (!detail || pending) return;
|
||||
setPending(true);
|
||||
setNotice("");
|
||||
try {
|
||||
const updated = await props.gateway.updateAssetMetadata(
|
||||
detail.asset.id,
|
||||
{
|
||||
expectedVersion: detail.asset.version,
|
||||
altText: altDraft.trim() ? altDraft : null,
|
||||
decorative: decorativeDraft,
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-asset-alt") },
|
||||
);
|
||||
setAssets((current) =>
|
||||
current.map((item) => (item.id === updated.id ? updated : item)),
|
||||
);
|
||||
setSelected({ ...detail, asset: updated });
|
||||
setNotice("대체 텍스트를 저장했습니다.");
|
||||
} catch (error) {
|
||||
setNotice(
|
||||
isStudioGatewayError(error) ? error.problem.detail : "저장하지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const visibleAssets = assets.filter((asset) =>
|
||||
usageFilter === "USED"
|
||||
? asset.usageCount > 0
|
||||
: usageFilter === "UNUSED"
|
||||
? asset.usageCount === 0
|
||||
: true,
|
||||
);
|
||||
export function AssetLibrary() {
|
||||
const copy = useTechLogCopy();
|
||||
const {
|
||||
assets,
|
||||
assetResultCount,
|
||||
altDraft,
|
||||
archive,
|
||||
closeDetail,
|
||||
confirmDelete,
|
||||
decorativeDraft,
|
||||
detailHeadingRef,
|
||||
kindFilter,
|
||||
listStatus,
|
||||
loadMore,
|
||||
morePending,
|
||||
nextCursor,
|
||||
notice,
|
||||
openDetail,
|
||||
pageHeadingRef,
|
||||
pending,
|
||||
q,
|
||||
remove,
|
||||
resetFilters,
|
||||
rowRefs,
|
||||
saveAltText,
|
||||
searchDraft,
|
||||
selected,
|
||||
setAltDraft,
|
||||
setConfirmDelete,
|
||||
setDecorativeDraft,
|
||||
setKindFilter,
|
||||
setSearchDraft,
|
||||
setUsageFilter,
|
||||
submitSearch,
|
||||
usageFilter,
|
||||
visibleAssets,
|
||||
} = useAssetLibraryController();
|
||||
|
||||
return (
|
||||
<div className="studio-page studio-assets-page">
|
||||
@@ -319,55 +100,66 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section className="studio-asset-tools" aria-label="Asset 검색 도구">
|
||||
<form role="search" onSubmit={submitSearch}>
|
||||
<label htmlFor={searchId}>Asset 검색</label>
|
||||
<div>
|
||||
<input
|
||||
id={searchId}
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
placeholder="Asset 키, 파일 이름"
|
||||
onChange={(event) => setSearchDraft(event.target.value)}
|
||||
/>
|
||||
<button type="submit">검색</button>
|
||||
</div>
|
||||
</form>
|
||||
{/*
|
||||
종류는 서버가 걸러 준다. 쓰임 여부는 계약에 없어 받아 온 목록에서 거르므로, 다음 쪽에
|
||||
있는 것까지 세지 못한다는 사실을 함께 적는다 — 없는 필터를 있는 척하지 않는다.
|
||||
*/}
|
||||
<div className="studio-asset-filters">
|
||||
<label>
|
||||
<span>종류</span>
|
||||
<select
|
||||
<SearchFilterToolbar
|
||||
className="studio-asset-tools"
|
||||
label="Asset 검색 도구"
|
||||
onReset={resetFilters}
|
||||
resetLabel={copy("techLog.action.resetFilters")}
|
||||
resultCount={assetResultCount}
|
||||
search={
|
||||
<Form pending={false} role="search" onSubmit={submitSearch}>
|
||||
<div className="studio-asset-search">
|
||||
<TextField
|
||||
className="studio-tool-field"
|
||||
label="Asset 검색"
|
||||
placeholder="Asset 키, 파일 이름"
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
onChange={(event) => setSearchDraft(event.currentTarget.value)}
|
||||
/>
|
||||
<Button type="submit" variant="ghost">
|
||||
{copy("techLog.action.search")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
}
|
||||
filters={
|
||||
<div className="studio-asset-filters">
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="종류"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
{ value: "IMAGE", label: "이미지" },
|
||||
{ value: "DIAGRAM", label: "도식" },
|
||||
{ value: "ATTACHMENT", label: "첨부" },
|
||||
]}
|
||||
value={kindFilter}
|
||||
onChange={(event) => setKindFilter(event.currentTarget.value as AssetKind | "")}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
<option value="IMAGE">이미지</option>
|
||||
<option value="DIAGRAM">도식</option>
|
||||
<option value="ATTACHMENT">첨부</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>쓰임</span>
|
||||
<select
|
||||
onChange={(event) =>
|
||||
setKindFilter(event.currentTarget.value as AssetKind | "")
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
description={
|
||||
usageFilter ? "불러온 목록 안에서만 거릅니다." : undefined
|
||||
}
|
||||
label="쓰임"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
{ value: "USED", label: "쓰이는 것" },
|
||||
{ value: "UNUSED", label: "쓰이지 않는 것" },
|
||||
]}
|
||||
value={usageFilter}
|
||||
onChange={(event) =>
|
||||
setUsageFilter(event.currentTarget.value as "" | "USED" | "UNUSED")
|
||||
setUsageFilter(
|
||||
event.currentTarget.value as "" | "USED" | "UNUSED",
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
<option value="USED">쓰이는 것</option>
|
||||
<option value="UNUSED">쓰이지 않는 것</option>
|
||||
</select>
|
||||
</label>
|
||||
{usageFilter ? (
|
||||
<small>불러온 목록 안에서만 거릅니다.</small>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{/*
|
||||
확인 창이 열려 있는 동안에는 같은 문구를 창 안에서만 말한다. 두 벌이 화면에 남으면 읽는
|
||||
@@ -379,30 +171,25 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
|
||||
{listStatus === "LOADING" ? (
|
||||
<p className="studio-loading" role="status">
|
||||
Asset 목록을 불러오는 중입니다.
|
||||
{copy("techLog.state.assetListLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
{listStatus === "ERROR" ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
Asset 목록을 불러오지 못했습니다.
|
||||
{copy("techLog.state.assetListLoadFailed")}
|
||||
</p>
|
||||
) : null}
|
||||
{/* The list changing is otherwise silent: a search replaces every row
|
||||
and "더 보기" appends without moving anything the reader can see. */}
|
||||
<p className="studio-result-count" role="status">
|
||||
{listStatus === "READY" ? `${assets.length}개의 Asset` : ""}
|
||||
</p>
|
||||
{listStatus === "READY" && assets.length === 0 ? (
|
||||
<section className="studio-empty-state">
|
||||
{q ? (
|
||||
<>
|
||||
<h2>조건에 맞는 Asset이 없습니다</h2>
|
||||
<p>검색어를 바꾸거나 비우면 전체 Asset을 다시 볼 수 있습니다.</p>
|
||||
<h2>{copy("techLog.state.emptyAssetSearch")}</h2>
|
||||
<p>{copy("techLog.state.emptyAssetSearchHint")}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2>등록된 Asset이 없습니다</h2>
|
||||
<p>Case 편집 화면에서 Asset을 업로드하면 여기에서 관리할 수 있습니다.</p>
|
||||
<h2>{copy("techLog.state.emptyAssetLibrary")}</h2>
|
||||
<p>{copy("techLog.state.emptyAssetLibraryHint")}</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
@@ -433,23 +220,22 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
가리키는 불변 식별자이지 사람이 기억하는 이름이 아니다. 이름을 앞에 두고 key 는
|
||||
아래에 작게 남긴다.
|
||||
*/}
|
||||
<button
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
ref={(node) => {
|
||||
const rows = rowRefs.current;
|
||||
if (node) rows.set(asset.id, node);
|
||||
else rows.delete(asset.id);
|
||||
}}
|
||||
aria-current={selected?.asset.id === asset.id ? "true" : undefined}
|
||||
/* 버튼의 이름은 사람이 부르는 이름까지다. 크기·형식까지 이름에 넣으면 목록을
|
||||
훑을 때 버튼 하나하나가 문장이 되어 고를 수 없다. */
|
||||
aria-label={asset.originalFilename || asset.assetKey}
|
||||
onClick={(event) => void openDetail(asset, event.currentTarget)}
|
||||
onClick={(event) => openDetail(asset, event.currentTarget)}
|
||||
>
|
||||
<strong>{asset.originalFilename || asset.assetKey}</strong>
|
||||
<small>{assetFacts(asset)}</small>
|
||||
<small className="asset-library-list__key">{asset.assetKey}</small>
|
||||
</button>
|
||||
</Button>
|
||||
<span>{ASSET_STATUS_LABELS[asset.managementStatus]}</span>
|
||||
{/*
|
||||
쓰이지 않는 자료는 지워도 되는 것이고, 쓰이는 자료는 지우면 화면이 깨진다. 그
|
||||
@@ -465,14 +251,17 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
) : null}
|
||||
|
||||
{nextCursor && listStatus === "READY" ? (
|
||||
<button
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
disabled={morePending}
|
||||
onClick={() => void loadMore()}
|
||||
pending={morePending}
|
||||
pendingLabel={copy("techLog.action.loading")}
|
||||
variant="ghost"
|
||||
onClick={loadMore}
|
||||
>
|
||||
더 보기
|
||||
</button>
|
||||
{copy("techLog.action.more")}
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{selected ? (
|
||||
@@ -508,35 +297,43 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
설명(caption)은 여기 없다. 같은 그림을 다른 기록에서 다른 말로 설명할 수 있어서
|
||||
자료가 아니라 본문이 갖는 값이다(`:::evidence caption=…`).
|
||||
*/}
|
||||
<form
|
||||
<Form
|
||||
className="asset-detail-alt"
|
||||
pending={pending}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveAltText();
|
||||
}}
|
||||
>
|
||||
<label htmlFor="asset-alt-text">대체 텍스트</label>
|
||||
<textarea
|
||||
id="asset-alt-text"
|
||||
rows={2}
|
||||
maxLength={1000}
|
||||
value={altDraft}
|
||||
<TextArea
|
||||
className="asset-detail-alt-field"
|
||||
disabled={pending}
|
||||
label="대체 텍스트"
|
||||
maxLength={1000}
|
||||
rows={2}
|
||||
value={altDraft}
|
||||
onChange={(event) => setAltDraft(event.currentTarget.value)}
|
||||
/>
|
||||
<label className="asset-detail-decorative">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={decorativeDraft}
|
||||
disabled={pending}
|
||||
onChange={(event) => setDecorativeDraft(event.currentTarget.checked)}
|
||||
/>
|
||||
<span>장식용입니다 (읽어 줄 내용이 없음)</span>
|
||||
</label>
|
||||
<button className="studio-secondary-button" type="submit" disabled={pending}>
|
||||
대체 텍스트 저장
|
||||
</button>
|
||||
</form>
|
||||
<Checkbox
|
||||
checked={decorativeDraft}
|
||||
disabled={pending}
|
||||
fieldClassName="asset-detail-decorative"
|
||||
label="장식용입니다 (읽어 줄 내용이 없음)"
|
||||
onChange={(event) =>
|
||||
setDecorativeDraft(event.currentTarget.checked)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
disabled={pending}
|
||||
pending={pending}
|
||||
pendingLabel={copy("techLog.action.savingBeforeNavigate")}
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.saveAltText")}
|
||||
</Button>
|
||||
</Form>
|
||||
{/*
|
||||
바꾸거나 지우기 전에 어디에 쓰이는지 전부 보여야 한다. 숫자만으로는 무엇이 깨질지
|
||||
알 수 없다.
|
||||
@@ -550,7 +347,7 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
평범한 링크다. 이 화면은 Studio 컨텍스트를 받지 않고 게이트웨이 하나만 받아
|
||||
혼자 설 수 있게 되어 있고, 여기서 떠날 때 지킬 편집 상태도 없다.
|
||||
*/}
|
||||
<a href={`/studio/documents/${usage.documentId}/edit`}>
|
||||
<a href={studioRoutes.documentEdit(usage.documentId)}>
|
||||
{usage.title || "제목 없는 작업본"}
|
||||
</a>
|
||||
</li>
|
||||
@@ -575,17 +372,27 @@ export function AssetLibrary(props: Readonly<{ gateway: StudioAssetGateway }>) {
|
||||
무게로 다루면 확인 창이 곧 습관이 되어 진짜 삭제도 그냥 지나간다.
|
||||
*/}
|
||||
{canHardDelete(selected) ? (
|
||||
<button type="button" disabled={pending} onClick={() => setConfirmDelete(true)}>
|
||||
삭제
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
variant="ghost"
|
||||
onClick={() => setConfirmDelete(true)}
|
||||
>
|
||||
{copy("techLog.action.delete")}
|
||||
</Button>
|
||||
) : (
|
||||
<button type="button" disabled={pending} onClick={() => void archive(selected)}>
|
||||
보관
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
variant="ghost"
|
||||
onClick={() => void archive(selected)}
|
||||
>
|
||||
{copy("techLog.action.archive")}
|
||||
</Button>
|
||||
)}
|
||||
<button type="button" onClick={closeDetail}>
|
||||
닫기
|
||||
</button>
|
||||
<Button type="button" variant="ghost" onClick={closeDetail}>
|
||||
{copy("techLog.action.close")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -1,97 +1,57 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts";
|
||||
import type { Asset } from "../../../contracts/studio/contract.ts";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { AssetPicker } from "./asset-picker.tsx";
|
||||
|
||||
/** 본문이 그림을 가리키는 방법. 이 수를 세면 "지금 몇 개를 쓰는가" 가 나온다. */
|
||||
const EVIDENCE_DIRECTIVE = /^:::evidence\b/gmu;
|
||||
|
||||
export function countBodyAssets(bodyMarkdown: string): number {
|
||||
return bodyMarkdown.match(EVIDENCE_DIRECTIVE)?.length ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 자료는 고르러 들어가는 것이지 폼에 펼쳐 두는 것이 아니다.
|
||||
*
|
||||
* <p>편집 폼 아래에 고를 수 있는 자료가 전부 펼쳐져 있었다. 36개면 36줄이고, 줄마다 파일 이름과
|
||||
* 삭제 단추가 따라붙어 본문보다 자료 목록이 길었다 — 좁은 화면에서는 그 덩어리가 여러 줄로
|
||||
* 깨지면서 삭제 단추만 따로 떨어지기도 했다. 글을 쓰는 화면이 자료 관리 화면이 되어 있었다.
|
||||
*
|
||||
* <p>폼에는 지금 몇 개를 쓰는지와 넣는 단추만 둔다. 고르는 일은 창 안에서 한다 — 검색과 목록은
|
||||
* 그대로 쓰되 글의 흐름을 막지 않는다.
|
||||
*
|
||||
* <p>관리(이름·대체 텍스트·사용처·삭제)는 Asset 화면이 맡는다. 같은 자료를 두 화면이 다루되
|
||||
* 하는 일이 다르다: 여기는 글에 넣기, 저기는 관리하기.
|
||||
*/
|
||||
export function AssetPickerDialog({
|
||||
gateway,
|
||||
usedCount,
|
||||
onInsert,
|
||||
}: {
|
||||
gateway: StudioAssetGateway;
|
||||
/** 본문이 지금 가리키는 자료 수. */
|
||||
usedCount: number;
|
||||
onInsert(directive: string): void;
|
||||
}) {
|
||||
const copy = useTechLogCopy();
|
||||
const [open, setOpen] = useState(false);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
/*
|
||||
`showModal` 이 없는 환경이 있다(jsdom 이 그렇다). 없으면 창을 그냥 보이는 상태로 둔다 —
|
||||
고르지 못하게 막는 것보다 낫다.
|
||||
*/
|
||||
if (open) {
|
||||
if (typeof dialog.showModal === "function") dialog.showModal();
|
||||
else dialog.setAttribute("open", "");
|
||||
} else if (dialog.open) {
|
||||
if (typeof dialog.close === "function") dialog.close();
|
||||
else dialog.removeAttribute("open");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
// 닫고 나면 초점이 갈 곳이 있어야 한다. 열었던 단추로 돌려준다.
|
||||
queueMicrotask(() => triggerRef.current?.focus());
|
||||
};
|
||||
const close = () => setOpen(false);
|
||||
|
||||
return (
|
||||
<div className="studio-asset-slot">
|
||||
<p className="studio-asset-slot__count">
|
||||
{usedCount > 0 ? `본문에서 자료 ${usedCount}개를 씁니다` : "본문에 넣은 자료가 없습니다"}
|
||||
{usedCount > 0
|
||||
? "본문에서 자료 " + usedCount + "개를 씁니다"
|
||||
: "본문에 넣은 자료가 없습니다"}
|
||||
</p>
|
||||
<button
|
||||
<Button
|
||||
ref={triggerRef}
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
variant="ghost"
|
||||
>
|
||||
본문에 자료 넣기
|
||||
</button>
|
||||
{copy("techLog.action.insertAsset")}
|
||||
</Button>
|
||||
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
<Dialog
|
||||
accessibleTitle="본문에 넣을 자료 고르기"
|
||||
className="studio-asset-dialog"
|
||||
aria-label="본문에 넣을 자료 고르기"
|
||||
onClose={() => setOpen(false)}
|
||||
onCancel={close}
|
||||
onClose={close}
|
||||
open={open}
|
||||
returnFocusRef={triggerRef}
|
||||
title="본문에 넣을 자료"
|
||||
>
|
||||
{/* 창을 그릴 때만 목록을 부른다 — 열지 않은 창이 매번 자료를 받아 올 이유가 없다. */}
|
||||
{open ? (
|
||||
<div className="studio-asset-dialog__body">
|
||||
<header>
|
||||
<h2>본문에 넣을 자료</h2>
|
||||
<button type="button" onClick={close}>
|
||||
닫기
|
||||
</button>
|
||||
</header>
|
||||
<AssetPicker
|
||||
gateway={gateway}
|
||||
onInsert={(directive) => {
|
||||
onInsert(directive);
|
||||
close();
|
||||
@@ -99,7 +59,7 @@ export function AssetPickerDialog({
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</dialog>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { useEffect, useId, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
SelectControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
import type { Asset } from "../../../contracts/studio/contract.ts";
|
||||
import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts";
|
||||
import { useStudioAssetListQuery } from "../studio-asset-server-state.ts";
|
||||
|
||||
/** One screenful of candidates; searching, not scrolling, reaches the rest. */
|
||||
const PAGE_SIZE = 50;
|
||||
@@ -18,10 +25,6 @@ function attributeValue(raw: string): string {
|
||||
return raw.replaceAll('"', "").replace(/\s+/gu, " ").trim();
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function buildEvidenceDirective(
|
||||
input: Readonly<{ assetKey: string; alt: string; caption: string; zoom: boolean }>,
|
||||
): string {
|
||||
@@ -38,14 +41,11 @@ function byteLabel(bytes: number): string {
|
||||
}
|
||||
|
||||
export function AssetPicker({
|
||||
gateway,
|
||||
onInsert,
|
||||
}: Readonly<{
|
||||
gateway: StudioAssetGateway;
|
||||
onInsert: (directive: string) => void;
|
||||
}>) {
|
||||
const [assets, setAssets] = useState<readonly Asset[]>([]);
|
||||
const [status, setStatus] = useState<"LOADING" | "ERROR" | "READY">("LOADING");
|
||||
const copy = useTechLogCopy();
|
||||
// Alignment follow-up, item 2. `searchDraft` is what the author is typing,
|
||||
// `q` the query actually submitted -- only `q` is an effect dependency. That
|
||||
// is a stronger guarantee than debouncing (zero requests while typing rather
|
||||
@@ -62,33 +62,20 @@ export function AssetPicker({
|
||||
const [q, setQ] = useState("");
|
||||
const searchId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
// `RequestOptions.signal` is advisory: an adapter that ignores it still
|
||||
// resolves, and an abandoned query's response would then replace the newer
|
||||
// one's results. This flag flips synchronously when `q` changes, so an
|
||||
// older search can never land last.
|
||||
let active = true;
|
||||
setStatus("LOADING");
|
||||
gateway
|
||||
.listAssets(
|
||||
{ managementStatus: "READY", ...(q ? { q } : {}), ...(kind ? { kind } : {}), limit: PAGE_SIZE },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((page) => {
|
||||
if (!active) return;
|
||||
setAssets(page.items);
|
||||
setStatus("READY");
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!active || isAbortError(error)) return;
|
||||
setStatus("ERROR");
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [gateway, kind, q]);
|
||||
const assetsQuery = useStudioAssetListQuery({
|
||||
managementStatus: "READY",
|
||||
...(q ? { q } : {}),
|
||||
...(kind ? { kind } : {}),
|
||||
limit: PAGE_SIZE,
|
||||
});
|
||||
const assets = assetsQuery.data?.items ?? [];
|
||||
const status =
|
||||
assetsQuery.state.base === "initial-loading"
|
||||
? "LOADING"
|
||||
: assetsQuery.state.base === "terminal-error"
|
||||
? "ERROR"
|
||||
: "READY";
|
||||
|
||||
|
||||
// READY만 삽입 후보다. 서버 필터를 신뢰하되 방어적으로 한 번 더 거른다.
|
||||
// A query does not relax this: an asset under review is never insertable,
|
||||
@@ -101,7 +88,7 @@ export function AssetPicker({
|
||||
};
|
||||
|
||||
const listMessage = status === "LOADING"
|
||||
? "Asset 목록을 불러오는 중입니다."
|
||||
? copy("techLog.state.assetListLoading")
|
||||
: selectable.length > 0
|
||||
? `삽입할 수 있는 Asset ${selectable.length}개`
|
||||
: q
|
||||
@@ -112,31 +99,31 @@ export function AssetPicker({
|
||||
{/* The search box stays mounted through the error and empty states: it is
|
||||
the only way to reach an asset outside the first page, so removing it
|
||||
with the list would strand the author on whatever went wrong. */}
|
||||
<form className="asset-picker-search" role="search" onSubmit={submitSearch}>
|
||||
<Form className="asset-picker-search" role="search" onSubmit={submitSearch}>
|
||||
<label htmlFor={searchId}>Asset 검색</label>
|
||||
<div>
|
||||
<input
|
||||
<InputControl
|
||||
id={searchId}
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
placeholder="Asset 키, 파일 이름"
|
||||
onChange={(event) => setSearchDraft(event.target.value)}
|
||||
/>
|
||||
<button type="submit">검색</button>
|
||||
<Button visualPolicy="inherit" type="submit">{copy("techLog.action.search")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
<div className="asset-picker-toolbar">
|
||||
<label className="asset-picker-kind">
|
||||
<span>종류</span>
|
||||
<select value={kind} onChange={(event) => setKind(event.currentTarget.value as "" | Asset["kind"])}>
|
||||
<SelectControl value={kind} onChange={(event) => setKind(event.currentTarget.value as "" | Asset["kind"])}>
|
||||
<option value="">전체</option>
|
||||
<option value="IMAGE">이미지</option>
|
||||
<option value="DIAGRAM">도식</option>
|
||||
<option value="ATTACHMENT">첨부</option>
|
||||
</select>
|
||||
</SelectControl>
|
||||
</label>
|
||||
<label className="asset-picker-option">
|
||||
<input
|
||||
<InputControl
|
||||
type="checkbox"
|
||||
checked={allowZoom}
|
||||
onChange={(event) => setAllowZoom(event.currentTarget.checked)}
|
||||
@@ -145,7 +132,7 @@ export function AssetPicker({
|
||||
</label>
|
||||
</div>
|
||||
{status === "ERROR"
|
||||
? <p className="studio-error" role="alert">Asset 목록을 불러오지 못했습니다.</p>
|
||||
? <p className="studio-error" role="alert">{copy("techLog.state.assetListLoadFailed")}</p>
|
||||
: <p className="studio-asset-picker-empty" role="status">{listMessage}</p>}
|
||||
{selectable.length > 0 ? <ul className="asset-picker-results">
|
||||
{selectable.map((asset) => {
|
||||
@@ -153,7 +140,7 @@ export function AssetPicker({
|
||||
const dimensions = asset.width && asset.height ? `${asset.width}×${asset.height}` : null;
|
||||
return (
|
||||
<li key={asset.id}>
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
className="asset-picker-card"
|
||||
aria-label={`${asset.originalFilename} (${asset.assetKey}) 삽입`}
|
||||
@@ -172,8 +159,8 @@ export function AssetPicker({
|
||||
<span>{[asset.kind, dimensions, byteLabel(asset.byteSize)].filter(Boolean).join(" · ")}</span>
|
||||
<small>{asset.usageCount > 0 ? `${asset.usageCount}개 기록에서 사용 중` : "아직 사용되지 않음"}</small>
|
||||
</span>
|
||||
<span className="asset-picker-insert">삽입</span>
|
||||
</button>
|
||||
<span className="asset-picker-insert">{copy("techLog.action.insert")}</span>
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import type { Asset, AssetKind } from "../../../contracts/studio/contract.ts";
|
||||
import type { StudioAssetGateway } from "../../../application/ports/studio-asset-gateway.ts";
|
||||
import { isStudioGatewayError } from "../../../application/ports/studio-gateway-error.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import { isStudioApplicationError } from "../../../application/studio-application.ts";
|
||||
import type { AppFailure } from "../../../../../contracts/errors.ts";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
assetFileIdentity,
|
||||
useStudioAssetCommands,
|
||||
} from "../studio-asset-server-state.ts";
|
||||
|
||||
export type UploadState =
|
||||
| { kind: "IDLE" }
|
||||
@@ -31,7 +41,7 @@ export function stateForUploaded(asset: Asset): UploadState {
|
||||
}
|
||||
|
||||
export function stateForError(error: unknown): UploadState {
|
||||
if (isStudioGatewayError(error)) {
|
||||
if (isStudioApplicationError(error)) {
|
||||
if (error.code === "PAYLOAD_TOO_LARGE") return { kind: "TOO_LARGE" };
|
||||
if (error.code === "UNSUPPORTED_MEDIA_TYPE") return { kind: "UNSUPPORTED_TYPE" };
|
||||
return { kind: "TRANSPORT_FAILED", message: error.problem.detail };
|
||||
@@ -39,6 +49,17 @@ export function stateForError(error: unknown): UploadState {
|
||||
return { kind: "TRANSPORT_FAILED", message: "업로드를 전송하지 못했습니다." };
|
||||
}
|
||||
|
||||
function stateForFailure(failure: AppFailure): UploadState {
|
||||
if (failure.code === "PAYLOAD_TOO_LARGE") return { kind: "TOO_LARGE" };
|
||||
if (failure.code === "UNSUPPORTED_MEDIA_TYPE") {
|
||||
return { kind: "UNSUPPORTED_TYPE" };
|
||||
}
|
||||
return {
|
||||
kind: "TRANSPORT_FAILED",
|
||||
message: "업로드를 전송하지 못했습니다.",
|
||||
};
|
||||
}
|
||||
|
||||
const MESSAGES: Record<UploadState["kind"], string> = {
|
||||
IDLE: "",
|
||||
SELECTION_FAILED: "파일을 선택하지 못했습니다.",
|
||||
@@ -53,35 +74,20 @@ const MESSAGES: Record<UploadState["kind"], string> = {
|
||||
};
|
||||
|
||||
export function AssetUploadDialog(props: Readonly<{
|
||||
gateway: StudioAssetGateway;
|
||||
kind: AssetKind;
|
||||
onUploaded: (asset: Asset) => void;
|
||||
onClose: () => void;
|
||||
}>) {
|
||||
const copy = useTechLogCopy();
|
||||
const commands = useStudioAssetCommands();
|
||||
const [state, setState] = useState<UploadState>({ kind: "IDLE" });
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [altText, setAltText] = useState("");
|
||||
const [decorative, setDecorative] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const altRef = useRef<HTMLInputElement>(null);
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const titleId = useId();
|
||||
const descriptionId = useId();
|
||||
const uploading = state.kind === "UPLOADING";
|
||||
|
||||
// This dialog has no `open` prop -- the caller mounts it to open it and
|
||||
// unmounts it to close it (`unpublish-dialog.tsx`'s toggle-by-prop shape
|
||||
// does not fit a one-shot upload flow). So the modal opens on mount and the
|
||||
// unmount cleanup below closes it if the user never did.
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
dialog.showModal();
|
||||
inputRef.current?.focus();
|
||||
return () => {
|
||||
if (dialog.open && typeof dialog.close === "function") dialog.close();
|
||||
};
|
||||
}, []);
|
||||
const uploading =
|
||||
state.kind === "UPLOADING" || commands.upload.state.overlay.mutationPending;
|
||||
|
||||
/**
|
||||
* Final fix wave, item 2. Alt text is collected here because it is a
|
||||
@@ -113,156 +119,118 @@ export function AssetUploadDialog(props: Readonly<{
|
||||
return;
|
||||
}
|
||||
setState({ kind: "UPLOADING" });
|
||||
try {
|
||||
// Fix round 1 (I1). A fresh key per call, not one generated once when
|
||||
// the dialog opened: every terminal state re-enables the file input,
|
||||
// so a user can retry with a *different* file after a failure, and two
|
||||
// different payloads must never share one idempotency key -- the exact
|
||||
// retry scenario idempotency keys exist for.
|
||||
const asset = await props.gateway.uploadAsset(
|
||||
{
|
||||
file,
|
||||
kind: props.kind,
|
||||
decorative,
|
||||
...(decorative ? {} : { altText: trimmedAlt }),
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-asset-upload") },
|
||||
);
|
||||
const next = stateForUploaded(asset);
|
||||
setState(next);
|
||||
if (next.kind === "READY") props.onUploaded(asset);
|
||||
} catch (error) {
|
||||
setState(stateForError(error));
|
||||
const result = await commands.upload.submit({
|
||||
form: {
|
||||
file,
|
||||
kind: props.kind,
|
||||
decorative,
|
||||
...(decorative ? {} : { altText: trimmedAlt }),
|
||||
},
|
||||
fileIdentity: assetFileIdentity(file),
|
||||
});
|
||||
if (!result.ok) {
|
||||
setState(stateForFailure(result.error));
|
||||
return;
|
||||
}
|
||||
|
||||
const next = stateForUploaded(result.value);
|
||||
setState(next);
|
||||
if (next.kind === "READY") props.onUploaded(result.value);
|
||||
}
|
||||
|
||||
const trapFocus = (event: KeyboardEvent<HTMLDialogElement>) => {
|
||||
if (event.key !== "Tab") return;
|
||||
const controls = Array.from(
|
||||
event.currentTarget.querySelectorAll<HTMLElement>(
|
||||
"input:not([disabled]), button:not([disabled])",
|
||||
),
|
||||
);
|
||||
if (!controls.length) return;
|
||||
const first = controls[0];
|
||||
const last = controls.at(-1)!;
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
<Dialog
|
||||
className="studio-asset-upload-dialog"
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={descriptionId}
|
||||
onCancel={(event) => {
|
||||
event.preventDefault();
|
||||
description="업로드한 파일은 서버 검증을 거친 뒤에만 본문에 삽입할 수 있습니다. 장식용이 아니면 대체 텍스트가 필요합니다."
|
||||
eyebrow={<p className="studio-eyebrow">ASSET UPLOAD</p>}
|
||||
hideCloseButton
|
||||
initialFocusRef={inputRef}
|
||||
onClose={() => {
|
||||
if (!uploading) props.onClose();
|
||||
}}
|
||||
onKeyDown={trapFocus}
|
||||
open
|
||||
title="Asset 업로드"
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
disabled={uploading}
|
||||
onClick={props.onClose}
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.close")}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={uploading}
|
||||
onClick={() => void submit()}
|
||||
pending={uploading}
|
||||
pendingLabel={copy("techLog.action.uploading")}
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.upload")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="studio-dialog-body">
|
||||
<p className="studio-eyebrow">ASSET UPLOAD</p>
|
||||
<h2 id={titleId}>Asset 업로드</h2>
|
||||
<p id={descriptionId}>
|
||||
업로드한 파일은 서버 검증을 거친 뒤에만 본문에 삽입할 수 있습니다. 장식용이
|
||||
아니면 대체 텍스트가 필요합니다.
|
||||
</p>
|
||||
<label className="studio-field">
|
||||
<span>Asset 파일</span>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml,application/pdf"
|
||||
disabled={uploading}
|
||||
onChange={(event) => {
|
||||
const selected = event.currentTarget.files?.[0] ?? null;
|
||||
setFile(selected);
|
||||
if (!selected) {
|
||||
setState({ kind: "SELECTION_FAILED", message: MESSAGES.SELECTION_FAILED });
|
||||
return;
|
||||
}
|
||||
// A new file clears whatever the previous attempt reported --
|
||||
// and its description with it. Alt text describes *this image*,
|
||||
// and every terminal failure state (REJECTED, QUARANTINED,
|
||||
// TRANSPORT_FAILED) leaves this dialog mounted with the file
|
||||
// input re-enabled, so the retry path is exactly where a stale
|
||||
// description survives: upload `db-schema.png` as "DB 스키마",
|
||||
// get it quarantined, pick `sequence.png`, upload -- and
|
||||
// `sequence.png` ships described as "DB 스키마" and validates as
|
||||
// publishable. Cleared unconditionally rather than only after a
|
||||
// failure: "which file is this text describing" has one honest
|
||||
// answer per selection, and `submit()`'s ALT_REQUIRED refusal
|
||||
// makes the emptied field impossible to ignore.
|
||||
//
|
||||
// `decorative` is reset for the same reason and a sharper one.
|
||||
// It does not merely describe the previous image, it *exempts*
|
||||
// it: `validate-working-copy.ts`'s EVIDENCE_ALT_REQUIRED reads
|
||||
// `Asset.decorative`, so a flag inherited from a discarded
|
||||
// divider lets a meaningful diagram publish with no accessible
|
||||
// name at all -- the check passes rather than catching it. Alt
|
||||
// text riding along produces a wrong description; this produces
|
||||
// none.
|
||||
setState({ kind: "IDLE" });
|
||||
setAltText("");
|
||||
setDecorative(false);
|
||||
// Unconditional now: the alt field is enabled again by the line
|
||||
// above, so there is no longer a case where focusing it would
|
||||
// land on a disabled control.
|
||||
altRef.current?.focus();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field studio-field--checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={decorative}
|
||||
disabled={uploading}
|
||||
onChange={(event) => {
|
||||
setDecorative(event.currentTarget.checked);
|
||||
if (state.kind === "ALT_REQUIRED") setState({ kind: "IDLE" });
|
||||
}}
|
||||
/>
|
||||
<span>장식용 이미지 (대체 텍스트 없음)</span>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>대체 텍스트</span>
|
||||
<input
|
||||
ref={altRef}
|
||||
type="text"
|
||||
value={altText}
|
||||
disabled={uploading || decorative}
|
||||
aria-invalid={state.kind === "ALT_REQUIRED"}
|
||||
onChange={(event) => {
|
||||
setAltText(event.currentTarget.value);
|
||||
if (state.kind === "ALT_REQUIRED") setState({ kind: "IDLE" });
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<p className="studio-dialog-status" role="status" aria-live="polite" aria-label="업로드 상태">{MESSAGES[state.kind]}</p>
|
||||
{/* `.studio-dialog-actions button:last-child` is the primary style, so
|
||||
the confirming action goes last -- same order as the other Studio
|
||||
dialogs. */}
|
||||
<div className="studio-dialog-actions">
|
||||
<button type="button" disabled={uploading} onClick={props.onClose}>
|
||||
닫기
|
||||
</button>
|
||||
<button type="button" disabled={uploading} onClick={() => void submit()}>
|
||||
업로드
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
<TextField
|
||||
ref={inputRef}
|
||||
autoFocus
|
||||
accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml,application/pdf"
|
||||
className="studio-field"
|
||||
disabled={uploading}
|
||||
label="Asset 파일"
|
||||
type="file"
|
||||
onChange={(event) => {
|
||||
const selected = event.currentTarget.files?.[0] ?? null;
|
||||
setFile(selected);
|
||||
if (!selected) {
|
||||
setState({
|
||||
kind: "SELECTION_FAILED",
|
||||
message: MESSAGES.SELECTION_FAILED,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState({ kind: "IDLE" });
|
||||
setAltText("");
|
||||
setDecorative(false);
|
||||
altRef.current?.focus();
|
||||
}}
|
||||
/>
|
||||
<Checkbox
|
||||
checked={decorative}
|
||||
className="studio-field studio-field--checkbox"
|
||||
disabled={uploading}
|
||||
label="장식용 이미지 (대체 텍스트 없음)"
|
||||
onChange={(event) => {
|
||||
setDecorative(event.currentTarget.checked);
|
||||
if (state.kind === "ALT_REQUIRED") setState({ kind: "IDLE" });
|
||||
}}
|
||||
/>
|
||||
<TextField
|
||||
ref={altRef}
|
||||
className="studio-field"
|
||||
disabled={uploading || decorative}
|
||||
error={state.kind === "ALT_REQUIRED" ? MESSAGES.ALT_REQUIRED : undefined}
|
||||
label="대체 텍스트"
|
||||
type="text"
|
||||
value={altText}
|
||||
onChange={(event) => {
|
||||
setAltText(event.currentTarget.value);
|
||||
if (state.kind === "ALT_REQUIRED") setState({ kind: "IDLE" });
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
/>
|
||||
<p
|
||||
aria-label="업로드 상태"
|
||||
aria-live="polite"
|
||||
className="studio-dialog-status"
|
||||
role="status"
|
||||
>
|
||||
{MESSAGES[state.kind]}
|
||||
</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
SelectControl,
|
||||
TextAreaControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type { Asset, AssetKind } from "../../../contracts/studio/contract.ts";
|
||||
import { useStudioAssetGateway } from "../use-studio.ts";
|
||||
import { buildEvidenceDirective } from "./asset-picker.tsx";
|
||||
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
|
||||
import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
|
||||
@@ -35,7 +41,7 @@ export function CaseFields({
|
||||
issues: readonly FieldIssue[];
|
||||
onChange(draft: CaseInput): void;
|
||||
}) {
|
||||
const assetGateway = useStudioAssetGateway();
|
||||
const copy = useTechLogCopy();
|
||||
const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
|
||||
const uploadTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE");
|
||||
@@ -63,7 +69,7 @@ export function CaseFields({
|
||||
<div className="studio-semantic-blocks">
|
||||
<label className="studio-document-block" data-tone="problem">
|
||||
<span className="studio-document-block__label">문제</span>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
aria-label="문제"
|
||||
value={draft.problem}
|
||||
placeholder="어떤 현상이 문제였는지 한 문단으로 적어 주세요."
|
||||
@@ -73,7 +79,7 @@ export function CaseFields({
|
||||
</label>
|
||||
<label className="studio-document-block" data-tone="conclusion">
|
||||
<span className="studio-document-block__label">결론</span>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
aria-label="결론"
|
||||
value={draft.conclusion}
|
||||
placeholder="검증을 통해 무엇을 확인했는지 적어 주세요."
|
||||
@@ -91,17 +97,17 @@ export function CaseFields({
|
||||
<div className="studio-detail-properties__body">
|
||||
<label className="studio-property-row studio-property-row--writing">
|
||||
<span className="studio-property-name">검증 환경</span>
|
||||
<textarea aria-label="검증 환경" value={draft.environment} placeholder="OS, 버전, 구성처럼 결과의 범위를 결정하는 조건" onChange={(event) => update({ environment: event.currentTarget.value })} />
|
||||
<TextAreaControl aria-label="검증 환경" value={draft.environment} placeholder="OS, 버전, 구성처럼 결과의 범위를 결정하는 조건" onChange={(event) => update({ environment: event.currentTarget.value })} />
|
||||
<FieldNotice issues={issues} path="/environment" />
|
||||
</label>
|
||||
<label className="studio-property-row studio-property-row--writing">
|
||||
<span className="studio-property-name">재현 조건</span>
|
||||
<textarea aria-label="재현 조건" value={draft.reproduction} placeholder="같은 현상을 다시 만들기 위해 필요한 조건" onChange={(event) => update({ reproduction: event.currentTarget.value })} />
|
||||
<TextAreaControl aria-label="재현 조건" value={draft.reproduction} placeholder="같은 현상을 다시 만들기 위해 필요한 조건" onChange={(event) => update({ reproduction: event.currentTarget.value })} />
|
||||
<FieldNotice issues={issues} path="/reproduction" />
|
||||
</label>
|
||||
<label className="studio-property-row">
|
||||
<span className="studio-property-name">마지막 검증일</span>
|
||||
<input aria-label="마지막 검증일" type="date" value={draft.lastVerifiedOn ?? ""} onChange={(event) => update({ lastVerifiedOn: event.currentTarget.value || null })} />
|
||||
<InputControl aria-label="마지막 검증일" type="date" value={draft.lastVerifiedOn ?? ""} onChange={(event) => update({ lastVerifiedOn: event.currentTarget.value || null })} />
|
||||
<FieldNotice issues={issues} path="/lastVerifiedOn" />
|
||||
</label>
|
||||
</div>
|
||||
@@ -114,14 +120,14 @@ export function CaseFields({
|
||||
<p>작성 화면이 곧 문서입니다. 빈 블록에서 / 를 입력해 제목·목록·코드 블록을 추가할 수 있습니다.</p>
|
||||
</div>
|
||||
<div className="studio-inline-asset-actions">
|
||||
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<AssetPickerDialog usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<label className="studio-asset-kind-field studio-asset-kind-field--compact">
|
||||
<span className="studio-visually-hidden">업로드 종류</span>
|
||||
<select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>
|
||||
<SelectControl value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>
|
||||
{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
|
||||
</select>
|
||||
</SelectControl>
|
||||
</label>
|
||||
<button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
|
||||
<Button visualPolicy="inherit" ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>{copy("techLog.action.upload")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<MarkdownBlockEditor ref={bodyEditorRef} label="본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
|
||||
@@ -130,7 +136,7 @@ export function CaseFields({
|
||||
|
||||
{uploadOpen ? (
|
||||
<AssetUploadDialog
|
||||
gateway={assetGateway}
|
||||
|
||||
kind={uploadKind}
|
||||
onUploaded={(asset) => {
|
||||
insertDirective(buildEvidenceDirective({
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
SelectControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
@@ -7,7 +13,7 @@ type CatalogEntry = components["schemas"]["CatalogEntry"];
|
||||
/**
|
||||
* Project/Topic property picker used by the document writing surface.
|
||||
*
|
||||
* Native <select> was technically correct but became painful once catalogs grew: authors had to
|
||||
* Native <SelectControl> was technically correct but became painful once catalogs grew: authors had to
|
||||
* scroll a flat list and the control looked like a settings form. This picker keeps the document
|
||||
* property row compact, then opens a searchable choice surface only when the property is edited.
|
||||
*/
|
||||
@@ -26,6 +32,7 @@ export function CatalogPropertyPicker({
|
||||
missingLabel?: string;
|
||||
onChange(value: string | null): void;
|
||||
}) {
|
||||
const copy = useTechLogCopy();
|
||||
const detailsRef = useRef<HTMLDetailsElement>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
const selected = value ? entries.find((entry) => entry.id === value) : undefined;
|
||||
@@ -51,7 +58,7 @@ export function CatalogPropertyPicker({
|
||||
<div className="studio-catalog-property-picker__popover">
|
||||
<label className="studio-catalog-property-picker__search">
|
||||
<span className="studio-visually-hidden">{label} 검색</span>
|
||||
<input
|
||||
<InputControl
|
||||
type="search"
|
||||
value={query}
|
||||
placeholder={`${label} 검색`}
|
||||
@@ -59,7 +66,7 @@ export function CatalogPropertyPicker({
|
||||
/>
|
||||
</label>
|
||||
<div className="studio-catalog-property-picker__options" role="listbox" aria-label={`${label} 선택`}>
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={!value}
|
||||
@@ -67,9 +74,9 @@ export function CatalogPropertyPicker({
|
||||
>
|
||||
<span>{emptyLabel}</span>
|
||||
{!value ? <strong aria-hidden="true">✓</strong> : null}
|
||||
</button>
|
||||
</Button>
|
||||
{filtered.map((entry) => (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
key={entry.id}
|
||||
type="button"
|
||||
role="option"
|
||||
@@ -78,9 +85,9 @@ export function CatalogPropertyPicker({
|
||||
>
|
||||
<span>{entry.label}</span>
|
||||
{entry.id === value ? <strong aria-hidden="true">✓</strong> : null}
|
||||
</button>
|
||||
</Button>
|
||||
))}
|
||||
{filtered.length === 0 ? <p>검색 결과가 없습니다.</p> : null}
|
||||
{filtered.length === 0 ? <p>{copy("techLog.state.emptySearchResult")}</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { InputControl, TextAreaControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type { WorkingCopyInput } from "../../../contracts/studio/contract.ts";
|
||||
import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
|
||||
@@ -63,7 +64,7 @@ export function CommonDocumentFields({
|
||||
<h1 className="studio-document-title-heading" aria-label={draft.title || "제목 없는 작업본"}>
|
||||
<label className="studio-field studio-document-title-field">
|
||||
<span className="studio-visually-hidden">제목</span>
|
||||
<input
|
||||
<InputControl
|
||||
aria-label="제목"
|
||||
value={draft.title}
|
||||
maxLength={120}
|
||||
@@ -76,7 +77,7 @@ export function CommonDocumentFields({
|
||||
|
||||
<div className="studio-field studio-document-summary-field">
|
||||
<label className="studio-visually-hidden" htmlFor="studio-field-summary">요약</label>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
id="studio-field-summary"
|
||||
aria-label="요약"
|
||||
value={draft.summary}
|
||||
@@ -135,7 +136,7 @@ export function CommonDocumentFields({
|
||||
<span className="studio-property-name">URL 이름</span>
|
||||
<span className="studio-property-control studio-property-control--slug">
|
||||
<span aria-hidden="true">/</span>
|
||||
<input
|
||||
<InputControl
|
||||
aria-label="slug"
|
||||
value={draft.slug}
|
||||
maxLength={100}
|
||||
@@ -157,7 +158,7 @@ export function CommonDocumentFields({
|
||||
const checked = (draft.variantIds ?? []).includes(id);
|
||||
return (
|
||||
<label key={variant.id ?? variant.slug} data-selected={checked ? "" : undefined}>
|
||||
<input
|
||||
<InputControl
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(event) => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { Button, InputControl, SelectControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type { Asset, AssetKind } from "../../../contracts/studio/contract.ts";
|
||||
import { useStudioAssetGateway } from "../use-studio.ts";
|
||||
import { buildEvidenceDirective } from "./asset-picker.tsx";
|
||||
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
|
||||
import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
|
||||
@@ -23,7 +24,7 @@ export function ConceptFields({ draft, issues, onChange }: {
|
||||
issues: readonly FieldIssue[];
|
||||
onChange(draft: ConceptInput): void;
|
||||
}) {
|
||||
const assetGateway = useStudioAssetGateway();
|
||||
const copy = useTechLogCopy();
|
||||
const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
|
||||
const uploadTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [uploadKind, setUploadKind] = useState<AssetKind>("IMAGE");
|
||||
@@ -41,7 +42,7 @@ export function ConceptFields({ draft, issues, onChange }: {
|
||||
|
||||
<label className="studio-inline-property studio-inline-property--version">
|
||||
<span>기준 버전</span>
|
||||
<input aria-label="기준 버전" value={draft.basisVersion} placeholder="예: Kubernetes 1.31" onChange={(event) => update({ basisVersion: event.currentTarget.value })} />
|
||||
<InputControl aria-label="기준 버전" value={draft.basisVersion} placeholder="예: Kubernetes 1.31" onChange={(event) => update({ basisVersion: event.currentTarget.value })} />
|
||||
<FieldNotice issues={issues} path="/basisVersion" />
|
||||
</label>
|
||||
|
||||
@@ -49,16 +50,16 @@ export function ConceptFields({ draft, issues, onChange }: {
|
||||
<div className="studio-body-authoring__heading">
|
||||
<div><span>본문</span><p>빈 블록에서 / 를 입력해 구조를 추가하세요.</p></div>
|
||||
<div className="studio-inline-asset-actions">
|
||||
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
|
||||
<button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
|
||||
<AssetPickerDialog usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><SelectControl value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</SelectControl></label>
|
||||
<Button visualPolicy="inherit" ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>{copy("techLog.action.upload")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<MarkdownBlockEditor ref={bodyEditorRef} label="본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
|
||||
<FieldNotice issues={issues} path="/bodyMarkdown" />
|
||||
</div>
|
||||
|
||||
{uploadOpen ? <AssetUploadDialog gateway={assetGateway} kind={uploadKind} onUploaded={(asset) => {
|
||||
{uploadOpen ? <AssetUploadDialog kind={uploadKind} onUploaded={(asset) => {
|
||||
insertDirective(buildEvidenceDirective({ assetKey: asset.assetKey, alt: asset.decorative ? "" : (asset.altText ?? ""), caption: "", zoom: asset.kind === "DIAGRAM" }));
|
||||
setUploadOpen(false);
|
||||
}} onClose={() => setUploadOpen(false)} /> : null}
|
||||
|
||||
+44
-67
@@ -1,16 +1,12 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
|
||||
/**
|
||||
* 되돌릴 수 없는 일을 하기 전에 한 번 묻는 자리.
|
||||
*
|
||||
* <p>Studio 의 삭제는 전부 한 번에 영구 삭제였다 — 확인도 되돌리기도 없었다. 그리고 그 「삭제」가
|
||||
* 행에서 시각적으로 가장 강한 요소였다(빨강 600). 실수로 누르면 그것으로 끝났다.
|
||||
*
|
||||
* <p>되돌리기(undo)를 두지 않는 이유는 서버가 삭제를 되돌릴 방법을 갖고 있지 않아서다. 그러니
|
||||
* 막을 자리는 누르기 직전뿐이고, 그때 <b>무엇이</b> 지워지는지를 이름으로 보여 준다 — "이 항목을
|
||||
* 지울까요?" 는 잘못 고른 것을 잡아 주지 못한다.
|
||||
*
|
||||
* <p>기본 초점은 「취소」에 둔다. 열자마자 Enter 를 눌러도 아무 일이 없어야 한다.
|
||||
* 되돌릴 수 없는 작업은 공통 Dialog가 포커스/ESC/복원을 관리하고,
|
||||
* TechLog는 대상 이름과 삭제 정책만 소유한다.
|
||||
*/
|
||||
export function DestructiveConfirmDialog({
|
||||
open,
|
||||
@@ -18,82 +14,63 @@ export function DestructiveConfirmDialog({
|
||||
title,
|
||||
targetName,
|
||||
description,
|
||||
confirmLabel = "삭제",
|
||||
confirmLabel,
|
||||
error,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: {
|
||||
open: boolean;
|
||||
/** 요청이 나가 있는 동안 두 버튼을 함께 막는다. 두 번 눌러 두 번 지우는 일을 없앤다. */
|
||||
pending: boolean;
|
||||
title: string;
|
||||
/** 지워지는 대상의 이름. 잘못 고른 것을 여기서 잡는다. */
|
||||
targetName: string;
|
||||
/** 함께 사라지는 것이 있으면 적는다. 없으면 비운다. */
|
||||
description?: string;
|
||||
confirmLabel?: string;
|
||||
error?: string;
|
||||
onCancel(): void;
|
||||
onConfirm(): void;
|
||||
}) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const cancelRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) {
|
||||
dialog.showModal();
|
||||
cancelRef.current?.focus();
|
||||
} else if (!open && dialog.open) {
|
||||
dialog.close();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const cancel = () => {
|
||||
dialogRef.current?.close();
|
||||
onCancel();
|
||||
};
|
||||
|
||||
const copy = useTechLogCopy();
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
<Dialog
|
||||
className="studio-confirm-dialog"
|
||||
aria-labelledby="studio-confirm-title"
|
||||
aria-describedby="studio-confirm-target"
|
||||
aria-hidden={open ? undefined : true}
|
||||
onCancel={(event) => {
|
||||
event.preventDefault();
|
||||
if (!pending) cancel();
|
||||
eyebrow={<p className="studio-eyebrow">CONFIRM</p>}
|
||||
hideCloseButton
|
||||
onClose={() => {
|
||||
if (!pending) onCancel();
|
||||
}}
|
||||
>
|
||||
<div className="studio-dialog-body">
|
||||
<p className="studio-eyebrow">CONFIRM</p>
|
||||
<h2 id="studio-confirm-title">{title}</h2>
|
||||
<p id="studio-confirm-target" className="studio-confirm-target">
|
||||
{targetName}
|
||||
</p>
|
||||
{description ? <p>{description}</p> : null}
|
||||
<p className="studio-confirm-warning">되돌릴 수 없습니다.</p>
|
||||
{error ? (
|
||||
<p className="studio-dialog-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="studio-dialog-actions">
|
||||
<button ref={cancelRef} type="button" disabled={pending} onClick={cancel}>
|
||||
취소
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
open={open}
|
||||
title={title}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
autoFocus
|
||||
disabled={pending}
|
||||
onClick={onCancel}
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
className="studio-confirm-destructive"
|
||||
disabled={pending}
|
||||
onClick={onConfirm}
|
||||
pending={pending}
|
||||
pendingLabel={copy("techLog.action.processing")}
|
||||
variant="ghost"
|
||||
>
|
||||
{pending ? "처리 중" : confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
{confirmLabel ?? copy("techLog.action.delete")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="studio-confirm-target">{targetName}</p>
|
||||
{description ? <p>{description}</p> : null}
|
||||
<p className="studio-confirm-warning">{copy("techLog.state.irreversible")}</p>
|
||||
{error ? (
|
||||
<p className="studio-dialog-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { collectCatalog } from "../../../application/collect-catalog.ts";
|
||||
import { isStudioGatewayError } from "../../../application/ports/studio-gateway-error.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type {
|
||||
WorkingCopy,
|
||||
WorkingCopyInput,
|
||||
WorkingCopyDetail,
|
||||
WorkingCopyInput,
|
||||
} from "../../../contracts/studio/contract.ts";
|
||||
import type { TopicVariantEdit } from "../../../contracts/management/contract.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import { deriveValidationState } from "../../../domain/studio/document-state.ts";
|
||||
import {
|
||||
useStudioDocumentCommands,
|
||||
useStudioDocumentQuery,
|
||||
} from "../studio-document-server-state.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { useStudio, useStudioEditorSession } from "../use-studio.ts";
|
||||
import { useManagementTopicVariantsQuery } from "../studio-management-server-state.ts";
|
||||
import { useStudioCatalogQuery } from "../studio-workspace-server-state.ts";
|
||||
import type { DocumentEditorController } from "./document-editor-controller.ts";
|
||||
import { DocumentEditor } from "./document-editor.tsx";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { deriveValidationState } from "../../../domain/studio/document-state.ts";
|
||||
import { slugFromName } from "./slug-from-name.ts";
|
||||
import { useSaveShortcut } from "./use-save-shortcut.ts";
|
||||
import { useStudio, useStudioEditorSession } from "../use-studio.ts";
|
||||
import { useStudioFailureMessage, useTechLogCopy } from "../studio-copy.ts";
|
||||
|
||||
type CatalogEntry = components["schemas"]["CatalogEntry"];
|
||||
const catalogTypes = ["TOPIC", "PROJECT", "RELATION", "EVIDENCE"] as const;
|
||||
type ValidationIssue = components["schemas"]["ValidationIssue"];
|
||||
|
||||
const SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
|
||||
|
||||
function inputOf(document: WorkingCopy): WorkingCopyInput {
|
||||
const input: Record<string, unknown> = { ...document };
|
||||
@@ -29,89 +36,59 @@ function inputOf(document: WorkingCopy): WorkingCopyInput {
|
||||
return input as WorkingCopyInput;
|
||||
}
|
||||
|
||||
/**
|
||||
* 백엔드가 문서 slug 에 요구하는 모양 (`WorkingCopyInputValidator.SLUG`). 저장 전에 여기서 먼저
|
||||
* 보는 이유는, 어긋난 값을 보내면 서버가 details 없는 422 로 거절하고 편집기는 그것을 이유 없는
|
||||
* 실패로만 보여 주기 때문이다 — 작성자에게는 어느 칸이 문제인지 알 방법이 없었다.
|
||||
*/
|
||||
type ValidationIssue = components["schemas"]["ValidationIssue"];
|
||||
|
||||
/**
|
||||
* 마지막 검증을 편집기가 쓸 모양으로 줄인다. `current` 는 "지금 저장된 버전을 검사한 결과인가"
|
||||
* 다 — 아니면 목록은 참고일 뿐이고, 방금 고친 것이 아직 모자라다고 말할 수 있다.
|
||||
*/
|
||||
function validationOf(detail: WorkingCopyDetail, now: Date) {
|
||||
const report = detail.currentValidation;
|
||||
if (!report) return null;
|
||||
return Object.freeze({
|
||||
current: deriveValidationState({ ...detail, currentValidation: report, now }).freshness === "CURRENT",
|
||||
current:
|
||||
deriveValidationState({
|
||||
...detail,
|
||||
currentValidation: report,
|
||||
now,
|
||||
}).freshness === "CURRENT",
|
||||
version: report.validatedVersion,
|
||||
issues: report.issues,
|
||||
});
|
||||
}
|
||||
|
||||
const SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
|
||||
|
||||
export function DocumentEditorScreen({ documentId }: { documentId: string }) {
|
||||
const copy = useTechLogCopy();
|
||||
const studioFailureMessage = useStudioFailureMessage();
|
||||
const studio = useStudio();
|
||||
const session = useStudioEditorSession();
|
||||
const { begin, clear, editor, setStatus, updateDraft } = session;
|
||||
const [retryKey, setRetryKey] = useState(0);
|
||||
const requestKey = `${documentId}:${retryKey}`;
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
catalog: CatalogEntry[];
|
||||
problem: Error | null;
|
||||
} | null>(null);
|
||||
const documentQuery = useStudioDocumentQuery(documentId);
|
||||
const commands = useStudioDocumentCommands();
|
||||
|
||||
const topicCatalogQuery = useStudioCatalogQuery({ type: "TOPIC" });
|
||||
const projectCatalogQuery = useStudioCatalogQuery({ type: "PROJECT" });
|
||||
const relationCatalogQuery = useStudioCatalogQuery({ type: "RELATION" });
|
||||
const evidenceCatalogQuery = useStudioCatalogQuery({ type: "EVIDENCE" });
|
||||
const [saveError, setSaveError] = useState("");
|
||||
/**
|
||||
* 마지막 검증 결과. 편집기가 이것을 들고 있는 이유는, 무엇이 모자라 게시가 막히는지 작성자가
|
||||
* 고치는 자리에서 보여야 하기 때문이다 — 예전에는 별도 화면으로 나가야만 알 수 있었고,
|
||||
* 돌아와서 어느 칸이었는지 기억해야 했다.
|
||||
*/
|
||||
const [validationSource, setValidationSource] = useState<WorkingCopyDetail | null>(null);
|
||||
const [validationSource, setValidationSource] =
|
||||
useState<WorkingCopyDetail | null>(null);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [publishError, setPublishError] = useState("");
|
||||
const [publishIssues, setPublishIssues] = useState<readonly ValidationIssue[]>([]);
|
||||
const [publishIssues, setPublishIssues] = useState<
|
||||
readonly ValidationIssue[]
|
||||
>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const request = new AbortController();
|
||||
clear();
|
||||
void Promise.all([
|
||||
studio.gateway.getDocument(documentId, { signal: request.signal }),
|
||||
/*
|
||||
한 번에 받는 상한은 계약이 100으로 정해 두었다(`Limit.maximum`). 그 한 번만 부르던 동안
|
||||
기록이 101개가 되자 101번째부터는 관계 대상 목록에 아예 나타나지 않았고, 화면에는 그
|
||||
사실이 보이지 않았다 — 커서를 따라 끝까지 읽는다.
|
||||
*/
|
||||
...catalogTypes.map((type) => collectCatalog(
|
||||
studio.gateway,
|
||||
{ type },
|
||||
{ signal: request.signal },
|
||||
)),
|
||||
]).then(
|
||||
([detail, ...catalogPages]) => {
|
||||
if (request.signal.aborted) return;
|
||||
setResult({
|
||||
key: requestKey,
|
||||
catalog: catalogPages.flat(),
|
||||
problem: null,
|
||||
});
|
||||
begin(detail.document, inputOf(detail.document));
|
||||
setValidationSource(detail);
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (request.signal.aborted) return;
|
||||
setResult({
|
||||
key: requestKey,
|
||||
catalog: [],
|
||||
problem: error instanceof Error
|
||||
? error
|
||||
: new Error("Studio 문서를 불러오지 못했습니다."),
|
||||
});
|
||||
},
|
||||
);
|
||||
return () => request.abort();
|
||||
}, [begin, clear, documentId, requestKey, studio.gateway]);
|
||||
setValidationSource(null);
|
||||
setSaveError("");
|
||||
setPublishError("");
|
||||
setPublishIssues([]);
|
||||
}, [clear, documentId]);
|
||||
|
||||
useEffect(() => {
|
||||
const detail = documentQuery.data;
|
||||
if (!detail) return;
|
||||
if (!editor || editor.documentId !== documentId) {
|
||||
begin(detail.document, inputOf(detail.document));
|
||||
setValidationSource(detail);
|
||||
}
|
||||
}, [begin, documentId, documentQuery.data, editor]);
|
||||
|
||||
const save = useCallback(async () => {
|
||||
const current = editor;
|
||||
@@ -120,120 +97,160 @@ export function DocumentEditorScreen({ documentId }: { documentId: string }) {
|
||||
current.status === "CLEAN" ||
|
||||
current.status === "SAVING" ||
|
||||
current.status === "CONFLICT"
|
||||
) return;
|
||||
// 비워 두면 제목에서 만든다. 한글 제목도 로마자로 옮겨 유효한 slug 가 되므로, 작성자가
|
||||
// slug 규칙을 몰라도 저장이 막히지 않는다.
|
||||
const slug = current.draft.slug.trim() || slugFromName(current.draft.title);
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const slug =
|
||||
current.draft.slug.trim() || slugFromName(current.draft.title);
|
||||
if (slug && !SLUG_SHAPE.test(slug)) {
|
||||
setSaveError(
|
||||
"slug 은 영문 소문자·숫자·하이픈만 쓸 수 있습니다. 비워 두면 제목에서 만들어 드립니다.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const draft = slug === current.draft.slug
|
||||
? current.draft
|
||||
: ({ ...current.draft, slug } as typeof current.draft);
|
||||
|
||||
const draft =
|
||||
slug === current.draft.slug
|
||||
? current.draft
|
||||
: ({ ...current.draft, slug } as typeof current.draft);
|
||||
|
||||
setSaveError("");
|
||||
setStatus("SAVING");
|
||||
try {
|
||||
const detail = await studio.gateway.saveDocument(
|
||||
current.documentId,
|
||||
{
|
||||
expectedVersion: current.saved.version,
|
||||
document: draft,
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-editor-save") },
|
||||
);
|
||||
begin(detail.document, inputOf(detail.document));
|
||||
// 저장하면 직전 검증은 그 버전의 것이 아니게 된다. 그 사실을 바로 반영해야 낡은 목록이
|
||||
// 방금 고친 항목을 아직 모자라다고 말하지 않는다.
|
||||
setValidationSource(detail);
|
||||
studio.setRequestAnnouncement(
|
||||
`버전 ${detail.document.version}으로 저장했습니다.`,
|
||||
const result = await commands.save.submit({
|
||||
documentId: current.documentId,
|
||||
command: {
|
||||
expectedVersion: current.saved.version,
|
||||
document: draft,
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const conflict = result.error.code === "VERSION_CONFLICT";
|
||||
setStatus(conflict ? "CONFLICT" : "DIRTY");
|
||||
const message = studioFailureMessage(
|
||||
result.error,
|
||||
copy("techLog.failure.saveFailed"),
|
||||
);
|
||||
} catch (error) {
|
||||
const conflict = isStudioGatewayError(error) &&
|
||||
error.code === "VERSION_CONFLICT";
|
||||
setStatus(conflict ? "CONFLICT" : "DIRTY");
|
||||
const detail = isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "저장하지 못했습니다.";
|
||||
setSaveError(detail);
|
||||
studio.setRequestAnnouncement(detail);
|
||||
setSaveError(message);
|
||||
studio.setRequestAnnouncement(message);
|
||||
return;
|
||||
}
|
||||
}, [begin, editor, setStatus, studio]);
|
||||
|
||||
const detail = result.value;
|
||||
begin(detail.document, inputOf(detail.document));
|
||||
setValidationSource(detail);
|
||||
studio.setRequestAnnouncement(
|
||||
copy("techLog.notice.savedVersion", { version: detail.document.version }),
|
||||
);
|
||||
void documentQuery.retry();
|
||||
}, [begin, commands.save, copy, documentQuery, editor, setStatus, studio, studioFailureMessage]);
|
||||
|
||||
/*
|
||||
`save` 가 스스로 CLEAN·SAVING·CONFLICT 를 걸러 내므로 단축키는 늘 열어 둔다 — 저장할 것이
|
||||
없을 때 눌러도 아무 일도 일어나지 않는다.
|
||||
*/
|
||||
useSaveShortcut(save);
|
||||
|
||||
/**
|
||||
* 저장 → 검증 → 미리보기 → 게시를 한 번에 수행한다.
|
||||
*
|
||||
* <p>백엔드는 게시 요청에 신선한 검증 id 와 미리보기 id, 그리고 현재 경고를 모두 확인했다는
|
||||
* 목록을 요구한다(`PublishStudioDocumentUseCase`). 예전에는 그 셋을 작성자가 세 화면을 차례로
|
||||
* 밟아 만들었다 — 검증 화면에서 버튼을 누르고, 미리보기 화면에서 또 누르고, 게시 화면에서
|
||||
* 경고를 하나씩 체크했다.
|
||||
*
|
||||
* <p>그 셋은 작성자에게 물어볼 것이 없다. 검증 결과는 서버가 판정하고, 미리보기는 그 판정에서
|
||||
* 만들어지며, 경고는 게시를 막지 않는다. 그래서 여기서 잇달아 부른다. 서버가 지키던 불변식은
|
||||
* 그대로다 — 사라진 것은 작성자가 밟던 화면뿐이다.
|
||||
*
|
||||
* <p>막는 것은 `ERROR` 뿐이다. 그때는 게시를 멈추고 지적을 그 칸 아래에 보여 준다.
|
||||
*/
|
||||
const publish = useCallback(async () => {
|
||||
const current = editor;
|
||||
if (!current || current.status === "SAVING" || current.status === "CONFLICT") return;
|
||||
if (
|
||||
!current ||
|
||||
current.status === "SAVING" ||
|
||||
current.status === "CONFLICT"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPublishError("");
|
||||
setPublishIssues([]);
|
||||
setPublishing(true);
|
||||
const id = current.documentId;
|
||||
const fail = (message: string, conflict: boolean) => {
|
||||
if (conflict) setStatus("CONFLICT");
|
||||
else if (current.status === "DIRTY") setStatus("DIRTY");
|
||||
setPublishError(message);
|
||||
studio.setRequestAnnouncement(message);
|
||||
};
|
||||
|
||||
try {
|
||||
// 게시는 저장된 버전을 대상으로 한다. 편집 중인 값이 있으면 먼저 맞춘다 — 그러지 않으면
|
||||
// 방금 고친 칸이 반영되지 않은 채 검증받는다.
|
||||
let version = current.saved.version;
|
||||
|
||||
if (current.status === "DIRTY") {
|
||||
const slug = current.draft.slug.trim() || slugFromName(current.draft.title);
|
||||
const slug =
|
||||
current.draft.slug.trim() || slugFromName(current.draft.title);
|
||||
if (slug && !SLUG_SHAPE.test(slug)) {
|
||||
setPublishError("slug 은 영문 소문자·숫자·하이픈만 쓸 수 있습니다. 비워 두면 제목에서 만들어 드립니다.");
|
||||
setPublishError(
|
||||
"slug 은 영문 소문자·숫자·하이픈만 쓸 수 있습니다. 비워 두면 제목에서 만들어 드립니다.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const draft = slug === current.draft.slug
|
||||
? current.draft
|
||||
: ({ ...current.draft, slug } as typeof current.draft);
|
||||
|
||||
const draft =
|
||||
slug === current.draft.slug
|
||||
? current.draft
|
||||
: ({ ...current.draft, slug } as typeof current.draft);
|
||||
|
||||
setStatus("SAVING");
|
||||
const saved = await studio.gateway.saveDocument(
|
||||
id,
|
||||
{ expectedVersion: version, document: draft },
|
||||
{ idempotencyKey: createLocalId("studio-publish-save") },
|
||||
);
|
||||
begin(saved.document, inputOf(saved.document));
|
||||
setValidationSource(saved);
|
||||
version = saved.document.version;
|
||||
const saved = await commands.save.submit({
|
||||
documentId: id,
|
||||
command: { expectedVersion: version, document: draft },
|
||||
});
|
||||
if (!saved.ok) {
|
||||
fail(
|
||||
studioFailureMessage(
|
||||
saved.error,
|
||||
copy("techLog.failure.saveBeforePublish"),
|
||||
),
|
||||
saved.error.code === "VERSION_CONFLICT",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
begin(saved.value.document, inputOf(saved.value.document));
|
||||
setValidationSource(saved.value);
|
||||
version = saved.value.document.version;
|
||||
}
|
||||
|
||||
const report = await studio.gateway.validateDocument(
|
||||
id,
|
||||
{ expectedVersion: version },
|
||||
{ idempotencyKey: createLocalId("studio-publish-validate") },
|
||||
);
|
||||
if (report.status === "INVALID") {
|
||||
setPublishIssues(report.issues);
|
||||
setPublishError("게시할 수 없습니다. 표시한 칸을 채워 주세요.");
|
||||
studio.setRequestAnnouncement("게시할 수 없습니다. 표시한 칸을 채워 주세요.");
|
||||
const validated = await commands.validate.submit({
|
||||
documentId: id,
|
||||
command: { expectedVersion: version },
|
||||
});
|
||||
if (!validated.ok) {
|
||||
fail(
|
||||
studioFailureMessage(
|
||||
validated.error,
|
||||
copy("techLog.failure.validationBeforePublish"),
|
||||
),
|
||||
validated.error.code === "VERSION_CONFLICT",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const preview = await studio.gateway.createPreview(
|
||||
id,
|
||||
{ expectedVersion: version, validationId: report.validationId },
|
||||
{ idempotencyKey: createLocalId("studio-publish-preview") },
|
||||
);
|
||||
const report = validated.value;
|
||||
if (report.status === "INVALID") {
|
||||
setPublishIssues(report.issues);
|
||||
const message = copy("techLog.failure.publishFieldsRequired");
|
||||
setPublishError(message);
|
||||
studio.setRequestAnnouncement(message);
|
||||
setStatus("DIRTY");
|
||||
return;
|
||||
}
|
||||
|
||||
const previewed = await commands.createPreview.submit({
|
||||
documentId: id,
|
||||
command: {
|
||||
expectedVersion: version,
|
||||
validationId: report.validationId,
|
||||
},
|
||||
});
|
||||
if (!previewed.ok) {
|
||||
fail(
|
||||
studioFailureMessage(
|
||||
previewed.error,
|
||||
copy("techLog.failure.previewBeforePublish"),
|
||||
),
|
||||
previewed.error.code === "VERSION_CONFLICT",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 경고는 게시를 막지 않는다. 서버는 "현재 경고를 모두 확인했다"는 목록을 요구할 뿐이므로
|
||||
// 방금 받은 경고를 그대로 넘긴다.
|
||||
const acknowledged = [
|
||||
...new Set(
|
||||
report.issues
|
||||
@@ -241,74 +258,60 @@ export function DocumentEditorScreen({ documentId }: { documentId: string }) {
|
||||
.map((issue) => issue.code),
|
||||
),
|
||||
].sort();
|
||||
const result = await studio.gateway.publishDocument(
|
||||
id,
|
||||
{
|
||||
|
||||
const published = await commands.publish.submit({
|
||||
documentId: id,
|
||||
command: {
|
||||
expectedVersion: version,
|
||||
validationId: report.validationId,
|
||||
previewId: preview.previewId,
|
||||
previewId: previewed.value.previewId,
|
||||
acknowledgedWarningCodes: acknowledged,
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-publish") },
|
||||
});
|
||||
if (!published.ok) {
|
||||
fail(
|
||||
studioFailureMessage(
|
||||
published.error,
|
||||
copy("techLog.failure.publishRetry"),
|
||||
),
|
||||
published.error.code === "VERSION_CONFLICT",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setPublishIssues(
|
||||
report.issues.filter((issue) => issue.severity === "WARNING"),
|
||||
);
|
||||
// 경고를 남긴 채 게시했다면 그 사실은 남겨 둔다 — 게시가 되었다고 해서 지적이 사라진 것은
|
||||
// 아니다.
|
||||
setPublishIssues(report.issues.filter((issue) => issue.severity === "WARNING"));
|
||||
studio.setRequestAnnouncement("게시했습니다.");
|
||||
studio.setRequestAnnouncement(copy("techLog.notice.published"));
|
||||
studio.clearEditor();
|
||||
studio.navigateInternal(
|
||||
`/studio/publications/${result.event.publicationEventId}/preview`,
|
||||
studioRoutes.publicationPreview(
|
||||
published.value.event.publicationEventId,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isStudioGatewayError(error) && error.code === "VERSION_CONFLICT") {
|
||||
setStatus("CONFLICT");
|
||||
} else if (current.status === "DIRTY") {
|
||||
setStatus("DIRTY");
|
||||
}
|
||||
const detail = isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "게시하지 못했습니다. 다시 시도해 주세요.";
|
||||
setPublishError(detail);
|
||||
studio.setRequestAnnouncement(detail);
|
||||
} finally {
|
||||
setPublishing(false);
|
||||
}
|
||||
}, [begin, editor, setStatus, studio]);
|
||||
}, [
|
||||
begin,
|
||||
commands.createPreview,
|
||||
commands.publish,
|
||||
commands.save,
|
||||
commands.validate,
|
||||
copy,
|
||||
editor,
|
||||
setStatus,
|
||||
studio,
|
||||
studioFailureMessage,
|
||||
]);
|
||||
|
||||
/**
|
||||
* 검증의 신선도는 시각에 달렸는데, 시계는 렌더마다 새 함수다. 그것을 효과 의존성에 넣었더니
|
||||
* 문서를 끝없이 다시 불러왔다 — 화면이 정착하지 못해 탭 전환조차 먹히지 않았다. 시각은
|
||||
* 저장할 값이 아니라 지금 묻는 값이므로 렌더에서 읽는다.
|
||||
*/
|
||||
const validation = validationSource ? validationOf(validationSource, studio.now()) : null;
|
||||
const validation = validationSource
|
||||
? validationOf(validationSource, studio.now())
|
||||
: null;
|
||||
|
||||
/*
|
||||
고른 주제의 축. 카탈로그(`TOPIC`/`PROJECT`/`RELATION`/`EVIDENCE`)는 주제와 무관한 전체
|
||||
목록이라 여기에 섞을 수 없다 — 축은 주제 안에서만 뜻이 있고, 주제를 바꾸면 고를 수 있는
|
||||
것이 통째로 바뀐다.
|
||||
*/
|
||||
const selectedTopicId = editor?.draft.topicId ?? null;
|
||||
const [variants, setVariants] = useState<readonly TopicVariantEdit[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedTopicId) {
|
||||
setVariants([]);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const loaded = await studio.managementGateway.listTopicVariants(selectedTopicId);
|
||||
if (!cancelled) setVariants(loaded);
|
||||
} catch {
|
||||
// 축을 못 읽어도 편집은 계속돼야 한다 — 축은 선택 사항이다.
|
||||
if (!cancelled) setVariants([]);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [selectedTopicId, studio.managementGateway]);
|
||||
const selectedTopicId = editor?.draft.topicId ?? "";
|
||||
const variantsQuery = useManagementTopicVariantsQuery(selectedTopicId);
|
||||
const variants = variantsQuery.data ?? [];
|
||||
|
||||
const controller = useMemo<DocumentEditorController | null>(() => {
|
||||
if (!editor || editor.documentId !== documentId) return null;
|
||||
@@ -322,7 +325,11 @@ export function DocumentEditorScreen({ documentId }: { documentId: string }) {
|
||||
publishError,
|
||||
publishIssues,
|
||||
update(patch) {
|
||||
updateDraft({ ...editor.draft, ...patch, kind: editor.draft.kind } as WorkingCopyInput);
|
||||
updateDraft({
|
||||
...editor.draft,
|
||||
...patch,
|
||||
kind: editor.draft.kind,
|
||||
} as WorkingCopyInput);
|
||||
},
|
||||
replace(draft) {
|
||||
if (draft.kind === editor.draft.kind) updateDraft(draft);
|
||||
@@ -330,39 +337,103 @@ export function DocumentEditorScreen({ documentId }: { documentId: string }) {
|
||||
publish,
|
||||
save,
|
||||
};
|
||||
}, [documentId, editor, publish, publishError, publishIssues, publishing, save, saveError, updateDraft, validation]);
|
||||
}, [
|
||||
documentId,
|
||||
editor,
|
||||
publish,
|
||||
publishError,
|
||||
publishIssues,
|
||||
publishing,
|
||||
save,
|
||||
saveError,
|
||||
updateDraft,
|
||||
validation,
|
||||
]);
|
||||
|
||||
const currentResult = result?.key === requestKey ? result : null;
|
||||
const problem = currentResult?.problem ?? null;
|
||||
if (!currentResult || (!problem && !controller)) {
|
||||
return <section className="studio-editor-loading" role="status"><p>문서 편집기를 준비하고 있습니다.</p></section>;
|
||||
const catalogQueries = [
|
||||
topicCatalogQuery,
|
||||
projectCatalogQuery,
|
||||
relationCatalogQuery,
|
||||
evidenceCatalogQuery,
|
||||
] as const;
|
||||
const catalogLoading = catalogQueries.some(
|
||||
(query) => query.state.base === "initial-loading",
|
||||
);
|
||||
const catalogProblem = catalogQueries.find(
|
||||
(query) => query.state.failure,
|
||||
)?.state.failure;
|
||||
const catalog = catalogQueries.flatMap(
|
||||
(query) => query.data ?? [],
|
||||
) as CatalogEntry[];
|
||||
const queryProblem = documentQuery.state.failure;
|
||||
|
||||
if (
|
||||
documentQuery.state.base === "initial-loading" ||
|
||||
catalogLoading ||
|
||||
(!queryProblem && !catalogProblem && !controller)
|
||||
) {
|
||||
return (
|
||||
<section className="studio-editor-loading" role="status">
|
||||
<p>{copy("techLog.state.editorPreparing")}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (problem && isStudioGatewayError(problem) && problem.code === "DOCUMENT_NOT_FOUND") {
|
||||
|
||||
if (queryProblem?.code === "DOCUMENT_NOT_FOUND") {
|
||||
return (
|
||||
<section className="studio-route-state">
|
||||
<p className="studio-eyebrow">404</p>
|
||||
<h1>Studio 화면을 찾을 수 없습니다</h1>
|
||||
<p>이 작업본은 현재 Studio 세션에 없습니다.</p>
|
||||
<GuardedStudioLink href="/studio/documents">
|
||||
<h1>{copy("techLog.state.studioNotFound")}</h1>
|
||||
<p>{copy("techLog.state.sessionDocumentMissing")}</p>
|
||||
<GuardedStudioLink href={studioRoutes.documents()}>
|
||||
작업본으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (problem) {
|
||||
|
||||
if (
|
||||
documentQuery.state.base === "terminal-error" ||
|
||||
queryProblem ||
|
||||
catalogProblem
|
||||
) {
|
||||
return (
|
||||
<section className="studio-route-state" role="alert">
|
||||
<p className="studio-eyebrow">EDITOR ERROR</p>
|
||||
<h1>문서를 불러오지 못했습니다</h1>
|
||||
<p>{isStudioGatewayError(problem) ? problem.problem.detail : problem.message}</p>
|
||||
<button type="button" onClick={() => setRetryKey((value) => value + 1)}>다시 시도</button>
|
||||
<h1>{copy("techLog.state.documentLoadFailed")}</h1>
|
||||
<p>
|
||||
{queryProblem
|
||||
? studioFailureMessage(
|
||||
queryProblem,
|
||||
"",
|
||||
)
|
||||
: studioFailureMessage(
|
||||
catalogProblem,
|
||||
"",
|
||||
)}
|
||||
</p>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void Promise.all([
|
||||
documentQuery.retry(),
|
||||
topicCatalogQuery.retry(),
|
||||
projectCatalogQuery.retry(),
|
||||
relationCatalogQuery.retry(),
|
||||
evidenceCatalogQuery.retry(),
|
||||
]);
|
||||
}}
|
||||
>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DocumentEditor
|
||||
controller={controller!}
|
||||
catalog={currentResult.catalog}
|
||||
catalog={catalog}
|
||||
variants={variants}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,64 +1,24 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx";
|
||||
|
||||
import { collectCatalog } from "../../../application/collect-catalog.ts";
|
||||
import type { ListDocumentsQuery } from "../../../application/ports/studio-gateway.ts";
|
||||
import type { CatalogPage, DocumentPage } from "../../../contracts/studio/contract.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import type { ListDocumentsQuery } from "../../../application/studio-application.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { StudioPagination } from "./studio-pagination.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import {
|
||||
Button,
|
||||
SearchFilterToolbar,
|
||||
Select,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
import { NEXT_ACTION_LABELS, nextActionHref } from "../next-action.ts";
|
||||
|
||||
type RecordKind = components["schemas"]["RecordKind"];
|
||||
|
||||
/*
|
||||
작업본 목록이 거를 수 있는 종류. 손으로 나열하지 않고 `Record<RecordKind, …>` 에서 뽑는다 —
|
||||
종류가 늘면 컴파일러가 빈 자리를 잡는다.
|
||||
*/
|
||||
const STUDIO_KIND_ORDER: Record<RecordKind, number> = {
|
||||
CASE: 1,
|
||||
CONCEPT: 2,
|
||||
REFERENCE: 3,
|
||||
QUESTION: 4,
|
||||
SETUP: 5,
|
||||
PROJECT_DECISION: 6,
|
||||
};
|
||||
|
||||
/** 상태 필터가 받는 값. 주소에서 온 문자열을 이 목록으로 좁힌다. */
|
||||
/** 정렬 선택지. 계약의 `ListDocumentsQuery.sort` 와 같은 집합이다. */
|
||||
const SORTS = Object.freeze(["UPDATED_DESC", "UPDATED_ASC", "TITLE_ASC"] as const);
|
||||
|
||||
/*
|
||||
다음 할 일로 거른다. 계약이 이미 주는 필터이고(`nextAction`), 작성자가 목록에서 실제로 묻는
|
||||
것이 이것이다 — "검증해야 하는 게 뭐지", "게시할 수 있는 게 뭐지".
|
||||
|
||||
주제·관계 없음·자료 없음으로 거르는 것은 아직 못 한다. `DocumentSummary` 에 그 값들이 없어
|
||||
화면에서 만들 수 없다.
|
||||
*/
|
||||
const NEXT_ACTIONS = Object.freeze([
|
||||
"CONTINUE_EDITING",
|
||||
"VALIDATE",
|
||||
"FIX_VALIDATION",
|
||||
"CREATE_PREVIEW",
|
||||
"PUBLISH",
|
||||
"NONE",
|
||||
] as const);
|
||||
|
||||
const PUBLICATION_STATUSES = Object.freeze([
|
||||
"NEVER_PUBLISHED",
|
||||
"PUBLISHED",
|
||||
"UNPUBLISHED",
|
||||
] as const);
|
||||
|
||||
const STUDIO_KINDS: ReadonlyArray<RecordKind> = Object.freeze(
|
||||
(Object.keys(STUDIO_KIND_ORDER) as RecordKind[]).sort(
|
||||
(left, right) => STUDIO_KIND_ORDER[left] - STUDIO_KIND_ORDER[right],
|
||||
),
|
||||
);
|
||||
import {
|
||||
DOCUMENT_NEXT_ACTIONS,
|
||||
DOCUMENT_STUDIO_KINDS,
|
||||
useDocumentListController,
|
||||
} from "../controllers/use-document-list-controller.ts";
|
||||
|
||||
const publicationLabel = {
|
||||
NEVER_PUBLISHED: "게시 전",
|
||||
@@ -67,204 +27,33 @@ const publicationLabel = {
|
||||
} as const;
|
||||
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function DocumentList() {
|
||||
const { gateway, managementGateway, setRequestAnnouncement } = useStudio();
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [deleteError, setDeleteError] = useState("");
|
||||
/*
|
||||
지우기 직전에 무엇이 지워지는지 이름으로 보여 주고 한 번 묻는다. 예전에는 이 버튼이 곧
|
||||
영구 삭제였고, 그 버튼이 행에서 시각적으로 가장 강한 요소였다.
|
||||
*/
|
||||
const [pendingDelete, setPendingDelete] =
|
||||
useState<DocumentPage["items"][number] | null>(null);
|
||||
/*
|
||||
목록의 상태는 주소가 갖는다.
|
||||
|
||||
컴포넌트 state 로만 들고 있던 동안 3쪽에서 문서를 열고 뒤로 오면 1쪽이었고, 걸어 둔
|
||||
종류·상태·검색어도 함께 사라졌다. 61개를 20개씩 넘겨 보던 사람은 그 왕복을 매번 다시
|
||||
했다. 공개 `/search` 는 처음부터 주소에 담고 있었다 — 같은 방식을 여기에 쓴다.
|
||||
|
||||
검색 입력만 state 다. 한 글자마다 주소를 바꾸면 뒤로가기가 글자 수만큼 쌓인다.
|
||||
*/
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const q = searchParams.get("q") ?? "";
|
||||
const kind = STUDIO_KINDS.find((item) => item === searchParams.get("kind"));
|
||||
const status = PUBLICATION_STATUSES.find((item) => item === searchParams.get("status"));
|
||||
const projectId = searchParams.get("project") ?? "";
|
||||
const sort = SORTS.find((item) => item === searchParams.get("sort")) ?? "UPDATED_DESC";
|
||||
const nextAction = NEXT_ACTIONS.find((item) => item === searchParams.get("next"));
|
||||
const pageNumber = Math.max(1, Number(searchParams.get("page")) || 1);
|
||||
const [searchDraft, setSearchDraft] = useState(q);
|
||||
const [projects, setProjects] = useState<CatalogPage["items"]>([]);
|
||||
|
||||
/*
|
||||
주소를 새로 쓴다. 값이 비면 조각을 빼서 `?kind=&status=` 같은 빈 꼬리가 남지 않게 한다.
|
||||
1쪽도 빼는데, `?page=1` 은 아무것도 더 말해 주지 않으면서 주소만 길게 만든다.
|
||||
*/
|
||||
const go = (
|
||||
next: Readonly<{
|
||||
q?: string;
|
||||
kind?: string;
|
||||
status?: string;
|
||||
project?: string;
|
||||
sort?: string;
|
||||
next?: string;
|
||||
page?: number;
|
||||
}>,
|
||||
) => {
|
||||
const params = new URLSearchParams();
|
||||
const merged = {
|
||||
q,
|
||||
kind,
|
||||
status,
|
||||
project: projectId,
|
||||
sort,
|
||||
next: nextAction,
|
||||
page: pageNumber,
|
||||
...next,
|
||||
};
|
||||
if (merged.q) params.set("q", merged.q);
|
||||
if (merged.kind) params.set("kind", merged.kind);
|
||||
if (merged.status) params.set("status", merged.status);
|
||||
if (merged.project) params.set("project", merged.project);
|
||||
// 기본 정렬은 주소에 적지 않는다 — 아무것도 더 말해 주지 않으면서 주소만 길어진다.
|
||||
if (merged.sort && merged.sort !== "UPDATED_DESC") params.set("sort", merged.sort);
|
||||
if (merged.next) params.set("next", merged.next);
|
||||
if (merged.page && merged.page > 1) params.set("page", String(merged.page));
|
||||
setSearchParams(params);
|
||||
};
|
||||
const [page, setPage] = useState<DocumentPage | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [retryGeneration, setRetryGeneration] = useState(0);
|
||||
|
||||
/**
|
||||
* 목록 행에는 version 이 없다 (계약의 `DocumentSummary`). 삭제는 expectedVersion 을 요구하므로
|
||||
* 지우기 직전에 작업본을 한 번 읽어 그 시점의 version 을 쓴다 — 목록을 띄워 둔 채 다른 곳에서
|
||||
* 수정된 경우 여기서 409 로 걸리는 편이, 목록이 기억하던 낡은 version 으로 지우는 것보다 낫다.
|
||||
*/
|
||||
const removeDocument = async (item: DocumentPage["items"][number]) => {
|
||||
if (deletingId !== null) return;
|
||||
setDeletingId(item.id);
|
||||
setDeleteError("");
|
||||
try {
|
||||
const detail = await gateway.getDocument(item.id);
|
||||
if (item.kind === "PROJECT_DECISION") {
|
||||
// Decision 은 프로젝트에 속하고 경로가 둘을 요구한다. 목록 행이 프로젝트를 들고 있지
|
||||
// 않으면 지울 주소를 만들 수 없다 — 그때는 프로젝트를 먼저 지정해야 한다.
|
||||
if (!item.project) {
|
||||
setDeleteError("프로젝트에 속하지 않은 결정은 여기서 지울 수 없습니다. 먼저 프로젝트를 지정해 주세요.");
|
||||
return;
|
||||
}
|
||||
await managementGateway.deleteDecision(
|
||||
item.project.id,
|
||||
item.id,
|
||||
detail.document.version,
|
||||
);
|
||||
} else {
|
||||
/*
|
||||
예전에는 여기서 `as "CASE" | "REFERENCE" | "QUESTION"` 으로 종류를 좁혔다. 개념이
|
||||
더해졌을 때 그 캐스팅이 개념을 가렸고, 게이트웨이의 마지막 else 가 질문 삭제를
|
||||
부르는 바람에 「질문을 찾을 수 없습니다」가 났다. 캐스팅을 걷어내면 새 종류가
|
||||
생길 때 타입이 여기서 막는다.
|
||||
*/
|
||||
await managementGateway.deleteDocument(
|
||||
item.kind,
|
||||
item.id,
|
||||
detail.document.version,
|
||||
);
|
||||
}
|
||||
setRequestAnnouncement(`작업본 ${item.title || "제목 없음"} 을(를) 삭제했습니다.`);
|
||||
setPendingDelete(null);
|
||||
// 다시 불러오지 않고 이 행만 지운다. 목록은 커서 페이지네이션이라 재조회하면 다음
|
||||
// 항목이 빈 자리를 즉시 채우고, 개수도 20 그대로다 — 작성자에게는 삭제가 아무 일도
|
||||
// 하지 않은 것처럼 보인다. 삭제가 성공한 뒤의 화면은 그 행이 없는 화면이 맞다.
|
||||
setPage((current) =>
|
||||
current
|
||||
? { ...current, items: current.items.filter((row) => row.id !== item.id) }
|
||||
: current,
|
||||
);
|
||||
} catch (error) {
|
||||
// 서버는 무엇이 막았는지 정확히 알고 그것을 보내 준다. 예전에는 그 문구를 버리고 추측 셋을
|
||||
// 늘어놓아, 버전 충돌도 "사용 중" 으로 읽혔다.
|
||||
setDeleteError(managementFailureMessage(error, "삭제하지 못했습니다."));
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
// 뒤로가기로 다른 검색어의 주소에 돌아오면 입력칸도 그 값이어야 한다.
|
||||
useEffect(() => {
|
||||
setSearchDraft(q);
|
||||
}, [q]);
|
||||
|
||||
/*
|
||||
프로젝트 선택지. 목록과 같은 카탈로그를 읽는다 — 편집기의 프로젝트 셀렉트가 쓰는 것과
|
||||
같은 원천이라 두 화면이 다른 목록을 보여 주지 않는다.
|
||||
|
||||
실패는 조용히 넘긴다. 프로젝트로 거르지 못하는 것은 불편이지만, 그것 때문에 작업본 목록
|
||||
자체를 못 보게 만들 이유는 없다.
|
||||
*/
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void collectCatalog(gateway, { type: "PROJECT" }, { signal: controller.signal }).then(
|
||||
(items) => setProjects(items),
|
||||
() => undefined,
|
||||
);
|
||||
return () => controller.abort();
|
||||
}, [gateway]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void gateway
|
||||
.listDocuments(
|
||||
{
|
||||
...(q ? { q } : {}),
|
||||
...(kind ? { kind } : {}),
|
||||
...(status ? { publicationStatus: status } : {}),
|
||||
...(projectId ? { projectId } : {}),
|
||||
...(nextAction ? { nextAction } : {}),
|
||||
sort,
|
||||
page: pageNumber,
|
||||
limit: 20,
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then(
|
||||
(value) => {
|
||||
setPage(value);
|
||||
setLoading(false);
|
||||
},
|
||||
(reason: unknown) => {
|
||||
if (isAbortError(reason)) return;
|
||||
setError("작업본을 불러오지 못했습니다.");
|
||||
setLoading(false);
|
||||
},
|
||||
);
|
||||
return () => controller.abort();
|
||||
}, [gateway, kind, nextAction, pageNumber, projectId, q, retryGeneration, sort, status]);
|
||||
|
||||
const changeFilter = (next: {
|
||||
kind?: ListDocumentsQuery["kind"];
|
||||
status?: ListDocumentsQuery["publicationStatus"];
|
||||
}) => {
|
||||
// 3쪽에 있던 채로 필터를 좁히면 결과가 그보다 적어 빈 화면이 나온다.
|
||||
go({
|
||||
...("kind" in next ? { kind: next.kind ?? "" } : {}),
|
||||
...("status" in next ? { status: next.status ?? "" } : {}),
|
||||
page: 1,
|
||||
});
|
||||
};
|
||||
const submitSearch = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
go({ q: searchDraft.trim(), page: 1 });
|
||||
};
|
||||
const copy = useTechLogCopy();
|
||||
const {
|
||||
changeFilter,
|
||||
clearDeleteError,
|
||||
deleteError,
|
||||
deletingId,
|
||||
error,
|
||||
go,
|
||||
kind,
|
||||
loading,
|
||||
nextAction,
|
||||
page,
|
||||
pageNumber,
|
||||
pendingDelete,
|
||||
projectId,
|
||||
projects,
|
||||
resultCount,
|
||||
retry,
|
||||
searchDraft,
|
||||
setPendingDelete,
|
||||
setSearchDraft,
|
||||
sort,
|
||||
status,
|
||||
submitSearch,
|
||||
removeDocument,
|
||||
} = useDocumentListController();
|
||||
|
||||
return (
|
||||
<div className="studio-page studio-documents-page">
|
||||
@@ -276,113 +65,130 @@ export function DocumentList() {
|
||||
세션에 있는 검증 기록·동작 원리·적용 기준·열린 질문·설계 결정을 찾고 다음 작업으로 이동합니다.
|
||||
</p>
|
||||
</div>
|
||||
<GuardedStudioLink className="studio-primary-action" href="/studio/documents/new">
|
||||
<GuardedStudioLink className="studio-primary-action" href={studioRoutes.documentNew()}>
|
||||
새 문서
|
||||
</GuardedStudioLink>
|
||||
</header>
|
||||
<section className="studio-document-tools" aria-label="작업본 검색과 필터">
|
||||
<form role="search" onSubmit={submitSearch}>
|
||||
<label htmlFor="studio-search">검색</label>
|
||||
<div>
|
||||
<input
|
||||
id="studio-search"
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
/* 서버가 뒤지는 것은 제목뿐이다(`lower(title) LIKE`). 없는 것을 적어 두지 않는다. */
|
||||
placeholder="제목"
|
||||
onChange={(event) => setSearchDraft(event.target.value)}
|
||||
<SearchFilterToolbar
|
||||
className="studio-document-tools"
|
||||
label="작업본 검색과 필터"
|
||||
onReset={() => {
|
||||
setSearchDraft("");
|
||||
go({
|
||||
q: "",
|
||||
kind: "",
|
||||
status: "",
|
||||
project: "",
|
||||
sort: "UPDATED_DESC",
|
||||
next: "",
|
||||
page: 1,
|
||||
});
|
||||
}}
|
||||
resetLabel={copy("techLog.action.resetFilters")}
|
||||
resultCount={resultCount}
|
||||
search={
|
||||
<Form pending={false} role="search" onSubmit={submitSearch}>
|
||||
<div className="studio-document-search">
|
||||
<TextField
|
||||
className="studio-tool-field"
|
||||
label="검색"
|
||||
placeholder="제목"
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
onChange={(event) => setSearchDraft(event.currentTarget.value)}
|
||||
/>
|
||||
<Button type="submit" variant="ghost">
|
||||
{copy("techLog.action.search")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
}
|
||||
filters={
|
||||
<div className="studio-document-filter-grid">
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="종류"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
...DOCUMENT_STUDIO_KINDS.map((value) => ({
|
||||
value,
|
||||
label: DOCUMENT_KIND_LABELS[value],
|
||||
})),
|
||||
]}
|
||||
value={kind ?? ""}
|
||||
onChange={(event) =>
|
||||
changeFilter({
|
||||
kind: (event.currentTarget.value ||
|
||||
undefined) as ListDocumentsQuery["kind"],
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="상태"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
{ value: "NEVER_PUBLISHED", label: "게시 전" },
|
||||
{ value: "PUBLISHED", label: "게시 중" },
|
||||
{ value: "UNPUBLISHED", label: "게시 취소" },
|
||||
]}
|
||||
value={status ?? ""}
|
||||
onChange={(event) =>
|
||||
changeFilter({
|
||||
status: (event.currentTarget.value ||
|
||||
undefined) as ListDocumentsQuery["publicationStatus"],
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="프로젝트"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
...projects.map((project) => ({
|
||||
value: project.id,
|
||||
label: project.label,
|
||||
})),
|
||||
]}
|
||||
value={projectId}
|
||||
onChange={(event) =>
|
||||
go({ project: event.currentTarget.value, page: 1 })
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="다음 할 일"
|
||||
options={[
|
||||
{ value: "", label: "전체" },
|
||||
...DOCUMENT_NEXT_ACTIONS.map((action) => ({
|
||||
value: action,
|
||||
label: NEXT_ACTION_LABELS[action],
|
||||
})),
|
||||
]}
|
||||
value={nextAction ?? ""}
|
||||
onChange={(event) =>
|
||||
go({ next: event.currentTarget.value, page: 1 })
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
className="studio-tool-field"
|
||||
label="정렬"
|
||||
options={[
|
||||
{ value: "UPDATED_DESC", label: "최근 수정 순" },
|
||||
{ value: "UPDATED_ASC", label: "오래된 수정 순" },
|
||||
{ value: "TITLE_ASC", label: "제목 순" },
|
||||
]}
|
||||
value={sort}
|
||||
onChange={(event) =>
|
||||
go({ sort: event.currentTarget.value, page: 1 })
|
||||
}
|
||||
/>
|
||||
<button type="submit">검색</button>
|
||||
</div>
|
||||
</form>
|
||||
<label>
|
||||
종류
|
||||
<select
|
||||
value={kind ?? ""}
|
||||
onChange={(event) =>
|
||||
changeFilter({
|
||||
kind: (event.target.value || undefined) as ListDocumentsQuery["kind"],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
{/*
|
||||
이름은 공용 표에서 가져온다. 여기 손으로 적어 두었을 때 개념이 통째로 빠져 있었고
|
||||
— 개념 작업본은 만들 수는 있는데 걸러 볼 수가 없었다 — 이름도 영문이라 목록 안의
|
||||
배지와 어긋났다. 같은 문서가 한 화면에서 두 이름으로 보였다.
|
||||
*/}
|
||||
{STUDIO_KINDS.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{DOCUMENT_KIND_LABELS[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
상태
|
||||
<select
|
||||
value={status ?? ""}
|
||||
onChange={(event) =>
|
||||
changeFilter({
|
||||
status: (event.target.value || undefined) as ListDocumentsQuery["publicationStatus"],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
<option value="NEVER_PUBLISHED">게시 전</option>
|
||||
<option value="PUBLISHED">게시 중</option>
|
||||
<option value="UNPUBLISHED">게시 취소</option>
|
||||
</select>
|
||||
</label>
|
||||
{/*
|
||||
프로젝트로 거르는 길이 없었다. 공개 `/explore` 는 독자에게 종류·주제·프로젝트 셋을
|
||||
주는데, 61개를 관리하는 작성자에게는 종류·상태 둘뿐이었다 — 읽는 사람이 쓰는 사람보다
|
||||
좋은 도구를 갖고 있었다.
|
||||
*/}
|
||||
<label>
|
||||
프로젝트
|
||||
<select
|
||||
value={projectId}
|
||||
onChange={(event) => go({ project: event.target.value, page: 1 })}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
{projects.map((project) => (
|
||||
<option key={project.id} value={project.id}>
|
||||
{project.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{/*
|
||||
작성자가 목록에서 실제로 묻는 것 — "검증해야 하는 게 뭐지", "게시할 수 있는 게 뭐지".
|
||||
계약이 이미 주는 필터라 서버가 거른다.
|
||||
*/}
|
||||
<label>
|
||||
다음 할 일
|
||||
<select
|
||||
value={nextAction ?? ""}
|
||||
onChange={(event) => go({ next: event.target.value, page: 1 })}
|
||||
>
|
||||
<option value="">전체</option>
|
||||
{NEXT_ACTIONS.map((action) => (
|
||||
<option key={action} value={action}>
|
||||
{NEXT_ACTION_LABELS[action]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
정렬
|
||||
<select value={sort} onChange={(event) => go({ sort: event.target.value, page: 1 })}>
|
||||
<option value="UPDATED_DESC">최근 수정 순</option>
|
||||
<option value="UPDATED_ASC">오래된 수정 순</option>
|
||||
<option value="TITLE_ASC">제목 순</option>
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
}
|
||||
/>
|
||||
{loading ? (
|
||||
<p className="studio-loading" role="status">
|
||||
작업본을 불러오는 중입니다.
|
||||
{copy("techLog.state.documentListLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
@@ -390,32 +196,18 @@ export function DocumentList() {
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
<button
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
onClick={() => setRetryGeneration((current) => current + 1)}
|
||||
variant="ghost"
|
||||
onClick={retry}
|
||||
>
|
||||
다시 시도
|
||||
</button>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{page && !loading && !error ? (
|
||||
<>
|
||||
{/*
|
||||
이 숫자는 전체가 아니라 이 페이지에 실린 수다. 예전 문구는 그것을 전체처럼 읽히게
|
||||
해서, 28건 중 20건이 보이는 동안 무엇을 지워도 "20개" 가 그대로였다.
|
||||
*/}
|
||||
<p className="studio-result-count">
|
||||
<span>
|
||||
{page.page.totalElements}개 중 {page.items.length}개 표시 중
|
||||
</span>
|
||||
{page.page.totalPages > 1 ? (
|
||||
<span>
|
||||
{" "}
|
||||
· {page.page.number} / {page.page.totalPages} 쪽
|
||||
</span>
|
||||
) : null}
|
||||
</p>
|
||||
{deleteError ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{deleteError}
|
||||
@@ -428,7 +220,7 @@ export function DocumentList() {
|
||||
<p className="studio-row-label">{DOCUMENT_KIND_LABELS[item.kind]}</p>
|
||||
<div className="studio-document-title">
|
||||
<h2>
|
||||
<GuardedStudioLink href={`/studio/documents/${item.id}/edit`}>
|
||||
<GuardedStudioLink href={studioRoutes.documentEdit(item.id)}>
|
||||
{item.title || "제목 없는 작업본"}
|
||||
</GuardedStudioLink>
|
||||
</h2>
|
||||
@@ -482,7 +274,7 @@ export function DocumentList() {
|
||||
<div className="studio-row-actions">
|
||||
<GuardedStudioLink
|
||||
className="studio-secondary-button"
|
||||
href={`/studio/documents/${item.id}/edit`}
|
||||
href={studioRoutes.documentEdit(item.id)}
|
||||
>
|
||||
편집
|
||||
</GuardedStudioLink>
|
||||
@@ -491,17 +283,18 @@ export function DocumentList() {
|
||||
⋯
|
||||
</summary>
|
||||
<div>
|
||||
<button
|
||||
<Button
|
||||
className="studio-secondary-button studio-danger-button"
|
||||
type="button"
|
||||
disabled={deletingId !== null}
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setDeleteError("");
|
||||
clearDeleteError();
|
||||
setPendingDelete(item);
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
{copy("techLog.action.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
@@ -510,9 +303,9 @@ export function DocumentList() {
|
||||
</div>
|
||||
) : (
|
||||
<section className="studio-empty-state">
|
||||
<h2>조건에 맞는 작업본이 없습니다</h2>
|
||||
<p>검색어 또는 필터를 바꾸거나 새 문서를 만드세요.</p>
|
||||
<GuardedStudioLink href="/studio/documents/new">
|
||||
<h2>{copy("techLog.state.emptyDocumentList")}</h2>
|
||||
<p>{copy("techLog.state.emptyDocumentListHint")}</p>
|
||||
<GuardedStudioLink href={studioRoutes.documentNew()}>
|
||||
새 문서 만들기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
import type { DocumentEditorController } from "./document-editor-controller.ts";
|
||||
import type { FieldIssue } from "./field-issues.tsx";
|
||||
|
||||
const labels = {
|
||||
CLEAN: "저장됨",
|
||||
DIRTY: "저장되지 않음",
|
||||
SAVING: "저장 중…",
|
||||
CONFLICT: "저장 충돌",
|
||||
const STATUS_LABEL_KEYS = {
|
||||
CLEAN: "techLog.editor.status.clean",
|
||||
DIRTY: "techLog.editor.status.dirty",
|
||||
SAVING: "techLog.editor.status.saving",
|
||||
CONFLICT: "techLog.editor.status.conflict",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -21,6 +23,7 @@ export function DocumentStatusBar({
|
||||
controller: DocumentEditorController;
|
||||
unplacedIssues: readonly FieldIssue[];
|
||||
}) {
|
||||
const { message } = useLocale();
|
||||
const busy = controller.status === "SAVING" || controller.publishing;
|
||||
const problem = controller.status === "CONFLICT"
|
||||
? "서버 최신본과 충돌했습니다. 이 세션에서는 다시 열어 비교해 주세요."
|
||||
@@ -28,32 +31,32 @@ export function DocumentStatusBar({
|
||||
|
||||
return (
|
||||
<aside className="studio-document-status-bar" aria-labelledby="studio-document-status-title">
|
||||
<h2 id="studio-document-status-title" className="studio-visually-hidden">작업 상태</h2>
|
||||
<h2 id="studio-document-status-title" className="studio-visually-hidden">{message("techLog.editor.workStatus")}</h2>
|
||||
<p
|
||||
className={`studio-editor-status studio-editor-status--${controller.status.toLowerCase()}`}
|
||||
role="status"
|
||||
aria-label="편집 상태"
|
||||
aria-label={message("techLog.editor.statusLabel")}
|
||||
>
|
||||
<span className="studio-editor-status__dot" aria-hidden="true" />
|
||||
{labels[controller.status]}
|
||||
{message(STATUS_LABEL_KEYS[controller.status])}
|
||||
</p>
|
||||
<div className="studio-document-status-bar__actions">
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
title="Ctrl+S"
|
||||
onClick={() => { void controller.save(); }}
|
||||
disabled={busy || controller.status === "CLEAN" || controller.status === "CONFLICT"}
|
||||
>
|
||||
{controller.status === "SAVING" ? "저장 중…" : "저장"}
|
||||
</button>
|
||||
<button
|
||||
{message(controller.status === "SAVING" ? "techLog.action.saving" : "techLog.action.save")}
|
||||
</Button>
|
||||
<Button visualPolicy="inherit"
|
||||
className="studio-primary-button"
|
||||
type="button"
|
||||
onClick={() => { void controller.publish(); }}
|
||||
disabled={busy || controller.status === "CONFLICT"}
|
||||
>
|
||||
{controller.publishing ? "게시 중…" : "게시"}
|
||||
</button>
|
||||
{message(controller.publishing ? "techLog.action.publishing" : "techLog.action.publish")}
|
||||
</Button>
|
||||
</div>
|
||||
{problem ? <p className="studio-editor-command-error" role="alert">{problem}</p> : null}
|
||||
{unplacedIssues.length ? (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import type {
|
||||
AnchorHTMLAttributes,
|
||||
MouseEvent as ReactMouseEvent,
|
||||
@@ -38,8 +39,8 @@ export function GuardedStudioLink({
|
||||
const target = new URL(href, window.location.href);
|
||||
if (target.origin !== window.location.origin) return;
|
||||
if (
|
||||
target.pathname !== "/studio" &&
|
||||
!target.pathname.startsWith("/studio/")
|
||||
target.pathname !== studioRoutes.home() &&
|
||||
!target.pathname.startsWith(`${studioRoutes.home()}/`)
|
||||
) return;
|
||||
event.preventDefault();
|
||||
navigateInternal(
|
||||
|
||||
@@ -1,194 +1,133 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { useEffect, type FormEvent } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type {
|
||||
HomeFocusResponse,
|
||||
ProjectIndexItem,
|
||||
} from "../../../contracts/management/contract.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import {
|
||||
Button,
|
||||
Select,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
useAppForm,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import {
|
||||
useManagementCommands,
|
||||
useManagementHomeFocusQuery,
|
||||
useManagementProjectDecisionsQuery,
|
||||
useManagementQuestionsQuery,
|
||||
} from "../studio-management-server-state.ts";
|
||||
|
||||
|
||||
/**
|
||||
* 고른 프로젝트의 slug.
|
||||
*
|
||||
* <p>질문 목록은 프로젝트를 slug 로만 알려 준다(계약의 `ProjectSummary` 에 id 가 없다). 한동안
|
||||
* 이 값을 `publication.canonicalPath` 에서 뽑았는데, 그 칸은 서버가 한 번도 채우지 않아 늘
|
||||
* 비어 있었다 — 그래서 어떤 프로젝트를 골라도 다른 프로젝트의 질문까지 목록에 남았다.
|
||||
* 지금은 목록 행이 slug 를 직접 싣는다.
|
||||
*/
|
||||
function projectSlug(projects: readonly ProjectIndexItem[], projectId: string) {
|
||||
function projectSlug(
|
||||
projects: readonly ProjectIndexItem[],
|
||||
projectId: string,
|
||||
) {
|
||||
return projects.find((project) => project.id === projectId)?.slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 홈의 "지금 집중하는 것" 을 정하는 화면.
|
||||
*
|
||||
* <p>그 영역은 세 칸(현재 작업·열린 질문·최근 결정)을 가지며 셋이 모두 비면 홈은 영역 자체를 그리지
|
||||
* 않는다. `home_focus_config` 는 마이그레이션이 빈 행 하나만 넣어 두었고 그 값을 채울 화면이 없었으므로,
|
||||
* 홈에서는 그 영역이 한 번도 나타난 적이 없었다.
|
||||
*
|
||||
* <p>고를 수 있는 것은 실제로 존재하는 기록뿐이다. 질문과 결정은 Studio catalog 의 `RELATION` 목록에서
|
||||
* 가져온다 — 그 목록이 곧 "연결 가능한 대상" 의 정의이고, 여기서 다른 기준을 쓰면 두 화면이 서로 다른
|
||||
* 것을 보여 준다.
|
||||
*
|
||||
* <p>비공개 프로젝트도 고를 수 있게 둔다. 미리 지목해 두고 게시와 동시에 홈에 뜨게 하는 것이 정상적인
|
||||
* 순서이기 때문이다. 다만 게시되지 않은 동안에는 홈이 그 칸을 그리지 않으므로 그 사실을 적어 둔다.
|
||||
*/
|
||||
|
||||
const HOME_FOCUS_SCHEMA = z.object({
|
||||
projectId: z.string(),
|
||||
questionId: z.string(),
|
||||
decisionId: z.string(),
|
||||
});
|
||||
|
||||
export function HomeFocusEditor() {
|
||||
const { gateway, managementGateway, setRequestAnnouncement } = useStudio();
|
||||
const [focus, setFocus] = useState<HomeFocusResponse | null>(null);
|
||||
const [projects, setProjects] = useState<ProjectIndexItem[]>([]);
|
||||
const [projectId, setProjectId] = useState("");
|
||||
const [questionId, setQuestionId] = useState("");
|
||||
const [decisionId, setDecisionId] = useState("");
|
||||
const [projectQuestions, setProjectQuestions] = useState<{ id: string; label: string }[]>([]);
|
||||
/** 고를 목록을 못 읽었다. 「없다」와 구분해야 작성자가 자기 글이 사라진 줄 알지 않는다. */
|
||||
const [questionsFailed, setQuestionsFailed] = useState(false);
|
||||
const [decisionsFailed, setDecisionsFailed] = useState(false);
|
||||
const [projectDecisions, setProjectDecisions] = useState<{ id: string; label: string }[]>([]);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const copy = useTechLogCopy();
|
||||
const { setRequestAnnouncement } = useStudio();
|
||||
const homeQuery = useManagementHomeFocusQuery();
|
||||
const questionsQuery = useManagementQuestionsQuery();
|
||||
const commands = useManagementCommands();
|
||||
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
const focus: HomeFocusResponse | null = homeQuery.data?.focus ?? null;
|
||||
const projects = homeQuery.data?.projects.items ?? [];
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
/*
|
||||
try/catch 로 감싼다. `Promise.all([gateway.foo()])` 은 `foo` 가 거절하는 것만 잡는다 —
|
||||
호출 자체가 동기적으로 던지면(예: 그 표면을 갖추지 않은 게이트웨이) 배열을 만드는 중에
|
||||
터지므로 rejection handler 를 지나지 못한다. 그러면 이 섹션이 아니라 대시보드 전체가
|
||||
빈 화면이 된다. 한 칸의 실패가 화면을 통째로 날리지 않게 한다.
|
||||
*/
|
||||
void (async () => {
|
||||
try {
|
||||
const [current, projectPage] = await Promise.all([
|
||||
managementGateway.getHomeFocus(),
|
||||
managementGateway.listProjects(0, 50),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
setFocus(current);
|
||||
setProjects(projectPage.items ?? []);
|
||||
setProjectId(current.currentProjectId ?? "");
|
||||
setQuestionId(current.openQuestionId ?? "");
|
||||
setDecisionId(current.recentDecisionId ?? "");
|
||||
setError("");
|
||||
} catch {
|
||||
if (!cancelled) setError("홈 설정을 불러오지 못했습니다.");
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [gateway, managementGateway, generation]);
|
||||
|
||||
/*
|
||||
고른 프로젝트의 질문·결정만 불러온다. 프로젝트를 바꾸면 이전 프로젝트의 선택은 목록에
|
||||
없으므로 함께 비운다 — 남겨 두면 홈에서 다른 프로젝트의 결정이 나온다.
|
||||
*/
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!projectId) {
|
||||
setProjectQuestions([]);
|
||||
setProjectDecisions([]);
|
||||
setQuestionsFailed(false);
|
||||
setDecisionsFailed(false);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
const form = useAppForm({
|
||||
schema: HOME_FOCUS_SCHEMA,
|
||||
defaultValues: {
|
||||
projectId: "",
|
||||
questionId: "",
|
||||
decisionId: "",
|
||||
},
|
||||
allowedServerFields: ["projectId", "questionId", "decisionId"] as const,
|
||||
mapToCommand(values) {
|
||||
return {
|
||||
expectedVersion: focus?.version ?? 0,
|
||||
currentProjectId: values.projectId || undefined,
|
||||
openQuestionId: values.questionId || undefined,
|
||||
recentDecisionId: values.decisionId || undefined,
|
||||
};
|
||||
}
|
||||
/*
|
||||
둘을 따로 읽는다. `Promise.all` 로 묶었더니 결정 쪽이 500 을 내는 동안 질문까지 함께
|
||||
실패로 처리돼, 멀쩡히 오던 질문 목록도 「불러오지 못했습니다」가 됐다 — 한 칸의 실패가
|
||||
옆 칸을 끌고 내려가지 않게 한다.
|
||||
*/
|
||||
void (async () => {
|
||||
try {
|
||||
const questionPage = await managementGateway.listQuestions(0, 100);
|
||||
if (cancelled) return;
|
||||
/*
|
||||
질문 항목은 프로젝트를 slug 로 알려 준다(계약의 `ProjectSummary` 에는 id 가 없다).
|
||||
그래서 고른 프로젝트의 slug 와 맞춘다.
|
||||
*/
|
||||
const chosenSlug = projectSlug(projects, projectId);
|
||||
setProjectQuestions(
|
||||
(questionPage.items ?? [])
|
||||
.filter((item) => !chosenSlug || item.primaryProject?.slug === chosenSlug)
|
||||
.map((item) => ({ id: item.id, label: item.question })),
|
||||
);
|
||||
setQuestionsFailed(false);
|
||||
} catch {
|
||||
/*
|
||||
못 읽은 것과 없는 것은 다르다. 예전에는 둘 다 빈 배열이 되어 화면이 「이 프로젝트에
|
||||
열린 질문이 없습니다」라고 적었고 — 실제로는 넷이 있었다 — 작성자는 자기가 아직
|
||||
쓰지 않은 줄 알게 됐다. 거짓말을 하느니 못 읽었다고 말한다.
|
||||
*/
|
||||
if (!cancelled) {
|
||||
setProjectQuestions([]);
|
||||
setQuestionsFailed(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
},
|
||||
submit: commands.updateHomeFocus.submit,
|
||||
resetOnSuccess: false,
|
||||
});
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const decisionList = await managementGateway.listProjectDecisions(projectId);
|
||||
if (cancelled) return;
|
||||
setProjectDecisions(
|
||||
decisionList.map((item) => ({ id: item.id, label: item.statement })),
|
||||
);
|
||||
setDecisionsFailed(false);
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setProjectDecisions([]);
|
||||
setDecisionsFailed(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [managementGateway, projectId, projects, generation]);
|
||||
const projectId = form.values.projectId;
|
||||
const questionId = form.values.questionId;
|
||||
const decisionId = form.values.decisionId;
|
||||
const resetHomeFocusForm = form.reset;
|
||||
const decisionsQuery = useManagementProjectDecisionsQuery(projectId);
|
||||
|
||||
/*
|
||||
이 화면은 「지금 집중하는 것」 하나를 고르는 자리다. 셋(프로젝트·질문·결정)이 서로 다른
|
||||
프로젝트를 가리키면 홈에서 프로젝트는 A 인데 결정은 B 의 것이 나온다 — 실제로 그렇게 나왔다.
|
||||
그래서 프로젝트를 고르면 그 프로젝트의 질문·결정만 고르게 한다.
|
||||
useEffect(() => {
|
||||
if (!focus) return;
|
||||
resetHomeFocusForm({
|
||||
projectId: focus.currentProjectId ?? "",
|
||||
questionId: focus.openQuestionId ?? "",
|
||||
decisionId: focus.recentDecisionId ?? "",
|
||||
});
|
||||
}, [focus, resetHomeFocusForm]);
|
||||
|
||||
질문 항목은 `primaryProject` 를 들고 오므로 그것으로 거르고, 결정은 경로 자체가 프로젝트를
|
||||
요구하므로 고른 프로젝트의 것만 온다.
|
||||
*/
|
||||
const questions = projectQuestions;
|
||||
const decisions = projectDecisions;
|
||||
const chosenSlug = projectSlug(projects, projectId);
|
||||
const questions = (questionsQuery.data?.items ?? [])
|
||||
.filter(
|
||||
(item) =>
|
||||
!chosenSlug || item.primaryProject?.slug === chosenSlug,
|
||||
)
|
||||
.map((item) => ({ id: item.id, label: item.question }));
|
||||
const decisions = (decisionsQuery.data ?? []).map((item) => ({
|
||||
id: item.id,
|
||||
label: item.statement,
|
||||
}));
|
||||
|
||||
const save = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pending || !focus) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
const saved = await managementGateway.updateHomeFocus({
|
||||
expectedVersion: focus.version,
|
||||
// 빈 문자열은 "고르지 않음" 이다. 계약은 uuid 만 받으므로 보내지 않는다.
|
||||
currentProjectId: projectId || undefined,
|
||||
openQuestionId: questionId || undefined,
|
||||
recentDecisionId: decisionId || undefined,
|
||||
});
|
||||
setFocus(saved);
|
||||
setRequestAnnouncement("홈에 표시할 항목을 저장했습니다.");
|
||||
reload();
|
||||
} catch (failure) {
|
||||
setError(managementFailureMessage(failure, "홈 설정을 저장하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
const questionsFailed =
|
||||
projectId !== "" && questionsQuery.state.base === "terminal-error";
|
||||
const decisionsFailed =
|
||||
projectId !== "" && decisionsQuery.state.base === "terminal-error";
|
||||
|
||||
const reload = async () => {
|
||||
await Promise.all([
|
||||
homeQuery.retry(),
|
||||
questionsQuery.retry(),
|
||||
decisionsQuery.retry(),
|
||||
]);
|
||||
};
|
||||
|
||||
const chosenProject = projects.find((project) => project.id === projectId);
|
||||
const projectHidden = chosenProject && chosenProject.targetVisibility === "PRIVATE";
|
||||
const save = async (event: FormEvent<HTMLFormElement>) => {
|
||||
const saved = await form.submitForm(event);
|
||||
if (!saved?.ok) return;
|
||||
|
||||
setRequestAnnouncement(copy("techLog.notice.homeFocusSaved"));
|
||||
await reload();
|
||||
};
|
||||
|
||||
const chosenProject = projects.find(
|
||||
(project) => project.id === projectId,
|
||||
);
|
||||
const projectHidden =
|
||||
chosenProject && chosenProject.targetVisibility === "PRIVATE";
|
||||
const nothingChosen = !projectId && !questionId && !decisionId;
|
||||
const loading = homeQuery.state.base === "initial-loading";
|
||||
const loadError =
|
||||
homeQuery.state.base === "terminal-error"
|
||||
? copy("techLog.state.homeLoadFailed")
|
||||
: "";
|
||||
|
||||
return (
|
||||
<section className="studio-editor-section" aria-labelledby="studio-home-focus-title">
|
||||
@@ -200,116 +139,140 @@ export function HomeFocusEditor() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
{loadError ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
{loadError}
|
||||
</p>
|
||||
) : null}
|
||||
{!focus && !error ? (
|
||||
{!focus && !loadError ? (
|
||||
<p className="studio-loading" role="status">
|
||||
홈 설정을 불러오는 중입니다.
|
||||
{loading ? copy("techLog.state.homeLoading") : copy("techLog.state.homePreparing")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{focus ? (
|
||||
<form onSubmit={save}>
|
||||
<Form
|
||||
pending={form.pending}
|
||||
onSubmit={(event) => {
|
||||
void save(event);
|
||||
}}
|
||||
>
|
||||
<div className="studio-field-grid">
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>현재 작업 (프로젝트)</span>
|
||||
<select
|
||||
value={projectId}
|
||||
onChange={(event) => {
|
||||
/*
|
||||
프로젝트를 바꾸면 질문·결정 선택을 비운다. 남겨 두면 홈에서 프로젝트는 A 인데
|
||||
결정은 B 의 것이 나온다 — 실제로 그렇게 나왔다.
|
||||
*/
|
||||
setProjectId(event.currentTarget.value);
|
||||
setQuestionId("");
|
||||
setDecisionId("");
|
||||
}}
|
||||
>
|
||||
<option value="">고르지 않음</option>
|
||||
{projects.map((project) => (
|
||||
<option key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
{project.targetVisibility === "PRIVATE" ? " (비공개)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{projectHidden ? (
|
||||
<small>
|
||||
이 프로젝트는 아직 비공개입니다. 주제·프로젝트 화면에서 게시해야 홈에 나타납니다.
|
||||
</small>
|
||||
) : (
|
||||
<small>단계·현재 목표·다음 작업이 카드에 함께 나옵니다.</small>
|
||||
)}
|
||||
</label>
|
||||
<Select
|
||||
className="studio-field studio-field--wide"
|
||||
description={
|
||||
projectHidden
|
||||
? "이 프로젝트는 아직 비공개입니다. 주제·프로젝트 화면에서 게시해야 홈에 나타납니다."
|
||||
: "단계·현재 목표·다음 작업이 카드에 함께 나옵니다."
|
||||
}
|
||||
label="현재 작업 (프로젝트)"
|
||||
options={[
|
||||
{ value: "", label: "고르지 않음" },
|
||||
...projects.map((project) => ({
|
||||
value: project.id,
|
||||
label:
|
||||
project.name +
|
||||
(project.targetVisibility === "PRIVATE"
|
||||
? " (비공개)"
|
||||
: ""),
|
||||
})),
|
||||
]}
|
||||
value={projectId}
|
||||
onChange={(event) => {
|
||||
form.setValue("projectId", event.currentTarget.value);
|
||||
form.setValue("questionId", "");
|
||||
form.setValue("decisionId", "");
|
||||
}}
|
||||
/>
|
||||
|
||||
<label className="studio-field">
|
||||
<span>열린 질문</span>
|
||||
<select
|
||||
value={questionId}
|
||||
onChange={(event) => setQuestionId(event.currentTarget.value)}
|
||||
disabled={questions.length === 0}
|
||||
>
|
||||
<option value="">고르지 않음</option>
|
||||
{questions.map((entry) => (
|
||||
<option key={entry.id} value={entry.id}>
|
||||
{entry.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{questions.length === 0 ? (
|
||||
<small>
|
||||
{questionsFailed
|
||||
? "열린 질문을 불러오지 못했습니다. 새로고침해 주세요."
|
||||
<Select
|
||||
className="studio-field"
|
||||
description={
|
||||
questions.length === 0
|
||||
? questionsFailed
|
||||
? copy("techLog.state.openQuestionsLoadFailed")
|
||||
: projectId
|
||||
? "이 프로젝트에 열린 질문이 없습니다."
|
||||
: "프로젝트를 먼저 고르세요."}
|
||||
</small>
|
||||
) : null}
|
||||
</label>
|
||||
? "이 프로젝트에 열린 질문이 없습니다."
|
||||
: "프로젝트를 먼저 고르세요."
|
||||
: undefined
|
||||
}
|
||||
disabled={questions.length === 0}
|
||||
label="열린 질문"
|
||||
options={[
|
||||
{ value: "", label: "고르지 않음" },
|
||||
...questions.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: entry.label,
|
||||
})),
|
||||
]}
|
||||
value={questionId}
|
||||
onChange={(event) =>
|
||||
form.setValue("questionId", event.currentTarget.value)
|
||||
}
|
||||
/>
|
||||
|
||||
<label className="studio-field">
|
||||
<span>최근 결정</span>
|
||||
<select
|
||||
value={decisionId}
|
||||
onChange={(event) => setDecisionId(event.currentTarget.value)}
|
||||
disabled={decisions.length === 0}
|
||||
>
|
||||
<option value="">고르지 않음</option>
|
||||
{decisions.map((entry) => (
|
||||
<option key={entry.id} value={entry.id}>
|
||||
{entry.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{decisions.length === 0 ? (
|
||||
<small>
|
||||
{decisionsFailed
|
||||
? "결정을 불러오지 못했습니다. 새로고침해 주세요."
|
||||
<Select
|
||||
className="studio-field"
|
||||
description={
|
||||
decisions.length === 0
|
||||
? decisionsFailed
|
||||
? copy("techLog.state.decisionsLoadFailed")
|
||||
: projectId
|
||||
? "이 프로젝트에 결정이 없습니다."
|
||||
: "프로젝트를 먼저 고르세요."}
|
||||
</small>
|
||||
) : null}
|
||||
</label>
|
||||
? "이 프로젝트에 결정이 없습니다."
|
||||
: "프로젝트를 먼저 고르세요."
|
||||
: undefined
|
||||
}
|
||||
disabled={decisions.length === 0}
|
||||
label="최근 결정"
|
||||
options={[
|
||||
{ value: "", label: "고르지 않음" },
|
||||
...decisions.map((entry) => ({
|
||||
value: entry.id,
|
||||
label: entry.label,
|
||||
})),
|
||||
]}
|
||||
value={decisionId}
|
||||
onChange={(event) =>
|
||||
form.setValue("decisionId", event.currentTarget.value)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldId={form.fieldId}
|
||||
fieldLabels={{
|
||||
projectId: "현재 작업",
|
||||
questionId: "열린 질문",
|
||||
decisionId: "최근 결정",
|
||||
}}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
|
||||
<div className="studio-editor-footer">
|
||||
<button className="studio-secondary-button" type="submit" disabled={pending}>
|
||||
{pending ? "저장하는 중" : "홈 설정 저장"}
|
||||
</button>
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
disabled={form.pending}
|
||||
pending={form.pending}
|
||||
pendingLabel={copy("techLog.action.savingPlain")}
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.saveHome")}
|
||||
</Button>
|
||||
<p className="studio-field-note">
|
||||
{nothingChosen
|
||||
? "지금은 아무것도 고르지 않아 홈에 이 영역이 나타나지 않습니다."
|
||||
: "저장하면 공개 홈에 바로 반영됩니다."}
|
||||
{" "}
|
||||
<GuardedStudioLink href="/studio/taxonomy">주제·프로젝트</GuardedStudioLink>
|
||||
<GuardedStudioLink href={studioRoutes.taxonomy()}>
|
||||
주제·프로젝트
|
||||
</GuardedStudioLink>
|
||||
에서 프로젝트를 만들고 게시할 수 있습니다.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
TextAreaControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { forwardRef, type KeyboardEvent, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
|
||||
|
||||
type BlockKind =
|
||||
@@ -164,6 +170,7 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
label: string;
|
||||
onChange(value: string): void;
|
||||
}>>(function MarkdownBlockEditor({ value, label, onChange }, ref) {
|
||||
const copy = useTechLogCopy();
|
||||
const parsed = useMemo(() => chunksOf(value).map(blockOf), [value]);
|
||||
const [blocks, setBlocks] = useState<MarkdownBlock[]>(() => parsed.length ? parsed : [blankBlock("paragraph")]);
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
@@ -251,7 +258,7 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
|
||||
return (
|
||||
<section className="studio-block-editor" aria-label={label}>
|
||||
<textarea className="studio-markdown-source" aria-hidden="true" tabIndex={-1} readOnly value={documentOf(blocks)} />
|
||||
<TextAreaControl className="studio-markdown-source" aria-hidden="true" tabIndex={-1} readOnly value={documentOf(blocks)} />
|
||||
<div className="studio-block-editor__blocks">
|
||||
{blocks.map((block, index) => (
|
||||
<div
|
||||
@@ -262,21 +269,21 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
onFocusCapture={() => setActiveIndex(index)}
|
||||
>
|
||||
<div className="studio-authoring-block__gutter" aria-label={`${kindLabel(block)} 블록 작업`}>
|
||||
<button type="button" className="studio-block-grip" title="블록 메뉴" onClick={() => setInsertMenu(insertMenu === index ? null : index)} aria-label={`${index + 1}번째 블록 메뉴`}>⋮⋮</button>
|
||||
<Button visualPolicy="inherit" type="button" className="studio-block-grip" title="블록 메뉴" onClick={() => setInsertMenu(insertMenu === index ? null : index)} aria-label={`${index + 1}번째 블록 메뉴`}>⋮⋮</Button>
|
||||
</div>
|
||||
<div className="studio-authoring-block__content">
|
||||
{block.kind === "divider" ? (
|
||||
<div className="studio-block-divider" role="separator" />
|
||||
) : block.kind === "code" ? (
|
||||
<div className="studio-code-authoring-block">
|
||||
<input
|
||||
<InputControl
|
||||
className="studio-code-language"
|
||||
aria-label={`${index + 1}번째 코드 언어`}
|
||||
value={block.language ?? ""}
|
||||
placeholder="language"
|
||||
onChange={(event) => replace(index, { ...block, language: event.currentTarget.value })}
|
||||
/>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
aria-label={`${index + 1}번째 코드`}
|
||||
value={block.content}
|
||||
spellCheck={false}
|
||||
@@ -288,7 +295,7 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
) : block.kind === "raw" ? (
|
||||
<div className="studio-raw-authoring-block">
|
||||
<span>{kindLabel(block)}</span>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
aria-label={`${index + 1}번째 ${kindLabel(block)}`}
|
||||
value={block.content}
|
||||
spellCheck={false}
|
||||
@@ -296,7 +303,7 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
className={`studio-block-input studio-block-input--${block.kind}`}
|
||||
aria-label={`${index + 1}번째 ${kindLabel(block)}`}
|
||||
rows={1}
|
||||
@@ -313,15 +320,15 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
)}
|
||||
</div>
|
||||
<div className="studio-authoring-block__actions" aria-label={`${index + 1}번째 블록 순서와 삭제`}>
|
||||
<button type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label="위로 이동">↑</button>
|
||||
<button type="button" onClick={() => move(index, 1)} disabled={index === blocks.length - 1} aria-label="아래로 이동">↓</button>
|
||||
<button type="button" onClick={() => remove(index)} aria-label="블록 삭제">삭제</button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label={copy("techLog.action.moveUp")}>↑</Button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => move(index, 1)} disabled={index === blocks.length - 1} aria-label={copy("techLog.action.moveDown")}>↓</Button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => remove(index)} aria-label={copy("techLog.action.deleteBlock")}>{copy("techLog.action.delete")}</Button>
|
||||
</div>
|
||||
{insertMenu === index ? (
|
||||
<div className="studio-slash-menu" role="menu" aria-label="블록 추가">
|
||||
<p>블록</p>
|
||||
{COMMANDS.map((command) => (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
key={command.kind}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@@ -329,14 +336,14 @@ export const MarkdownBlockEditor = forwardRef<MarkdownBlockEditorHandle, Readonl
|
||||
>
|
||||
<strong>{command.label}</strong>
|
||||
<span>{command.hint}</span>
|
||||
</button>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button className="studio-block-add" type="button" onClick={() => insert(blocks.length, blankBlock("paragraph"))}>+ 블록 추가</button>
|
||||
<Button visualPolicy="inherit" className="studio-block-add" type="button" onClick={() => insert(blocks.length, blankBlock("paragraph"))}>{copy("techLog.action.addBlock")}</Button>
|
||||
<p className="studio-block-editor__hint">빈 블록에서 <kbd>/</kbd> 를 입력하면 제목·목록·코드 같은 블록으로 바꿀 수 있습니다.</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { type RefObject } from "react";
|
||||
|
||||
/**
|
||||
@@ -82,7 +83,7 @@ export function MarkdownToolbar({
|
||||
return (
|
||||
<div className="studio-markdown-toolbar" role="group" aria-label="Markdown 삽입">
|
||||
{MARKDOWN_SNIPPETS.map((snippet) => (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
key={snippet.label}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
@@ -92,7 +93,7 @@ export function MarkdownToolbar({
|
||||
}}
|
||||
>
|
||||
{snippet.label}
|
||||
</button>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,12 +1,23 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { z } from "zod";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
useAppForm,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
import type {
|
||||
CreateDocumentInput,
|
||||
RecordKind,
|
||||
} from "../../../contracts/studio/contract.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import { useStudioWorkspaceCommands } from "../studio-workspace-server-state.ts";
|
||||
|
||||
/*
|
||||
이름은 `document-kind-labels.ts` 가 정한다. 여기서 따로 적던 동안 작업본 목록은 「검증 기록」,
|
||||
@@ -124,47 +135,28 @@ function emptyDocument(kind: RecordKind): CreateDocumentInput {
|
||||
};
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function NewDocumentForm() {
|
||||
const { gateway, navigateInternal, setRequestAnnouncement } = useStudio();
|
||||
const [kind, setKind] = useState<RecordKind>("CASE");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const locked = useRef(false);
|
||||
const activeRequest = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => () => activeRequest.current?.abort(), []);
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (locked.current) return;
|
||||
locked.current = true;
|
||||
setPending(true);
|
||||
setError("");
|
||||
const controller = new AbortController();
|
||||
activeRequest.current = controller;
|
||||
try {
|
||||
const document = await gateway.createDocument(emptyDocument(kind), {
|
||||
idempotencyKey: createLocalId("studio-create"),
|
||||
signal: controller.signal,
|
||||
});
|
||||
setRequestAnnouncement(
|
||||
`${types.find((type) => type.kind === kind)?.title} 작업본을 만들었습니다.`,
|
||||
);
|
||||
navigateInternal(`/studio/documents/${document.id}/edit`);
|
||||
} catch (reason) {
|
||||
if (!isAbortError(reason)) {
|
||||
setError("작업본을 만들지 못했습니다. 다시 시도해 주세요.");
|
||||
}
|
||||
} finally {
|
||||
if (activeRequest.current === controller) activeRequest.current = null;
|
||||
locked.current = false;
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
const copy = useTechLogCopy();
|
||||
const { navigateInternal, setRequestAnnouncement } = useStudio();
|
||||
const commands = useStudioWorkspaceCommands();
|
||||
const form = useAppForm({
|
||||
schema: z.object({
|
||||
kind: z.enum([
|
||||
"CASE",
|
||||
"REFERENCE",
|
||||
"CONCEPT",
|
||||
"SETUP",
|
||||
"QUESTION",
|
||||
"PROJECT_DECISION",
|
||||
]),
|
||||
}),
|
||||
defaultValues: { kind: "CASE" as RecordKind },
|
||||
allowedServerFields: ["kind"] as const,
|
||||
mapToCommand(values) {
|
||||
return { document: emptyDocument(values.kind) };
|
||||
},
|
||||
submit: commands.createDocument.submit,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="studio-page studio-new-page">
|
||||
@@ -175,21 +167,30 @@ export function NewDocumentForm() {
|
||||
목적에 맞는 기록 종류를 선택하면 빈 작업본을 만들고 바로 편집을 시작합니다.
|
||||
</p>
|
||||
</header>
|
||||
<form
|
||||
<Form
|
||||
pending={form.pending}
|
||||
onSubmit={(event) => {
|
||||
void submit(event);
|
||||
void (async () => {
|
||||
const result = await form.submitForm(event);
|
||||
if (!result?.ok) return;
|
||||
setRequestAnnouncement(
|
||||
(types.find((type) => type.kind === form.values.kind)?.title ??
|
||||
form.values.kind) + " 작업본을 만들었습니다.",
|
||||
);
|
||||
navigateInternal(studioRoutes.documentEdit(result.value.id));
|
||||
})();
|
||||
}}
|
||||
>
|
||||
<fieldset className="studio-type-list">
|
||||
<legend>문서 종류</legend>
|
||||
{types.map((type) => (
|
||||
<label key={type.kind}>
|
||||
<input
|
||||
<InputControl
|
||||
type="radio"
|
||||
name="kind"
|
||||
value={type.kind}
|
||||
checked={kind === type.kind}
|
||||
onChange={() => setKind(type.kind)}
|
||||
checked={form.values.kind === type.kind}
|
||||
onChange={() => form.setValue("kind", type.kind)}
|
||||
/>
|
||||
<strong>{type.title}</strong>
|
||||
<span>{type.description}</span>
|
||||
@@ -197,17 +198,25 @@ export function NewDocumentForm() {
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldId={form.fieldId}
|
||||
fieldLabels={{ kind: "문서 종류" }}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
<div className="studio-create-footer">
|
||||
<button className="studio-primary-button" type="submit" disabled={pending}>
|
||||
{pending ? "만드는 중…" : "작업본 만들기"}
|
||||
</button>
|
||||
<Button
|
||||
className="studio-primary-button"
|
||||
disabled={form.pending}
|
||||
pending={form.pending}
|
||||
pendingLabel={copy("techLog.action.creatingPlain")}
|
||||
type="submit"
|
||||
>
|
||||
{copy("techLog.action.createWorkingCopy")}
|
||||
</Button>
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
TextAreaControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
@@ -23,6 +28,7 @@ export function OrderedTextList({
|
||||
tone?: "fact" | "assumption" | "unknown" | "constraint" | "example" | "impact";
|
||||
onChange(items: OrderedText[]): void;
|
||||
}) {
|
||||
const copy = useTechLogCopy();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [draggingIndex, setDraggingIndex] = useState<number | null>(null);
|
||||
|
||||
@@ -48,13 +54,13 @@ export function OrderedTextList({
|
||||
<legend>
|
||||
<span>{label}</span>
|
||||
<span className="studio-block-collection__count">{items.length}</span>
|
||||
<button className="studio-ordered-list__toggle" type="button" aria-expanded={!collapsed} onClick={() => setCollapsed((current) => !current)}>
|
||||
{collapsed ? "펼치기" : "접기"}
|
||||
</button>
|
||||
<Button visualPolicy="inherit" className="studio-ordered-list__toggle" type="button" aria-expanded={!collapsed} onClick={() => setCollapsed((current) => !current)}>
|
||||
{collapsed ? copy("techLog.action.expand") : copy("techLog.action.collapse")}
|
||||
</Button>
|
||||
</legend>
|
||||
{collapsed ? null : (
|
||||
<>
|
||||
{items.length === 0 ? <p className="studio-block-collection__empty">아직 입력한 항목이 없습니다.</p> : null}
|
||||
{items.length === 0 ? <p className="studio-block-collection__empty">{copy("techLog.state.emptyOrderedText")}</p> : null}
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
className={`studio-ordered-item studio-list-block${draggingIndex === index ? " is-dragging" : ""}`}
|
||||
@@ -66,7 +72,7 @@ export function OrderedTextList({
|
||||
<span className="studio-list-block__index" aria-hidden="true">{String(index + 1).padStart(2, "0")}</span>
|
||||
<label>
|
||||
<span className="studio-visually-hidden">{label} {index + 1}</span>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
id={fieldId ? `${fieldId}-${index}-text` : undefined}
|
||||
aria-label={`${label} ${index + 1}`}
|
||||
value={item.text}
|
||||
@@ -75,13 +81,13 @@ export function OrderedTextList({
|
||||
/>
|
||||
</label>
|
||||
<div className="studio-item-actions">
|
||||
<button type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label="위로">↑</button>
|
||||
<button type="button" onClick={() => move(index, 1)} disabled={index === items.length - 1} aria-label="아래로">↓</button>
|
||||
<button type="button" onClick={() => onChange(ordered(items.filter((_, candidateIndex) => candidateIndex !== index)))}>삭제</button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => move(index, -1)} disabled={index === 0} aria-label={copy("techLog.action.moveUp")}>↑</Button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => move(index, 1)} disabled={index === items.length - 1} aria-label={copy("techLog.action.moveDown")}>↓</Button>
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => onChange(ordered(items.filter((_, candidateIndex) => candidateIndex !== index)))}>{copy("techLog.action.delete")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button className="studio-add-item" aria-label={`${label} 추가`} type="button" disabled={items.length >= 50} onClick={() => { if (items.length < 50) onChange(ordered([...items, { id: createNewItemId(), text: "", order: items.length }])); }}>+ {label}</button>
|
||||
<Button visualPolicy="inherit" className="studio-add-item" aria-label={`${label} 추가`} type="button" disabled={items.length >= 50} onClick={() => { if (items.length < 50) onChange(ordered([...items, { id: createNewItemId(), text: "", order: items.length }])); }}>+ {label}</Button>
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Button, InputControl, TextAreaControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
|
||||
import { OrderedTextList } from "./ordered-text-list.tsx";
|
||||
@@ -12,12 +13,12 @@ export function ProjectDecisionFields({ draft, issues, onChange }: { draft: Proj
|
||||
<div className="studio-editor-section-heading"><p className="studio-eyebrow">PROJECT DECISION</p><h2 id="studio-project-decision-fields-title">프로젝트 결정</h2><p>선택 자체보다 왜 그렇게 결정했는지와 남는 영향을 함께 기록합니다.</p></div>
|
||||
|
||||
<div className="studio-decision-properties">
|
||||
<fieldset className="studio-inline-choice" aria-label="결정 상태"><legend>상태</legend>{([ [null,"미정"], ["PROPOSED","PROPOSED"], ["ADOPTED","ADOPTED"] ] as const).map(([value,label]) => <button key={label} type="button" aria-pressed={draft.decisionStatus===value || (!draft.decisionStatus&&value===null)} onClick={() => update({ decisionStatus: value })}>{label}</button>)}<FieldNotice issues={issues} path="/decisionStatus" /></fieldset>
|
||||
<label className="studio-inline-property studio-inline-property--date"><span>결정일</span><input aria-label="결정일" type="date" value={draft.decidedOn ?? ""} onChange={(event) => update({ decidedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/decidedOn" /></label>
|
||||
<fieldset className="studio-inline-choice" aria-label="결정 상태"><legend>상태</legend>{([ [null,"미정"], ["PROPOSED","PROPOSED"], ["ADOPTED","ADOPTED"] ] as const).map(([value,label]) => <Button visualPolicy="inherit" key={label} type="button" aria-pressed={draft.decisionStatus===value || (!draft.decisionStatus&&value===null)} onClick={() => update({ decisionStatus: value })}>{label}</Button>)}<FieldNotice issues={issues} path="/decisionStatus" /></fieldset>
|
||||
<label className="studio-inline-property studio-inline-property--date"><span>결정일</span><InputControl aria-label="결정일" type="date" value={draft.decidedOn ?? ""} onChange={(event) => update({ decidedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/decidedOn" /></label>
|
||||
</div>
|
||||
|
||||
<label className="studio-document-block" data-tone="decision"><span className="studio-document-block__label">결정문</span><textarea aria-label="결정문" value={draft.statement} placeholder="무엇을 선택했는지 단정적으로 적어 주세요." onChange={(event) => update({ statement: event.currentTarget.value })} /><FieldNotice issues={issues} path="/statement" /></label>
|
||||
<label className="studio-document-block" data-tone="rationale"><span className="studio-document-block__label">판단 이유</span><textarea aria-label="판단 이유" value={draft.rationale} placeholder="어떤 근거와 제약 때문에 이 선택을 했는지 적어 주세요." onChange={(event) => update({ rationale: event.currentTarget.value })} /><FieldNotice issues={issues} path="/rationale" /></label>
|
||||
<label className="studio-document-block" data-tone="decision"><span className="studio-document-block__label">결정문</span><TextAreaControl aria-label="결정문" value={draft.statement} placeholder="무엇을 선택했는지 단정적으로 적어 주세요." onChange={(event) => update({ statement: event.currentTarget.value })} /><FieldNotice issues={issues} path="/statement" /></label>
|
||||
<label className="studio-document-block" data-tone="rationale"><span className="studio-document-block__label">판단 이유</span><TextAreaControl aria-label="판단 이유" value={draft.rationale} placeholder="어떤 근거와 제약 때문에 이 선택을 했는지 적어 주세요." onChange={(event) => update({ rationale: event.currentTarget.value })} /><FieldNotice issues={issues} path="/rationale" /></label>
|
||||
<OrderedTextList label="영향" tone="impact" fieldId="studio-field-consequences" items={draft.consequences} onChange={(consequences) => update({ consequences })} />
|
||||
<FieldNotice issues={issues} path="/consequences" />
|
||||
</section>
|
||||
|
||||
@@ -1,92 +1,29 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { PROJECT_PHASE_LABELS } from "../../../domain/public/project-phase-labels.ts";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type {
|
||||
ProjectActivityResponse,
|
||||
ProjectEditResponse,
|
||||
TopicEdit,
|
||||
} from "../../../contracts/management/contract.ts";
|
||||
import { collectCatalog } from "../../../application/collect-catalog.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import { useRouteInput } from "../../../../../presentation/routes/route-input.tsx";
|
||||
import { PROJECT_ACTIVITY_TYPE_LABELS } from "../management-labels.ts";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Select,
|
||||
TextArea,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { slugFromName } from "./slug-from-name.ts";
|
||||
import { useSaveShortcut } from "./use-save-shortcut.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
|
||||
type CatalogEntry = components["schemas"]["CatalogEntry"];
|
||||
|
||||
/** 경로 파라미터는 `unknown` 으로 들어온다 — 라우터가 코덱을 통과시킨 값이라도 타입은 좁혀 써야 한다. */
|
||||
function routeId(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
import { useProjectEditorController } from "../controllers/use-project-editor-controller.ts";
|
||||
|
||||
/** `project_phase_check` 와 같은 집합이다 — 화면이 더 많은 값을 보여 주면 저장이 제약에서 터진다. */
|
||||
const PHASES = Object.entries(PROJECT_PHASE_LABELS).map(([value, label]) => ({ value, label }));
|
||||
|
||||
/** `project_activity_activity_type_check` 와 같은 집합이다. */
|
||||
const ACTIVITY_TYPES = [
|
||||
{ value: "MILESTONE_REACHED", label: "이정표 도달" },
|
||||
{ value: "PHASE_CHANGED", label: "단계 전환" },
|
||||
{ value: "QUESTION_OPENED", label: "질문 열림" },
|
||||
{ value: "QUESTION_RESOLVED", label: "질문 해결" },
|
||||
{ value: "DECISION_ACCEPTED", label: "결정 수락" },
|
||||
{ value: "CASE_PUBLISHED", label: "Case 게시" },
|
||||
{ value: "REFERENCE_PUBLISHED", label: "Reference 게시" },
|
||||
{ value: "PROJECT_PAUSED", label: "프로젝트 중단" },
|
||||
{ value: "PROJECT_RESUMED", label: "프로젝트 재개" },
|
||||
] as const;
|
||||
|
||||
const activityTypeLabel = (value: string) =>
|
||||
ACTIVITY_TYPES.find((type) => type.value === value)?.label ?? value;
|
||||
|
||||
/** `<input type="datetime-local">` 은 초와 시간대가 없는 지역 시각을 쓴다. */
|
||||
function toLocalInput(isoTimestamp: string): string {
|
||||
const value = new Date(isoTimestamp);
|
||||
if (Number.isNaN(value.getTime())) return "";
|
||||
const pad = (part: number) => String(part).padStart(2, "0");
|
||||
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}T${pad(
|
||||
value.getHours(),
|
||||
)}:${pad(value.getMinutes())}`;
|
||||
}
|
||||
|
||||
function fromLocalInput(value: string): string {
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? new Date().toISOString() : parsed.toISOString();
|
||||
}
|
||||
|
||||
type Draft = {
|
||||
name: string;
|
||||
slug: string;
|
||||
oneLinePurpose: string;
|
||||
thesis: string;
|
||||
purposeMarkdown: string;
|
||||
boundaryMarkdown: string;
|
||||
systemOverviewMarkdown: string;
|
||||
phase: string;
|
||||
currentObjective: string;
|
||||
nextStep: string;
|
||||
technologyLabels: string;
|
||||
topicIds: readonly string[];
|
||||
};
|
||||
|
||||
function toDraft(project: ProjectEditResponse): Draft {
|
||||
return {
|
||||
name: project.name,
|
||||
slug: project.slug ?? "",
|
||||
oneLinePurpose: project.oneLinePurpose ?? "",
|
||||
thesis: project.thesis ?? "",
|
||||
purposeMarkdown: project.purposeMarkdown ?? "",
|
||||
boundaryMarkdown: project.boundaryMarkdown ?? "",
|
||||
systemOverviewMarkdown: project.systemOverviewMarkdown ?? "",
|
||||
phase: project.phase,
|
||||
currentObjective: project.currentObjective ?? "",
|
||||
nextStep: project.nextStep ?? "",
|
||||
technologyLabels: (project.technologyLabels ?? []).join(", "),
|
||||
topicIds: project.topicIds ?? [],
|
||||
};
|
||||
}
|
||||
/** 허용 값은 generated management contract가 소유하고, 이 화면은 한국어 표현만 소유한다. */
|
||||
const activityTypeLabel = (
|
||||
value: keyof typeof PROJECT_ACTIVITY_TYPE_LABELS,
|
||||
) => PROJECT_ACTIVITY_TYPE_LABELS[value];
|
||||
|
||||
/**
|
||||
* 프로젝트 한 편의 편집 화면.
|
||||
@@ -102,120 +39,22 @@ function toDraft(project: ProjectEditResponse): Draft {
|
||||
* 목록의 행 클래스를 그대로 쓰므로 Studio 의 나머지와 같은 간격·타이포·색을 따른다.
|
||||
*/
|
||||
export function ProjectEditor() {
|
||||
const { params } = useRouteInput<"TECH_LOG_STUDIO_PROJECT_EDIT">();
|
||||
const projectId = routeId(params.id);
|
||||
const { gateway, managementGateway, setRequestAnnouncement } = useStudio();
|
||||
|
||||
const [project, setProject] = useState<ProjectEditResponse | null>(null);
|
||||
const [topics, setTopics] = useState<TopicEdit[]>([]);
|
||||
const [records, setRecords] = useState<CatalogEntry[]>([]);
|
||||
const [activities, setActivities] = useState<ProjectActivityResponse[]>([]);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [generation, setGeneration] = useState(0);
|
||||
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// 동기적으로 던지는 호출도 잡는다 — `home-focus-editor` 와 같은 이유다.
|
||||
void (async () => {
|
||||
try {
|
||||
const [loaded, activityList, topicList, catalog] = await Promise.all([
|
||||
managementGateway.getProject(projectId),
|
||||
managementGateway.listProjectActivities(projectId),
|
||||
managementGateway.listTopics(),
|
||||
collectCatalog(gateway, { type: "RELATION" }),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
setProject(loaded);
|
||||
setDraft(toDraft(loaded));
|
||||
setActivities(activityList);
|
||||
setTopics(topicList.filter((topic) => topic.status !== "ARCHIVED"));
|
||||
setRecords(catalog);
|
||||
setError("");
|
||||
} catch {
|
||||
if (!cancelled) setError("프로젝트를 불러오지 못했습니다.");
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [gateway, managementGateway, projectId, generation]);
|
||||
|
||||
const update = (patch: Partial<Draft>) =>
|
||||
setDraft((current) => (current ? { ...current, ...patch } : current));
|
||||
|
||||
const toggleTopic = (topicId: string) =>
|
||||
setDraft((current) => {
|
||||
if (!current) return current;
|
||||
const chosen = current.topicIds.includes(topicId)
|
||||
? current.topicIds.filter((id) => id !== topicId)
|
||||
: [...current.topicIds, topicId];
|
||||
return { ...current, topicIds: chosen };
|
||||
});
|
||||
|
||||
const save = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pending || !project || !draft) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
/*
|
||||
slug 는 공개 주소다. 비워 두면 게시할 수 없으므로 이름에서 만들어 채운다 — 예전에는 조용히
|
||||
빈 값으로 저장되었고, 게시할 때가 되어서야 "slug 가 없다" 는 말을 들었다.
|
||||
*/
|
||||
const saved = await managementGateway.updateProject(project.id, {
|
||||
expectedVersion: project.version,
|
||||
name: draft.name.trim(),
|
||||
slug: draft.slug.trim() || slugFromName(draft.name),
|
||||
oneLinePurpose: draft.oneLinePurpose,
|
||||
thesis: draft.thesis,
|
||||
purposeMarkdown: draft.purposeMarkdown,
|
||||
boundaryMarkdown: draft.boundaryMarkdown,
|
||||
systemOverviewMarkdown: draft.systemOverviewMarkdown,
|
||||
phase: draft.phase,
|
||||
currentObjective: draft.currentObjective,
|
||||
nextStep: draft.nextStep,
|
||||
technologyLabels: draft.technologyLabels
|
||||
.split(",")
|
||||
.map((label) => label.trim())
|
||||
.filter(Boolean),
|
||||
topicIds: [...draft.topicIds],
|
||||
targetVisibility:
|
||||
project.targetVisibility === "PUBLIC" || project.targetVisibility === "UNLISTED"
|
||||
? project.targetVisibility
|
||||
: "PRIVATE",
|
||||
featuredOrder: project.featuredOrder,
|
||||
});
|
||||
/*
|
||||
이미 공개된 프로젝트라면 공개 투영도 함께 세워야 한다. 투영은 게시할 때 만들어지므로 저장만
|
||||
하면 공개 화면에는 예전 값이 남는다.
|
||||
*/
|
||||
if (saved.targetVisibility !== "PRIVATE") {
|
||||
await managementGateway.publishProject(
|
||||
saved.id,
|
||||
saved.version,
|
||||
saved.targetVisibility === "UNLISTED" ? "UNLISTED" : "PUBLIC",
|
||||
);
|
||||
}
|
||||
setRequestAnnouncement(`프로젝트를 버전 ${saved.version}으로 저장했습니다.`);
|
||||
reload();
|
||||
} catch (failure) {
|
||||
setError(managementFailureMessage(failure, "프로젝트를 저장하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 폼 제출과 같은 일을 하므로 submit 이벤트를 만들어 보낸다 — 검증·기본값 처리가 한 곳에 남는다.
|
||||
useSaveShortcut(
|
||||
() => void save({ preventDefault: () => {} } as FormEvent),
|
||||
Boolean(project && draft) && !pending,
|
||||
);
|
||||
|
||||
const published = project ? project.targetVisibility !== "PRIVATE" : false;
|
||||
const copy = useTechLogCopy();
|
||||
const {
|
||||
activities,
|
||||
draft,
|
||||
form,
|
||||
loadError,
|
||||
loading,
|
||||
pending,
|
||||
project,
|
||||
published,
|
||||
records,
|
||||
save,
|
||||
toggleTopic,
|
||||
topics,
|
||||
update,
|
||||
} = useProjectEditorController();
|
||||
|
||||
return (
|
||||
<div className="studio-page studio-editor-page">
|
||||
@@ -230,25 +69,23 @@ export function ProjectEditor() {
|
||||
그대로 읽습니다.
|
||||
</p>
|
||||
</div>
|
||||
<GuardedStudioLink className="studio-primary-action" href="/studio/taxonomy">
|
||||
<GuardedStudioLink className="studio-primary-action" href={studioRoutes.taxonomy()}>
|
||||
주제·프로젝트로
|
||||
</GuardedStudioLink>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
{loadError ? (
|
||||
<p className="studio-screen-error" role="alert">{loadError}</p>
|
||||
) : null}
|
||||
{!project && !error ? (
|
||||
{loading ? (
|
||||
<p className="studio-loading" role="status">
|
||||
프로젝트를 불러오는 중입니다.
|
||||
{copy("techLog.state.projectLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{project && draft ? (
|
||||
{project ? (
|
||||
<>
|
||||
<form onSubmit={save}>
|
||||
<Form pending={pending} onSubmit={save}>
|
||||
<section
|
||||
className="studio-editor-section"
|
||||
aria-labelledby="studio-project-basics-title"
|
||||
@@ -259,81 +96,85 @@ export function ProjectEditor() {
|
||||
<p>목록과 카드에 그대로 나가는 값입니다.</p>
|
||||
</div>
|
||||
<div className="studio-field-grid">
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>이름</span>
|
||||
<input
|
||||
value={draft.name}
|
||||
maxLength={120}
|
||||
onChange={(event) => update({ name: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>slug</span>
|
||||
<input
|
||||
value={draft.slug}
|
||||
maxLength={100}
|
||||
placeholder="비우면 이름에서 만듭니다"
|
||||
onChange={(event) => update({ slug: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>단계</span>
|
||||
<select
|
||||
value={draft.phase}
|
||||
onChange={(event) => update({ phase: event.currentTarget.value })}
|
||||
>
|
||||
{PHASES.map((phase) => (
|
||||
<option key={phase.value} value={phase.value}>
|
||||
{phase.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>한 줄 목적</span>
|
||||
<input
|
||||
value={draft.oneLinePurpose}
|
||||
maxLength={200}
|
||||
onChange={(event) => update({ oneLinePurpose: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
{/*
|
||||
목적은 시작할 때 쓰는 글이고 논지는 끝나고 쓰는 글이다. 담을 칸이 없어 공개
|
||||
화면은 목적을 대신 보여 줬고, 그래서 프로젝트 화면에는 늘 시작할 때의 말만
|
||||
남았다.
|
||||
*/}
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>논지 — 프로젝트를 통해 확인한 결과</span>
|
||||
<textarea
|
||||
value={draft.thesis}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="공개 프로젝트 화면의 첫 문단입니다. 비우면 한 줄 목적이 대신 나갑니다."
|
||||
onChange={(event) => update({ thesis: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>현재 목표</span>
|
||||
<input
|
||||
value={draft.currentObjective}
|
||||
onChange={(event) => update({ currentObjective: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>다음 작업</span>
|
||||
<input
|
||||
value={draft.nextStep}
|
||||
onChange={(event) => update({ nextStep: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>기술 라벨</span>
|
||||
<input
|
||||
value={draft.technologyLabels}
|
||||
placeholder="쉼표로 구분합니다"
|
||||
onChange={(event) => update({ technologyLabels: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<TextField
|
||||
className="studio-field studio-field--wide"
|
||||
label="이름"
|
||||
id={form.fieldId("name")}
|
||||
error={form.fieldErrors.name}
|
||||
maxLength={120}
|
||||
value={draft.name}
|
||||
onChange={(event) => update({ name: event.currentTarget.value })}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="slug"
|
||||
id={form.fieldId("slug")}
|
||||
error={form.fieldErrors.slug}
|
||||
maxLength={100}
|
||||
placeholder="비우면 이름에서 만듭니다"
|
||||
value={draft.slug}
|
||||
onChange={(event) => update({ slug: event.currentTarget.value })}
|
||||
/>
|
||||
<Select
|
||||
className="studio-field"
|
||||
label="단계"
|
||||
id={form.fieldId("phase")}
|
||||
error={form.fieldErrors.phase}
|
||||
options={PHASES}
|
||||
value={draft.phase}
|
||||
onChange={(event) => update({ phase: event.currentTarget.value })}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field studio-field--wide"
|
||||
label="한 줄 목적"
|
||||
id={form.fieldId("oneLinePurpose")}
|
||||
error={form.fieldErrors.oneLinePurpose}
|
||||
maxLength={200}
|
||||
value={draft.oneLinePurpose}
|
||||
onChange={(event) =>
|
||||
update({ oneLinePurpose: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
<TextArea
|
||||
className="studio-field studio-field--wide"
|
||||
label="논지 — 프로젝트를 통해 확인한 결과"
|
||||
id={form.fieldId("thesis")}
|
||||
error={form.fieldErrors.thesis}
|
||||
maxLength={2000}
|
||||
placeholder="공개 프로젝트 화면의 첫 문단입니다. 비우면 한 줄 목적이 대신 나갑니다."
|
||||
rows={3}
|
||||
value={draft.thesis}
|
||||
onChange={(event) => update({ thesis: event.currentTarget.value })}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="현재 목표"
|
||||
id={form.fieldId("currentObjective")}
|
||||
error={form.fieldErrors.currentObjective}
|
||||
value={draft.currentObjective}
|
||||
onChange={(event) =>
|
||||
update({ currentObjective: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="다음 작업"
|
||||
id={form.fieldId("nextStep")}
|
||||
error={form.fieldErrors.nextStep}
|
||||
value={draft.nextStep}
|
||||
onChange={(event) => update({ nextStep: event.currentTarget.value })}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field studio-field--wide"
|
||||
label="기술 라벨"
|
||||
id={form.fieldId("technologyLabels")}
|
||||
error={form.fieldErrors.technologyLabels}
|
||||
placeholder="쉼표로 구분합니다"
|
||||
value={draft.technologyLabels}
|
||||
onChange={(event) =>
|
||||
update({ technologyLabels: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -355,22 +196,22 @@ export function ProjectEditor() {
|
||||
</p>
|
||||
</div>
|
||||
{topics.length === 0 ? (
|
||||
<p className="studio-empty-inline">
|
||||
아직 주제가 없습니다. 주제·프로젝트 화면에서 먼저 만듭니다.
|
||||
</p>
|
||||
<p className="studio-empty-inline">{copy("techLog.state.projectTopicsEmpty")}</p>
|
||||
) : (
|
||||
<ul className="studio-choice-list">
|
||||
<ul
|
||||
className="studio-choice-list"
|
||||
id={form.fieldId("topicIds")}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{topics.map((topic) => (
|
||||
<li key={topic.id}>
|
||||
<label className="studio-choice">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.topicIds.includes(topic.id ?? "")}
|
||||
onChange={() => toggleTopic(topic.id ?? "")}
|
||||
/>
|
||||
<span>{topic.name}</span>
|
||||
<small>{topic.slug}</small>
|
||||
</label>
|
||||
<Checkbox
|
||||
checked={draft.topicIds.includes(topic.id ?? "")}
|
||||
description={topic.slug}
|
||||
fieldClassName="studio-choice"
|
||||
label={topic.name}
|
||||
onChange={() => toggleTopic(topic.id ?? "")}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -397,29 +238,58 @@ export function ProjectEditor() {
|
||||
때 서버가 가진 값을 그대로 돌려보내므로 지워지지 않는다.
|
||||
*/}
|
||||
<div className="studio-field-grid">
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>목적</span>
|
||||
<textarea
|
||||
className="studio-markdown"
|
||||
value={draft.purposeMarkdown}
|
||||
onChange={(event) => update({ purposeMarkdown: event.currentTarget.value })}
|
||||
/>
|
||||
<small>마크다운을 씁니다.</small>
|
||||
</label>
|
||||
<TextArea
|
||||
className="studio-field studio-field--wide"
|
||||
controlClassName="studio-markdown"
|
||||
description="마크다운을 씁니다."
|
||||
label="목적"
|
||||
id={form.fieldId("purposeMarkdown")}
|
||||
error={form.fieldErrors.purposeMarkdown}
|
||||
value={draft.purposeMarkdown}
|
||||
onChange={(event) =>
|
||||
update({ purposeMarkdown: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldId={form.fieldId}
|
||||
fieldLabels={{
|
||||
name: "이름",
|
||||
slug: "slug",
|
||||
oneLinePurpose: "한 줄 목적",
|
||||
thesis: "논지",
|
||||
purposeMarkdown: "목적",
|
||||
phase: "단계",
|
||||
currentObjective: "현재 목표",
|
||||
nextStep: "다음 작업",
|
||||
technologyLabels: "기술 라벨",
|
||||
topicIds: "주요 주제",
|
||||
}}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
|
||||
<div className="studio-editor-footer">
|
||||
<button className="studio-primary-button" type="submit" title="Ctrl+S" disabled={pending}>
|
||||
{pending ? "저장하는 중" : "저장"}
|
||||
</button>
|
||||
<Button
|
||||
className="studio-primary-button"
|
||||
disabled={pending}
|
||||
pending={pending}
|
||||
pendingLabel={copy("techLog.action.savingPlain")}
|
||||
title="Ctrl+S"
|
||||
type="submit"
|
||||
>
|
||||
{copy("techLog.action.save")}
|
||||
</Button>
|
||||
<p className="studio-field-note">
|
||||
{published
|
||||
? "공개된 프로젝트입니다. 저장하면 공개 화면도 함께 갱신됩니다."
|
||||
: "아직 비공개입니다. 주제·프로젝트 화면에서 게시해야 공개 화면에 나옵니다."}
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
<section
|
||||
className="studio-editor-section"
|
||||
@@ -434,9 +304,7 @@ export function ProjectEditor() {
|
||||
</div>
|
||||
|
||||
{activities.length === 0 ? (
|
||||
<p className="studio-empty-inline">
|
||||
아직 이 프로젝트에서 게시한 기록이 없습니다.
|
||||
</p>
|
||||
<p className="studio-empty-inline">{copy("techLog.state.noProjectPublishedRecords")}</p>
|
||||
) : (
|
||||
<div className="studio-document-list">
|
||||
{activities.map((activity) => (
|
||||
|
||||
@@ -1,34 +1,22 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useState } from "react";
|
||||
|
||||
import {
|
||||
isStudioGatewayError,
|
||||
type StudioGatewayError,
|
||||
} from "../../../application/ports/studio-gateway-error.ts";
|
||||
import type {
|
||||
PreviewDetail,
|
||||
WorkingCopyDetail,
|
||||
} from "../../../contracts/studio/contract.ts";
|
||||
import type { WorkingCopyDetail } from "../../../contracts/studio/contract.ts";
|
||||
import { deriveValidationState } from "../../../domain/studio/document-state.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import {
|
||||
bodyBlocksOf,
|
||||
createResolvedAssetResolver,
|
||||
} from "../../shared/public-render/asset-resolvers.ts";
|
||||
import { PublicRecordRenderer } from "../../shared/public-render/public-record-renderer.tsx";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import {
|
||||
useStudioCurrentPreviewQuery,
|
||||
useStudioDocumentCommands,
|
||||
useStudioDocumentQuery,
|
||||
} from "../studio-document-server-state.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
|
||||
type LoadedPreview = {
|
||||
detail: WorkingCopyDetail;
|
||||
preview: PreviewDetail | null;
|
||||
};
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return typeof error === "object" &&
|
||||
error !== null &&
|
||||
"name" in error &&
|
||||
error.name === "AbortError";
|
||||
}
|
||||
import { useStudioFailureMessage, useTechLogCopy } from "../studio-copy.ts";
|
||||
|
||||
function usableValidation(detail: WorkingCopyDetail, now: Date) {
|
||||
const validation = detail.currentValidation;
|
||||
@@ -50,98 +38,56 @@ function formatDateTime(value: string): string {
|
||||
}
|
||||
|
||||
export function PublicPreviewScreen({ documentId }: { documentId: string }) {
|
||||
const copy = useTechLogCopy();
|
||||
const studioFailureMessage = useStudioFailureMessage();
|
||||
const studio = useStudio();
|
||||
const [retryKey, setRetryKey] = useState(0);
|
||||
const [loaded, setLoaded] = useState<LoadedPreview | null>(null);
|
||||
const [problem, setProblem] = useState<StudioGatewayError | Error | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const documentQuery = useStudioDocumentQuery(documentId);
|
||||
const previewQuery = useStudioCurrentPreviewQuery(documentId);
|
||||
const commands = useStudioDocumentCommands();
|
||||
const [feedback, setFeedback] = useState("");
|
||||
const sequence = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const request = new AbortController();
|
||||
void Promise.all([
|
||||
studio.gateway.getDocument(documentId, { signal: request.signal }),
|
||||
studio.gateway.getCurrentPreview(
|
||||
documentId,
|
||||
{ signal: request.signal },
|
||||
).catch((error: unknown) => {
|
||||
if (
|
||||
isStudioGatewayError(error) &&
|
||||
error.code === "PREVIEW_NOT_FOUND"
|
||||
) return null;
|
||||
throw error;
|
||||
}),
|
||||
]).then(
|
||||
([detail, preview]) => {
|
||||
if (request.signal.aborted) return;
|
||||
setLoaded({ detail, preview });
|
||||
setLoading(false);
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (request.signal.aborted || isAbortError(error)) return;
|
||||
setProblem(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Public Preview를 불러오지 못했습니다."),
|
||||
);
|
||||
setLoading(false);
|
||||
},
|
||||
);
|
||||
return () => request.abort();
|
||||
}, [documentId, retryKey, studio.gateway]);
|
||||
const detail = documentQuery.data ?? null;
|
||||
const previewDetail = previewQuery.data ?? null;
|
||||
const creating = commands.createPreview.state.overlay.mutationPending;
|
||||
const loading =
|
||||
documentQuery.state.base === "initial-loading" ||
|
||||
previewQuery.state.base === "initial-loading";
|
||||
const documentProblem = documentQuery.state.failure;
|
||||
const previewProblem = previewQuery.state.failure;
|
||||
|
||||
const retry = () => {
|
||||
setLoading(true);
|
||||
setProblem(null);
|
||||
setRetryKey((value) => value + 1);
|
||||
const retry = async () => {
|
||||
setFeedback("");
|
||||
await Promise.all([documentQuery.retry(), previewQuery.retry()]);
|
||||
};
|
||||
|
||||
const createPreview = async () => {
|
||||
if (!loaded || creating) return;
|
||||
const validation = usableValidation(loaded.detail, studio.now());
|
||||
if (!detail || creating) return;
|
||||
const validation = usableValidation(detail, studio.now());
|
||||
if (!validation) return;
|
||||
setCreating(true);
|
||||
|
||||
setFeedback("");
|
||||
try {
|
||||
const preview = await studio.gateway.createPreview(
|
||||
documentId,
|
||||
{
|
||||
expectedVersion: loaded.detail.document.version,
|
||||
validationId: validation.validationId,
|
||||
},
|
||||
{
|
||||
idempotencyKey: createLocalId(
|
||||
`studio-preview-${++sequence.current}`,
|
||||
),
|
||||
},
|
||||
);
|
||||
setLoaded((current) => current
|
||||
? {
|
||||
...current,
|
||||
preview: {
|
||||
preview,
|
||||
state: "CURRENT",
|
||||
currentDocumentVersion: current.detail.document.version,
|
||||
currentValidationId: validation.validationId,
|
||||
},
|
||||
}
|
||||
: current);
|
||||
setFeedback("Public Preview를 만들었습니다.");
|
||||
studio.setRequestAnnouncement(
|
||||
"현재 저장 버전의 Public Preview를 만들었습니다.",
|
||||
);
|
||||
} catch (error) {
|
||||
if (isAbortError(error)) return;
|
||||
const result = await commands.createPreview.submit({
|
||||
documentId,
|
||||
command: {
|
||||
expectedVersion: detail.document.version,
|
||||
validationId: validation.validationId,
|
||||
},
|
||||
});
|
||||
if (!result.ok) {
|
||||
setFeedback(
|
||||
isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "Public Preview를 만들지 못했습니다. 다시 시도해 주세요.",
|
||||
studioFailureMessage(
|
||||
result.error,
|
||||
copy("techLog.failure.previewRetry"),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setCreating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await previewQuery.retry();
|
||||
setFeedback("Public Preview를 만들었습니다.");
|
||||
studio.setRequestAnnouncement(
|
||||
copy("techLog.notice.previewCreated"),
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
@@ -151,70 +97,82 @@ export function PublicPreviewScreen({ documentId }: { documentId: string }) {
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (
|
||||
problem &&
|
||||
isStudioGatewayError(problem) &&
|
||||
problem.code === "DOCUMENT_NOT_FOUND"
|
||||
) {
|
||||
|
||||
if (documentProblem?.code === "DOCUMENT_NOT_FOUND") {
|
||||
return (
|
||||
<section className="studio-route-state">
|
||||
<p className="studio-eyebrow">404</p>
|
||||
<h1>작업본을 찾을 수 없습니다</h1>
|
||||
<p>이 작업본은 현재 Studio 세션에 없습니다.</p>
|
||||
<GuardedStudioLink href="/studio/documents">
|
||||
<h1>{copy("techLog.state.documentNotFound")}</h1>
|
||||
<p>{copy("techLog.state.sessionDocumentMissing")}</p>
|
||||
<GuardedStudioLink href={studioRoutes.documents()}>
|
||||
작업본으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (problem || !loaded) {
|
||||
|
||||
if (
|
||||
documentQuery.state.base === "terminal-error" ||
|
||||
previewQuery.state.base === "terminal-error" ||
|
||||
!detail
|
||||
) {
|
||||
const problem = documentProblem ?? previewProblem;
|
||||
return (
|
||||
<section className="studio-route-state" role="alert">
|
||||
<p className="studio-eyebrow">PREVIEW ERROR</p>
|
||||
<h1>Public Preview를 불러오지 못했습니다</h1>
|
||||
<h1>{copy("techLog.state.publicPreviewLoadFailed")}</h1>
|
||||
<p>
|
||||
{problem && isStudioGatewayError(problem)
|
||||
? problem.problem.detail
|
||||
: problem?.message}
|
||||
{studioFailureMessage(
|
||||
problem,
|
||||
"",
|
||||
)}
|
||||
</p>
|
||||
<button type="button" onClick={retry}>다시 시도</button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void retry();
|
||||
}}
|
||||
>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const validation = usableValidation(loaded.detail, studio.now());
|
||||
const previewDetail = loaded.preview;
|
||||
const validation = usableValidation(detail, studio.now());
|
||||
const state = previewDetail?.state ?? "NONE";
|
||||
const message = state === "CURRENT"
|
||||
? "현재 저장 버전의 Public Preview입니다."
|
||||
: state === "STALE"
|
||||
? "저장본보다 이전에 만든 Public Preview입니다."
|
||||
: state === "EXPIRED"
|
||||
? "이 Public Preview는 만료되었습니다."
|
||||
: "아직 만든 Public Preview가 없습니다";
|
||||
const canCreate = Boolean(validation) &&
|
||||
state !== "CURRENT" &&
|
||||
state !== "EXPIRED";
|
||||
const message =
|
||||
state === "CURRENT"
|
||||
? "현재 저장 버전의 Public Preview입니다."
|
||||
: state === "STALE"
|
||||
? "저장본보다 이전에 만든 Public Preview입니다."
|
||||
: state === "EXPIRED"
|
||||
? "이 Public Preview는 만료되었습니다."
|
||||
: "아직 만든 Public Preview가 없습니다";
|
||||
const canCreate =
|
||||
Boolean(validation) && state !== "CURRENT" && state !== "EXPIRED";
|
||||
|
||||
return (
|
||||
<div className="studio-preview-screen">
|
||||
<header
|
||||
className={`studio-preview-toolbar ${previewDetail ? "studio-preview-toolbar--compact" : ""}`}
|
||||
className={`studio-preview-toolbar ${
|
||||
previewDetail ? "studio-preview-toolbar--compact" : ""
|
||||
}`}
|
||||
>
|
||||
<div>
|
||||
<p className="studio-eyebrow">
|
||||
PUBLIC PREVIEW · VERSION {loaded.detail.document.version}
|
||||
PUBLIC PREVIEW · VERSION {detail.document.version}
|
||||
</p>
|
||||
{previewDetail ? (
|
||||
<p className="studio-preview-title">Public Preview</p>
|
||||
) : (
|
||||
<h1>Public Preview</h1>
|
||||
)}
|
||||
<p>{loaded.detail.document.title}</p>
|
||||
<p>{detail.document.title}</p>
|
||||
</div>
|
||||
<GuardedStudioLink
|
||||
className="studio-workflow-quiet-link"
|
||||
href={`/studio/documents/${documentId}/validation`}
|
||||
href={studioRoutes.documentValidation(documentId)}
|
||||
>
|
||||
검증 결과 보기
|
||||
</GuardedStudioLink>
|
||||
@@ -224,12 +182,17 @@ export function PublicPreviewScreen({ documentId }: { documentId: string }) {
|
||||
className={`studio-preview-state studio-preview-state--${state.toLowerCase()}`}
|
||||
aria-label="Public Preview 상태"
|
||||
>
|
||||
<div><strong>{state}</strong><p>{message}</p></div>
|
||||
<div>
|
||||
<strong>{state}</strong>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="studio-workflow-actions">
|
||||
{canCreate ? (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => { void createPreview(); }}
|
||||
onClick={() => {
|
||||
void createPreview();
|
||||
}}
|
||||
disabled={creating}
|
||||
>
|
||||
{creating
|
||||
@@ -237,25 +200,30 @@ export function PublicPreviewScreen({ documentId }: { documentId: string }) {
|
||||
: state === "NONE"
|
||||
? "Public Preview 만들기"
|
||||
: "Public Preview 다시 만들기"}
|
||||
</button>
|
||||
</Button>
|
||||
) : null}
|
||||
{state === "CURRENT" ? (
|
||||
<GuardedStudioLink href={`/studio/documents/${documentId}/publish`}>
|
||||
<GuardedStudioLink href={studioRoutes.documentPublish(documentId)}>
|
||||
게시 준비로 이동
|
||||
</GuardedStudioLink>
|
||||
) : null}
|
||||
{!canCreate && state !== "CURRENT" ? (
|
||||
<GuardedStudioLink href={`/studio/documents/${documentId}/validation`}>
|
||||
<GuardedStudioLink
|
||||
href={studioRoutes.documentValidation(documentId)}
|
||||
>
|
||||
검증 화면으로 이동
|
||||
</GuardedStudioLink>
|
||||
) : null}
|
||||
<GuardedStudioLink href={`/studio/documents/${documentId}/edit`}>
|
||||
<GuardedStudioLink href={studioRoutes.documentEdit(documentId)}>
|
||||
편집으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{feedback ? (
|
||||
<p className="studio-workflow-feedback" role="status">{feedback}</p>
|
||||
<p className="studio-workflow-feedback" role="status">
|
||||
{feedback}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{previewDetail ? (
|
||||
@@ -287,24 +255,21 @@ export function PublicPreviewScreen({ documentId }: { documentId: string }) {
|
||||
</>
|
||||
) : (
|
||||
<section className="studio-workflow-empty-panel">
|
||||
{/*
|
||||
버튼이 없는 이유를 말한다.
|
||||
|
||||
검증 기록이 없으면 만들기 버튼이 나타나지 않는데, 화면은 "현재 검증 결과를 기준으로
|
||||
생성합니다" 라고만 적어 두었다 — 할 수 있는 일을 설명하면서 그 일을 할 자리는 주지
|
||||
않았고, 왜 없는지도 말하지 않았다. 작성자에게는 미리보기가 고장난 것으로 보인다.
|
||||
*/}
|
||||
{validation ? (
|
||||
<>
|
||||
<h2>공개 레이아웃을 아직 만들지 않았습니다</h2>
|
||||
<p>위의 「Public Preview 만들기」를 누르면 현재 검증 결과를 기준으로 만듭니다.</p>
|
||||
<p>
|
||||
위의 「Public Preview 만들기」를 누르면 현재 검증 결과를
|
||||
기준으로 만듭니다.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2>먼저 저장본을 검증해야 합니다</h2>
|
||||
<p>
|
||||
Public Preview 는 검증 결과를 기준으로 만듭니다. 검증 기록이 없으면 무엇을 기준으로
|
||||
그릴지 정할 수 없어 만들기가 열리지 않습니다.
|
||||
Public Preview 는 검증 결과를 기준으로 만듭니다. 검증 기록이
|
||||
없으면 무엇을 기준으로 그릴지 정할 수 없어 만들기가 열리지
|
||||
않습니다.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
+41
-61
@@ -1,10 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
|
||||
import {
|
||||
isStudioGatewayError,
|
||||
type StudioGatewayError,
|
||||
} from "../../../application/ports/studio-gateway-error.ts";
|
||||
import type { PublicationSnapshot } from "../../../contracts/studio/contract.ts";
|
||||
import {
|
||||
bodyBlocksOf,
|
||||
createResolvedAssetResolver,
|
||||
@@ -16,6 +13,8 @@ import {
|
||||
type PublicationFlowClasses,
|
||||
} from "./publication-flow-classes.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import { useStudioPublicationSnapshotQuery } from "../studio-workspace-server-state.ts";
|
||||
import { useStudioFailureMessage } from "../studio-copy.ts";
|
||||
|
||||
const eventLabels = {
|
||||
PUBLISHED: "게시",
|
||||
@@ -38,88 +37,65 @@ export function PublicationEventPreviewScreen({
|
||||
publicationEventId: string;
|
||||
classes?: PublicationFlowClasses;
|
||||
}) {
|
||||
const copy = useTechLogCopy();
|
||||
const studioFailureMessage = useStudioFailureMessage();
|
||||
const studio = useStudio();
|
||||
const { gateway } = studio;
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [state, setState] = useState<
|
||||
| { status: "LOADING" }
|
||||
| { status: "ERROR"; problem: StudioGatewayError | Error }
|
||||
| { status: "READY"; snapshot: PublicationSnapshot }
|
||||
>({ status: "LOADING" });
|
||||
const snapshotQuery =
|
||||
useStudioPublicationSnapshotQuery(publicationEventId);
|
||||
const snapshot = snapshotQuery.data ?? null;
|
||||
const problem = snapshotQuery.state.failure;
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let current = true;
|
||||
setState({ status: "LOADING" });
|
||||
void gateway
|
||||
.getPublicationSnapshot(publicationEventId, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(
|
||||
(snapshot) => {
|
||||
if (current) setState({ status: "READY", snapshot });
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (!current || controller.signal.aborted) return;
|
||||
setState({
|
||||
status: "ERROR",
|
||||
problem:
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Snapshot을 불러오지 못했습니다."),
|
||||
});
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [gateway, publicationEventId, retry]);
|
||||
|
||||
if (state.status === "LOADING") {
|
||||
if (snapshotQuery.state.base === "initial-loading") {
|
||||
return (
|
||||
<p className={styles.loading} role="status">
|
||||
게시 Snapshot을 불러오는 중입니다.
|
||||
{copy("techLog.state.publicationSnapshotLoading")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (state.status === "ERROR") {
|
||||
|
||||
if (snapshotQuery.state.base === "terminal-error" || !snapshot) {
|
||||
const missing =
|
||||
isStudioGatewayError(state.problem) &&
|
||||
(state.problem.code === "PUBLICATION_EVENT_NOT_FOUND" ||
|
||||
state.problem.code === "PUBLICATION_SNAPSHOT_NOT_FOUND");
|
||||
problem?.code === "PUBLICATION_EVENT_NOT_FOUND" ||
|
||||
problem?.code === "PUBLICATION_SNAPSHOT_NOT_FOUND";
|
||||
if (missing) {
|
||||
return (
|
||||
<section className={styles.routeState}>
|
||||
<p className={styles.eyebrow}>NOT FOUND</p>
|
||||
<h1>게시 기록을 찾을 수 없습니다</h1>
|
||||
<h1>{copy("techLog.state.publicationRecordNotFound")}</h1>
|
||||
<p>
|
||||
이 이벤트는 현재 Studio 세션에 없거나 Snapshot을 소유하지
|
||||
않습니다.
|
||||
</p>
|
||||
<GuardedStudioLink href="/studio/publications">
|
||||
<GuardedStudioLink href={studioRoutes.publications()}>
|
||||
게시 기록으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={styles.routeState} role="alert">
|
||||
<p className={styles.eyebrow}>SNAPSHOT ERROR</p>
|
||||
<h1>게시 Snapshot을 불러오지 못했습니다</h1>
|
||||
<h1>{copy("techLog.state.publicationSnapshotLoadFailed")}</h1>
|
||||
<p>
|
||||
{isStudioGatewayError(state.problem)
|
||||
? state.problem.problem.detail
|
||||
: state.problem.message}
|
||||
{studioFailureMessage(
|
||||
problem,
|
||||
copy("techLog.state.publicationSnapshotLoadFailed"),
|
||||
)}
|
||||
</p>
|
||||
<button type="button" onClick={() => setRetry((value) => value + 1)}>
|
||||
다시 시도
|
||||
</button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void snapshotQuery.retry();
|
||||
}}
|
||||
>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const { event, renderModel } = state.snapshot;
|
||||
const { event, renderModel } = snapshot;
|
||||
return (
|
||||
<div className={styles.snapshotPage}>
|
||||
<section
|
||||
@@ -128,7 +104,9 @@ export function PublicationEventPreviewScreen({
|
||||
>
|
||||
<div>
|
||||
<p className={styles.eyebrow}>IMMUTABLE SNAPSHOT</p>
|
||||
<p className={styles.snapshotTitle}>게시 이벤트 시점의 공개 화면</p>
|
||||
<p className={styles.snapshotTitle}>
|
||||
게시 이벤트 시점의 공개 화면
|
||||
</p>
|
||||
</div>
|
||||
<dl>
|
||||
<div>
|
||||
@@ -148,7 +126,7 @@ export function PublicationEventPreviewScreen({
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<GuardedStudioLink href="/studio/publications">
|
||||
<GuardedStudioLink href={studioRoutes.publications()}>
|
||||
게시 기록으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
@@ -156,7 +134,9 @@ export function PublicationEventPreviewScreen({
|
||||
<PublicRecordRenderer
|
||||
model={renderModel}
|
||||
embedded
|
||||
resolveEvidenceAsset={createResolvedAssetResolver(bodyBlocksOf(renderModel))}
|
||||
resolveEvidenceAsset={createResolvedAssetResolver(
|
||||
bodyBlocksOf(renderModel),
|
||||
)}
|
||||
resolvePublishedLabel={studio.resolvePublishedLabel}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import { type FormEvent, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
import {
|
||||
isStudioGatewayError,
|
||||
type StudioGatewayError,
|
||||
} from "../../../application/ports/studio-gateway-error.ts";
|
||||
import type { ListPublicationsQuery } from "../../../application/ports/studio-gateway.ts";
|
||||
import type {
|
||||
PublicationListItem,
|
||||
PublicationPage,
|
||||
} from "../../../contracts/studio/contract.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
Button,
|
||||
InputControl,
|
||||
SelectControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { type FormEvent, useMemo, useRef, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Form } from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
import type { ListPublicationsQuery } from "../../../application/studio-application.ts";
|
||||
import type { PublicationListItem } from "../../../contracts/studio/contract.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import {
|
||||
defaultPublicationFlowClasses,
|
||||
@@ -18,8 +16,14 @@ import {
|
||||
} from "./publication-flow-classes.ts";
|
||||
import { UnpublishDialog } from "./unpublish-dialog.tsx";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import {
|
||||
useStudioPublicationsQuery,
|
||||
useStudioWorkspaceCommands,
|
||||
} from "../studio-workspace-server-state.ts";
|
||||
import { StudioPagination } from "./studio-pagination.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { useStudioFailureMessage, useTechLogCopy } from "../studio-copy.ts";
|
||||
|
||||
const eventLabels = {
|
||||
PUBLISHED: "게시",
|
||||
@@ -40,10 +44,10 @@ function snapshotHref(item: PublicationListItem) {
|
||||
item.availableActions.includes("VIEW_SOURCE_SNAPSHOT") &&
|
||||
item.event.sourcePublishedEventId
|
||||
) {
|
||||
return `/studio/publications/${item.event.sourcePublishedEventId}/preview`;
|
||||
return studioRoutes.publicationPreview(item.event.sourcePublishedEventId);
|
||||
}
|
||||
if (item.availableActions.includes("VIEW_SNAPSHOT")) {
|
||||
return `/studio/publications/${item.event.publicationEventId}/preview`;
|
||||
return studioRoutes.publicationPreview(item.event.publicationEventId);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -54,6 +58,8 @@ const EVENT_TYPES = Object.freeze(["PUBLISHED", "REPUBLISHED", "UNPUBLISHED"] as
|
||||
export function PublicationList({
|
||||
classes: styles = defaultPublicationFlowClasses,
|
||||
}: { classes?: PublicationFlowClasses } = {}) {
|
||||
const copy = useTechLogCopy();
|
||||
const studioFailureMessage = useStudioFailureMessage();
|
||||
const studio = useStudio();
|
||||
/*
|
||||
작업본 목록과 같은 규칙으로 상태를 주소에 담는다. 담지 않던 동안 게시 기록에서 Snapshot 을
|
||||
@@ -85,45 +91,15 @@ export function PublicationList({
|
||||
if (merged.page && merged.page > 1) params.set("page", String(merged.page));
|
||||
setSearchParams(params);
|
||||
};
|
||||
const [reload, setReload] = useState(0);
|
||||
const [state, setState] = useState<
|
||||
| { status: "LOADING" }
|
||||
| { status: "ERROR"; problem: StudioGatewayError | Error }
|
||||
| { status: "READY"; page: PublicationPage }
|
||||
>({ status: "LOADING" });
|
||||
const publicationsQuery = useStudioPublicationsQuery(query);
|
||||
const commands = useStudioWorkspaceCommands();
|
||||
const page = publicationsQuery.data ?? null;
|
||||
const [selected, setSelected] = useState<PublicationListItem | null>(null);
|
||||
const [pending, setPending] = useState(false);
|
||||
const pending = commands.unpublish.state.overlay.mutationPending;
|
||||
const [dialogError, setDialogError] = useState("");
|
||||
const [announcement, setAnnouncement] = useState("");
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let current = true;
|
||||
setState({ status: "LOADING" });
|
||||
void studio.gateway.listPublications(query, {
|
||||
signal: controller.signal,
|
||||
}).then(
|
||||
(page) => {
|
||||
if (current) setState({ status: "READY", page });
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (!current || controller.signal.aborted) return;
|
||||
setState({
|
||||
status: "ERROR",
|
||||
problem:
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("게시 기록을 불러오지 못했습니다."),
|
||||
});
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [query, reload, studio.gateway]);
|
||||
|
||||
const applyFilter = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
go({ q: queryDraft.trim().slice(0, 100), page: 1 });
|
||||
@@ -143,30 +119,29 @@ export function PublicationList({
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
|
||||
setDialogError("");
|
||||
try {
|
||||
const result = await studio.gateway.unpublishPublication(
|
||||
selected.publication.publicationId,
|
||||
{
|
||||
expectedPublicationRevision:
|
||||
selected.publication.publicationRevision,
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-unpublish") },
|
||||
);
|
||||
setSelected(null);
|
||||
setAnnouncement("게시를 취소했습니다.");
|
||||
studio.setRequestAnnouncement("게시를 취소했습니다.");
|
||||
setReload((value) => value + 1);
|
||||
} catch (error) {
|
||||
const result = await commands.unpublish.submit({
|
||||
publicationId: selected.publication.publicationId,
|
||||
command: {
|
||||
expectedPublicationRevision:
|
||||
selected.publication.publicationRevision,
|
||||
},
|
||||
});
|
||||
if (!result.ok) {
|
||||
setDialogError(
|
||||
isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "게시를 취소하지 못했습니다.",
|
||||
studioFailureMessage(
|
||||
result.error,
|
||||
copy("techLog.failure.unpublishFailed"),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSelected(null);
|
||||
setAnnouncement(copy("techLog.notice.unpublished"));
|
||||
studio.setRequestAnnouncement(copy("techLog.notice.unpublished"));
|
||||
await publicationsQuery.retry();
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -179,7 +154,7 @@ export function PublicationList({
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<form className={styles.filters} onSubmit={applyFilter}>
|
||||
<Form className={styles.filters} onSubmit={applyFilter}>
|
||||
{/*
|
||||
검색 버튼은 검색 칸에 붙인다. 셋을 나란한 칸으로 두었더니 격자가 「검색칸 · 버튼 ·
|
||||
이벤트」로 잘려, 검색칸이 871px 로 벌어지고 이벤트 셀렉트는 91px 로 눌려 「게시 취소」가
|
||||
@@ -188,7 +163,7 @@ export function PublicationList({
|
||||
<div className={styles.searchField}>
|
||||
<label htmlFor="studio-publication-search">검색</label>
|
||||
<div>
|
||||
<input
|
||||
<InputControl
|
||||
id="studio-publication-search"
|
||||
type="search"
|
||||
value={queryDraft}
|
||||
@@ -197,12 +172,12 @@ export function PublicationList({
|
||||
/* 서버가 실제로 뒤지는 것은 제목뿐이다. 요약을 적어 두면 넣어도 안 나오는 이유를 알 수 없다. */
|
||||
placeholder="제목"
|
||||
/>
|
||||
<button type="submit">검색</button>
|
||||
<Button visualPolicy="inherit" type="submit">{copy("techLog.action.search")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<label>
|
||||
<span>이벤트</span>
|
||||
<select
|
||||
<SelectControl
|
||||
value={eventType ?? ""}
|
||||
onChange={(event) => go({ event: event.currentTarget.value, page: 1 })}
|
||||
>
|
||||
@@ -210,42 +185,48 @@ export function PublicationList({
|
||||
<option value="PUBLISHED">게시</option>
|
||||
<option value="REPUBLISHED">재게시</option>
|
||||
<option value="UNPUBLISHED">게시 취소</option>
|
||||
</select>
|
||||
</SelectControl>
|
||||
</label>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
{announcement ? (
|
||||
<p className={styles.success} role="status">
|
||||
{announcement}
|
||||
</p>
|
||||
) : null}
|
||||
{state.status === "LOADING" ? (
|
||||
{publicationsQuery.state.base === "initial-loading" ? (
|
||||
<p className={styles.loading} role="status">
|
||||
게시 기록을 불러오는 중입니다.
|
||||
{copy("techLog.state.publicationListLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
{state.status === "ERROR" ? (
|
||||
{publicationsQuery.state.base === "terminal-error" ? (
|
||||
<section className={styles.errorState} role="alert">
|
||||
<h2>게시 기록을 불러오지 못했습니다</h2>
|
||||
<h2>{copy("techLog.state.publicationListLoadFailed")}</h2>
|
||||
<p>
|
||||
{isStudioGatewayError(state.problem)
|
||||
? state.problem.problem.detail
|
||||
: state.problem.message}
|
||||
{studioFailureMessage(
|
||||
publicationsQuery.state.failure,
|
||||
"",
|
||||
)}
|
||||
</p>
|
||||
<button type="button" onClick={() => setReload((value) => value + 1)}>
|
||||
다시 시도
|
||||
</button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void publicationsQuery.retry();
|
||||
}}
|
||||
>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</section>
|
||||
) : null}
|
||||
{state.status === "READY" && state.page.items.length === 0 ? (
|
||||
{page && page.items.length === 0 ? (
|
||||
<section className={styles.emptyState}>
|
||||
<h2>조건에 맞는 게시 기록이 없습니다</h2>
|
||||
<p>검색어 또는 이벤트 필터를 바꿔 보세요.</p>
|
||||
<h2>{copy("techLog.state.emptyPublicationList")}</h2>
|
||||
<p>{copy("techLog.state.emptyPublicationListHint")}</p>
|
||||
</section>
|
||||
) : null}
|
||||
{state.status === "READY" && state.page.items.length > 0 ? (
|
||||
{page && page.items.length > 0 ? (
|
||||
<ol className={styles.historyList}>
|
||||
{state.page.items.map((item) => {
|
||||
{page.items.map((item) => {
|
||||
const href = snapshotHref(item);
|
||||
const source = item.availableActions.includes(
|
||||
"VIEW_SOURCE_SNAPSHOT",
|
||||
@@ -280,7 +261,7 @@ export function PublicationList({
|
||||
</GuardedStudioLink>
|
||||
) : null}
|
||||
{canUnpublish ? (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
aria-label={`${item.document.title || "제목 없는 작업본"} 게시 취소`}
|
||||
onClick={(event) => {
|
||||
@@ -289,8 +270,8 @@ export function PublicationList({
|
||||
setSelected(item);
|
||||
}}
|
||||
>
|
||||
게시 취소
|
||||
</button>
|
||||
{copy("techLog.action.unpublish")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
@@ -299,9 +280,9 @@ export function PublicationList({
|
||||
})}
|
||||
</ol>
|
||||
) : null}
|
||||
{state.status === "READY" ? (
|
||||
{page ? (
|
||||
<StudioPagination
|
||||
page={state.page.page}
|
||||
page={page.page}
|
||||
label="게시 기록 페이지"
|
||||
onChange={(next) => go({ page: next })}
|
||||
/>
|
||||
|
||||
@@ -1,28 +1,21 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
isStudioGatewayError,
|
||||
type StudioGatewayError,
|
||||
} from "../../../application/ports/studio-gateway-error.ts";
|
||||
import type {
|
||||
PreviewDetail,
|
||||
WorkingCopyDetail,
|
||||
} from "../../../contracts/studio/contract.ts";
|
||||
import { deriveValidationState } from "../../../domain/studio/document-state.ts";
|
||||
import { createLocalId } from "../../../domain/studio/local-id.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import {
|
||||
useStudioDocumentCommands,
|
||||
useStudioPublishSnapshotQuery,
|
||||
} from "../studio-document-server-state.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import {
|
||||
defaultPublicationFlowClasses,
|
||||
type PublicationFlowClasses,
|
||||
} from "./publication-flow-classes.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import { WarningAcknowledgements } from "./warning-acknowledgements.tsx";
|
||||
import { countBodyAssets } from "./asset-picker-dialog.tsx";
|
||||
|
||||
type LoadState =
|
||||
| { status: "LOADING" }
|
||||
| { status: "ERROR"; problem: StudioGatewayError | Error }
|
||||
| { status: "READY"; detail: WorkingCopyDetail; preview: PreviewDetail | null };
|
||||
import { useStudioFailureMessage, useTechLogCopy } from "../studio-copy.ts";
|
||||
|
||||
function dateTime(value: string) {
|
||||
return new Intl.DateTimeFormat("ko-KR", {
|
||||
@@ -32,10 +25,6 @@ function dateTime(value: string) {
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function notFound(problem: StudioGatewayError | Error) {
|
||||
return isStudioGatewayError(problem) && problem.code === "DOCUMENT_NOT_FOUND";
|
||||
}
|
||||
|
||||
export function PublishScreen({
|
||||
documentId,
|
||||
classes: styles = defaultPublicationFlowClasses,
|
||||
@@ -43,113 +32,78 @@ export function PublishScreen({
|
||||
documentId: string;
|
||||
classes?: PublicationFlowClasses;
|
||||
}) {
|
||||
const copy = useTechLogCopy();
|
||||
const studioFailureMessage = useStudioFailureMessage();
|
||||
const studio = useStudio();
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [state, setState] = useState<LoadState>({ status: "LOADING" });
|
||||
const snapshotQuery = useStudioPublishSnapshotQuery(documentId);
|
||||
const commands = useStudioDocumentCommands();
|
||||
const [acknowledged, setAcknowledged] = useState<Set<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [actionError, setActionError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
let current = true;
|
||||
setState({ status: "LOADING" });
|
||||
setAcknowledged(new Set());
|
||||
setActionError("");
|
||||
setSuccess("");
|
||||
}, [documentId]);
|
||||
|
||||
void (async () => {
|
||||
const detail = await studio.gateway.getDocument(documentId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
const sameVersion =
|
||||
detail.currentPublication?.status === "PUBLISHED" &&
|
||||
detail.currentPublication.publishedVersion === detail.document.version;
|
||||
let preview: PreviewDetail | null = null;
|
||||
if (!sameVersion && detail.latestPreview) {
|
||||
try {
|
||||
preview = await studio.gateway.getCurrentPreview(documentId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
!(
|
||||
isStudioGatewayError(error) &&
|
||||
error.code === "PREVIEW_NOT_FOUND"
|
||||
)
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (current) setState({ status: "READY", detail, preview });
|
||||
})().catch((error: unknown) => {
|
||||
if (!current || controller.signal.aborted) return;
|
||||
setState({
|
||||
status: "ERROR",
|
||||
problem:
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("게시 정보를 불러오지 못했습니다."),
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [attempt, documentId, studio.gateway]);
|
||||
|
||||
const ready = state.status === "READY" ? state : null;
|
||||
const validation = ready?.detail.currentValidation ?? null;
|
||||
const snapshot = snapshotQuery.data ?? null;
|
||||
const validation = snapshot?.detail.currentValidation ?? null;
|
||||
const warnings = useMemo(
|
||||
() =>
|
||||
validation?.issues.filter((issue) => issue.severity === "WARNING") ?? [],
|
||||
[validation],
|
||||
);
|
||||
|
||||
if (state.status === "LOADING") {
|
||||
if (snapshotQuery.state.base === "initial-loading") {
|
||||
return (
|
||||
<p className={styles.loading} role="status">
|
||||
게시 준비 정보를 불러오는 중입니다.
|
||||
{copy("techLog.state.publicationLoading")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (state.status === "ERROR" && notFound(state.problem)) {
|
||||
|
||||
const problem = snapshotQuery.state.failure;
|
||||
if (problem?.code === "DOCUMENT_NOT_FOUND") {
|
||||
return (
|
||||
<section className={styles.routeState}>
|
||||
<p className={styles.eyebrow}>NOT FOUND</p>
|
||||
<h1>작업본을 찾을 수 없습니다</h1>
|
||||
<p>이 작업본은 현재 Studio 세션에 없습니다.</p>
|
||||
<GuardedStudioLink href="/studio/documents">
|
||||
<h1>{copy("techLog.state.documentNotFound")}</h1>
|
||||
<p>{copy("techLog.state.sessionDocumentMissing")}</p>
|
||||
<GuardedStudioLink href={studioRoutes.documents()}>
|
||||
작업본으로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (state.status === "ERROR") {
|
||||
|
||||
if (snapshotQuery.state.base === "terminal-error" || !snapshot) {
|
||||
return (
|
||||
<section className={styles.routeState} role="alert">
|
||||
<p className={styles.eyebrow}>PUBLISH ERROR</p>
|
||||
<h1>게시 정보를 불러오지 못했습니다</h1>
|
||||
<h1>{copy("techLog.state.publicationLoadFailed")}</h1>
|
||||
<p>
|
||||
{isStudioGatewayError(state.problem)
|
||||
? state.problem.problem.detail
|
||||
: state.problem.message}
|
||||
{studioFailureMessage(
|
||||
problem,
|
||||
copy("techLog.state.publicationLoadFailed"),
|
||||
)}
|
||||
</p>
|
||||
<button type="button" onClick={() => setAttempt((value) => value + 1)}>
|
||||
다시 시도
|
||||
</button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void snapshotQuery.retry();
|
||||
}}
|
||||
>
|
||||
{copy("techLog.action.retry")}
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const { detail, preview } = state;
|
||||
const { detail, preview } = snapshot;
|
||||
const { document, currentPublication } = detail;
|
||||
/* 본문이 가리키는 자료 수. 본문을 갖지 않는 종류는 0 이다. */
|
||||
const bodyAssetCount =
|
||||
"bodyMarkdown" in document ? countBodyAssets(document.bodyMarkdown) : 0;
|
||||
const sameVersion =
|
||||
@@ -168,9 +122,12 @@ export function PublishScreen({
|
||||
const warningsDone = warnings.every((warning) =>
|
||||
acknowledged.has(warning.code),
|
||||
);
|
||||
const pending = commands.publish.state.overlay.mutationPending;
|
||||
const canPublish =
|
||||
validationAllowsPreview && previewIsCurrent && warningsDone && !pending;
|
||||
const actionLabel = currentPublication ? "다시 게시" : "게시";
|
||||
const actionLabel = currentPublication
|
||||
? copy("techLog.action.republish")
|
||||
: copy("techLog.action.publish");
|
||||
|
||||
const toggleWarning = (code: string, checked: boolean) => {
|
||||
setAcknowledged((current) => {
|
||||
@@ -183,35 +140,35 @@ export function PublishScreen({
|
||||
|
||||
const publish = async () => {
|
||||
if (!canPublish || !validation || !preview) return;
|
||||
setPending(true);
|
||||
setActionError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const result = await studio.gateway.publishDocument(
|
||||
document.id,
|
||||
{
|
||||
expectedVersion: document.version,
|
||||
validationId: validation.validationId,
|
||||
previewId: preview.preview.previewId,
|
||||
acknowledgedWarningCodes: [...acknowledged].sort(),
|
||||
},
|
||||
{ idempotencyKey: createLocalId("studio-publish") },
|
||||
);
|
||||
setSuccess("게시했습니다.");
|
||||
studio.setRequestAnnouncement("게시했습니다.");
|
||||
studio.clearEditor();
|
||||
studio.navigateInternal(
|
||||
`/studio/publications/${result.event.publicationEventId}/preview`,
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
const result = await commands.publish.submit({
|
||||
documentId: document.id,
|
||||
command: {
|
||||
expectedVersion: document.version,
|
||||
validationId: validation.validationId,
|
||||
previewId: preview.preview.previewId,
|
||||
acknowledgedWarningCodes: [...acknowledged].sort(),
|
||||
},
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
setActionError(
|
||||
isStudioGatewayError(error)
|
||||
? error.problem.detail
|
||||
: "게시하지 못했습니다. 다시 시도해 주세요.",
|
||||
studioFailureMessage(
|
||||
result.error,
|
||||
copy("techLog.failure.publishRetry"),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSuccess(copy("techLog.notice.published"));
|
||||
studio.setRequestAnnouncement(copy("techLog.notice.published"));
|
||||
studio.clearEditor();
|
||||
studio.navigateInternal(
|
||||
studioRoutes.publicationPreview(result.value.event.publicationEventId),
|
||||
);
|
||||
};
|
||||
|
||||
if (sameVersion && currentPublication) {
|
||||
@@ -232,7 +189,7 @@ export function PublishScreen({
|
||||
이벤트를 만들지 않습니다.
|
||||
</p>
|
||||
<GuardedStudioLink
|
||||
href={`/studio/publications/${currentPublication.latestEventId}/preview`}
|
||||
href={studioRoutes.publicationPreview(currentPublication.latestEventId)}
|
||||
>
|
||||
현재 게시 Snapshot 보기
|
||||
</GuardedStudioLink>
|
||||
@@ -251,28 +208,28 @@ export function PublishScreen({
|
||||
blocked = {
|
||||
title: "저장 버전 검증이 필요합니다",
|
||||
detail: "게시 전에 현재 저장 버전을 검증해 주세요.",
|
||||
href: `/studio/documents/${document.id}/validation`,
|
||||
href: studioRoutes.documentValidation(document.id),
|
||||
label: "검증하기",
|
||||
};
|
||||
} else if (!validationMatches) {
|
||||
blocked = {
|
||||
title: "검증 결과가 현재 버전과 다릅니다",
|
||||
detail: "현재 저장 버전으로 다시 검증해야 합니다.",
|
||||
href: `/studio/documents/${document.id}/validation`,
|
||||
href: studioRoutes.documentValidation(document.id),
|
||||
label: "다시 검증",
|
||||
};
|
||||
} else if (validation.status === "INVALID") {
|
||||
blocked = {
|
||||
title: "검증 오류를 먼저 수정해야 합니다",
|
||||
detail: `${validation.issues.filter((issue) => issue.severity === "ERROR").length}개의 오류가 게시를 막고 있습니다.`,
|
||||
href: `/studio/documents/${document.id}/validation`,
|
||||
href: studioRoutes.documentValidation(document.id),
|
||||
label: "검증 오류 보기",
|
||||
};
|
||||
} else if (!preview) {
|
||||
blocked = {
|
||||
title: "Public Preview가 필요합니다",
|
||||
detail: "검증된 저장 버전의 공개 레이아웃을 먼저 확인해 주세요.",
|
||||
href: `/studio/documents/${document.id}/preview`,
|
||||
href: studioRoutes.documentPreview(document.id),
|
||||
label: "Public Preview 만들기",
|
||||
};
|
||||
} else if (!previewIsCurrent) {
|
||||
@@ -282,7 +239,7 @@ export function PublishScreen({
|
||||
? "Public Preview가 만료되었습니다"
|
||||
: "Public Preview가 오래되었습니다",
|
||||
detail: "현재 검증과 저장 버전으로 Preview를 다시 만들어야 합니다.",
|
||||
href: `/studio/documents/${document.id}/preview`,
|
||||
href: studioRoutes.documentPreview(document.id),
|
||||
label: "Public Preview 다시 만들기",
|
||||
};
|
||||
}
|
||||
@@ -402,19 +359,19 @@ export function PublishScreen({
|
||||
) : null}
|
||||
<div className={styles.actions}>
|
||||
<GuardedStudioLink
|
||||
href={`/studio/documents/${document.id}/preview`}
|
||||
href={studioRoutes.documentPreview(document.id)}
|
||||
>
|
||||
Preview로 돌아가기
|
||||
</GuardedStudioLink>
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
disabled={!canPublish}
|
||||
onClick={() => {
|
||||
void publish();
|
||||
}}
|
||||
>
|
||||
{pending ? "게시 중…" : actionLabel}
|
||||
</button>
|
||||
{pending ? copy("techLog.action.publishing") : actionLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { Button, InputControl, TextAreaControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { createNewItemId } from "../../../domain/studio/local-id.ts";
|
||||
import { CatalogPropertyPicker } from "./catalog-property-picker.tsx";
|
||||
@@ -12,6 +14,7 @@ type QuestionOption = components["schemas"]["QuestionOption"];
|
||||
const orderedOptions = (options: QuestionOption[]) => options.map((option, order) => ({ ...option, order }));
|
||||
|
||||
export function QuestionFields({ draft, evidence, issues, onChange }: { draft: QuestionInput; evidence: CatalogEntry[]; issues: readonly FieldIssue[]; onChange(draft: QuestionInput): void }) {
|
||||
const copy = useTechLogCopy();
|
||||
const update = (patch: Partial<QuestionInput>) => onChange({ ...draft, ...patch });
|
||||
const setStatus = (status: "OPEN" | "RESOLVED" | null) => {
|
||||
if (status === "RESOLVED") update({ questionStatus: "RESOLVED", resolution: draft.resolution ?? { summary: "", evidenceTargetId: null, linkLabel: "" } });
|
||||
@@ -25,7 +28,7 @@ export function QuestionFields({ draft, evidence, issues, onChange }: { draft: Q
|
||||
<fieldset className="studio-inline-choice" aria-label="질문 상태">
|
||||
<legend>상태</legend>
|
||||
{([ [null, "미정"], ["OPEN", "OPEN"], ["RESOLVED", "RESOLVED"] ] as const).map(([value, label]) => (
|
||||
<button key={label} type="button" aria-pressed={draft.questionStatus === value || (!draft.questionStatus && value === null)} onClick={() => setStatus(value)}>{label}</button>
|
||||
<Button visualPolicy="inherit" key={label} type="button" aria-pressed={draft.questionStatus === value || (!draft.questionStatus && value === null)} onClick={() => setStatus(value)}>{label}</Button>
|
||||
))}
|
||||
<FieldNotice issues={issues} path="/questionStatus" />
|
||||
</fieldset>
|
||||
@@ -46,29 +49,29 @@ export function QuestionFields({ draft, evidence, issues, onChange }: { draft: Q
|
||||
<div className="studio-option-block studio-ordered-item" key={option.id}>
|
||||
<span className="studio-option-block__number">{String(index + 1).padStart(2, "0")}</span>
|
||||
<div className="studio-option-block__writing">
|
||||
<input aria-label={`선택지 ${index + 1} 제목`} value={option.title} placeholder="선택지" onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
|
||||
<textarea aria-label={`선택지 ${index + 1} 설명`} value={option.description} placeholder="장단점과 배제 이유를 적어 주세요." onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, description: event.currentTarget.value } : candidate)) })} />
|
||||
<InputControl aria-label={`선택지 ${index + 1} 제목`} value={option.title} placeholder="선택지" onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
|
||||
<TextAreaControl aria-label={`선택지 ${index + 1} 설명`} value={option.description} placeholder="장단점과 배제 이유를 적어 주세요." onChange={(event) => update({ options: orderedOptions(draft.options.map((candidate, at) => at === index ? { ...candidate, description: event.currentTarget.value } : candidate)) })} />
|
||||
</div>
|
||||
<div className="studio-item-actions"><button type="button" aria-label="위로" onClick={() => { const target=index-1; if(target<0)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===0}>↑</button><button type="button" aria-label="아래로" onClick={() => { const target=index+1; if(target>=draft.options.length)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===draft.options.length-1}>↓</button><button type="button" onClick={() => update({ options: orderedOptions(draft.options.filter((_, at) => at !== index)) })}>삭제</button></div>
|
||||
<div className="studio-item-actions"><Button visualPolicy="inherit" type="button" aria-label={copy("techLog.action.moveUp")} onClick={() => { const target=index-1; if(target<0)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===0}>↑</Button><Button visualPolicy="inherit" type="button" aria-label={copy("techLog.action.moveDown")} onClick={() => { const target=index+1; if(target>=draft.options.length)return; const next=[...draft.options]; [next[index],next[target]]=[next[target]!,next[index]!]; update({options:orderedOptions(next)}); }} disabled={index===draft.options.length-1}>↓</Button><Button visualPolicy="inherit" type="button" onClick={() => update({ options: orderedOptions(draft.options.filter((_, at) => at !== index)) })}>{copy("techLog.action.delete")}</Button></div>
|
||||
</div>
|
||||
))}
|
||||
<button className="studio-add-item" aria-label="선택지 추가" type="button" disabled={draft.options.length >= 50} onClick={() => { if (draft.options.length < 50) update({ options: orderedOptions([...draft.options, { id: createNewItemId(), title: "", description: "", order: draft.options.length }]) }); }}>+ 선택지</button>
|
||||
<Button visualPolicy="inherit" className="studio-add-item" aria-label="선택지 추가" type="button" disabled={draft.options.length >= 50} onClick={() => { if (draft.options.length < 50) update({ options: orderedOptions([...draft.options, { id: createNewItemId(), title: "", description: "", order: draft.options.length }]) }); }}>{copy("techLog.action.addOption")}</Button>
|
||||
</fieldset>
|
||||
|
||||
<label className="studio-document-block" data-tone="next">
|
||||
<span className="studio-document-block__label">다음 검증</span>
|
||||
<textarea aria-label="다음 검증" value={draft.nextValidation} placeholder="무엇을 확인해야 다음 판단으로 넘어갈 수 있는지 적어 주세요." onChange={(event) => update({ nextValidation: event.currentTarget.value })} />
|
||||
<TextAreaControl aria-label="다음 검증" value={draft.nextValidation} placeholder="무엇을 확인해야 다음 판단으로 넘어갈 수 있는지 적어 주세요." onChange={(event) => update({ nextValidation: event.currentTarget.value })} />
|
||||
<FieldNotice issues={issues} path="/nextValidation" />
|
||||
</label>
|
||||
|
||||
{draft.questionStatus === "RESOLVED" && draft.resolution ? (
|
||||
<section className="studio-resolution-block" aria-label="해결 내용">
|
||||
<div className="studio-resolution-block__heading"><span>해결 내용</span><small>이 질문을 닫은 근거와 결론</small></div>
|
||||
<textarea aria-label="해결 요약" value={draft.resolution.summary} placeholder="어떤 근거로 질문을 해결했는지 적어 주세요." onChange={(event) => update({ resolution: { ...draft.resolution!, summary: event.currentTarget.value } })} />
|
||||
<TextAreaControl aria-label="해결 요약" value={draft.resolution.summary} placeholder="어떤 근거로 질문을 해결했는지 적어 주세요." onChange={(event) => update({ resolution: { ...draft.resolution!, summary: event.currentTarget.value } })} />
|
||||
<div className="studio-resolution-block__properties">
|
||||
<span>근거 기록</span>
|
||||
<CatalogPropertyPicker label="해결 근거" value={draft.resolution.evidenceTargetId} entries={evidence} emptyLabel="근거 선택" onChange={(evidenceTargetId) => update({ resolution: { ...draft.resolution!, evidenceTargetId } })} />
|
||||
<input aria-label="근거 링크 문구" value={draft.resolution.linkLabel} placeholder="링크에 표시할 문구" onChange={(event) => update({ resolution: { ...draft.resolution!, linkLabel: event.currentTarget.value } })} />
|
||||
<InputControl aria-label="근거 링크 문구" value={draft.resolution.linkLabel} placeholder="링크에 표시할 문구" onChange={(event) => update({ resolution: { ...draft.resolution!, linkLabel: event.currentTarget.value } })} />
|
||||
</div>
|
||||
<FieldNotice issues={issues} path="/resolution" />
|
||||
</section>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { Button, InputControl, TextAreaControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { createNewItemId } from "../../../domain/studio/local-id.ts";
|
||||
import { FieldNotice, type FieldIssue } from "./field-issues.tsx";
|
||||
@@ -10,6 +12,7 @@ export const REFERENCE_FIELD_PATHS = ["/purpose", "/rules", "/applyWhen", "/exce
|
||||
const orderedRules = (rules: ReferenceRule[]) => rules.map((rule, order) => ({ ...rule, order }));
|
||||
|
||||
export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceInput; issues: readonly FieldIssue[]; onChange(draft: ReferenceInput): void }) {
|
||||
const copy = useTechLogCopy();
|
||||
const update = (patch: Partial<ReferenceInput>) => onChange({ ...draft, ...patch });
|
||||
const moveRule = (index: number, delta: -1 | 1) => {
|
||||
const target = index + delta;
|
||||
@@ -25,7 +28,7 @@ export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceI
|
||||
|
||||
<label className="studio-document-block" data-tone="purpose">
|
||||
<span className="studio-document-block__label">이 기준을 쓰는 이유</span>
|
||||
<textarea aria-label="이 기준을 쓰는 이유" value={draft.purpose} placeholder="이 기준이 어떤 판단을 빠르게 만드는지 적어 주세요." onChange={(event) => update({ purpose: event.currentTarget.value })} />
|
||||
<TextAreaControl aria-label="이 기준을 쓰는 이유" value={draft.purpose} placeholder="이 기준이 어떤 판단을 빠르게 만드는지 적어 주세요." onChange={(event) => update({ purpose: event.currentTarget.value })} />
|
||||
<FieldNotice issues={issues} path="/purpose" />
|
||||
</label>
|
||||
|
||||
@@ -36,13 +39,13 @@ export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceI
|
||||
<div className="studio-rule-block studio-ordered-item" key={rule.id}>
|
||||
<span className="studio-rule-block__number" aria-hidden="true">{String(index + 1).padStart(2, "0")}</span>
|
||||
<div className="studio-rule-block__writing">
|
||||
<input aria-label={`판단 기준 ${index + 1} 제목`} value={rule.title} placeholder="한 줄 판단 기준" onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
|
||||
<textarea aria-label={`판단 기준 ${index + 1} 본문`} value={rule.body} placeholder="왜 이 기준을 쓰는지, 적용 범위가 무엇인지 설명하세요." onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, body: event.currentTarget.value } : candidate)) })} />
|
||||
<InputControl aria-label={`판단 기준 ${index + 1} 제목`} value={rule.title} placeholder="한 줄 판단 기준" onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, title: event.currentTarget.value } : candidate)) })} />
|
||||
<TextAreaControl aria-label={`판단 기준 ${index + 1} 본문`} value={rule.body} placeholder="왜 이 기준을 쓰는지, 적용 범위가 무엇인지 설명하세요." onChange={(event) => update({ rules: orderedRules(draft.rules.map((candidate, at) => at === index ? { ...candidate, body: event.currentTarget.value } : candidate)) })} />
|
||||
</div>
|
||||
<div className="studio-item-actions"><button type="button" aria-label="위로" onClick={() => moveRule(index, -1)} disabled={index === 0}>↑</button><button type="button" aria-label="아래로" onClick={() => moveRule(index, 1)} disabled={index === draft.rules.length - 1}>↓</button><button type="button" onClick={() => update({ rules: orderedRules(draft.rules.filter((_, at) => at !== index)) })}>삭제</button></div>
|
||||
<div className="studio-item-actions"><Button visualPolicy="inherit" type="button" aria-label={copy("techLog.action.moveUp")} onClick={() => moveRule(index, -1)} disabled={index === 0}>↑</Button><Button visualPolicy="inherit" type="button" aria-label={copy("techLog.action.moveDown")} onClick={() => moveRule(index, 1)} disabled={index === draft.rules.length - 1}>↓</Button><Button visualPolicy="inherit" type="button" onClick={() => update({ rules: orderedRules(draft.rules.filter((_, at) => at !== index)) })}>{copy("techLog.action.delete")}</Button></div>
|
||||
</div>
|
||||
))}
|
||||
<button className="studio-add-item" aria-label="판단 기준 추가" type="button" disabled={draft.rules.length >= 50} onClick={() => { if (draft.rules.length < 50) update({ rules: orderedRules([...draft.rules, { id: createNewItemId(), title: "", body: "", order: draft.rules.length }]) }); }}>+ 판단 기준</button>
|
||||
<Button visualPolicy="inherit" className="studio-add-item" aria-label="판단 기준 추가" type="button" disabled={draft.rules.length >= 50} onClick={() => { if (draft.rules.length < 50) update({ rules: orderedRules([...draft.rules, { id: createNewItemId(), title: "", body: "", order: draft.rules.length }]) }); }}>{copy("techLog.action.addCriterion")}</Button>
|
||||
</fieldset>
|
||||
|
||||
<OrderedTextList label="적용할 때" tone="fact" items={draft.applyWhen} onChange={(applyWhen) => update({ applyWhen })} />
|
||||
@@ -52,7 +55,7 @@ export function ReferenceFields({ draft, issues, onChange }: { draft: ReferenceI
|
||||
<OrderedTextList label="예시" tone="example" items={draft.examples} onChange={(examples) => update({ examples })} />
|
||||
<FieldNotice issues={issues} path="/examples" />
|
||||
|
||||
<label className="studio-inline-property studio-inline-property--date"><span>마지막 검증일</span><input aria-label="마지막 검증일" type="date" value={draft.verifiedOn ?? ""} onChange={(event) => update({ verifiedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/verifiedOn" /></label>
|
||||
<label className="studio-inline-property studio-inline-property--date"><span>마지막 검증일</span><InputControl aria-label="마지막 검증일" type="date" value={draft.verifiedOn ?? ""} onChange={(event) => update({ verifiedOn: event.currentTarget.value || null })} /><FieldNotice issues={issues} path="/verifiedOn" /></label>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import {
|
||||
Button,
|
||||
InputControl,
|
||||
SelectControl,
|
||||
TextAreaControl,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
@@ -51,6 +58,7 @@ function grouped(catalog: CatalogEntry[]) {
|
||||
}
|
||||
|
||||
export function RelationEditor({ relations, catalog, evidence = false, onChange }: { relations: RelationInput[]; catalog: CatalogEntry[]; evidence?: boolean; onChange(relations: RelationInput[]): void }) {
|
||||
const copy = useTechLogCopy();
|
||||
const noun = evidence ? "근거" : "관계";
|
||||
/*
|
||||
고를 것이 105개다. 평면 셀렉트에서 그것을 이름으로 찾으려면 목록 전체를 눈으로 훑어야 하고,
|
||||
@@ -86,7 +94,7 @@ export function RelationEditor({ relations, catalog, evidence = false, onChange
|
||||
<legend>{evidence ? "근거 기록" : "관계"}</legend>
|
||||
<label className="studio-relation-filter">
|
||||
<span>대상 거르기</span>
|
||||
<input
|
||||
<InputControl
|
||||
type="search"
|
||||
value={filter}
|
||||
placeholder="제목의 일부를 적으세요"
|
||||
@@ -103,7 +111,7 @@ export function RelationEditor({ relations, catalog, evidence = false, onChange
|
||||
<div className="studio-relation-item" key={relation.id ?? `relation-${index}`}>
|
||||
<label>
|
||||
<span>{noun} {index + 1} 대상</span>
|
||||
<select
|
||||
<SelectControl
|
||||
value={relation.targetId ?? ""}
|
||||
onChange={(event) => update(index, { targetId: event.currentTarget.value || null })}
|
||||
>
|
||||
@@ -122,7 +130,7 @@ export function RelationEditor({ relations, catalog, evidence = false, onChange
|
||||
{entry.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</SelectControl>
|
||||
</label>
|
||||
{/*
|
||||
이 문장은 이제 공개 화면의 「다음에 읽을 것」에 그대로 나간다. 한 줄 input 이던 동안
|
||||
@@ -135,7 +143,7 @@ export function RelationEditor({ relations, catalog, evidence = false, onChange
|
||||
<label htmlFor={`relation-reason-${index}`}>
|
||||
{noun} {index + 1} 이유
|
||||
</label>
|
||||
<textarea
|
||||
<TextAreaControl
|
||||
id={`relation-reason-${index}`}
|
||||
rows={2}
|
||||
value={relation.reason}
|
||||
@@ -145,10 +153,10 @@ export function RelationEditor({ relations, catalog, evidence = false, onChange
|
||||
공개 화면의 「다음에 읽을 것」에 그대로 나갑니다.
|
||||
</span>
|
||||
</div>
|
||||
<div className="studio-item-actions"><button type="button" onClick={() => move(index, -1)} disabled={index === 0}>위로</button><button type="button" onClick={() => move(index, 1)} disabled={index === relations.length - 1}>아래로</button><button type="button" onClick={() => onChange(ordered(relations.filter((_, candidateIndex) => candidateIndex !== index)))}>삭제</button></div>
|
||||
<div className="studio-item-actions"><Button visualPolicy="inherit" type="button" onClick={() => move(index, -1)} disabled={index === 0}>{copy("techLog.action.moveUp")}</Button><Button visualPolicy="inherit" type="button" onClick={() => move(index, 1)} disabled={index === relations.length - 1}>{copy("techLog.action.moveDown")}</Button><Button visualPolicy="inherit" type="button" onClick={() => onChange(ordered(relations.filter((_, candidateIndex) => candidateIndex !== index)))}>{copy("techLog.action.delete")}</Button></div>
|
||||
</div>
|
||||
))}
|
||||
<button className="studio-add-item" type="button" disabled={relations.length >= 20} onClick={() => { if (relations.length < 20) onChange(ordered([...relations, { id: createNewItemId(), targetId: null, reason: "", order: relations.length }])); }}>{noun} 추가</button>
|
||||
<Button visualPolicy="inherit" className="studio-add-item" type="button" disabled={relations.length >= 20} onClick={() => { if (relations.length < 20) onChange(ordered([...relations, { id: createNewItemId(), targetId: null, reason: "", order: relations.length }])); }}>{noun} 추가</Button>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,33 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { useEffect, useState } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import type {
|
||||
ReleaseEditResponse,
|
||||
ReleaseUpdateRequest,
|
||||
ReleaseChangeType,
|
||||
} from "../../../contracts/management/contract.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import { RELEASE_CHANGE_TYPE_OPTIONS } from "../management-labels.ts";
|
||||
import { useRouteInput } from "../../../../../presentation/routes/route-input.tsx";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
TextArea,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
useAppForm,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { useSaveShortcut } from "./use-save-shortcut.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import { useManagementFailureMessage } from "../studio-copy.ts";
|
||||
import {
|
||||
useManagementCommands,
|
||||
useManagementReleaseQuery,
|
||||
} from "../studio-management-server-state.ts";
|
||||
|
||||
/**
|
||||
* 릴리즈 한 편의 편집 화면.
|
||||
@@ -21,15 +40,8 @@ import { useStudio } from "../use-studio.ts";
|
||||
* 서술이었다면 "검증을 안 썼다"를 아무도 알아채지 못한다.
|
||||
*/
|
||||
|
||||
/** 백엔드 {@code UpdateReleaseUseCase.CHANGE_TYPES} 와 같은 집합이다. */
|
||||
const CHANGE_TYPES = [
|
||||
{ value: "FEATURE", label: "기능" },
|
||||
{ value: "FIX", label: "수정" },
|
||||
{ value: "REFACTOR", label: "구조" },
|
||||
{ value: "DOCS", label: "문서" },
|
||||
{ value: "INFRA", label: "인프라" },
|
||||
{ value: "BREAKING", label: "호환 깨짐" },
|
||||
] as const;
|
||||
/** 허용 값은 generated management contract가 소유하고, 이 화면은 한국어 표현만 소유한다. */
|
||||
const CHANGE_TYPES = RELEASE_CHANGE_TYPE_OPTIONS;
|
||||
|
||||
const SECTIONS = [
|
||||
{ key: "reasonMarkdown", label: "왜 바꿨나" },
|
||||
@@ -46,7 +58,7 @@ type Draft = Readonly<{
|
||||
title: string;
|
||||
summary: string;
|
||||
releasedOn: string;
|
||||
changeTypes: readonly string[];
|
||||
changeTypes: readonly ReleaseChangeType[];
|
||||
reasonMarkdown: string;
|
||||
changesMarkdown: string;
|
||||
userImpactMarkdown: string;
|
||||
@@ -72,6 +84,71 @@ function toDraft(release: ReleaseEditResponse): Draft {
|
||||
};
|
||||
}
|
||||
|
||||
const EMPTY_RELEASE_DRAFT: Draft = Object.freeze({
|
||||
expectedVersion: 0,
|
||||
versionLabel: "",
|
||||
title: "",
|
||||
summary: "",
|
||||
releasedOn: "",
|
||||
changeTypes: [],
|
||||
reasonMarkdown: "",
|
||||
changesMarkdown: "",
|
||||
userImpactMarkdown: "",
|
||||
implementationImpactMarkdown: "",
|
||||
verificationMarkdown: "",
|
||||
knownLimitationsMarkdown: "",
|
||||
});
|
||||
|
||||
const RELEASE_SCHEMA = z.object({
|
||||
expectedVersion: z.number().int().nonnegative(),
|
||||
versionLabel: z.string().trim().min(1),
|
||||
title: z.string().trim().min(1),
|
||||
summary: z.string(),
|
||||
releasedOn: z.string(),
|
||||
changeTypes: z.array(
|
||||
z.custom<ReleaseChangeType>((value) =>
|
||||
CHANGE_TYPES.some((option) => option.value === value),
|
||||
),
|
||||
),
|
||||
reasonMarkdown: z.string(),
|
||||
changesMarkdown: z.string(),
|
||||
userImpactMarkdown: z.string(),
|
||||
implementationImpactMarkdown: z.string(),
|
||||
verificationMarkdown: z.string(),
|
||||
knownLimitationsMarkdown: z.string(),
|
||||
});
|
||||
|
||||
const RELEASE_FIELDS = Object.freeze([
|
||||
"versionLabel",
|
||||
"title",
|
||||
"summary",
|
||||
"releasedOn",
|
||||
"changeTypes",
|
||||
"reasonMarkdown",
|
||||
"changesMarkdown",
|
||||
"userImpactMarkdown",
|
||||
"implementationImpactMarkdown",
|
||||
"verificationMarkdown",
|
||||
"knownLimitationsMarkdown",
|
||||
] as const);
|
||||
|
||||
function releaseRequest(current: Draft): ReleaseUpdateRequest {
|
||||
return {
|
||||
expectedVersion: current.expectedVersion,
|
||||
versionLabel: current.versionLabel.trim(),
|
||||
title: current.title.trim(),
|
||||
summary: current.summary,
|
||||
changeTypes: [...current.changeTypes],
|
||||
changesMarkdown: current.changesMarkdown,
|
||||
verificationMarkdown: current.verificationMarkdown,
|
||||
...(current.releasedOn ? { releasedOn: current.releasedOn } : {}),
|
||||
reasonMarkdown: current.reasonMarkdown,
|
||||
userImpactMarkdown: current.userImpactMarkdown,
|
||||
implementationImpactMarkdown: current.implementationImpactMarkdown,
|
||||
knownLimitationsMarkdown: current.knownLimitationsMarkdown,
|
||||
} as ReleaseUpdateRequest;
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Readonly<Record<string, string>> = {
|
||||
DRAFT: "작성 중",
|
||||
PUBLISHED: "공개",
|
||||
@@ -84,119 +161,113 @@ function routeId(value: unknown): string {
|
||||
}
|
||||
|
||||
export function ReleaseEditor() {
|
||||
const copy = useTechLogCopy();
|
||||
const managementFailureMessage = useManagementFailureMessage();
|
||||
const { params } = useRouteInput<"TECH_LOG_STUDIO_RELEASE_EDIT">();
|
||||
const releaseId = routeId(params.id);
|
||||
const { managementGateway, setRequestAnnouncement } = useStudio();
|
||||
const { setRequestAnnouncement } = useStudio();
|
||||
const releaseQuery = useManagementReleaseQuery(releaseId);
|
||||
const commands = useManagementCommands();
|
||||
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [status, setStatus] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const [operationError, setOperationError] = useState("");
|
||||
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
const form = useAppForm({
|
||||
schema: RELEASE_SCHEMA,
|
||||
defaultValues: EMPTY_RELEASE_DRAFT,
|
||||
allowedServerFields: RELEASE_FIELDS,
|
||||
mapToCommand(values) {
|
||||
return {
|
||||
id: releaseId,
|
||||
body: releaseRequest(values),
|
||||
};
|
||||
},
|
||||
submit: commands.updateRelease.submit,
|
||||
resetOnSuccess: false,
|
||||
});
|
||||
const draft = form.values;
|
||||
const status = releaseQuery.data?.workflowStatus ?? "";
|
||||
const pending =
|
||||
form.pending ||
|
||||
commands.publishRelease.state.overlay.mutationPending ||
|
||||
commands.archiveRelease.state.overlay.mutationPending;
|
||||
|
||||
const resetReleaseForm = form.reset;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void managementGateway.getRelease(releaseId).then(
|
||||
(release) => {
|
||||
if (cancelled) return;
|
||||
setDraft(toDraft(release));
|
||||
setStatus(release.workflowStatus);
|
||||
setError("");
|
||||
},
|
||||
() => {
|
||||
if (!cancelled) setError("릴리즈를 불러오지 못했습니다.");
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [managementGateway, releaseId, generation]);
|
||||
const release = releaseQuery.data;
|
||||
if (!release) return;
|
||||
resetReleaseForm(toDraft(release));
|
||||
setOperationError("");
|
||||
}, [releaseQuery.data, resetReleaseForm]);
|
||||
|
||||
const update = (patch: Partial<Draft>) =>
|
||||
setDraft((current) => (current === null ? current : { ...current, ...patch }));
|
||||
|
||||
const requestOf = (current: Draft): ReleaseUpdateRequest =>
|
||||
({
|
||||
expectedVersion: current.expectedVersion,
|
||||
versionLabel: current.versionLabel.trim(),
|
||||
title: current.title.trim(),
|
||||
summary: current.summary,
|
||||
changeTypes: [...current.changeTypes],
|
||||
changesMarkdown: current.changesMarkdown,
|
||||
verificationMarkdown: current.verificationMarkdown,
|
||||
...(current.releasedOn ? { releasedOn: current.releasedOn } : {}),
|
||||
reasonMarkdown: current.reasonMarkdown,
|
||||
userImpactMarkdown: current.userImpactMarkdown,
|
||||
implementationImpactMarkdown: current.implementationImpactMarkdown,
|
||||
knownLimitationsMarkdown: current.knownLimitationsMarkdown,
|
||||
}) as ReleaseUpdateRequest;
|
||||
const update = (patch: Partial<Draft>) => {
|
||||
for (const [name, value] of Object.entries(patch)) {
|
||||
form.setValue(name as keyof Draft, value as Draft[keyof Draft]);
|
||||
}
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (pending || draft === null) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
const saved = await managementGateway.updateRelease(releaseId, requestOf(draft));
|
||||
setDraft(toDraft(saved));
|
||||
setRequestAnnouncement(`릴리즈 ${saved.versionLabel} 을(를) 저장했습니다.`);
|
||||
reload();
|
||||
} catch (failure) {
|
||||
setError(managementFailureMessage(failure, "저장하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
setOperationError("");
|
||||
const saved = await form.submitForm();
|
||||
if (!saved?.ok) return;
|
||||
|
||||
setRequestAnnouncement(
|
||||
`릴리즈 ${saved.value.versionLabel} 을(를) 저장했습니다.`,
|
||||
);
|
||||
await releaseQuery.retry();
|
||||
};
|
||||
|
||||
const publish = async () => {
|
||||
if (pending || draft === null) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
/*
|
||||
먼저 저장한다. 발행은 서버에 저장된 릴리즈를 검사하는데(`PublishReleaseUseCase`), 예전에는
|
||||
저장하지 않고 발행만 불렀다 — 화면의 칸을 다 채우고 공개를 눌러도 서버 쪽은 여전히 빈
|
||||
초안이라 "모두 채워져야 합니다" 가 떴다. 채웠는데 안 된다는 말이 나온 이유가 이것이다.
|
||||
*/
|
||||
const saved = await managementGateway.updateRelease(releaseId, requestOf(draft));
|
||||
setDraft(toDraft(saved));
|
||||
const published = await managementGateway.publishRelease(releaseId, saved.version);
|
||||
setRequestAnnouncement(`릴리즈를 공개했습니다: ${published.canonicalPath}`);
|
||||
reload();
|
||||
} catch (failure) {
|
||||
// 무엇이 모자란지는 서버가 안다. 예전에는 그 답을 버리고 필수 항목을 전부 나열했는데,
|
||||
// 그러면 이미 채운 칸까지 비었다고 말하게 된다.
|
||||
setError(
|
||||
setOperationError("");
|
||||
const saved = await form.submitForm();
|
||||
if (!saved?.ok) return;
|
||||
|
||||
const published = await commands.publishRelease.submit({
|
||||
id: releaseId,
|
||||
expectedVersion: saved.value.version,
|
||||
});
|
||||
if (!published.ok) {
|
||||
setOperationError(
|
||||
managementFailureMessage(
|
||||
failure,
|
||||
"공개하지 못했습니다. 버전, 제목, 한 줄 요약, 변경 유형, 변경 내용, 검증, 공개일이 모두 채워져야 합니다.",
|
||||
published.error,
|
||||
copy("techLog.failure.releasePublishFields"),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
await releaseQuery.retry();
|
||||
return;
|
||||
}
|
||||
|
||||
setRequestAnnouncement(
|
||||
`릴리즈를 공개했습니다: ${published.value.canonicalPath}`,
|
||||
);
|
||||
await releaseQuery.retry();
|
||||
};
|
||||
|
||||
const archive = async () => {
|
||||
if (pending || draft === null) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await managementGateway.archiveRelease(releaseId, draft.expectedVersion);
|
||||
setRequestAnnouncement("릴리즈를 공개에서 내렸습니다.");
|
||||
reload();
|
||||
} catch (failure) {
|
||||
setError(managementFailureMessage(failure, "공개에서 내리지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
if (pending) return;
|
||||
setOperationError("");
|
||||
|
||||
const archived = await commands.archiveRelease.submit({
|
||||
id: releaseId,
|
||||
expectedVersion: draft.expectedVersion,
|
||||
});
|
||||
if (!archived.ok) {
|
||||
setOperationError(
|
||||
managementFailureMessage(
|
||||
archived.error,
|
||||
copy("techLog.failure.releaseUnpublishFailed"),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setRequestAnnouncement(copy("techLog.notice.releaseUnpublished"));
|
||||
await releaseQuery.retry();
|
||||
};
|
||||
|
||||
useSaveShortcut(save, draft !== null && !pending);
|
||||
useSaveShortcut(save, releaseQuery.data !== undefined && !pending);
|
||||
|
||||
const toggleChangeType = (value: string) => {
|
||||
if (draft === null) return;
|
||||
const toggleChangeType = (value: ReleaseChangeType) => {
|
||||
update({
|
||||
changeTypes: draft.changeTypes.includes(value)
|
||||
? draft.changeTypes.filter((entry) => entry !== value)
|
||||
@@ -214,23 +285,27 @@ export function ReleaseEditor() {
|
||||
<h1>{draft?.title || "릴리즈"}</h1>
|
||||
<p>공개 변경 기록 화면과 푸터 링크가 이 값을 그대로 읽습니다.</p>
|
||||
</div>
|
||||
<GuardedStudioLink className="studio-primary-action" href="/studio/releases">
|
||||
<GuardedStudioLink className="studio-primary-action" href={studioRoutes.releases()}>
|
||||
릴리즈 목록으로
|
||||
</GuardedStudioLink>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
{operationError || releaseQuery.state.base === "terminal-error" ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
{operationError ||
|
||||
managementFailureMessage(
|
||||
releaseQuery.state.failure,
|
||||
copy("techLog.state.releaseLoadFailed"),
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{draft === null && !error ? (
|
||||
{!releaseQuery.data && !operationError && releaseQuery.state.base !== "terminal-error" ? (
|
||||
<p className="studio-loading" role="status">
|
||||
릴리즈를 불러오는 중입니다.
|
||||
{copy("techLog.state.releaseLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{draft === null ? null : (
|
||||
{!releaseQuery.data ? null : (
|
||||
<section className="studio-editor-section" aria-labelledby="studio-release-edit-title">
|
||||
<div className="studio-editor-section-heading">
|
||||
<p className="studio-eyebrow">RELEASE · {draft.versionLabel}</p>
|
||||
@@ -238,102 +313,134 @@ export function ReleaseEditor() {
|
||||
<p>변경 기록 화면과 푸터 링크가 이 값을 그대로 읽습니다.</p>
|
||||
</div>
|
||||
<div className="studio-field-grid">
|
||||
<label className="studio-field">
|
||||
<span>버전</span>
|
||||
<input
|
||||
type="text"
|
||||
value={draft.versionLabel}
|
||||
placeholder="0.1.0"
|
||||
onChange={(event) => update({ versionLabel: event.currentTarget.value })}
|
||||
/>
|
||||
{/*
|
||||
새 릴리즈는 `draft-…` 라는 자리표시자 버전으로 만들어지고, 서버는 그것이 남아
|
||||
있으면 공개를 거절한다(`ReleaseDrafts.isPlaceholder`). 화면에는 값이 채워져
|
||||
보이므로 왜 거절당하는지 알 길이 없었다.
|
||||
*/}
|
||||
{draft.versionLabel.startsWith("draft-") ? (
|
||||
<span className="studio-field-notice studio-field-notice--error" role="alert">
|
||||
자리표시자 버전입니다. 공개하려면 실제 버전으로 바꿔 주세요 (예: 0.2.0).
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>제목</span>
|
||||
<input
|
||||
type="text"
|
||||
value={draft.title}
|
||||
onChange={(event) => update({ title: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field">
|
||||
<span>공개일</span>
|
||||
<input
|
||||
type="date"
|
||||
value={draft.releasedOn}
|
||||
onChange={(event) => update({ releasedOn: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="studio-field studio-field--wide">
|
||||
<span>한 줄 요약</span>
|
||||
<textarea
|
||||
value={draft.summary}
|
||||
onChange={(event) => update({ summary: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="버전"
|
||||
id={form.fieldId("versionLabel")}
|
||||
error={
|
||||
form.fieldErrors.versionLabel ??
|
||||
(draft.versionLabel.startsWith("draft-")
|
||||
? "자리표시자 버전입니다. 공개하려면 실제 버전으로 바꿔 주세요 (예: 0.2.0)."
|
||||
: undefined)
|
||||
}
|
||||
placeholder="0.1.0"
|
||||
type="text"
|
||||
value={draft.versionLabel}
|
||||
onChange={(event) =>
|
||||
update({ versionLabel: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="제목"
|
||||
id={form.fieldId("title")}
|
||||
error={form.fieldErrors.title}
|
||||
type="text"
|
||||
value={draft.title}
|
||||
onChange={(event) => update({ title: event.currentTarget.value })}
|
||||
/>
|
||||
<TextField
|
||||
className="studio-field"
|
||||
label="공개일"
|
||||
id={form.fieldId("releasedOn")}
|
||||
error={form.fieldErrors.releasedOn}
|
||||
type="date"
|
||||
value={draft.releasedOn}
|
||||
onChange={(event) =>
|
||||
update({ releasedOn: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
<TextArea
|
||||
className="studio-field studio-field--wide"
|
||||
label="한 줄 요약"
|
||||
id={form.fieldId("summary")}
|
||||
error={form.fieldErrors.summary}
|
||||
value={draft.summary}
|
||||
onChange={(event) => update({ summary: event.currentTarget.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<fieldset className="studio-checkbox-set">
|
||||
<fieldset
|
||||
className="studio-checkbox-set"
|
||||
id={form.fieldId("changeTypes")}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<legend>변경 유형</legend>
|
||||
{CHANGE_TYPES.map((changeType) => (
|
||||
<label key={changeType.value} className="studio-field studio-field--checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={draft.changeTypes.includes(changeType.value)}
|
||||
onChange={() => toggleChangeType(changeType.value)}
|
||||
/>
|
||||
<span>{changeType.label}</span>
|
||||
</label>
|
||||
<Checkbox
|
||||
checked={draft.changeTypes.includes(changeType.value)}
|
||||
fieldClassName="studio-field studio-field--checkbox"
|
||||
key={changeType.value}
|
||||
label={changeType.label}
|
||||
onChange={() => toggleChangeType(changeType.value)}
|
||||
/>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className="studio-field-grid">
|
||||
{SECTIONS.map((section) => (
|
||||
<label key={section.key} className="studio-field studio-field--wide">
|
||||
<span>{section.label}</span>
|
||||
<textarea
|
||||
value={draft[section.key]}
|
||||
onChange={(event) => update({ [section.key]: event.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
<TextArea
|
||||
className="studio-field studio-field--wide"
|
||||
key={section.key}
|
||||
label={section.label}
|
||||
id={form.fieldId(section.key)}
|
||||
error={form.fieldErrors[section.key]}
|
||||
value={draft[section.key]}
|
||||
onChange={(event) =>
|
||||
update({ [section.key]: event.currentTarget.value })
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<ErrorSummary
|
||||
fieldErrors={form.fieldErrors}
|
||||
formErrors={form.formErrors}
|
||||
fieldId={form.fieldId}
|
||||
fieldLabels={{
|
||||
versionLabel: "버전",
|
||||
title: "제목",
|
||||
summary: "한 줄 요약",
|
||||
releasedOn: "공개일",
|
||||
changeTypes: "변경 유형",
|
||||
reasonMarkdown: "왜 바꿨나",
|
||||
changesMarkdown: "무엇을 바꿨나",
|
||||
userImpactMarkdown: "사용자에게 달라지는 것",
|
||||
implementationImpactMarkdown: "구현에 남는 것",
|
||||
verificationMarkdown: "어떻게 검증했나",
|
||||
knownLimitationsMarkdown: "아직 못 한 것",
|
||||
}}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
|
||||
<div className="studio-create-footer">
|
||||
<button
|
||||
<Button
|
||||
className="studio-primary-button"
|
||||
type="button"
|
||||
title="Ctrl+S"
|
||||
disabled={pending}
|
||||
title="Ctrl+S"
|
||||
type="button"
|
||||
onClick={() => void save()}
|
||||
>
|
||||
저장
|
||||
</button>
|
||||
<button
|
||||
{copy("techLog.action.save")}
|
||||
</Button>
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
공개
|
||||
</button>
|
||||
<button
|
||||
{copy("techLog.action.makePublic")}
|
||||
</Button>
|
||||
<Button
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => void archive()}
|
||||
>
|
||||
공개에서 내리기
|
||||
</button>
|
||||
{copy("techLog.action.removeFromPublic")}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -1,78 +1,26 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { z } from "zod";
|
||||
import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx";
|
||||
import {
|
||||
Button,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
useAppForm,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
import type {
|
||||
ReleaseEditResponse,
|
||||
ReleaseIndexItem,
|
||||
ReleaseUpdateRequest,
|
||||
} from "../../../contracts/management/contract.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import type { ReleaseIndexItem } from "../../../contracts/management/contract.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
|
||||
/**
|
||||
* 릴리즈 작성.
|
||||
*
|
||||
* <p>공개 사이트에 변경 기록 화면과 푸터 링크가 있는데 둘 다 비어 있었다 — 읽기는 처음부터
|
||||
* 있었고 쓰는 곳이 없었다. 그래서 이 화면의 범위는 목록·작성·발행이다.
|
||||
*
|
||||
* <p>본문이 마크다운 여섯 칸으로 나뉜 것은 계약의 모양이자 릴리즈 노트의 성격이다. 한 칸짜리
|
||||
* 자유 서술이었다면 "검증을 안 썼다"를 아무도 알아채지 못한다.
|
||||
*
|
||||
* <p>새 CSS 를 만들지 않는다 — 문서 편집기가 쓰는 field 클래스와 작업본 목록의 행 클래스를 그대로
|
||||
* 재사용하므로 Studio 의 나머지와 같은 간격·타이포·색을 따른다.
|
||||
*/
|
||||
|
||||
/** 백엔드 {@code UpdateReleaseUseCase.CHANGE_TYPES} 와 같은 집합이다. */
|
||||
const CHANGE_TYPES = [
|
||||
{ value: "FEATURE", label: "기능" },
|
||||
{ value: "FIX", label: "수정" },
|
||||
{ value: "REFACTOR", label: "구조" },
|
||||
{ value: "DOCS", label: "문서" },
|
||||
{ value: "INFRA", label: "인프라" },
|
||||
{ value: "BREAKING", label: "호환 깨짐" },
|
||||
] as const;
|
||||
|
||||
const SECTIONS = [
|
||||
{ key: "reasonMarkdown", label: "왜 바꿨나" },
|
||||
{ key: "changesMarkdown", label: "무엇을 바꿨나" },
|
||||
{ key: "userImpactMarkdown", label: "사용자에게 달라지는 것" },
|
||||
{ key: "implementationImpactMarkdown", label: "구현에 남는 것" },
|
||||
{ key: "verificationMarkdown", label: "어떻게 검증했나" },
|
||||
{ key: "knownLimitationsMarkdown", label: "아직 못 한 것" },
|
||||
] as const;
|
||||
|
||||
type Draft = Readonly<{
|
||||
expectedVersion: number;
|
||||
versionLabel: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
releasedOn: string;
|
||||
changeTypes: readonly string[];
|
||||
reasonMarkdown: string;
|
||||
changesMarkdown: string;
|
||||
userImpactMarkdown: string;
|
||||
implementationImpactMarkdown: string;
|
||||
verificationMarkdown: string;
|
||||
knownLimitationsMarkdown: string;
|
||||
}>;
|
||||
|
||||
function toDraft(release: ReleaseEditResponse): Draft {
|
||||
return {
|
||||
expectedVersion: release.version,
|
||||
versionLabel: release.versionLabel,
|
||||
title: release.title,
|
||||
summary: release.summary ?? "",
|
||||
releasedOn: release.releasedOn ?? "",
|
||||
changeTypes: release.changeTypes ?? [],
|
||||
reasonMarkdown: release.reasonMarkdown ?? "",
|
||||
changesMarkdown: release.changesMarkdown ?? "",
|
||||
userImpactMarkdown: release.userImpactMarkdown ?? "",
|
||||
implementationImpactMarkdown: release.implementationImpactMarkdown ?? "",
|
||||
verificationMarkdown: release.verificationMarkdown ?? "",
|
||||
knownLimitationsMarkdown: release.knownLimitationsMarkdown ?? "",
|
||||
};
|
||||
}
|
||||
import { useManagementFailureMessage } from "../studio-copy.ts";
|
||||
import {
|
||||
useManagementCommands,
|
||||
useManagementReleasesQuery,
|
||||
} from "../studio-management-server-state.ts";
|
||||
|
||||
const STATUS_LABELS: Readonly<Record<string, string>> = {
|
||||
DRAFT: "작성 중",
|
||||
@@ -80,81 +28,71 @@ const STATUS_LABELS: Readonly<Record<string, string>> = {
|
||||
ARCHIVED: "보관",
|
||||
};
|
||||
|
||||
|
||||
const RELEASE_CREATE_SCHEMA = z.object({
|
||||
title: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export function ReleaseManager() {
|
||||
const { managementGateway, setRequestAnnouncement } = useStudio();
|
||||
const [releases, setReleases] = useState<ReleaseIndexItem[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const copy = useTechLogCopy();
|
||||
const managementFailureMessage = useManagementFailureMessage();
|
||||
const { setRequestAnnouncement } = useStudio();
|
||||
const releasesQuery = useManagementReleasesQuery();
|
||||
const commands = useManagementCommands();
|
||||
|
||||
const releases = releasesQuery.data?.items ?? null;
|
||||
const loading = releasesQuery.state.base === "initial-loading";
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
/* 릴리즈는 공개 사이트에 남는 기록이다. 지우기 전에 무엇이 지워지는지 이름으로 보여 준다. */
|
||||
const [pendingDelete, setPendingDelete] = useState<ReleaseIndexItem | null>(null);
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const [newTitle, setNewTitle] = useState("");
|
||||
/* 방금 만든 릴리즈를 목록에서 짚어 준다 — 목록이 길면 어느 것이 새것인지 알기 어렵다. */
|
||||
const [pendingDelete, setPendingDelete] =
|
||||
useState<ReleaseIndexItem | null>(null);
|
||||
const [createdId, setCreatedId] = useState<string | null>(null);
|
||||
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
const createForm = useAppForm({
|
||||
schema: RELEASE_CREATE_SCHEMA,
|
||||
defaultValues: { title: "" },
|
||||
allowedServerFields: ["title"] as const,
|
||||
mapToCommand(values) {
|
||||
return { title: values.title.trim() };
|
||||
},
|
||||
submit: commands.createRelease.submit,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void managementGateway.listReleases(0, 50).then(
|
||||
(page) => {
|
||||
if (cancelled) return;
|
||||
setReleases(page.items ?? []);
|
||||
setLoading(false);
|
||||
},
|
||||
() => {
|
||||
if (cancelled) return;
|
||||
setError("릴리즈를 불러오지 못했습니다.");
|
||||
setLoading(false);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [managementGateway, generation]);
|
||||
const pending =
|
||||
createForm.pending ||
|
||||
commands.deleteRelease.state.overlay.mutationPending;
|
||||
|
||||
const submitNew = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
const title = newTitle.trim();
|
||||
if (!title) {
|
||||
setError("릴리즈 제목을 입력해 주세요.");
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
const submitNew = async (event: FormEvent<HTMLFormElement>) => {
|
||||
setError("");
|
||||
try {
|
||||
const created = await managementGateway.createRelease(title);
|
||||
setNewTitle("");
|
||||
setRequestAnnouncement(
|
||||
`릴리즈 ${title} 초안을 만들었습니다. 목록에서 편집을 눌러 내용을 채웁니다.`,
|
||||
);
|
||||
setCreatedId(created.id);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "릴리즈를 만들지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
const title = createForm.values.title.trim();
|
||||
const created = await createForm.submitForm(event);
|
||||
if (!created?.ok) return;
|
||||
|
||||
setRequestAnnouncement(copy("techLog.notice.releaseDraftCreated", { title }));
|
||||
setCreatedId(created.value.id);
|
||||
await releasesQuery.retry();
|
||||
};
|
||||
|
||||
const remove = async (release: ReleaseIndexItem) => {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await managementGateway.deleteRelease(release.id, release.version);
|
||||
setRequestAnnouncement(`릴리즈 ${release.versionLabel} 을(를) 삭제했습니다.`);
|
||||
setPendingDelete(null);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "삭제하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
|
||||
const removed = await commands.deleteRelease.submit({
|
||||
id: release.id,
|
||||
expectedVersion: release.version,
|
||||
});
|
||||
if (!removed.ok) {
|
||||
setError(
|
||||
managementFailureMessage(
|
||||
removed.error,
|
||||
copy("techLog.failure.deleteFailed"),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setRequestAnnouncement(copy("techLog.notice.releaseDeleted", { version: release.versionLabel }));
|
||||
setPendingDelete(null);
|
||||
await releasesQuery.retry();
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -168,33 +106,50 @@ export function ReleaseManager() {
|
||||
</header>
|
||||
|
||||
<section className="studio-document-tools" aria-label="릴리즈 만들기">
|
||||
<form onSubmit={submitNew}>
|
||||
<label htmlFor="release-new-title">새 릴리즈</label>
|
||||
<div>
|
||||
<input
|
||||
id="release-new-title"
|
||||
type="text"
|
||||
value={newTitle}
|
||||
<Form
|
||||
className="studio-taxonomy-create-form"
|
||||
pending={createForm.pending}
|
||||
onSubmit={(event) => {
|
||||
void submitNew(event);
|
||||
}}
|
||||
>
|
||||
<div className="studio-taxonomy-create-controls">
|
||||
<TextField
|
||||
{...createForm.field("title")}
|
||||
className="studio-taxonomy-create-field"
|
||||
label="새 릴리즈"
|
||||
placeholder="릴리즈 제목"
|
||||
onChange={(event) => setNewTitle(event.target.value)}
|
||||
/>
|
||||
<button type="submit" disabled={pending}>
|
||||
추가
|
||||
</button>
|
||||
<Button
|
||||
disabled={pending}
|
||||
pending={createForm.pending}
|
||||
pendingLabel={copy("techLog.action.adding")}
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.add")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
<ErrorSummary
|
||||
fieldErrors={createForm.fieldErrors}
|
||||
formErrors={createForm.formErrors}
|
||||
fieldId={createForm.fieldId}
|
||||
fieldLabels={{ title: "새 릴리즈" }}
|
||||
onFocusField={createForm.focusField}
|
||||
/>
|
||||
</Form>
|
||||
</section>
|
||||
|
||||
{error ? (
|
||||
{error || releasesQuery.state.base === "terminal-error" ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
{error || copy("techLog.state.releaseLoadFailed")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{loading ? (
|
||||
<p className="studio-empty-inline">불러오는 중입니다.</p>
|
||||
<p className="studio-empty-inline">{copy("techLog.state.releaseLoading")}</p>
|
||||
) : (releases?.length ?? 0) === 0 ? (
|
||||
<p className="studio-empty-inline">아직 릴리즈가 없습니다.</p>
|
||||
<p className="studio-empty-inline">{copy("techLog.state.releasesEmpty")}</p>
|
||||
) : (
|
||||
<section aria-label="릴리즈 목록">
|
||||
<p className="studio-result-count">{releases?.length}개의 릴리즈</p>
|
||||
@@ -238,21 +193,22 @@ export function ReleaseManager() {
|
||||
<div className="studio-row-actions">
|
||||
<GuardedStudioLink
|
||||
className="studio-secondary-button"
|
||||
href={`/studio/releases/${release.id}`}
|
||||
href={studioRoutes.releaseEdit(release.id)}
|
||||
>
|
||||
편집
|
||||
</GuardedStudioLink>
|
||||
<button
|
||||
<Button
|
||||
className="studio-secondary-button studio-danger-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setError("");
|
||||
setPendingDelete(release);
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
{copy("techLog.action.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { Button, InputControl, SelectControl } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import type { Asset, AssetKind } from "../../../contracts/studio/contract.ts";
|
||||
import { useStudioAssetGateway } from "../use-studio.ts";
|
||||
import { buildEvidenceDirective } from "./asset-picker.tsx";
|
||||
import { AssetPickerDialog, countBodyAssets } from "./asset-picker-dialog.tsx";
|
||||
import { AssetUploadDialog } from "./asset-upload-dialog.tsx";
|
||||
@@ -24,7 +25,7 @@ export function SetupFields({ draft, issues, onChange }: {
|
||||
issues: readonly FieldIssue[];
|
||||
onChange(draft: SetupInput): void;
|
||||
}) {
|
||||
const assetGateway = useStudioAssetGateway();
|
||||
const copy = useTechLogCopy();
|
||||
const bodyEditorRef = useRef<MarkdownBlockEditorHandle>(null);
|
||||
const uploadTriggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [uploadKind, setUploadKind] = useState<AssetKind>("DIAGRAM");
|
||||
@@ -46,12 +47,12 @@ export function SetupFields({ draft, issues, onChange }: {
|
||||
<div className="studio-version-properties">
|
||||
{draft.pinnedVersions.map((pinned, index) => (
|
||||
<div className="studio-version-property" key={index}>
|
||||
<input aria-label={`고정 버전 ${index + 1} 이름`} value={pinned.name} placeholder="Keycloak" onChange={(event) => replaceVersion(index, { name: event.currentTarget.value })} />
|
||||
<input aria-label={`고정 버전 ${index + 1} 버전`} value={pinned.version} placeholder="26.7.0" onChange={(event) => replaceVersion(index, { version: event.currentTarget.value })} />
|
||||
<button type="button" onClick={() => update({ pinnedVersions: draft.pinnedVersions.filter((_, at) => at !== index) })}>삭제</button>
|
||||
<InputControl aria-label={`고정 버전 ${index + 1} 이름`} value={pinned.name} placeholder="Keycloak" onChange={(event) => replaceVersion(index, { name: event.currentTarget.value })} />
|
||||
<InputControl aria-label={`고정 버전 ${index + 1} 버전`} value={pinned.version} placeholder="26.7.0" onChange={(event) => replaceVersion(index, { version: event.currentTarget.value })} />
|
||||
<Button visualPolicy="inherit" type="button" onClick={() => update({ pinnedVersions: draft.pinnedVersions.filter((_, at) => at !== index) })}>{copy("techLog.action.delete")}</Button>
|
||||
</div>
|
||||
))}
|
||||
<button className="studio-inline-add" type="button" onClick={() => update({ pinnedVersions: [...draft.pinnedVersions, { name: "", version: "" }] })}>+ 버전 추가</button>
|
||||
<Button visualPolicy="inherit" className="studio-inline-add" type="button" onClick={() => update({ pinnedVersions: [...draft.pinnedVersions, { name: "", version: "" }] })}>{copy("techLog.action.addVersion")}</Button>
|
||||
<FieldNotice issues={issues} path="/pinnedVersions" />
|
||||
</div>
|
||||
</details>
|
||||
@@ -60,16 +61,16 @@ export function SetupFields({ draft, issues, onChange }: {
|
||||
<div className="studio-body-authoring__heading">
|
||||
<div><span>절차</span><p>명령은 코드 블록으로, 단계는 제목과 목록으로 나누면 공개 화면에도 그대로 반영됩니다.</p></div>
|
||||
<div className="studio-inline-asset-actions">
|
||||
<AssetPickerDialog gateway={assetGateway} usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><select value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</select></label>
|
||||
<button ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>업로드</button>
|
||||
<AssetPickerDialog usedCount={countBodyAssets(draft.bodyMarkdown)} onInsert={insertDirective} />
|
||||
<label className="studio-asset-kind-field studio-asset-kind-field--compact"><span className="studio-visually-hidden">업로드 종류</span><SelectControl value={uploadKind} onChange={(event) => setUploadKind(event.currentTarget.value as AssetKind)}>{ASSET_KIND_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}</SelectControl></label>
|
||||
<Button visualPolicy="inherit" ref={uploadTriggerRef} type="button" className="studio-secondary-button" aria-label="Asset 업로드" onClick={() => setUploadOpen(true)}>{copy("techLog.action.upload")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
<MarkdownBlockEditor ref={bodyEditorRef} label="절차 본문" value={draft.bodyMarkdown} onChange={(bodyMarkdown) => update({ bodyMarkdown })} />
|
||||
<FieldNotice issues={issues} path="/bodyMarkdown" />
|
||||
</div>
|
||||
|
||||
{uploadOpen ? <AssetUploadDialog gateway={assetGateway} kind={uploadKind} onUploaded={(asset) => {
|
||||
{uploadOpen ? <AssetUploadDialog kind={uploadKind} onUploaded={(asset) => {
|
||||
insertDirective(buildEvidenceDirective({ assetKey: asset.assetKey, alt: asset.decorative ? "" : (asset.altText ?? ""), caption: "", zoom: asset.kind === "DIAGRAM" }));
|
||||
setUploadOpen(false);
|
||||
}} onClose={() => setUploadOpen(false)} /> : null}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import type { StudioDashboard as StudioDashboardData } from "../../../contracts/studio/contract.ts";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
import { useStudioDashboardQuery } from "../studio-workspace-server-state.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { HomeFocusEditor } from "./home-focus-editor.tsx";
|
||||
import { DOCUMENT_KIND_LABELS } from "../../shared/document-kind-labels.ts";
|
||||
@@ -29,7 +28,7 @@ function ContinueWorking({ item }: Readonly<{ item: DocumentSummary }>) {
|
||||
이어서 하기
|
||||
</p>
|
||||
<h2>
|
||||
<GuardedStudioLink href={`/studio/documents/${item.id}/edit`}>
|
||||
<GuardedStudioLink href={studioRoutes.documentEdit(item.id)}>
|
||||
{item.title || "제목 없는 작업본"}
|
||||
</GuardedStudioLink>
|
||||
</h2>
|
||||
@@ -56,7 +55,7 @@ function WorkRow({ item }: Readonly<{ item: DocumentSummary }>) {
|
||||
<p className="studio-row-label">{DOCUMENT_KIND_LABELS[item.kind]}</p>
|
||||
<div>
|
||||
<h3>
|
||||
<GuardedStudioLink href={`/studio/documents/${item.id}/edit`}>
|
||||
<GuardedStudioLink href={studioRoutes.documentEdit(item.id)}>
|
||||
{item.title || "제목 없는 작업본"}
|
||||
</GuardedStudioLink>
|
||||
</h3>
|
||||
@@ -109,25 +108,14 @@ function WorkSection({
|
||||
);
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown): boolean {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function StudioDashboard() {
|
||||
const { gateway } = useStudio();
|
||||
const [dashboard, setDashboard] = useState<StudioDashboardData | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void gateway.getDashboard({ signal: controller.signal }).then(
|
||||
(value) => setDashboard(value),
|
||||
(reason: unknown) => {
|
||||
if (!isAbortError(reason)) setError("작업 흐름을 불러오지 못했습니다.");
|
||||
},
|
||||
);
|
||||
return () => controller.abort();
|
||||
}, [gateway]);
|
||||
const copy = useTechLogCopy();
|
||||
const dashboardQuery = useStudioDashboardQuery();
|
||||
const dashboard = dashboardQuery.data ?? null;
|
||||
const error =
|
||||
dashboardQuery.state.base === "terminal-error"
|
||||
? copy("techLog.state.dashboardLoadFailed")
|
||||
: "";
|
||||
|
||||
/*
|
||||
세 칸은 한 줄기의 서로 다른 구간이다. 예전에는 「검증과 미리보기」와 「게시 준비」가
|
||||
@@ -162,7 +150,7 @@ export function StudioDashboard() {
|
||||
<h1>작업 흐름</h1>
|
||||
<p>작성 중인 기록을 이어서 정리하고 검증·게시 흐름으로 연결합니다.</p>
|
||||
</div>
|
||||
<GuardedStudioLink className="studio-primary-action" href="/studio/documents/new">
|
||||
<GuardedStudioLink className="studio-primary-action" href={studioRoutes.documentNew()}>
|
||||
새 문서
|
||||
</GuardedStudioLink>
|
||||
</header>
|
||||
@@ -173,7 +161,7 @@ export function StudioDashboard() {
|
||||
) : null}
|
||||
{!dashboard && !error ? (
|
||||
<p className="studio-loading" role="status">
|
||||
Studio 요약을 불러오는 중입니다.
|
||||
{copy("techLog.state.dashboardLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
{dashboard ? (
|
||||
@@ -190,19 +178,19 @@ export function StudioDashboard() {
|
||||
*/}
|
||||
{continueItem ? <ContinueWorking item={continueItem} /> : null}
|
||||
<section className="studio-summary-grid" aria-label="Studio 요약">
|
||||
<GuardedStudioLink href="/studio/documents">
|
||||
<GuardedStudioLink href={studioRoutes.documents()}>
|
||||
<span>전체 작업본</span>
|
||||
<strong>{dashboard.totals.documents}</strong>
|
||||
</GuardedStudioLink>
|
||||
<GuardedStudioLink href="/studio/documents?status=NEVER_PUBLISHED">
|
||||
<GuardedStudioLink href={studioRoutes.documents({ status: "NEVER_PUBLISHED" })}>
|
||||
<span>검증할 기록</span>
|
||||
<strong>{validationItems.length}</strong>
|
||||
</GuardedStudioLink>
|
||||
<GuardedStudioLink href="/studio/documents?status=NEVER_PUBLISHED">
|
||||
<GuardedStudioLink href={studioRoutes.documents({ status: "NEVER_PUBLISHED" })}>
|
||||
<span>게시 준비</span>
|
||||
<strong>{dashboard.totals.readyToPublish}</strong>
|
||||
</GuardedStudioLink>
|
||||
<GuardedStudioLink href="/studio/publications">
|
||||
<GuardedStudioLink href={studioRoutes.publications()}>
|
||||
<span>게시 기록</span>
|
||||
<strong>{dashboard.totals.publications}</strong>
|
||||
</GuardedStudioLink>
|
||||
@@ -210,25 +198,25 @@ export function StudioDashboard() {
|
||||
<WorkSection
|
||||
title="이어서 작성"
|
||||
items={writingItems}
|
||||
href="/studio/documents"
|
||||
empty="이어서 작성할 문서가 없습니다."
|
||||
href={studioRoutes.documents()}
|
||||
empty={copy("techLog.state.dashboardContinueEmpty")}
|
||||
/>
|
||||
<WorkSection
|
||||
title="검증과 미리보기"
|
||||
items={validationItems}
|
||||
href="/studio/documents"
|
||||
empty="현재 검증할 문서가 없습니다."
|
||||
href={studioRoutes.documents()}
|
||||
empty={copy("techLog.state.dashboardValidateEmpty")}
|
||||
/>
|
||||
<WorkSection
|
||||
title="게시 준비"
|
||||
items={dashboard.readyToPublish}
|
||||
href="/studio/documents"
|
||||
empty="게시 준비가 끝난 문서가 없습니다."
|
||||
href={studioRoutes.documents()}
|
||||
empty={copy("techLog.state.dashboardReadyEmpty")}
|
||||
/>
|
||||
<section className="studio-work-section">
|
||||
<div className="studio-section-title">
|
||||
<h2>최근 게시</h2>
|
||||
<GuardedStudioLink href="/studio/publications">
|
||||
<GuardedStudioLink href={studioRoutes.publications()}>
|
||||
게시 기록 보기
|
||||
</GuardedStudioLink>
|
||||
</div>
|
||||
@@ -258,7 +246,7 @@ export function StudioDashboard() {
|
||||
</article>
|
||||
))
|
||||
) : (
|
||||
<p className="studio-empty-inline">아직 게시 기록이 없습니다.</p>
|
||||
<p className="studio-empty-inline">{copy("techLog.state.emptyPublicationHistory")}</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Button } from "../../../../../presentation/design-system/index.ts";
|
||||
import { useId, useState } from "react";
|
||||
|
||||
import { useLocale } from "../../../../../presentation/i18n/index.ts";
|
||||
@@ -5,7 +6,9 @@ import { useSession } from "../../../../../presentation/providers/session-provid
|
||||
|
||||
import { techLogNavigation } from "../../tech-log-navigation.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
|
||||
import { publicRoutes } from "../../public/public-routes.ts";
|
||||
/**
|
||||
* Which entries exist, what they are called and in what order comes from the
|
||||
* route contract. Only the active-state rule stays here: "작업본" stays
|
||||
@@ -15,10 +18,12 @@ import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
const activeRules: Readonly<Record<string, (path: string) => boolean>> =
|
||||
Object.freeze({
|
||||
TECH_LOG_STUDIO_DOCUMENTS: (path) =>
|
||||
path.startsWith("/studio/documents") && path !== "/studio/documents/new",
|
||||
path.startsWith(studioRoutes.documents()) &&
|
||||
path !== studioRoutes.documentNew(),
|
||||
TECH_LOG_STUDIO_PUBLICATIONS: (path) =>
|
||||
path.startsWith("/studio/publications"),
|
||||
TECH_LOG_STUDIO_DOCUMENT_NEW: (path) => path === "/studio/documents/new",
|
||||
path.startsWith(studioRoutes.publications()),
|
||||
TECH_LOG_STUDIO_DOCUMENT_NEW: (path) =>
|
||||
path === studioRoutes.documentNew(),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -33,45 +38,58 @@ const activeRules: Readonly<Record<string, (path: string) => boolean>> =
|
||||
*
|
||||
* <p>`Record<…>` 라 계약에 탐색 항목이 늘면 컴파일러가 빈 자리를 잡는다.
|
||||
*/
|
||||
type StudioGroup = "작업" | "구조" | "자료" | "게시";
|
||||
type StudioGroup = "WORK" | "STRUCTURE" | "ASSETS" | "PUBLISH";
|
||||
|
||||
const GROUP_LABEL_KEYS = {
|
||||
WORK: "techLog.studio.group.work",
|
||||
STRUCTURE: "techLog.studio.group.structure",
|
||||
ASSETS: "techLog.studio.group.assets",
|
||||
PUBLISH: "techLog.studio.group.publish",
|
||||
} as const;
|
||||
|
||||
const GROUP_OF: Record<string, StudioGroup> = {
|
||||
TECH_LOG_STUDIO_DOCUMENTS: "작업",
|
||||
TECH_LOG_STUDIO_DOCUMENT_NEW: "작업",
|
||||
TECH_LOG_STUDIO_TAXONOMY: "구조",
|
||||
TECH_LOG_STUDIO_ASSETS: "자료",
|
||||
TECH_LOG_STUDIO_PUBLICATIONS: "게시",
|
||||
TECH_LOG_STUDIO_RELEASES: "게시",
|
||||
TECH_LOG_STUDIO_DOCUMENTS: "WORK",
|
||||
TECH_LOG_STUDIO_DOCUMENT_NEW: "WORK",
|
||||
TECH_LOG_STUDIO_TAXONOMY: "STRUCTURE",
|
||||
TECH_LOG_STUDIO_ASSETS: "ASSETS",
|
||||
TECH_LOG_STUDIO_PUBLICATIONS: "PUBLISH",
|
||||
TECH_LOG_STUDIO_RELEASES: "PUBLISH",
|
||||
};
|
||||
|
||||
const GROUP_ORDER: ReadonlyArray<StudioGroup> = ["작업", "구조", "자료", "게시"];
|
||||
const GROUP_ORDER: ReadonlyArray<StudioGroup> = [
|
||||
"WORK",
|
||||
"STRUCTURE",
|
||||
"ASSETS",
|
||||
"PUBLISH",
|
||||
];
|
||||
|
||||
/** 그 일을 고르면 먼저 열리는 화면. */
|
||||
const GROUP_HOME: Record<StudioGroup, string> = {
|
||||
작업: "/studio/documents",
|
||||
구조: "/studio/taxonomy",
|
||||
자료: "/studio/assets",
|
||||
게시: "/studio/publications",
|
||||
WORK: studioRoutes.documents(),
|
||||
STRUCTURE: studioRoutes.taxonomy(),
|
||||
ASSETS: studioRoutes.assets(),
|
||||
PUBLISH: studioRoutes.publications(),
|
||||
};
|
||||
|
||||
const navigation = techLogNavigation("STUDIO").map((entry) => ({
|
||||
routeId: entry.routeId,
|
||||
href: entry.path,
|
||||
label: entry.label,
|
||||
group: GROUP_OF[entry.routeId] ?? "작업",
|
||||
messageKey: entry.messageKey,
|
||||
group: GROUP_OF[entry.routeId] ?? "WORK",
|
||||
active: activeRules[entry.routeId] ?? ((path: string) => path === entry.path),
|
||||
}));
|
||||
|
||||
/** 지금 보고 있는 일. 어느 화면에도 걸리지 않으면(대시보드 등) 「작업」으로 둔다. */
|
||||
function currentGroup(path: string): StudioGroup {
|
||||
const match = navigation.find((item) => item.active(path));
|
||||
return match?.group ?? "작업";
|
||||
return match?.group ?? "WORK";
|
||||
}
|
||||
|
||||
function StudioNavigation({
|
||||
currentPath,
|
||||
label,
|
||||
}: Readonly<{ currentPath: string; label: string }>) {
|
||||
const { message } = useLocale();
|
||||
const here = currentGroup(currentPath);
|
||||
const inGroup = navigation.filter((item) => item.group === here);
|
||||
return (
|
||||
@@ -83,7 +101,7 @@ function StudioNavigation({
|
||||
href={GROUP_HOME[group]}
|
||||
aria-current={group === here ? "true" : undefined}
|
||||
>
|
||||
{group}
|
||||
{message(GROUP_LABEL_KEYS[group])}
|
||||
</GuardedStudioLink>
|
||||
))}
|
||||
</span>
|
||||
@@ -99,13 +117,13 @@ function StudioNavigation({
|
||||
href={item.href}
|
||||
aria-current={item.active(currentPath) ? "page" : undefined}
|
||||
>
|
||||
{item.label}
|
||||
{message(item.messageKey)}
|
||||
</GuardedStudioLink>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="studio-nav-tail">
|
||||
<a href="/">공개 사이트 보기</a>
|
||||
<a href={publicRoutes.home()}>{message("techLog.studio.publicSite")}</a>
|
||||
<StudioSessionAction />
|
||||
</span>
|
||||
</nav>
|
||||
@@ -125,7 +143,7 @@ function StudioSessionAction() {
|
||||
const [pending, setPending] = useState(false);
|
||||
if (sessionState !== "authenticated") return null;
|
||||
return (
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
className="studio-session-action"
|
||||
disabled={pending}
|
||||
@@ -135,11 +153,12 @@ function StudioSessionAction() {
|
||||
}}
|
||||
>
|
||||
{message("action.signOut")}
|
||||
</button>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function StudioHeader({ currentPath }: Readonly<{ currentPath: string }>) {
|
||||
const { message } = useLocale();
|
||||
const [open, setOpen] = useState(false);
|
||||
const mobileId = useId();
|
||||
return (
|
||||
@@ -147,26 +166,32 @@ export function StudioHeader({ currentPath }: Readonly<{ currentPath: string }>)
|
||||
<div className="studio-header-inner">
|
||||
<GuardedStudioLink
|
||||
className="studio-wordmark"
|
||||
href="/studio"
|
||||
href={studioRoutes.home()}
|
||||
aria-label="TechLog Studio"
|
||||
>
|
||||
TechLog <span>Studio</span>
|
||||
</GuardedStudioLink>
|
||||
<div className="studio-desktop-navigation">
|
||||
<StudioNavigation currentPath={currentPath} label="Studio 주 탐색" />
|
||||
<StudioNavigation
|
||||
currentPath={currentPath}
|
||||
label={message("techLog.studio.primaryNavigation")}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
className="studio-menu-trigger"
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
aria-controls={mobileId}
|
||||
onClick={() => setOpen((current) => !current)}
|
||||
>
|
||||
{open ? "Studio 메뉴 닫기" : "Studio 메뉴 열기"}
|
||||
</button>
|
||||
{message(open ? "techLog.studio.menuClose" : "techLog.studio.menuOpen")}
|
||||
</Button>
|
||||
</div>
|
||||
<div id={mobileId} className="studio-mobile-navigation" hidden={!open}>
|
||||
<StudioNavigation currentPath={currentPath} label="Studio 모바일 탐색" />
|
||||
<StudioNavigation
|
||||
currentPath={currentPath}
|
||||
label={message("techLog.studio.mobileNavigation")}
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
|
||||
@@ -1,36 +1,8 @@
|
||||
import { Pagination } from "../../../../../presentation/design-system/index.ts";
|
||||
import type { components } from "../../../contracts/studio/generated.ts";
|
||||
|
||||
type PageMetadata = components["schemas"]["StudioPageMetadata"];
|
||||
|
||||
/**
|
||||
* 페이지가 많아지면 번호를 다 그릴 수 없다. 현재 쪽 좌우로 이만큼씩만 그리고 나머지는 생략한다 —
|
||||
* 첫 쪽과 끝 쪽은 늘 남긴다. 목록 어디에 있든 처음과 끝으로 한 번에 갈 수 있어야 한다.
|
||||
*/
|
||||
const AROUND = 2;
|
||||
|
||||
function pageNumbers(current: number, total: number): ReadonlyArray<number | "gap"> {
|
||||
if (total <= 1) return total === 1 ? [1] : [];
|
||||
const shown = new Set<number>([1, total]);
|
||||
for (let n = current - AROUND; n <= current + AROUND; n += 1) {
|
||||
if (n >= 1 && n <= total) shown.add(n);
|
||||
}
|
||||
const sorted = [...shown].sort((left, right) => left - right);
|
||||
const out: (number | "gap")[] = [];
|
||||
let previous = 0;
|
||||
for (const n of sorted) {
|
||||
if (previous && n - previous > 1) out.push("gap");
|
||||
out.push(n);
|
||||
previous = n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Studio 목록의 페이지 이동.
|
||||
*
|
||||
* <p>예전에는 「다음」 하나뿐이었다 — 목록이 커서 페이지네이션이라 앞으로만 갈 수 있었고, 뒤로
|
||||
* 넘어간 뒤 앞쪽으로 돌아올 방법이 없었다. 지금은 서버가 총 쪽수를 주므로 번호를 그린다.
|
||||
*/
|
||||
export function StudioPagination({
|
||||
page,
|
||||
onChange,
|
||||
@@ -38,51 +10,23 @@ export function StudioPagination({
|
||||
}: {
|
||||
page: PageMetadata;
|
||||
onChange: (next: number) => void;
|
||||
/** 이 목록이 무엇인지 — 화면에 목록이 둘 이상일 때 보조 기술이 구분한다. */
|
||||
label: string;
|
||||
}) {
|
||||
if (page.totalPages <= 1) return null;
|
||||
const numbers = pageNumbers(page.number, page.totalPages);
|
||||
|
||||
return (
|
||||
<nav className="studio-pagination" aria-label={label}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(page.number - 1)}
|
||||
disabled={!page.hasPrevious}
|
||||
aria-label="이전 페이지"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
<ol>
|
||||
{numbers.map((entry, index) =>
|
||||
entry === "gap" ? (
|
||||
// 생략된 구간. 읽어 줄 것이 없으므로 보조 기술에서는 숨긴다.
|
||||
<li key={`gap-${index}`} aria-hidden="true" className="studio-pagination__gap">
|
||||
…
|
||||
</li>
|
||||
) : (
|
||||
<li key={entry}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(entry)}
|
||||
aria-label={`${entry} 페이지`}
|
||||
aria-current={entry === page.number ? "page" : undefined}
|
||||
>
|
||||
{entry}
|
||||
</button>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ol>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(page.number + 1)}
|
||||
disabled={!page.hasNext}
|
||||
aria-label="다음 페이지"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</nav>
|
||||
<Pagination
|
||||
around={2}
|
||||
className="studio-pagination"
|
||||
label={label}
|
||||
nextLabel="다음 페이지"
|
||||
onChange={onChange}
|
||||
page={page.number}
|
||||
pageCount={page.totalPages}
|
||||
pageAccessibleLabel={(candidate) => String(candidate) + " 페이지"}
|
||||
pageControl="button"
|
||||
pageLabel={(candidate) => String(candidate)}
|
||||
previousLabel="이전 페이지"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
import { useTechLogCopy } from "../studio-copy.ts";
|
||||
import { studioRoutes } from "../studio-routes.ts";
|
||||
import { PROJECT_PHASE_LABELS } from "../../../domain/public/project-phase-labels.ts";
|
||||
import { DestructiveConfirmDialog } from "./destructive-confirm-dialog.tsx";
|
||||
import { useTaxonomyController } from "../controllers/use-taxonomy-controller.ts";
|
||||
import {
|
||||
Button,
|
||||
TextField,
|
||||
} from "../../../../../presentation/design-system/index.ts";
|
||||
import {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
} from "../../../../../presentation/forms/index.ts";
|
||||
|
||||
import type { ProjectIndexItem, TopicEdit } from "../../../contracts/management/contract.ts";
|
||||
import { managementFailureMessage } from "../../../application/ports/management-gateway-error.ts";
|
||||
import { GuardedStudioLink } from "./guarded-studio-link.tsx";
|
||||
import { slugFromName } from "./slug-from-name.ts";
|
||||
import { useStudio } from "../use-studio.ts";
|
||||
|
||||
/**
|
||||
* 주제와 프로젝트 관리.
|
||||
*
|
||||
* <p>이 화면이 존재하는 이유는 문서 발행이 주제를 요구하는데 주제를 만들 곳이 없었기 때문이다.
|
||||
* 그래서 범위를 목록·생성·삭제로 끊었다 — 편집(이름 변경, 단계 전환, 공개 범위)은 계약에 있고
|
||||
* 백엔드도 구현돼 있으나, 그 화면은 별도 설계가 필요하다.
|
||||
*
|
||||
* <p>새 CSS 를 만들지 않는다. 작업본 목록이 쓰는 클래스만 재사용하므로 이 화면은 Studio 의
|
||||
* 나머지와 같은 간격·타이포·색을 그대로 따른다.
|
||||
*/
|
||||
|
||||
const visibilityLabel: Record<string, string> = {
|
||||
PRIVATE: "비공개",
|
||||
@@ -25,216 +20,30 @@ const visibilityLabel: Record<string, string> = {
|
||||
PUBLIC: "공개",
|
||||
};
|
||||
|
||||
|
||||
export function TaxonomyManager() {
|
||||
const { managementGateway, setRequestAnnouncement } = useStudio();
|
||||
const [topics, setTopics] = useState<TopicEdit[] | null>(null);
|
||||
const [projects, setProjects] = useState<ProjectIndexItem[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
/*
|
||||
주제와 프로젝트는 다른 기록이 매달려 있는 자리다. 지우기 직전에 무엇이 지워지는지 이름으로
|
||||
보여 주고 한 번 묻는다 — 목록에서 두 줄 아래를 눌렀다는 것을 여기서 잡는다.
|
||||
*/
|
||||
/*
|
||||
한 화면이 성격이 다른 두 엔티티를 같은 문법으로 다루고 있었다. 만들기 폼 둘이 한 줄에 붙어
|
||||
「추가」 버튼 두 개가 같은 이름·같은 모양으로 나란히 섰고, 주제 행은 프로젝트에 맞춘 그리드라
|
||||
절반이 빈칸이었다. 탭으로 나눠 한 번에 한 종류만 다룬다.
|
||||
*/
|
||||
const [tab, setTab] = useState<"STRUCTURE" | "TOPIC" | "PROJECT">("STRUCTURE");
|
||||
/* 프로젝트마다 어느 주제를 묶었는지. 목록에는 없고 상세에만 있어 따로 읽는다. */
|
||||
const [links, setLinks] = useState<ReadonlyMap<string, readonly string[]>>(new Map());
|
||||
const [pendingDelete, setPendingDelete] = useState<
|
||||
{ kind: "TOPIC"; topic: TopicEdit } | { kind: "PROJECT"; project: ProjectIndexItem } | null
|
||||
>(null);
|
||||
const [generation, setGeneration] = useState(0);
|
||||
|
||||
const [topicName, setTopicName] = useState("");
|
||||
const [topicSlug, setTopicSlug] = useState("");
|
||||
const [projectTitle, setProjectTitle] = useState("");
|
||||
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void Promise.all([managementGateway.listTopics(), managementGateway.listProjects(0, 50)]).then(
|
||||
([topicList, projectPage]) => {
|
||||
if (cancelled) return;
|
||||
setTopics(topicList);
|
||||
const items = projectPage.items ?? [];
|
||||
setProjects(items);
|
||||
setLoading(false);
|
||||
/*
|
||||
어느 프로젝트가 어느 주제를 묶었는지는 목록에 없고 상세에만 있다. 구조를 그리려면
|
||||
그 연결이 필요하므로 따로 읽는다 — 실패해도 목록 두 개는 이미 그려져 있으므로
|
||||
구조 탭만 비고 화면 전체가 죽지는 않는다.
|
||||
*/
|
||||
void Promise.all(
|
||||
items.map(async (project) =>
|
||||
project.id
|
||||
? ([project.id, (await managementGateway.getProject(project.id)).topicIds ?? []] as const)
|
||||
: null,
|
||||
),
|
||||
).then(
|
||||
(pairs) => {
|
||||
if (cancelled) return;
|
||||
setLinks(new Map(pairs.filter((pair) => pair !== null)));
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
},
|
||||
() => {
|
||||
if (cancelled) return;
|
||||
setError("주제와 프로젝트를 불러오지 못했습니다.");
|
||||
setLoading(false);
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [managementGateway, generation]);
|
||||
|
||||
/**
|
||||
* slug 를 비워 두면 이름에서 만든다. 한글 이름이 흔한데 이전 규칙은 한글을 전부 버려서, 이름에
|
||||
* 섞인 영문·숫자만 남았다 — `인증` 은 빈 slug 가 되고 `Redis 캐시` 와 `Redis 클러스터` 는 둘 다
|
||||
* `redis` 가 됐다. 지금은 로마자로 옮긴다 ({@link slugFromName}).
|
||||
*/
|
||||
const slugify = slugFromName;
|
||||
|
||||
const submitTopic = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
const name = topicName.trim();
|
||||
const slug = slugify(topicSlug || topicName);
|
||||
if (!name || !slug) {
|
||||
setError("주제 이름과 slug 를 입력해 주세요. slug 는 영문·숫자·하이픈만 가능합니다.");
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await managementGateway.createTopic({ name, slug } as TopicEdit);
|
||||
setTopicName("");
|
||||
setTopicSlug("");
|
||||
setRequestAnnouncement(`주제 ${name} 을(를) 만들었습니다.`);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "주제를 만들지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submitProject = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
const title = projectTitle.trim();
|
||||
if (!title) {
|
||||
setError("프로젝트 이름을 입력해 주세요.");
|
||||
return;
|
||||
}
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
const created = await managementGateway.createProject(title);
|
||||
/*
|
||||
생성 계약은 이름만 받는데(`CreateDraftRequest`), slug 가 없는 프로젝트는 공개 화면에
|
||||
나타날 수 없다 — 공개 계약의 `ProjectSummary` 는 `slug` 와 `path` 를 요구하므로 서버는
|
||||
slug 가 빈 프로젝트를 통째로 생략한다. 기록에 프로젝트를 붙여 게시해도 공개 문서의
|
||||
프로젝트 칸이 비어 있던 이유가 이것이다.
|
||||
|
||||
그래서 만든 직후에 이름에서 만든 slug 를 채운다. 주제가 `{name, slug}` 를 함께 보내는
|
||||
것과 같은 규칙이고(`slugFromName`), 한글 이름도 로마자로 옮겨 유효한 slug 가 된다.
|
||||
*/
|
||||
const project = await managementGateway.getProject(created.id);
|
||||
await managementGateway.updateProject(created.id, {
|
||||
expectedVersion: project.version,
|
||||
name: project.name,
|
||||
slug: slugFromName(project.name),
|
||||
oneLinePurpose: project.oneLinePurpose ?? "",
|
||||
purposeMarkdown: project.purposeMarkdown ?? "",
|
||||
boundaryMarkdown: project.boundaryMarkdown ?? "",
|
||||
phase: project.phase,
|
||||
technologyLabels: project.technologyLabels ?? [],
|
||||
targetVisibility:
|
||||
project.targetVisibility === "PUBLIC" || project.targetVisibility === "UNLISTED"
|
||||
? project.targetVisibility
|
||||
: "PRIVATE",
|
||||
});
|
||||
setProjectTitle("");
|
||||
setRequestAnnouncement(`프로젝트 ${title} 을(를) 만들었습니다.`);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "프로젝트를 만들지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removeTopic = async (topic: TopicEdit) => {
|
||||
if (pending || topic.id === undefined || topic.version === undefined) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await managementGateway.deleteTopic(topic.id, topic.version);
|
||||
setRequestAnnouncement(`주제 ${topic.name} 을(를) 삭제했습니다.`);
|
||||
setPendingDelete(null);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "주제를 삭제하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removeProject = async (project: ProjectIndexItem) => {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
try {
|
||||
await managementGateway.deleteProject(project.id, project.version);
|
||||
setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 삭제했습니다.`);
|
||||
setPendingDelete(null);
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(managementFailureMessage(error, "프로젝트를 삭제하지 못했습니다."));
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
프로젝트 게시는 문서 게시와 별개다. 문서를 게시해도 그 문서가 속한 프로젝트는 비공개로 남고,
|
||||
공개 화면들(프로젝트 목록·프로필의 "현재 프로젝트"·홈의 focus)은 전부 게시된 프로젝트만 읽는다.
|
||||
그래서 그 화면들이 조용히 비어 있었다 — 게시할 방법 자체가 없었기 때문이다.
|
||||
*/
|
||||
const togglePublish = async (project: ProjectIndexItem) => {
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError("");
|
||||
const published = project.targetVisibility !== "PRIVATE";
|
||||
try {
|
||||
if (published) {
|
||||
await managementGateway.unpublishProject(project.id, project.version);
|
||||
setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 비공개로 되돌렸습니다.`);
|
||||
} else {
|
||||
await managementGateway.publishProject(project.id, project.version, "PUBLIC");
|
||||
setRequestAnnouncement(`프로젝트 ${project.name} 을(를) 공개했습니다.`);
|
||||
}
|
||||
reload();
|
||||
} catch (error) {
|
||||
setError(
|
||||
managementFailureMessage(
|
||||
error,
|
||||
published ? "프로젝트를 비공개로 되돌리지 못했습니다." : "프로젝트를 게시하지 못했습니다.",
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
};
|
||||
const copy = useTechLogCopy();
|
||||
const {
|
||||
error,
|
||||
links,
|
||||
loadError,
|
||||
loading,
|
||||
pending,
|
||||
pendingDelete,
|
||||
projectForm,
|
||||
projects,
|
||||
removeProject,
|
||||
removeTopic,
|
||||
setError,
|
||||
setPendingDelete,
|
||||
setTab,
|
||||
submitProject,
|
||||
submitTopic,
|
||||
tab,
|
||||
togglePublish,
|
||||
topicForm,
|
||||
topics,
|
||||
} = useTaxonomyController();
|
||||
|
||||
return (
|
||||
<div className="studio-page studio-documents-page">
|
||||
@@ -251,7 +60,7 @@ export function TaxonomyManager() {
|
||||
구조가 먼저다. 주제와 프로젝트를 따로 세는 목록 둘만 있으면 이 화면은 여느 CMS 의
|
||||
분류 관리와 같아진다 — 이 제품에서 값어치 있는 것은 그 둘의 <em>관계</em>다.
|
||||
*/}
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
role="tab"
|
||||
id="taxonomy-tab-structure"
|
||||
@@ -260,9 +69,9 @@ export function TaxonomyManager() {
|
||||
tabIndex={tab === "STRUCTURE" ? 0 : -1}
|
||||
onClick={() => setTab("STRUCTURE")}
|
||||
>
|
||||
구조
|
||||
</button>
|
||||
<button
|
||||
{copy("techLog.studio.group.structure")}
|
||||
</Button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
role="tab"
|
||||
id="taxonomy-tab-topic"
|
||||
@@ -272,8 +81,8 @@ export function TaxonomyManager() {
|
||||
onClick={() => setTab("TOPIC")}
|
||||
>
|
||||
{`주제 ${topics?.length ?? 0}`}
|
||||
</button>
|
||||
<button
|
||||
</Button>
|
||||
<Button visualPolicy="inherit"
|
||||
type="button"
|
||||
role="tab"
|
||||
id="taxonomy-tab-project"
|
||||
@@ -283,7 +92,7 @@ export function TaxonomyManager() {
|
||||
onClick={() => setTab("PROJECT")}
|
||||
>
|
||||
{`프로젝트 ${projects?.length ?? 0}`}
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<section
|
||||
@@ -294,58 +103,90 @@ export function TaxonomyManager() {
|
||||
aria-label={tab === "TOPIC" ? "주제 만들기" : "프로젝트 만들기"}
|
||||
>
|
||||
{tab === "TOPIC" ? (
|
||||
<form onSubmit={submitTopic}>
|
||||
<label htmlFor="taxonomy-topic-name">새 주제</label>
|
||||
<div>
|
||||
<input
|
||||
id="taxonomy-topic-name"
|
||||
type="text"
|
||||
value={topicName}
|
||||
placeholder="주제 이름"
|
||||
onChange={(event) => setTopicName(event.target.value)}
|
||||
<Form
|
||||
className="studio-taxonomy-create-form"
|
||||
pending={topicForm.pending}
|
||||
onSubmit={(event) => {
|
||||
void submitTopic(event);
|
||||
}}
|
||||
>
|
||||
<div className="studio-taxonomy-create-controls">
|
||||
<TextField
|
||||
{...topicForm.field("name")}
|
||||
className="studio-taxonomy-create-field"
|
||||
label="새 주제"
|
||||
placeholder="주제 이름"
|
||||
/>
|
||||
<TextField
|
||||
{...topicForm.field("slug")}
|
||||
className="studio-taxonomy-create-field"
|
||||
label="slug"
|
||||
placeholder="비우면 이름에서 생성"
|
||||
/>
|
||||
<Button
|
||||
disabled={pending}
|
||||
pending={topicForm.pending}
|
||||
pendingLabel={copy("techLog.action.adding")}
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.addTopic")}
|
||||
</Button>
|
||||
</div>
|
||||
<ErrorSummary
|
||||
fieldErrors={topicForm.fieldErrors}
|
||||
formErrors={topicForm.formErrors}
|
||||
fieldId={topicForm.fieldId}
|
||||
fieldLabels={{ name: "새 주제", slug: "slug" }}
|
||||
onFocusField={topicForm.focusField}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={topicSlug}
|
||||
placeholder="slug (비우면 이름에서 생성)"
|
||||
aria-label="주제 slug"
|
||||
onChange={(event) => setTopicSlug(event.target.value)}
|
||||
/>
|
||||
<button type="submit" disabled={pending}>
|
||||
주제 추가
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
) : (
|
||||
<form onSubmit={submitProject}>
|
||||
<label htmlFor="taxonomy-project-title">새 프로젝트</label>
|
||||
<div>
|
||||
<input
|
||||
id="taxonomy-project-title"
|
||||
type="text"
|
||||
value={projectTitle}
|
||||
placeholder="프로젝트 이름"
|
||||
onChange={(event) => setProjectTitle(event.target.value)}
|
||||
<Form
|
||||
className="studio-taxonomy-create-form"
|
||||
pending={projectForm.pending}
|
||||
onSubmit={(event) => {
|
||||
void submitProject(event);
|
||||
}}
|
||||
>
|
||||
<div className="studio-taxonomy-create-controls">
|
||||
<TextField
|
||||
{...projectForm.field("title")}
|
||||
className="studio-taxonomy-create-field"
|
||||
label="새 프로젝트"
|
||||
placeholder="프로젝트 이름"
|
||||
/>
|
||||
<Button
|
||||
disabled={pending}
|
||||
pending={projectForm.pending}
|
||||
pendingLabel={copy("techLog.action.adding")}
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
>
|
||||
{copy("techLog.action.addProject")}
|
||||
</Button>
|
||||
</div>
|
||||
<ErrorSummary
|
||||
fieldErrors={projectForm.fieldErrors}
|
||||
formErrors={projectForm.formErrors}
|
||||
fieldId={projectForm.fieldId}
|
||||
fieldLabels={{ title: "새 프로젝트" }}
|
||||
onFocusField={projectForm.focusField}
|
||||
/>
|
||||
<button type="submit" disabled={pending}>
|
||||
프로젝트 추가
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{loading ? (
|
||||
<p className="studio-loading" role="status">
|
||||
주제와 프로젝트를 불러오는 중입니다.
|
||||
{copy("techLog.state.taxonomyLoading")}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
{error || loadError ? (
|
||||
<p className="studio-screen-error" role="alert">
|
||||
{error}
|
||||
{error || loadError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!loading && topics && projects && tab === "STRUCTURE" ? (
|
||||
<div className="studio-structure-tree">
|
||||
<ol>
|
||||
@@ -356,7 +197,7 @@ export function TaxonomyManager() {
|
||||
<li key={project.id ?? project.slug}>
|
||||
<div className="studio-structure-project">
|
||||
{project.id ? (
|
||||
<GuardedStudioLink href={`/studio/projects/${project.id}`}>
|
||||
<GuardedStudioLink href={studioRoutes.projectEdit(project.id)}>
|
||||
{project.name}
|
||||
</GuardedStudioLink>
|
||||
) : (
|
||||
@@ -374,7 +215,7 @@ export function TaxonomyManager() {
|
||||
{inProject.map((topic) => (
|
||||
<li key={topic.id ?? topic.slug}>
|
||||
{topic.id ? (
|
||||
<GuardedStudioLink href={`/studio/topics/${topic.id}`}>
|
||||
<GuardedStudioLink href={studioRoutes.topicEdit(topic.id)}>
|
||||
{topic.name}
|
||||
</GuardedStudioLink>
|
||||
) : (
|
||||
@@ -386,7 +227,7 @@ export function TaxonomyManager() {
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="studio-structure-empty">묶은 주제가 없습니다.</p>
|
||||
<p className="studio-structure-empty">{copy("techLog.state.groupedTopicsEmpty")}</p>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
@@ -407,7 +248,7 @@ export function TaxonomyManager() {
|
||||
{orphans.map((topic) => (
|
||||
<li key={topic.id ?? topic.slug}>
|
||||
{topic.id ? (
|
||||
<GuardedStudioLink href={`/studio/topics/${topic.id}`}>
|
||||
<GuardedStudioLink href={studioRoutes.topicEdit(topic.id)}>
|
||||
{topic.name}
|
||||
</GuardedStudioLink>
|
||||
) : (
|
||||
@@ -438,7 +279,7 @@ export function TaxonomyManager() {
|
||||
*/}
|
||||
<h2>
|
||||
{topic.id ? (
|
||||
<GuardedStudioLink href={`/studio/topics/${topic.id}`}>
|
||||
<GuardedStudioLink href={studioRoutes.topicEdit(topic.id)}>
|
||||
{topic.name}
|
||||
</GuardedStudioLink>
|
||||
) : (
|
||||
@@ -467,12 +308,12 @@ export function TaxonomyManager() {
|
||||
{topic.id ? (
|
||||
<GuardedStudioLink
|
||||
className="studio-secondary-button"
|
||||
href={`/studio/topics/${topic.id}`}
|
||||
href={studioRoutes.topicEdit(topic.id)}
|
||||
>
|
||||
편집
|
||||
</GuardedStudioLink>
|
||||
) : null}
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
className="studio-secondary-button studio-danger-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
@@ -481,14 +322,14 @@ export function TaxonomyManager() {
|
||||
setPendingDelete({ kind: "TOPIC", topic });
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
{copy("techLog.action.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="studio-empty">아직 주제가 없습니다. 위에서 하나 만들어 주세요.</p>
|
||||
<p className="studio-empty">{copy("techLog.state.topicsCreateFirst")}</p>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
@@ -503,7 +344,7 @@ export function TaxonomyManager() {
|
||||
<p className="studio-row-label">PROJECT</p>
|
||||
<div className="studio-document-title">
|
||||
<h2>
|
||||
<GuardedStudioLink href={`/studio/projects/${project.id}`}>
|
||||
<GuardedStudioLink href={studioRoutes.projectEdit(project.id)}>
|
||||
{project.name}
|
||||
</GuardedStudioLink>
|
||||
</h2>
|
||||
@@ -532,19 +373,21 @@ export function TaxonomyManager() {
|
||||
*/}
|
||||
<GuardedStudioLink
|
||||
className="studio-secondary-button"
|
||||
href={`/studio/projects/${project.id}`}
|
||||
href={studioRoutes.projectEdit(project.id)}
|
||||
>
|
||||
내용 편집
|
||||
</GuardedStudioLink>
|
||||
<button
|
||||
<Button visualPolicy="inherit"
|
||||
className="studio-secondary-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => void togglePublish(project)}
|
||||
>
|
||||
{project.targetVisibility === "PRIVATE" ? "게시" : "게시 취소"}
|
||||
</button>
|
||||
<button
|
||||
{project.targetVisibility === "PRIVATE"
|
||||
? copy("techLog.action.publish")
|
||||
: copy("techLog.action.unpublish")}
|
||||
</Button>
|
||||
<Button visualPolicy="inherit"
|
||||
className="studio-secondary-button studio-danger-button"
|
||||
type="button"
|
||||
disabled={pending}
|
||||
@@ -553,14 +396,14 @@ export function TaxonomyManager() {
|
||||
setPendingDelete({ kind: "PROJECT", project });
|
||||
}}
|
||||
>
|
||||
삭제
|
||||
</button>
|
||||
{copy("techLog.action.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="studio-empty">아직 프로젝트가 없습니다.</p>
|
||||
<p className="studio-empty">{copy("techLog.state.projectsEmpty")}</p>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user