diff --git a/config/contracts/registry-change-evidence.json b/config/contracts/registry-change-evidence.json index b039daa..008c74b 100644 --- a/config/contracts/registry-change-evidence.json +++ b/config/contracts/registry-change-evidence.json @@ -96,6 +96,30 @@ "compatibilityWindow": "Existing valid envelopes continue to decode; invalid values fail closed.", "rollback": "Remove the required codec field and runtime codec dispatch together.", "owner": "frontend-platform" + }, + { + "changeId": "FE-REG-ROUTE:APP_HOME:chunkId:field-changed", + "versionBump": "Memento product composition takes ownership of the root route and its lazy chunk identity.", + "migration": "The compiled product manifest installs Memento APP_HOME at / and the route runtime resolves it to the Memento home page while preserving the root URL.", + "compatibilityWindow": "Each release owns its route/chunk manifest and cache epoch, so old and new chunk identities are not mixed within one admitted release.", + "rollback": "Remove the Memento feature from the compiled product manifest and restore the platform APP_HOME route/runtime pair together.", + "owner": "memento-web" + }, + { + "changeId": "FE-REG-ROUTE-RUNTIME:APP_HOME:moduleId:field-changed", + "versionBump": "The root route runtime module changes from the template home module to the Memento home module.", + "migration": "Memento contributes the root route contract and matching lazy runtime module through the installed feature composition.", + "compatibilityWindow": "Release-manifest chunk verification keeps module/chunk identities release-scoped; no cross-release runtime module lookup is accepted.", + "rollback": "Remove the Memento feature contribution and restore the platform APP_HOME route/runtime pair in the same release.", + "owner": "memento-web" + }, + { + "changeId": "FE-REG-ROUTE:$contract:allowedValues:contract-field-changed", + "versionBump": "The route registry governance contract admits the Memento feature's typed route schemas and loading surfaces.", + "migration": "Memento route/search schema IDs and loading-surface IDs are installed through the product feature contract and validated by the same registry/runtime composition as platform and reference routes.", + "compatibilityWindow": "The new allowed values are additive; existing route definitions and their runtime codecs remain valid during the transition.", + "rollback": "Remove the Memento product feature contribution and then remove the additive Memento schema/loading-surface values from registry governance.", + "owner": "memento-web" } ] } diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index a19036d..1c86cc4 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -41,8 +41,22 @@ "uniqueFields": ["routeId", "path", "chunkId"], "allowedValues": { "access": ["public", "session-required"], - "paramsSchema": [null, "NotFoundSplat", "ReferenceResourceParams"], - "searchSchema": [null, "ReferenceResourceListQuery"], + "paramsSchema": [ + null, + "NotFoundSplat", + "ReferenceResourceParams", + "MementoMemoryParams", + "MementoAlbumParams", + "MementoPersonParams", + "MementoPlaceParams" + ], + "searchSchema": [ + null, + "ReferenceResourceListQuery", + "MementoLibrarySearch", + "MementoDetailSearch", + "MementoSettingsSearch" + ], "loadingSurface": [ "app-shell", "example-page", @@ -50,6 +64,20 @@ "reference-resource-detail", "reference-resource-form", "reference-resource-status", + "memento-home", + "memento-library", + "memento-memories", + "memento-memory-detail", + "memento-albums", + "memento-album-detail", + "memento-search", + "memento-people", + "memento-person-detail", + "memento-places", + "memento-place-detail", + "memento-login", + "memento-register", + "memento-settings", "none" ], "errorSurface": [ @@ -235,7 +263,9 @@ "consumerDirectories": [ "src/presentation/routes", "src/features/reference-feature/presentation", - "src/features/reference-feature/contracts" + "src/features/reference-feature/contracts", + "src/features/memento-web/contracts", + "src/features/memento-web/presentation" ], "breakingFields": ["schemaId", "boundary", "runtime"] }, diff --git a/docs/reviews/2026-09-20-memento-template-integration-followup-review.md b/docs/reviews/2026-09-20-memento-template-integration-followup-review.md new file mode 100644 index 0000000..c9eb960 --- /dev/null +++ b/docs/reviews/2026-09-20-memento-template-integration-followup-review.md @@ -0,0 +1,1153 @@ +# Memento Frontend — Follow-up Review for Remaining Work + +> 검토일: 2026-09-20 +> 대상: `/shared/codebase/memento-frontend` +> 선행 리뷰: `docs/reviews/2026-09-20-memento-template-integration-visual-parity-review.md` +> 현재 판정: **아직 더 봐야댐** +> 범위: 1차 리뷰 반영 후 남은 미완료 항목만 다룬다. + +--- + +# 1. 이번 재검수 결론 + +1차 리뷰에서 요구한 큰 구조 전환은 대부분 제대로 반영되었다. + +현재 확인된 완료 항목: + +- Static prototype이 실제 UI를 소유하던 구조 제거 +- `index.html`을 React root만 남기는 구조로 변경 +- `beta.js`, `beta.css`, static login/register 제거 +- `MementoRuntimeBridge` / prototype DOM integration 제거 +- Memento page를 TS/TSX component로 분해 +- React Router 및 feature route runtime으로 전환 +- Memento feature contract/runtime 등록 +- local -> mock, development/staging/production -> API 구조 유지 +- template의 Application Feature Input 사용 +- template의 Query / Mutation bridge 사용 +- template의 reusable HTTP capability 사용 +- feature 내부 direct `fetch` 제거 +- feature presentation direct DOM query 제거 +- Storybook 추가 +- Memento assurance gate 추가 +- Visual regression test 추가 +- E2E 추가 + +검증 결과: + +```text +check:memento-assurance PASS +check:architecture PASS +check:design-system PASS +check:types:app PASS + +Memento unit/component 7 / 7 PASS +Memento visual 26 / 26 PASS +Memento E2E 9 / 9 PASS + Chromium / Firefox / WebKit +``` + +하지만 현재 상태를 **완료**로 판정하지 않은 이유는 세 가지다. + +1. Memento Design System이 아직 완전히 token contract 안으로 들어오지 않았다. +2. Visual regression baseline이 원본 prototype과의 동일성을 공식적으로 보장하지 않는다. +3. E2E가 1차 리뷰에서 요구했던 핵심 사용자 흐름을 전부 검증하지 않는다. + +추가로, 전체 공식 component suite는 현재 Coka host의 Node.js 버전 때문에 실행하지 못했다. + +--- + +# 2. P1 — Memento Design System tokenization 미완료 + +## 2.1 현재 상태 + +현재 Memento presentation은 template design-system public barrel을 사용하도록 개선되었다. + +예: + +```ts +import { + MementoButton, + MementoChip, + MementoBadge, + MementoIconButton, +} from "../../../../presentation/design-system/index.ts"; +``` + +그리고 Memento wrapper는 template primitive를 실제로 감싼다. + +```text +MementoButton -> Button +MementoIconButton -> IconButton +MementoBadge -> Badge +MementoChip -> Button +``` + +이 방향은 맞다. + +또 다음 Memento token도 기존 token contract에 추가되어 있다. + +```text +--memento-background +--memento-surface +--memento-surface-muted +--memento-content +--memento-content-muted +--memento-border +--memento-action +--memento-action-muted +--memento-danger +--memento-sidebar-width +--memento-shadow +``` + +문제는 여기서 끝나 있다는 점이다. + +--- + +## 2.2 현재 `memento.css`는 여전히 Beta CSS의 상당 부분을 직접 보유한다 + +현재 파일: + +```text +src/presentation/design-system/memento/memento.css +``` + +측정 결과: + +```text +416 lines +39,544 bytes + +raw color occurrences: 152 +unique raw color values: 84 +``` + +예를 들면 다음 값들이 여전히 component stylesheet에 직접 존재한다. + +```css +background:#e6e7e2; +color:#161715; +background:#e8e9e4; + +background:linear-gradient(135deg,#9db0a4,#d7c5a9); +background:#5e8b6c; + +color:#d6d9d5; +border-color:#c8d8cd; +color:#2f4c3d; + +background:#1d211e; +color:#f8f8f6; +color:#bdc9c1; +color:#c8cbc6; + +background:#94633d; + +background:#e7ebe7; +color:#8a8d87; +``` + +즉 현재 상태는: + +```text +기존 beta.css + ↓ +memento.css 안으로 이동 + + +핵심 색상/폭/그림자 일부만 token contract 등록 +``` + +에 가깝다. + +1차 리뷰에서 요구한 최종 상태는 이보다 한 단계 더 나가야 한다. + +```text +Primitive Token + ↓ +Semantic Token + ↓ +Component / Product Token + ↓ +Memento Design Component + ↓ +Feature Component + ↓ +Page +``` + +--- + +# 3. P1 해결 방향 — 기존 디자인 값은 유지하면서 token contract에 편입 + +중요한 제약은 그대로다. + +> **디자인 값을 바꾸면 안 된다.** + +따라서 현재 raw value를 새로운 값으로 개선하는 것이 아니다. + +현재 값을 그대로 token 이름 아래로 이동해야 한다. + +--- + +## 3.1 Primitive token 후보 + +반복되는 물리 값을 primitive로 먼저 분류한다. + +예: + +```css +--memento-palette-ink-950: #161715; +--memento-palette-forest-950: #1d211e; +--memento-palette-forest-700: #31433a; +--memento-palette-forest-600: #496356; +--memento-palette-forest-500: #5e8b6c; + +--memento-palette-stone-100: #f4f4f1; +--memento-palette-stone-150: #ecece7; +--memento-palette-stone-200: #e6e7e2; +--memento-palette-stone-300: #dddeda; + +--memento-radius-sm: 9px; +--memento-radius-md: 12px; +--memento-radius-lg: 18px; +--memento-radius-xl: 22px; +--memento-radius-2xl: 26px; +``` + +단 실제 이름은 repository의 기존 naming convention에 맞춰 조정한다. + +--- + +## 3.2 Semantic token 후보 + +화면 의미 단위로 재매핑한다. + +예: + +```css +--memento-color-page-background +--memento-color-panel +--memento-color-panel-muted + +--memento-color-text-primary +--memento-color-text-secondary +--memento-color-text-inverse + +--memento-color-border +--memento-color-action +--memento-color-action-muted +--memento-color-action-content + +--memento-color-success +--memento-color-warning +--memento-color-danger + +--memento-color-overlay +--memento-color-dark-surface +``` + +현재 존재하는 token과 중복된다면 새로 만들지 말고 기존 이름에 매핑한다. + +--- + +## 3.3 Component token 후보 + +Component에서 반복되는 값을 product component token으로 올린다. + +예: + +```css +--memento-sidebar-background +--memento-sidebar-border +--memento-sidebar-active-background + +--memento-button-background +--memento-button-border +--memento-button-primary-background +--memento-button-primary-content +--memento-button-radius + +--memento-chip-active-background +--memento-chip-active-border +--memento-chip-active-content + +--memento-dialog-radius +--memento-dialog-shadow +--memento-drawer-width + +--memento-selection-bar-background +--memento-selection-bar-shadow + +--memento-card-radius +--memento-media-tile-radius + +--memento-auth-visual-background +``` + +모든 CSS 수치를 억지로 token으로 만드는 것은 목적이 아니다. + +반복되거나 제품 시각 정체성을 구성하는 값, 테마/variant에서 의미를 갖는 값을 우선 대상으로 한다. + +--- + +# 4. P1 — `check:design-system` blind spot도 반드시 수정 + +현재 `scripts/check-design-system.ts`의 CSS 검사 범위는 다음에 국한된다. + +```text +primitive.css +semantic.css +component.css +theme.css +``` + +실제 코드는 현재 다음과 같다. + +```ts +const cssSources = await Promise.all( + [...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map(...) +); +``` + +따라서: + +```text +src/presentation/design-system/memento/memento.css +``` + +는 검사하지 않는다. + +결과적으로 Memento CSS에 raw color가 152회 있어도: + +```text +Design system contract: 59 tokens and vendor boundaries PASS +``` + +가 나온다. + +이는 design-system gate가 Memento product design을 실제로 보호하지 못하고 있다는 뜻이다. + +--- + +## 4.1 Gate 개선안 + +방법은 두 가지가 가능하다. + +### 방법 A — 기존 `check:design-system`에 product stylesheet 포함 + +권장. + +예: + +```ts +const productDesignSources = [ + "src/presentation/design-system/memento/memento.css", +]; + +const cssSources = await Promise.all( + [ + ...Object.values(tokenFiles), + "src/presentation/styles/theme.css", + ...productDesignSources, + ].map(...) +); +``` + +그리고 product stylesheet에서 허용되지 않는 raw palette를 탐지한다. + +### 방법 B — Memento assurance에 별도 CSS gate 추가 + +예: + +```text +FE-MEMENTO-008 MEMENTO_RAW_DESIGN_VALUE +``` + +단 design-system 자체의 책임이라는 점을 고려하면 A가 더 자연스럽다. + +--- + +## 4.2 Raw value 허용 정책 + +무조건 모든 `#fff`, rgba까지 금지하면 실용성이 떨어질 수 있다. + +명시적인 정책을 둔다. + +예: + +허용: + +- transparent +- currentColor +- CSS keyword +- gradient 안에서 기술적으로 1회만 쓰이는 overlay 값 +- Story/demo 전용 fixture + +금지: + +- 제품 palette의 반복 raw hex +- 동일한 의미를 가진 반복 rgba +- 이미 token이 존재하는 값을 raw value로 다시 사용하는 것 + +가능하면 allowlist는 파일 단위가 아니라 **값 + 이유** 단위로 최소화한다. + +--- + +# 5. P1 완료 조건 + +다음 조건이 모두 만족되어야 한다. + +- [ ] Memento 핵심 palette가 token contract 아래에 있다. +- [ ] 반복되는 raw color가 product stylesheet에 직접 남아 있지 않다. +- [ ] Memento component visual value가 token을 통해 전달된다. +- [ ] `memento.css`가 design-system gate 검사 범위에 포함된다. +- [ ] raw palette를 다시 추가하면 gate가 실패한다. +- [ ] 기존 screenshot 결과는 변경되지 않는다. +- [ ] `check:design-system` PASS +- [ ] `check:memento-assurance` PASS + +--- + +# 6. P2 — Visual baseline provenance 미완료 + +## 6.1 현재 Visual Test 자체는 잘 구성되어 있다 + +현재: + +```text +tests/visual/memento-prototype.visual.spec.ts +``` + +와 26개의 snapshot이 존재한다. + +범위: + +- Desktop 12개 주요 surface +- Mobile 4개 주요 surface +- Profile Drawer +- Upload Dialog +- Create Album Dialog +- Share Dialog +- Edit Memory Dialog +- Library Selection +- Media Viewer +- Login +- Register +- Action Modal + +실제 실행 결과: + +```text +26 / 26 PASS +``` + +여기까지는 좋다. + +--- + +# 7. 문제 — 이 snapshot이 원래 Beta prototype의 golden baseline이라는 증거가 없다 + +현재 snapshot은 이번 React migration과 함께 새로 생성된 파일이다. + +즉 CI가 지금 증명하는 것은 기본적으로: + +```text +현재 React 렌더링 + vs +현재 저장된 React snapshot +``` + +이다. + +하지만 요구사항은: + +> 기존 디자인을 1도 바꾸지 않는다. + +이므로 더 중요한 비교는: + +```text +Legacy approved Beta prototype + vs +New React implementation +``` + +이다. + +현재 repository 안에는 이 provenance가 명확하게 남아 있지 않다. + +--- + +# 8. 실제 재검수에서 원본 prototype과 비교한 결과 + +이번 검수에서는 Git `HEAD`에 남아 있는 기존: + +```text +index.html +public/beta.css +public/beta.js +``` + +를 별도 임시 디렉터리에 복원했다. + +그리고 legacy prototype과 현재 React implementation을 각각 별도 HTTP server로 띄운 뒤 Chromium에서 동일 viewport로 직접 screenshot을 비교했다. + +조건: + +```text +Viewport: 1600 x 1100 +Browser: Chromium +iframe: 비교 시 동일하게 hidden +assets: 동일 public/assets 사용 +``` + +결과: + +| Surface | Render Size | Changed Pixels | +| --- | --- | ---: | +| Home | 1600 x 1505 / 동일 | 425 | +| Library | 1600 x 1619 / 동일 | 1,946 | +| Memories | 1600 x 1872 / 동일 | 314 | +| Memory Detail | 1600 x 3346 / 동일 | 8,580 | +| Albums | 1600 x 1100 / 동일 | 1,114 | +| People | 1600 x 1100 / 동일 | 296 | +| Places Map | 1600 x 1100 / 동일 | 1,416 | +| Search | 1600 x 1100 / 동일 | 2,473 | +| Settings | 1600 x 1100 / 동일 | 296 | + +해석: + +- 전체 layout dimension은 모두 동일했다. +- 구조가 무너진 수준의 변경은 없다. +- 대부분 화면은 매우 작은 차이만 존재한다. +- 현재 migration은 시각적으로 상당히 정확하게 수행되었다. + +하지만 **pixel-identical은 아니다.** + +--- + +# 9. P2 해결 방향 — Golden Visual Migration Evidence 추가 + +권장 방식은 legacy prototype을 production source로 되살리는 것이 아니다. + +Legacy 화면을 **visual migration fixture/evidence**로만 보존한다. + +예: + +```text +tests/ +└── fixtures/ + └── memento-visual-baseline/ + ├── README.md + ├── legacy/ + │ ├── index.html + │ ├── beta.css + │ ├── beta.js + │ └── ... + └── baseline/ + ├── desktop-home.png + ├── desktop-library.png + └── ... +``` + +또는 source fixture를 보존하기 싫다면 승인된 screenshot만 저장한다. + +핵심은: + +> snapshot의 출처가 “React 구현 자체”가 아니라 “승인된 기존 prototype”이라는 사실을 repository가 설명할 수 있어야 한다. + +--- + +## 9.1 권장 evidence 문서 + +예: + +```text +tests/visual/MEMENTO_VISUAL_BASELINE.md +``` + +내용: + +- baseline 생성 기준 commit +- legacy source +- browser version +- viewport +- font condition +- iframe/map masking rule +- screenshot 생성 명령 +- 승인된 변경 허용 정책 +- snapshot update 절차 + +--- + +## 9.2 Snapshot update 규칙도 강화 + +현재처럼: + +```bash +pnpm test:visual:update +``` + +만 실행하면 디자인 변경이 쉽게 baseline으로 흡수될 수 있다. + +Memento에 대해서는 다음 정책이 필요하다. + +```text +Visual diff 발생 + ↓ +원인 확인 + ↓ +구조 변경 때문에 발생한 미세 차이인지 확인 + ↓ +디자인 변경 여부 확인 + ↓ +승인된 경우에만 snapshot update +``` + +즉 visual update는 실패를 없애는 명령이 아니라 **승인 절차의 마지막 단계**여야 한다. + +--- + +# 10. 남은 pixel difference 처리 + +현재 차이가 매우 작다고 해서 자동으로 무시하면 안 된다. + +특히 Memory Detail의 8,580 changed pixels는 다른 화면보다 상대적으로 크다. + +우선 diff image를 생성해서 영역을 확인한다. + +예: + +```bash +compare legacy-memory.png react-memory.png memory-diff.png +``` + +확인 대상: + +- native button rendering +- font anti-aliasing +- line-height +- heading default style +- focus normalization +- image decode timing +- responsive rounding +- primitive wrapper가 삽입한 style +- route/React DOM 차이로 발생한 cascade + +실제 디자인 값 차이라면 수정한다. + +브라우저 rasterization 차이처럼 구조상 불가피하다면 이유와 허용 기준을 baseline 문서에 기록한다. + +--- + +# 11. P2 완료 조건 + +- [ ] Legacy approved prototype이 baseline의 출처라는 evidence가 있다. +- [ ] desktop 주요 화면 legacy ↔ React 비교가 자동화되어 있다. +- [ ] mobile 주요 화면 legacy ↔ React 비교가 있다. +- [ ] overlay/dialog/drawer도 legacy ↔ React 기준을 갖는다. +- [ ] visual snapshot update 절차가 문서화되어 있다. +- [ ] Memory Detail 등 남은 diff의 원인이 확인되어 있다. +- [ ] 의도하지 않은 실제 visual change는 0이다. +- [ ] 현재 26 visual regression test가 계속 PASS한다. + +--- + +# 12. P3 — E2E coverage 미완료 + +## 12.1 현재 상태 + +현재: + +```text +tests/e2e/memento-flow.spec.ts +``` + +에는 3개의 logical scenario가 있다. + +1. Router navigation / browser history +2. Local mock + Create Album / Upload overlay +3. Settings deep link + Login/Register + +3 browser: + +```text +Chromium +Firefox +WebKit +``` + +에서 실행되어 총: + +```text +9 / 9 PASS +``` + +했다. + +현재 작성된 테스트는 의미가 있고 정상 동작한다. + +문제는 1차 리뷰의 최소 E2E 요구 범위보다 좁다는 점이다. + +--- + +# 13. 추가해야 할 E2E 흐름 + +## E2E-1 — Library interaction + +반드시 검증할 것: + +```text +/library + ↓ +filter 변경 + ↓ +search 입력 + ↓ +media select + ↓ +selection bar 표시 + ↓ +selection clear / action +``` + +검증 예: + +- URL search param 또는 state가 의도대로 변경되는지 +- 결과 filtering이 적용되는지 +- 선택 개수가 표시되는지 +- browser navigation 시 상태 정책이 의도대로인지 + +--- + +## E2E-2 — Home -> Memory Detail + +```text +Home + ↓ +Memory Card + ↓ +/memories/:memoryId + ↓ +detail data render + ↓ +tab 전환 +``` + +검증: + +- hard-coded page toggle이 아닌 실제 route navigation +- deep link reload +- story/photos/info tab +- 뒤로 가기 + +--- + +## E2E-3 — Memory candidate save + +```text +/memories + ↓ +suggested candidate + ↓ +save command + ↓ +mutation + ↓ +UI feedback / destination state +``` + +Local mock에서 mutation이 실제 application input을 통과하는지 검증한다. + +--- + +## E2E-4 — Search -> Person + +```text +/search + ↓ +person result + ↓ +/people/:personId +``` + +검증: + +- search interaction +- person detail deep link +- detail render + +--- + +## E2E-5 — Search -> Place + +```text +/search + ↓ +place result + ↓ +/places/:placeId +``` + +검증: + +- route +- detail render +- back navigation + +--- + +## E2E-6 — Share flow + +```text +Memory Detail + ↓ +Share + ↓ +Dialog + ↓ +createShare mutation + ↓ +result state +``` + +단순히 dialog가 열리는 것만이 아니라 command까지 통과하도록 한다. + +--- + +## E2E-7 — API mode boot + +현재 local mock은 잘 검증되고 있다. + +추가로: + +```text +APP_PROFILE=development +``` + +에서 Memento가 mock이 아니라 HTTP capability를 사용하는지 검증해야 한다. + +실제 backend가 필요하지 않도록 MSW 또는 test server를 사용해도 된다. + +검증해야 하는 것은 네트워크 성공 자체보다 **composition 선택**이다. + +예: + +```text +local -> mock +development -> API +production -> API +``` + +그리고 development E2E에서 예상 endpoint request가 발생하는지 확인한다. + +--- + +# 14. E2E 완료 조건 + +최소 다음 user journey가 browser test로 존재해야 한다. + +- [ ] Home -> Library +- [ ] Library filter +- [ ] Library search +- [ ] Library select +- [ ] Home -> Memory Detail +- [ ] Memory Detail tabs +- [ ] Memories -> Candidate Save +- [ ] Albums -> Create Album +- [ ] Search -> Person +- [ ] Search -> Place +- [ ] Profile -> Settings +- [ ] Upload +- [ ] Share +- [ ] Login -> Register +- [ ] Browser back/forward +- [ ] Deep link reload +- [ ] Local mock boot +- [ ] Development API boot + +모든 flow를 모든 브라우저에서 동일하게 돌릴 필요는 없다. + +권장: + +```text +Critical navigation/state: + Chromium + Firefox + WebKit + +Long mutation scenarios: + Chromium 중심 + 필요 시 cross-browser smoke 추가 +``` + +테스트 시간만 늘어나고 의미가 없는 중복은 피한다. + +--- + +# 15. P4 — 공식 전체 component suite 환경 검증 + +이번 검수에서는 Memento에 직접 관련된 test를 Vitest로 실행했다. + +결과: + +```text +tests/unit/memento-environment-gateway.test.ts +tests/component/memento-design-system.test.tsx + +7 / 7 PASS +``` + +하지만 공식: + +```bash +pnpm test:component +``` + +는 실행되지 않았다. + +이유: + +```text +Current Node.js: 22.23.2 +Required: >=24.11.0 <25.0.0 +``` + +repository의 runtime guard가 정상적으로 차단했다. + +즉 이는 코드 failure는 아니다. + +그러나 완료 판정 전에는 지원 runtime에서 공식 command를 한 번 통과시키는 것이 맞다. + +--- + +## 15.1 지원 Node에서 최종 실행할 명령 + +최소: + +```bash +corepack pnpm check:memento-assurance +corepack pnpm check:architecture +corepack pnpm check:design-system +corepack pnpm check:types + +corepack pnpm test:unit +corepack pnpm test:component +corepack pnpm test:integration + +corepack pnpm test:e2e +corepack pnpm test:visual +corepack pnpm test:storybook + +corepack pnpm build +``` + +Memento 변경이 template의 공용 HTTP/design-system/runtime을 수정했기 때문에 Memento 전용 테스트만으로 끝내면 안 된다. + +특히 현재 변경에는 다음 공용 영역도 포함된다. + +```text +src/adapters/http/* +src/contracts/* +src/features/installed-* +src/presentation/design-system/* +src/presentation/routes/* +src/bootstrap/* +``` + +따라서 full regression이 필요하다. + +--- + +# 16. 추가 권장 정리 — Application type ownership + +현재: + +```text +src/features/memento-web/presentation/hooks/use-memento.ts +``` + +가 다음 타입을: + +```ts +../../application/memento-gateway.ts +``` + +에서 import 한다. + +예: + +```text +AlbumQuery +CreateAlbumInput +CreateShareInput +LibraryQuery +MemoryQuery +ShareTarget +UpdateAlbumInput +UpdateMemoryInput +``` + +런타임 Gateway를 presentation에서 호출하는 것은 아니기 때문에 현재 architecture violation은 아니다. + +다만 presentation -> application input이라는 경계를 더 명확히 하려면 이 type들도 application public API 또는 command/query contract 쪽에서 export하는 것이 낫다. + +권장: + +```text +memento-application.ts +또는 +application/contracts/ +``` + +에서 presentation이 필요한 query/command type을 export한다. + +최종 의존 방향: + +```text +Presentation + ↓ +Application Public Contract + ↓ +Port + ↓ +Adapter +``` + +를 명확하게 만든다. + +이 항목은 P1~P3를 막는 blocker는 아니지만 이번 정리 시 같이 처리하는 편이 좋다. + +--- + +# 17. 구현 권장 순서 + +남은 작업은 다음 순서가 가장 안전하다. + +## Step 1 — Design token 정리 + +먼저 visual value의 이름과 위치만 바꾼다. + +디자인 수치는 바꾸지 않는다. + +완료 후: + +```bash +pnpm check:design-system +pnpm test:visual +``` + +## Step 2 — Design-system gate 강화 + +`memento.css`를 gate 범위에 포함한다. + +고의로 raw palette 하나를 fixture에 넣었을 때 실패하는 regression fixture도 추가한다. + +## Step 3 — Legacy visual baseline evidence 구축 + +현재 Git HEAD prototype을 기준으로 approved baseline을 만든다. + +기존 production prototype source는 fixture/evidence 용도로만 다룬다. + +## Step 4 — Pixel diff 분석 + +특히: + +- Memory Detail +- Search +- Library +- Places + +의 차이가 실제 디자인 변경인지 확인한다. + +## Step 5 — E2E user journey 확대 + +우선 mutation + search/detail 흐름부터 추가한다. + +## Step 6 — Supported Node에서 full regression + +마지막에 전체 suite/build를 실행한다. + +--- + +# 18. 이번 후속 리뷰의 완료 Definition of Done + +다음이 전부 충족될 때 이번 1차 template integration 작업을 **완료**로 판정한다. + +## Design System + +- [ ] Memento 핵심 visual palette가 token contract로 편입됨 +- [ ] 반복 raw product color가 제거됨 +- [ ] `memento.css`가 design-system 검사 범위에 포함됨 +- [ ] raw design value regression fixture 존재 +- [ ] Memento component가 template primitive를 계속 사용함 + +## Visual Parity + +- [ ] 승인된 legacy prototype이 golden baseline의 출처로 기록됨 +- [ ] desktop legacy ↔ React comparison 존재 +- [ ] mobile legacy ↔ React comparison 존재 +- [ ] overlay legacy ↔ React comparison 존재 +- [ ] 남은 pixel diff 원인이 분석됨 +- [ ] 의도하지 않은 visual design change가 없음 +- [ ] Visual regression 26개 이상 PASS + +## Architecture + +- [ ] direct DOM query 없음 +- [ ] feature direct fetch 없음 +- [ ] prototype bridge 없음 +- [ ] static product markup 없음 +- [ ] route runtime 사용 +- [ ] application input 사용 +- [ ] reusable HTTP binding 사용 +- [ ] local mock / dev-prod API composition 유지 + +## E2E + +- [ ] Library filter/search/select +- [ ] Memory detail +- [ ] Memory candidate save +- [ ] Create Album +- [ ] Person navigation +- [ ] Place navigation +- [ ] Settings +- [ ] Upload +- [ ] Share mutation +- [ ] Auth route +- [ ] Browser history +- [ ] Local mock +- [ ] Development API mode + +## Full Verification + +지원 Node `>=24.11 <25` 환경에서: + +- [ ] `check:memento-assurance` +- [ ] `check:architecture` +- [ ] `check:design-system` +- [ ] `check:types` +- [ ] `test:unit` +- [ ] `test:component` +- [ ] `test:integration` +- [ ] `test:e2e` +- [ ] `test:visual` +- [ ] `test:storybook` +- [ ] `build` + +전부 PASS. + +--- + +# 19. 최종 작업 지시 + +현재 구조를 다시 뒤엎을 필요는 없다. + +React ownership, Router, feature contract/runtime, application/query boundary, HTTP capability 도입은 현재 방향을 유지한다. + +이번 후속 작업의 핵심은 다음 세 문장으로 정리된다. + +> **1. `memento.css`를 단순한 Beta CSS 보관소로 두지 말고 실제 Design System contract 아래로 끝까지 편입한다.** + +> **2. 현재 React snapshot을 기준으로 삼는 데서 끝내지 말고, 기존 승인 prototype이 visual baseline의 원본이라는 증거를 repository에 남긴다.** + +> **3. 화면이 보인다는 수준의 E2E가 아니라 주요 사용자 command/navigation flow가 application boundary를 실제로 통과하는지 검증한다.** + +이 세 항목과 supported Node에서의 full regression까지 끝나면 이번 template integration 작업은 **완료**로 판정할 수 있다. diff --git a/docs/reviews/2026-09-20-memento-template-integration-visual-parity-review.md b/docs/reviews/2026-09-20-memento-template-integration-visual-parity-review.md new file mode 100644 index 0000000..79ff5ea --- /dev/null +++ b/docs/reviews/2026-09-20-memento-template-integration-visual-parity-review.md @@ -0,0 +1,1653 @@ +# Memento Frontend — Template Integration & Visual-Parity Refactoring Review + +> 검토일: 2026-09-20 +> 대상: `/shared/codebase/memento-frontend` +> 기준: 현재 `main` / `85c804b feat: memento-frontend 디자인 구성 및 셋팅` +> 최우선 제약: **현재 디자인은 시각적으로 변경하지 않는다.** +> 목표: 현재 Memento 디자인 시안을 제품 디자인 시스템으로 편입하고, 화면을 TypeScript/TSX 컴포넌트로 분해한 뒤 기존 frontend template이 제공하는 routing, provider, design-system, application boundary, reusable capability, test/assurance 구조를 실제 제품 코드가 사용하도록 재구성한다. + +--- + +## 1. 결론 + +현재 `memento-frontend`는 **template을 기반으로 만들어진 프로젝트이지만, 실제 Memento 화면은 template 위에서 렌더링되는 React 제품이 아니다.** + +실제 사용자에게 보이는 UI의 소유권은 다음 세 파일에 있다. + +- `index.html` — 전체 화면 DOM을 정적으로 보유 +- `public/beta.css` — 실제 Memento 디자인을 보유 +- `public/beta.js` — 화면 전환, modal, drawer, selection, filtering 등 UI 동작을 imperative DOM 조작으로 보유 + +반면 React는 다음과 같이 동작한다. + +- `#root`는 `hidden aria-hidden="true"` 상태다. +- `RuntimeApplication`은 화면을 렌더링하지 않는다. +- `MementoRuntimeBridge`는 `useEffect`에서 `document.body`를 넘겨받아 기존 정적 DOM을 조작한다. +- `memento-prototype-integration.ts`는 1,124 LOC이며 `querySelector` 계열 접근을 대량으로 사용한다. +- Memento feature에서 template design-system import는 현재 0건이다. +- Memento route는 template의 feature route registry/runtime에 등록되어 있지 않다. + +즉 현재 구조는 아래에 가깝다. + +```text +Clean Architecture Frontend Template +├── bootstrap / provider / router / design-system / HTTP capability / tests +│ +└── React root (hidden) + └── MementoRuntimeBridge + └── document.body의 정적 prototype DOM을 찾아서 조작 + +실제 화면 +├── index.html +├── beta.css +└── beta.js +``` + +원하는 구조는 반대가 되어야 한다. + +```text +bootstrap + -> RuntimeApplication + -> template providers + -> AppRouter + -> MementoAppShell + -> Memento routes/pages + -> Memento design-system components + -> feature hooks / application input + -> MementoGateway port + -> local: mock adapter + -> dev/staging/prod: reusable HTTP capability binding +``` + +따라서 이번 리팩터링의 핵심은 **디자인을 새로 만드는 것이 아니라, 현재 디자인의 소유권을 static prototype에서 React + template architecture로 옮기는 것**이다. + +--- + +## 2. 현재 상태에서 확인된 근거 + +### 2.1 화면 소유권이 React가 아니다 + +현재 `index.html`은 213 LOC / 약 31 KB이며 다음을 직접 포함한다. + +- Sidebar +- Mobile top navigation +- Home +- Library +- Memories +- Search +- Place detail +- Memory detail +- Albums +- Album detail +- People +- Person detail +- Places map +- Settings +- Selection bar +- Profile drawer +- Upload modal +- Create Album modal +- Share modal +- Edit Memory modal +- Action modal +- Media viewer + +정적으로 포함된 `.page` surface만 12개, modal은 5개다. + +그리고 마지막 부분이 다음 구조다. + +```html + + + + +``` + +React가 페이지를 렌더링하는 것이 아니라 **이미 완성된 DOM 뒤에서 부수 기능만 연결하고 있다.** + +### 2.2 `beta.js`가 사실상 UI framework 역할을 한다 + +`public/beta.js`는 353 LOC이며 다음 책임을 직접 가진다. + +- 페이지 전환 +- active class 관리 +- 뒤로 가기 상태 +- modal / drawer open-close +- filter 상태 +- library selection +- album filter/search/sort +- detail tab +- person/place navigation +- image viewer +- settings surface 교체 +- toast +- logout redirect +- action modal의 동적 HTML 생성 + +실제 코드도 다음 패턴이다. + +```text +document.querySelector(...) +document.querySelectorAll(...) +document.getElementById(...) +element.classList.toggle(...) +element.onclick = ... +document.addEventListener(...) +``` + +확인 시 `beta.js` 내부에는: + +- `getElementById`: 67회 +- `querySelector` 계열 문자열: 약 70회 +- `addEventListener`: 6회 + +가 존재한다. + +이는 React 상태/라우팅/컴포넌트 lifecycle을 사용하지 않는 별도 UI runtime이다. + +### 2.3 React integration 역시 DOM adapter에 가깝다 + +`src/features/memento-web/presentation/memento-runtime-bridge.tsx`는 시각적 React component가 아니다. + +```ts +useEffect(() => { + document.documentElement.dataset.mementoDataMode = gateway.mode; + const cleanup = installMementoPrototypeIntegration(document.body, gateway); + ... +}, [gateway]); + +return null; +``` + +그리고 `memento-prototype-integration.ts`가 정적 DOM을 찾아 데이터를 주입한다. + +이 파일은 1,124 LOC이고 `querySelector` 계열 접근이 약 60회 존재한다. + +결과적으로 UI에 두 개의 imperative owner가 생겼다. + +```text +beta.js + + +memento-prototype-integration.ts + ↓ +동일한 static DOM +``` + +이 구조는 장기적으로 이벤트 중복, 상태 불일치, cleanup 누락, DOM selector coupling을 만들 가능성이 높다. + +--- + +## 3. 가장 큰 구조적 문제 + +## P0-1. Template의 React render tree가 실제 제품 화면을 소유하지 않는다 + +Template에는 이미 다음 기반이 있다. + +- `RuntimeApplication` +- `ApplicationProvider` +- server-state provider +- `AppRouter` +- `AppShell` +- route registry/runtime +- render/chunk/error boundary +- locale provider +- session provider +- theme provider + +하지만 현재 `RuntimeApplication`은 `MementoRuntimeBridge`만 mount한다. + +즉 template이 가진 렌더링 구조가 준비되어 있지만 **Memento가 그 구조에 들어오지 않았다.** + +### 교정 방향 + +최종적으로 `RuntimeApplication`은 Memento가 포함된 Router를 렌더링해야 한다. + +```tsx + + + + + + + +``` + +그리고 실제 화면은 route component가 소유한다. + +--- + +## P0-2. Memento 디자인이 template design-system 밖에 있다 + +Template에는 이미 다음 구조가 존재한다. + +```text +src/presentation/design-system/ +├── index.ts +├── primitives/ +├── patterns/ +├── icons/ +└── tokens/ + ├── primitive.css + ├── semantic.css + ├── component.css + └── token-contract.ts +``` + +그리고 `check:design-system`이 token 존재 여부, vendor boundary, raw palette 등을 검사한다. + +하지만 실제 Memento 디자인은 `public/beta.css`에 있다. + +현재 Beta CSS의 시작점은 다음과 같다. + +```css +:root { + --bg: #f4f4f1; + --surface: #fff; + --surface2: #ecece7; + --ink: #171816; + --sub: #6d7069; + --line: #dddeda; + --accent: #496356; + --accent2: #dfe9e2; + --danger: #a34b42; + --side: 232px; + --shadow: 0 18px 50px rgba(...); +} +``` + +즉 **실제 제품의 디자인 토큰이 template의 token contract에 등록되지 않은 상태**다. + +더 중요한 문제는 `check:design-system`이 PASS한다는 점이다. + +검토 시: + +```text +Design system contract: 48 tokens and vendor boundaries PASS +``` + +했지만 이것은 Memento 디자인이 design-system을 잘 사용한다는 뜻이 아니다. + +실제 검사는 주로 `src/**`의 TypeScript/TSX와 기존 token CSS를 보고 있으며, `public/beta.css`는 제품 디자인을 소유하면서도 해당 계약을 우회한다. + +### 교정 방향 + +현재 Beta 디자인을 **없애거나 새 디자인으로 바꾸면 안 된다.** + +먼저 현재 값을 그대로 product design token으로 승격해야 한다. + +예: + +```text +beta --bg -> --color-surface +beta --surface -> --color-panel +beta --surface2 -> --color-surface-muted +beta --ink -> --color-content +beta --sub -> --color-content-muted +beta --line -> --color-border +beta --accent -> Memento action/accent semantic token +beta --accent2 -> Memento accent-surface semantic token +beta --danger -> --color-danger +beta --side -> shell/sidebar component token +beta --shadow -> product surface elevation token +``` + +Pretendard, radius, spacing, shadow, transition도 동일한 방식으로 token contract 아래로 옮긴다. + +**중요: 1차 migration에서는 값 자체를 개선하거나 정리하지 않는다. 현재 값 그대로 옮긴다.** + +디자인 개선은 별도 작업이다. 이번 작업에서는 visual parity가 우선이다. + +--- + +## P0-3. 기존 template component가 존재하지만 Memento는 사용하지 않는다 + +Template design-system에는 이미 다음 component/pattern이 존재한다. + +- Button +- LinkButton +- IconButton +- Badge +- Card +- Dialog +- Drawer +- ToastProvider +- Tooltip +- Field / TextField +- Checkbox +- Select +- Switch +- Tabs +- Pagination +- Skeleton +- ProgressBar +- PageHeader +- StandardPage +- CollectionPage +- DetailPage +- FormPage +- StatusPage + +Memento feature에서 design-system import는 현재 0건이다. + +대신 `index.html`에 직접 다음이 작성되어 있다. + +```html + + + +... + +
...
+
...
+``` + +### 교정 방향 + +“기존 Button을 그대로 가져다 써서 디자인을 template 기본 디자인으로 바꾼다”가 목표가 아니다. + +정확한 목표는: + +> **template의 component contract와 accessibility/lifecycle 구조를 재사용하면서 Memento의 시각 토큰과 variant를 그 component에 입힌다.** + +예: + +```text +Button behavior/accessibility contract + + Memento button tokens/variants + = 현재 .btn / .btn.primary와 동일한 시각 결과 + +Dialog lifecycle/focus management + + Memento modal tokens + = 현재 .modal과 동일한 시각 결과 + +Drawer behavior + + Memento drawer tokens + = 현재 profile drawer와 동일한 시각 결과 +``` + +기존 component의 기본 class가 visual parity를 깨뜨리는 경우에는 억지로 바로 치환하지 않는다. + +우선 **product variant를 design-system에 추가한 뒤** 사용한다. + +--- + +## P0-4. 현재 Memento navigation은 Router가 아니라 class toggle이다 + +현재 `beta.js`의 `showPage(name)`가: + +- `.page.active`를 변경하고 +- `[data-page]` active 상태를 변경하고 +- 내부 변수 `lastPage`를 갱신한다. + +이 구조에서는 URL이 실제 application state를 표현하지 못한다. + +Template에는 이미: + +- typed route registry +- React Router +- route codec +- navigation policy +- route error/loading boundary +- feature-owned route contribution +- route diagnostics + +가 있다. + +그러나 Memento route는 installed feature runtime에 등록되어 있지 않다. + +현재 `installed-product-manifest.ts`의 compiled product feature는 사실상 reference feature 중심이고, `installed-feature-runtimes.tsx`도 Memento route runtime을 조립하지 않는다. + +### 목표 route 예시 + +```text +/ -> Home +/library -> Library +/memories -> Memories +/memories/:memoryId -> Memory Detail +/albums -> Albums +/albums/:albumId -> Album Detail +/search -> Search +/people -> People +/people/:personId -> Person Detail +/places -> Places Map +/places/:placeId -> Place Detail +/settings/:section? -> Settings +/login -> Login surface (필요 시) +/register -> Register surface (필요 시) +``` + +현재 query-string 기반 prototype 진입점이 외부에서 사용되고 있다면 compatibility redirect/codec을 두고 제거한다. + +--- + +## P0-5. Presentation이 application input이 아니라 gateway를 직접 받는다 + +현재: + +```text +createRuntimeComposition + -> createMementoGateway + -> RuntimeApplication + -> MementoRuntimeBridge(gateway) + -> prototype integration +``` + +이다. + +즉 feature presentation이 사실상 outbound gateway를 직접 사용한다. + +Template의 의도는: + +```text +Presentation + -> application input/use case + -> output port + -> adapter +``` + +다. + +### 교정 방향 + +Memento feature에도 명시적인 application API를 둔다. + +예: + +```text +features/memento-web/ +├── domain/ +├── application/ +│ ├── ports/ +│ ├── use-cases/ +│ └── memento-application.ts +├── adapters/ +└── presentation/ +``` + +Presentation에서는: + +```text +useMementoHome() +useLibrary() +useMemory(id) +useAlbums() +useSearch(...) +useDevices() +``` + +같은 좁은 consumer surface를 사용한다. + +Gateway 자체를 page component에 전달하지 않는다. + +--- + +## P0-6. API adapter가 template의 reusable HTTP capability를 우회한다 + +환경 선택 자체는 잘 되어 있다. + +현재 `create-memento-gateway.ts`는: + +```text +local -> mock +development -> API +staging -> API +production -> API +``` + +로 분리한다. + +이 방향은 유지한다. + +문제는 `http-memento-gateway.ts`가 자체적으로 `fetch`, timeout, JSON 처리, CSRF, status handling 등을 구현하고 있다는 점이다. + +반면 template에는 이미: + +- installed HTTP contract +- input/output/problem validator +- reusable HTTP executor +- retry/effect certainty +- bounded body handling +- diagnostics +- schema validation +- feature HTTP binding +- wire -> domain mapper +- typed Result / ApiFailure + +구조가 존재한다. + +Reference feature는 이미 다음 형태를 사용한다. + +```ts +const defineReferenceHttpOperation = + defineFeatureHttpOperationForRoutes(); + +export const REFERENCE_HTTP_OPERATIONS = { + ... +}; + +export function createReferenceHttpGateway(http: ReferenceHttpBinding) { + return { + list: (...) => http.execute(...), + create: (...) => http.execute(...), + get: (...) => http.execute(...), + }; +} +``` + +Memento도 이 경로를 따라야 한다. + +### 목표 + +Memento가 소유할 것: + +- operation identity +- endpoint-specific input/output schema +- Memento DTO +- mapper +- feature-specific problem mapping + +Template HTTP capability가 소유할 것: + +- fetch transport +- timeout +- cancellation +- retry +- auth/session integration +- response body bound +- content-type +- validation execution +- effect certainty +- diagnostics +- generic failure normalization + +즉 `http-memento-gateway.ts` 469 LOC의 상당 부분은 제품 코드가 직접 소유할 필요가 없다. + +--- + +## P0-7. Template gate가 현재 prototype 우회를 탐지하지 못한다 + +검토 시 다음 검증은 모두 PASS했다. + +```text +check:design-system -> PASS +check:architecture -> PASS +check:types:app -> PASS +``` + +`check:architecture` 결과: + +```text +Static import graph: 322 modules, 967 dependencies, all imports resolved +Architecture graph fixtures: 14 regression checks PASS +TypeScript-only source policy: PASS +``` + +그럼에도 현재 실제 UI는 plain HTML/JS/CSS다. + +이유는 static architecture graph가 `src` 중심이고, 제품 동작의 상당 부분이 `public/beta.js`와 `index.html`에 있기 때문이다. + +이는 assurance 관점에서 중요한 blind spot이다. + +### 추가해야 할 gate + +최종 구조에서는 다음을 자동 검증하는 것이 좋다. + +1. `index.html`에 product page markup 금지 +2. production `public/*.js`에 제품 UI logic 금지 +3. Memento presentation에서 직접 DOM query 금지 +4. Memento presentation에서 direct `fetch` 금지 +5. Memento feature는 design-system public barrel만 사용 +6. Memento route contribution이 registry/runtime에 등록되어 있는지 검증 +7. `beta.js`, `beta.css`가 production/service-worker asset manifest에 남아 있지 않은지 검증 + +--- + +## P0-8. 현재 visual test가 Memento 디자인을 보호하지 않는다 + +현재 visual snapshot은 주로 template platform surface를 대상으로 한다. + +확인된 snapshot: + +- app shell +- design-system gallery +- platform overview +- state surfaces + +그러나 실제 Memento의 12개 page surface와 주요 overlay를 보호하는 snapshot은 없다. + +따라서 지금 바로 TSX 전환을 시작하면 “구조는 좋아졌지만 디자인이 조금씩 달라지는” 회귀를 잡기 어렵다. + +### 반드시 먼저 해야 할 일 + +현재 prototype을 **golden visual baseline**으로 고정한다. + +최소 viewport: + +- Desktop +- Mobile + +최소 화면: + +- Home +- Library +- Memories +- Search +- Place Detail +- Memory Detail +- Albums +- Album Detail +- People +- Person Detail +- Places Map +- Settings + +최소 overlay/state: + +- Profile Drawer +- Upload Modal +- Create Album Modal +- Share Modal +- Edit Memory Modal +- Action Modal +- Viewer +- Library selected state +- Library dense state +- Album tab states +- Memory detail tab states + +같은 Chromium, 같은 viewport, 같은 font 조건에서는 **migration 전후 screenshot diff 0을 목표**로 한다. + +DOM 구조상 불가피한 anti-aliasing 차이를 허용해야 한다면 그 사유를 별도 evidence로 남기고 임계치를 극소로 제한한다. 기본값부터 느슨하게 잡으면 안 된다. + +--- + +## 4. 현재 구현에서 유지할 부분 + +전부 버리고 다시 만들 필요는 없다. + +### 유지 1. 환경별 gateway 선택 + +현재: + +```text +local -> mock +development/staging/production -> API +``` + +구조는 사용자 요구와 일치한다. + +이를 bootstrap/composition 경계에서 계속 유지한다. + +Presentation에는 환경 분기 코드가 들어가면 안 된다. + +### 유지 2. Memento API contract와 gateway interface + +현재 Memento API 타입과 `MementoGateway` 추상화는 활용 가치가 있다. + +다만 DTO/domain/application model 책임이 섞여 있다면 feature refactoring 단계에서 분리한다. + +### 유지 3. Mock adapter + +Local 개발에서 backend 없이 UI를 개발할 수 있도록 mock adapter는 그대로 중요한 자산이다. + +다만 mock 데이터가 DOM을 직접 채우는 구조가 아니라 application/gateway contract를 통해 React page로 흘러야 한다. + +### 유지 4. 현재 시각 디자인 + +`beta.css`는 폐기 대상이 아니라 **디자인 시스템으로 이관할 원본 사양**이다. + +현재 화면이 visual source of truth다. + +--- + +## 5. 목표 구조 + +권장 최종 구조는 다음과 같다. + +```text +src/ +├── bootstrap/ +│ ├── main.tsx +│ ├── create-runtime-composition.ts +│ └── runtime-application.tsx +│ +├── presentation/ +│ └── design-system/ +│ ├── index.ts +│ ├── tokens/ +│ │ ├── primitive.css +│ │ ├── semantic.css +│ │ ├── component.css +│ │ └── token-contract.ts +│ ├── primitives/ +│ ├── patterns/ +│ └── memento/ +│ ├── memento-design.stories.tsx +│ └── product-patterns.tsx +│ +└── features/ + └── memento-web/ + ├── domain/ + ├── contracts/ + │ ├── memento-api.ts + │ ├── memento-contract-contribution.ts + │ ├── memento-mappers.ts + │ └── memento-schemas.ts + ├── application/ + │ ├── ports/ + │ ├── use-cases/ + │ └── memento-application.ts + ├── adapters/ + │ ├── create-memento-gateway.ts + │ ├── mock/ + │ └── http/ + └── presentation/ + ├── memento-feature-runtime.tsx + ├── hooks/ + ├── layouts/ + ├── pages/ + ├── components/ + └── overlays/ +``` + +핵심은 **product component도 design-system primitive를 사용하고, page는 product component를 조립하며, data access는 hook/application boundary를 통과하는 것**이다. + +--- + +## 6. Memento 디자인 시스템 분해안 + +## 6.1 Token 계층 + +현재 `beta.css` 값을 다음 세 계층으로 옮긴다. + +### Primitive + +제품의 물리 값: + +- color palette +- spacing +- typography +- radius +- shadow +- transition +- size + +예: + +```text +#f4f4f1 +#ffffff +#ecece7 +#171816 +#6d7069 +#dddeda +#496356 +#dfe9e2 +#a34b42 +232px sidebar width +12/14/18/22/26px radius family +``` + +### Semantic + +의미 기반 token: + +```text +surface +panel +surface-muted +content +content-muted +border +accent +accent-surface +danger +overlay +inverse-content +``` + +### Component + +특정 component 계약: + +```text +button-height +button-radius +chip-height +sidebar-width +modal-radius +drawer-width +media-card-radius +detail-hero-radius +selection-bar-elevation +toast-layer +``` + +### 주의 + +현재 template의 token 이름을 무조건 제거할 필요는 없다. + +가능한 경우 기존 semantic contract에 Memento 값을 매핑하고, Memento 고유 의미만 추가한다. + +--- + +## 6.2 Primitive / reusable UI component + +최소 다음을 design-system 또는 product design pattern으로 승격한다. + +```text +Button +IconButton +Chip +Badge +TextField / SearchField +Avatar +ProgressBar +Tabs +Dialog +Drawer +Toast +Card / Surface +MediaThumbnail +SectionHeader +PageHeading +``` + +기존 template component가 기능적으로 동일하면 **기존 component에 Memento variant/token을 추가**한다. + +기능 semantics가 다르면 억지로 generic component를 확장하지 말고 product pattern으로 둔다. + +예: + +```text +design-system primitive: Dialog +product pattern: CreateAlbumDialog + +design-system primitive: Card +product pattern: MemoryCard + +design-system primitive: Tabs +product pattern: MemoryDetailTabs +``` + +--- + +## 7. 화면 component 분해안 + +## App Shell + +```text +MementoAppShell +├── MementoSidebar +│ ├── Brand +│ ├── PrimaryNavigation +│ └── ProfileSummary +├── MobileTopBar +├── Outlet +├── MobileTabs +└── ProfileDrawer +``` + +기존 template의 `AppShell`을 그대로 시각적으로 사용하지 않는다. + +**Shell contract/router integration은 재사용하되, Memento shell 디자인을 동일하게 구현**한다. + +## Home + +```text +HomePage +├── PageHead +├── DiscoveryCard +├── ResurfacedMemorySection +│ └── MemoryCard[] +├── TodayMediaSection +│ ├── TodayMediaGrid +│ └── BackupProgressCard +└── ArchiveStatusSection + └── ArchiveStatusCard[] +``` + +## Library + +```text +LibraryPage +├── LibraryToolbar +│ ├── SearchField +│ ├── FilterChip[] +│ └── ViewModeSwitch +├── ActiveFilterSummary +├── MediaGroup[] +│ └── MediaGrid +└── SelectionBar +``` + +## Memories / Albums + +```text +MemoriesPage +├── SuggestedMemoryBanner +├── SavedMemoryGrid +└── ManualAlbumGrid + +AlbumsPage +├── AlbumToolbar +└── AlbumGrid +``` + +## Search + +```text +SearchPage +├── GlobalSearchField +├── RecentSearches +├── PeopleStrip +├── PlaceGrid +├── MediaTypeGrid +└── YearGrid +``` + +## Detail + +```text +MemoryDetailPage +├── MemoryDetailHero +├── DetailTabs +├── MemoryStory +│ └── MomentSection[] +├── MemoryPhotoGrid +└── MemoryInfoPanel + +AlbumDetailPage +├── AlbumHeader +├── AlbumTabs +├── AlbumPhotoGrid +├── AlbumStory +└── AlbumInfoPanel + +PlaceDetailPage +├── PlaceMapHeader +├── RelatedMemoryGrid +└── PlacePhotoGrid + +PersonDetailPage +├── PersonHeader +├── RelatedMemoryGrid +└── PersonPhotoGrid +``` + +## Overlay + +```text +UploadDialog +CreateAlbumDialog +ShareDialog +EditMemoryDialog +ActionDialog +MediaViewer +ProfileDrawer +Toast +``` + +여기서는 기존 template의 Dialog / Drawer / Toast behavior를 적극적으로 재사용할 수 있다. + +--- + +## 8. 상태 소유권을 React로 이동해야 한다 + +현재 `beta.js`에서 class toggle로 관리하는 상태를 다음처럼 나눈다. + +| 현재 prototype 상태 | 목표 owner | +| --- | --- | +| 현재 page | React Router | +| 뒤로 가기 | Router history | +| modal open/close | component state / dialog primitive | +| drawer open/close | component state / drawer primitive | +| library filter | route search param 또는 page state | +| library search | route search param 또는 controlled state | +| dense/mosaic | page preference state | +| selected media | Library page reducer/state | +| detail tab | route search param 또는 local state | +| album search/filter | controlled state | +| settings section | nested route 또는 route param | +| toast | ToastProvider | +| viewer | component state / viewer overlay | +| loading/error | Query/Application async state | + +원칙은 다음이다. + +> DOM class가 상태를 소유하면 안 된다. React state가 상태를 소유하고 class는 그 상태를 표현해야 한다. + +--- + +## 9. Data flow 목표 + +현재: + +```text +React bridge + -> gateway + -> direct fetch/mock + -> querySelector + -> static DOM 변경 +``` + +목표: + +```text +Page + -> feature hook/controller + -> application input/use case + -> MementoGateway port + -> mock adapter + 또는 + -> Memento HTTP feature binding + -> reusable HTTP executor + -> fetch +``` + +Server state를 표시하는 화면은 template이 이미 가진 TanStack Query bridge와 query cache lifecycle을 사용한다. + +예: + +```text +useHome() +useLibrary(filters) +useMemory(memoryId) +useAlbums(filters) +useAlbum(albumId) +useSearch(query) +usePeople() +usePlaces() +useDevices() +useStorageSettings() +``` + +Mutation도: + +```text +useCreateAlbum() +useSaveMemoryCandidate() +useUpdateMemory() +useUpdateAlbum() +useUpdateDeviceBackupPolicy() +useCreateShare() +``` + +같은 feature-owned hook으로 감싼다. + +Page에서 query client나 raw gateway를 직접 호출하지 않는다. + +--- + +## 10. 환경 구성은 현재 방향을 유지한다 + +요구사항: + +```text +local -> mock +dev -> API +prod -> API +``` + +현재 코드는 사실상 이를 이미 만족하며 staging도 API다. + +따라서 환경 분기는 새로 만들 필요가 없다. + +리팩터링 과정에서 반드시 지켜야 할 규칙은: + +```text +Presentation -> APP_ENV를 모른다. +Application -> APP_ENV를 모른다. +Composition -> 어떤 adapter를 연결할지만 결정한다. +``` + +즉 화면 코드는 local/dev/prod에 따라 달라지면 안 된다. + +--- + +## 11. 디자인을 1도 바꾸지 않기 위한 migration 순서 + +이 작업은 일반적인 “리팩터링하면서 CSS도 정리” 방식으로 하면 안 된다. + +순서를 엄격하게 분리해야 한다. + +## Phase 0 — Visual baseline 고정 + +코드는 바꾸지 않는다. + +먼저 현재 prototype을 기준으로: + +- desktop screenshot +- mobile screenshot +- page별 screenshot +- overlay별 screenshot +- 주요 interaction state screenshot + +을 만든다. + +이 baseline이 이후 migration의 승인 기준이다. + +## Phase 1 — Beta CSS를 design-system 계약으로 이동 + +이 단계에서도 DOM과 React 구조는 바꾸지 않는다. + +- 현재 CSS 값을 token으로 이관 +- Pretendard 유지 +- 기존 spacing/radius/shadow 유지 +- 기존 responsive breakpoint 유지 +- design-system gate가 Memento token을 검사하도록 확장 + +**시각 결과는 0 변경.** + +초기 migration에서는 기존 class selector를 compatibility layer로 유지해도 된다. + +즉 바로 `.btn`을 전부 삭제할 필요는 없다. + +## Phase 2 — Static HTML을 TSX로 1:1 이전 + +가장 중요한 원칙: + +> 먼저 component 구조만 바꾸고 DOM shape와 class name은 최대한 그대로 유지한다. + +예: + +```html +
...
+``` + +를: + +```tsx + +``` + +로 바꾸되 component가 처음에는 동일한 article/class/child 순서를 출력하게 한다. + +이렇게 해야 visual parity를 확보하기 쉽다. + +이 단계에서는 아직 CSS redesign을 하지 않는다. + +## Phase 3 — `beta.js` 상태를 React로 이전 + +page별로 하나씩 옮긴다. + +권장 순서: + +1. Shell/navigation +2. Home +3. Library +4. Memories +5. Search +6. Memory/Album detail +7. People/Place +8. Settings +9. Overlay +10. Viewer + +한 page를 옮길 때마다 해당 page의 prototype handler를 제거한다. + +React와 `beta.js`가 같은 element를 동시에 소유하는 기간을 최소화한다. + +## Phase 4 — Router에 Memento feature 등록 + +- Memento route contract contribution +- route runtime contribution +- route codec +- product manifest 등록 +- navigation registry 연결 + +을 추가한다. + +이 시점부터 `showPage()`는 제거한다. + +## Phase 5 — Application / Query / reusable HTTP 연결 + +UI를 안정화한 뒤 data path를 template에 맞춘다. + +- gateway direct usage 제거 +- feature application input 정의 +- server-state hook 도입 +- Memento HTTP operation contract 등록 +- generic HTTP binding 사용 +- direct `fetch` 제거 + +Local mock은 같은 application port 뒤에 유지한다. + +## Phase 6 — Prototype compatibility 자산 제거 + +다음이 모두 충족된 이후에만 삭제한다. + +- `public/beta.js` +- `public/beta.css` +- `memento-prototype-integration.ts` +- `memento-runtime-bridge.tsx` +- static product markup in `index.html` +- service-worker asset manifest의 beta asset +- prototype-specific test helper + +삭제 전에 visual baseline 전체를 다시 통과시킨다. + +--- + +## 12. `index.html`의 최종 형태 + +최종 `index.html`은 application markup을 소유하면 안 된다. + +개념적으로 다음 정도만 남는 것이 맞다. + +```html + + + + ... + + + +
+ + + +``` + +실제 Sidebar/Home/Modal/Drawer를 여기에 두지 않는다. + +--- + +## 13. Login/Register 정적 HTML도 같은 원칙으로 정리해야 한다 + +현재: + +- `public/login-v2.html` +- `public/register-v2.html` + +도 static page다. + +이 화면이 제품 UI라면 main app migration이 끝난 뒤 TSX로 옮겨야 한다. + +다만 실제 인증 redirect entry나 Keycloak integration 요구가 별도로 있다면 **auth route와 외부 IdP 경계를 먼저 확인한 후** 옮긴다. + +Main shell보다 먼저 건드릴 필요는 없다. + +--- + +## 14. Service Worker / build에서도 prototype 자산을 제거해야 한다 + +현재 service-worker asset 생성 코드가 다음을 명시적으로 포함한다. + +- `index.html` +- `beta.css` +- `beta.js` + +즉 prototype이 단순 임시 파일이 아니라 release artifact에 포함되는 구조다. + +React migration 후에는: + +- application JS/CSS chunk +- manifest +- approved static asset + +을 build manifest가 소유해야 한다. + +`beta.js`, `beta.css`를 삭제하면서 service-worker generator도 함께 수정해야 한다. + +--- + +## 15. 테스트 전략 + +## Unit + +검증 대상: + +- Memento mapper +- route codec +- filtering/sorting policy +- selection reducer +- application use case +- mock gateway behavior + +## Component + +검증 대상: + +- MemoryCard +- AlbumCard +- LibraryToolbar +- SelectionBar +- Dialog +- DetailTabs +- MementoSidebar +- ProfileDrawer + +DOM class toggle 구현을 테스트하는 것이 아니라 user interaction과 rendered state를 테스트한다. + +## Storybook + +최소 다음 variant를 독립적으로 볼 수 있어야 한다. + +- buttons +- chips +- badges +- cards +- memory cards +- album cards +- media tiles +- loading/empty/error +- modal +- drawer +- selection bar +- desktop/mobile shell + +## Visual + +이번 리팩터링에서는 가장 중요한 gate다. + +**현재 prototype screenshot을 baseline으로 사용한다.** + +React 전환 후 동일 screenshot과 비교한다. + +## E2E + +최소 user flow: + +```text +Home -> Library +Library filter/search/select +Home -> Memory Detail +Memories -> Save Candidate +Albums -> Create Album +Search -> Person +Search -> Place +Profile -> Settings +Upload dialog +Share dialog +local mock boot +development API boot +``` + +--- + +## 16. 추가 architecture gate 권장안 + +이 repository는 gate가 강점이므로 Memento도 gate 안에 넣는 것이 좋다. + +### FE-MEMENTO-001 — Static product markup 금지 + +`index.html`에서 `.page`, `.modal`, Memento product DOM을 금지한다. + +### FE-MEMENTO-002 — Public imperative UI JS 금지 + +production `public/*.js`에 application UI state logic을 두지 않는다. + +### FE-MEMENTO-003 — Presentation direct DOM query 금지 + +`src/features/memento-web/presentation/**`에서: + +- `document.querySelector` +- `document.getElementById` +- global click handler + +를 금지한다. + +예외는 명시적인 browser capability adapter만 허용한다. + +### FE-MEMENTO-004 — Presentation direct gateway 금지 + +Page/component는 `MementoGateway`를 직접 import하지 않는다. + +### FE-MEMENTO-005 — Direct fetch 금지 + +Memento HTTP adapter는 template reusable HTTP binding을 통해 실행한다. + +### FE-MEMENTO-006 — Design-system barrel 강제 + +Memento presentation은 design-system deep import/vendor direct import를 하지 않는다. + +### FE-MEMENTO-007 — Visual baseline 필수 + +Memento page/overlay visual snapshot 누락 시 CI 실패. + +--- + +## 17. 구현 우선순위 + +### 1순위 — Visual baseline + +이것이 없으면 “디자인 1도 변경 금지”를 객관적으로 보장할 수 없다. + +### 2순위 — Memento token/design-system 편입 + +현재 `beta.css`가 제품 디자인의 SSOT이므로 먼저 구조화한다. + +### 3순위 — Shell + Home을 React TSX로 1:1 이전 + +가장 작은 end-to-end proof를 만든다. + +이 단계에서: + +```text +React +-> Memento design system +-> Memento shell +-> page component +``` + +가 실제 화면을 렌더링해야 한다. + +### 4순위 — 나머지 page/overlay component화 + +Library, Memories, Search, Detail, Settings 순으로 이전한다. + +### 5순위 — Router/feature registry 완전 연결 + +Prototype `showPage`를 제거한다. + +### 6순위 — Application/Query/HTTP capability 연결 + +정적 DOM bridge 없이 실제 server state를 React로 흘린다. + +### 7순위 — beta compatibility layer 삭제 + +마지막에만 삭제한다. + +--- + +## 18. 완료 기준 + +다음 조건이 모두 만족되어야 이 작업을 “완료”로 보는 것이 맞다. + +### Rendering + +- [ ] `index.html`에는 product page markup이 없다. +- [ ] `#root`가 숨겨져 있지 않다. +- [ ] React가 전체 Memento UI를 렌더링한다. +- [ ] `MementoRuntimeBridge`가 제거되었다. +- [ ] `memento-prototype-integration.ts`가 제거되었다. +- [ ] `public/beta.js`가 production runtime에서 제거되었다. + +### Design System + +- [ ] 현재 Beta 디자인 값이 design token contract 아래에 있다. +- [ ] Memento component가 design-system public API를 사용한다. +- [ ] raw product color/spacing이 page TSX에 흩어져 있지 않다. +- [ ] Storybook에서 Memento component를 개별 확인할 수 있다. +- [ ] desktop/mobile visual parity가 유지된다. + +### Routing + +- [ ] Memento route가 feature contract/runtime으로 등록되어 있다. +- [ ] class toggle 기반 `showPage`가 없다. +- [ ] browser back/forward가 정상 동작한다. +- [ ] deep link가 정상 동작한다. + +### Data / Architecture + +- [ ] Presentation이 gateway를 직접 받지 않는다. +- [ ] local은 mock adapter를 사용한다. +- [ ] development/staging/production은 API adapter를 사용한다. +- [ ] Memento API가 reusable HTTP capability를 사용한다. +- [ ] feature adapter의 direct `fetch`가 제거되었다. +- [ ] template query/application boundary를 통해 server state가 전달된다. + +### Assurance + +- [ ] `check:architecture` PASS +- [ ] `check:design-system` PASS +- [ ] `check:types` PASS +- [ ] component test PASS +- [ ] Memento visual test PASS +- [ ] Memento E2E PASS +- [ ] beta asset가 service-worker/release manifest에 남아 있지 않다. + +--- + +## 19. 작업하면서 하지 말아야 할 것 + +### 금지 1. 디자인까지 함께 “정리”하기 + +이번 작업에서 radius, spacing, 색, typography를 보기 좋게 정리하면 안 된다. + +구조 리팩터링과 visual redesign을 섞으면 regression 원인을 찾기 어렵다. + +### 금지 2. Static HTML 전체를 한 번에 거대한 `MementoPage.tsx`로 옮기기 + +HTML을 TSX로 확장자만 바꾸는 것은 해결이 아니다. + +Page -> section -> product component -> primitive 순으로 분리한다. + +### 금지 3. 기존 `beta.js`를 React `useEffect` 안에 그대로 넣기 + +이는 현재 `MementoRuntimeBridge` 방식의 반복이다. + +DOM owner는 React가 되어야 한다. + +### 금지 4. Template component의 기본 디자인을 강제로 적용하기 + +“template을 사용한다”는 이유로 현재 Memento 디자인을 template gallery 디자인으로 바꾸면 요구사항 위반이다. + +재사용할 것은 component contract/lifecycle/accessibility/architecture이고, 시각 표현은 Memento token으로 맞춘다. + +### 금지 5. Generic HTTP capability를 두고 Memento 전용 fetch stack을 계속 유지하기 + +특별한 protocol requirement가 없는 일반 API endpoint라면 template capability를 우선 사용한다. + +--- + +## 20. 최종 판단 + +현재 Memento frontend의 문제는 **컴포넌트가 조금 덜 분리된 정도가 아니다.** + +더 정확하게 말하면: + +> **template의 architecture와 Memento prototype이 같은 repository에 공존하지만, 실제 제품 UI가 template의 architecture 안으로 들어오지 않은 상태다.** + +따라서 다음 리팩터링은 CSS 미세 정리나 파일 분할이 아니라 **UI ownership migration**이어야 한다. + +가장 중요한 원칙은 두 개다. + +1. **현재 디자인은 visual source of truth로 고정한다.** +2. **그 디자인을 그대로 유지한 채 ownership만 static HTML/JS에서 React + template architecture로 이동한다.** + +이 원칙대로 진행하면 최종 상태는: + +```text +현재 디자인 + = 유지 + +현재 beta HTML/JS 구조 + = 제거 + +Memento design system + = 현재 시안에서 추출 + +UI + = component 단위 TS/TSX + +navigation + = template Router + +state + = React / route / query + +business interaction + = application input/use case + +local + = mock + +dev/prod + = API + +HTTP + = template reusable capability + +verification + = template gates + Memento visual parity gate +``` + +가 된다. + +이 구조가 사용자가 의도한 **“기존 template에 도메인과 디자인을 흡수하되 디자인은 바꾸지 않고, template이 제공하는 기능을 최대한 활용하는 Memento frontend”**에 가장 가깝다. + +--- + +## Appendix A. 검토 시 실행한 검증 + +실행: + +```bash +corepack pnpm check:design-system +corepack pnpm check:architecture +corepack pnpm check:types:app +``` + +결과: + +```text +check:design-system PASS +check:architecture PASS +check:types:app PASS +``` + +단 실행 환경 Node는 repository 요구사항 `>=24.11.0 <25`와 달리 `v22.23.2`였으므로 engine warning이 발생했다. + +이번 검증의 중요한 의미는 “현재 구조가 문제가 없다”가 아니라 반대다. + +**기존 gate가 모두 PASS해도 static prototype이 architecture/design-system 경계를 우회할 수 있다는 blind spot이 확인되었다.** + +--- + +## Appendix B. 주요 증거 파일 + +```text +index.html +public/beta.css +public/beta.js + +src/bootstrap/main.tsx +src/bootstrap/runtime-application.tsx +src/bootstrap/create-runtime-composition.ts + +src/features/memento-web/presentation/memento-runtime-bridge.tsx +src/features/memento-web/presentation/memento-prototype-integration.ts + +src/features/memento-web/adapters/create-memento-gateway.ts +src/features/memento-web/adapters/http-memento-gateway.ts +src/features/memento-web/adapters/mock-memento-gateway.ts + +src/presentation/design-system/index.ts +src/presentation/design-system/tokens/* +src/presentation/layouts/app-shell.tsx +src/presentation/routes/app-router.tsx +src/presentation/templates/page-templates.tsx + +src/features/installed-product-manifest.ts +src/features/installed-feature-contracts.ts +src/features/installed-feature-runtimes.tsx + +src/features/reference-feature/adapters/reference-http-gateway.ts +src/adapters/http/feature-http-binding.ts + +scripts/check-design-system.ts +scripts/check-architecture.ts +scripts/generate-service-worker-assets.ts +``` diff --git a/eslint.config.ts b/eslint.config.ts index 2505f4b..c451a67 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -427,6 +427,7 @@ export default [ "tests/fixtures/security/forbidden/**", "tests/fixtures/optional-recipes/**", "tests/fixtures/browser-file-storage-boundaries/**", + "tests/fixtures/memento-visual-baseline/legacy/**", ], }, eslint.configs.recommended, diff --git a/index.html b/index.html index dcc510d..c5ad61a 100644 --- a/index.html +++ b/index.html @@ -6,209 +6,9 @@ Memento — Living Archive - - - -
- - -
Memento
- -
-
-
-
9월 15일 화요일 · Galaxy 동기화 완료

좋은 오후예요.

-
-
- -
-
-
-
✦새로운 순간을 찾았어요
-

3박 4일의 제주를
하나의 Memory로 묶었습니다.

-

7월 12일부터 15일까지 촬영한 84장의 사진과 영상을 시간과 장소의 흐름으로 정리했습니다.

-
84개 미디어4개 장소3개 순간
-
-
-
- -

다시 떠오른 기억

-
-
1년 전 오늘강릉에서 보낸 주말
-
지난 가을가평 드라이브
-
3년 전처음 떠난 부산
-
-
- -

오늘 들어온 사진

-
-
42장Galaxy · 16:42 동기화
중복 3장 건너뜀
- -
-
- -

보관함 상태

-
-
정리 필요
128장

아직 어떤 Memory나 Album에도 포함되지 않았습니다.

-
중복 후보
14장

시각적으로 거의 같은 사진을 검토할 수 있습니다.

-
저장 공간
428 GB

1 TB 중 42% 사용 · 원본 3,184개

-
-
-
- -
-
모든 원본이 있는 곳

라이브러리

-
- - -
-
-
-
-
- -
-
사진을 다시 보는 방식

Memories

-
-

새로 발견한 Memory

사진을 추가하면 자동으로 갱신됩니다.

-
추천

제주, 여름의 끝

84장의 사진 · 4개 장소 · 3개의 순간을 하나의 흐름으로 묶었습니다.

-
-

저장된 Memories

-

내가 만든 Albums

직접 만든 컬렉션은 자동 Memory와 구분해서 관리합니다.

-
-
- - - -
-
-
동적 컬렉션

제주도

GPS 메타데이터가 제주도로 분류된 168장의 사진과 영상 · 사진이 추가되면 자동으로 갱신됩니다.

-

이 장소에서의 기록

Memory84
제주, 여름의 끝2026.07.12 — 07.15
방문 묶음37
2024년 5월 제주2024.05.04 — 05.06
-

제주에서 찍은 모든 사진

-
- -
-
Memory

제주, 여름의 끝

2026.07.12 — 07.15 · 제주 · 84개의 사진과 영상

-
-
-
7월 12일 · 27개

협재 · 첫날 오후

12:40 — 16:10 · 협재해수욕장 주변
-
7월 13일 · 31개

애월 · 늦은 오후

16:40 — 19:05 · 애월
-
7월 14일 · 26개

제주시 · 마지막 저녁

18:10 — 21:02 · 제주시
-
-
-

Memory 정보

자동 구성

촬영 시간, GPS, 사진 간 시간 간격을 기준으로 자동 구성되었습니다. 사용자는 커버·제목·구간 합치기/나누기만 수정하면 됩니다.

미디어84
장소4
기간4일
-
- -
-
직접 만든 컬렉션

내 Albums

-
-
-
- -
-
-
-
수동 Album

가족 사진

124개의 사진과 영상 · 최근 수정 9월 14일

-
-
-
124개 항목직접 정렬
-
지난 설날 · 36개

다 같이 모였던 오후

2026.02.17 · 서울
5월 · 28개

봄 나들이

2026.05.05 · 경기
-

Album 정보

이름가족 사진
생성일2025.01.03
공유비공개
정렬직접 설정
커버직접 선택
-
- -
-
얼굴을 기준으로 모아보기

사람

-

이름 지정됨

나
나842장
가
가족381장
친
친구264장
-

이름 미지정

자주 함께 등장한 얼굴부터 보여줍니다.

?
이름 지정97장
?
이름 지정63장
?
이름 지정41장
-
- -
-
-
가
사람

가족

381장의 사진 · 12개의 Memory

-

함께한 Memories

84
제주, 여름의 끝2026.07.12 — 07.15
67
강릉에서 보낸 주말2025.09.14 — 09.15
-

모든 사진

-
- -
-
GPS가 있는 사진

장소 지도

-
-
- -
-
개인 저장소 설정

동기화된 기기

-
-
- -
- - - -
0개 선택
-
- - -
프로필 & 저장소
동현Keycloak 계정 · donghyeon
저장 공간428 GB1 TB 중 42%
미디어3,184사진 2,947 · 영상 237
- - - - - - - - - - -
2026.07.13 · 제주 · 서버 원본
-
- -
- - +
- \ No newline at end of file + diff --git a/package.json b/package.json index 1b920ec..5585762 100644 --- a/package.json +++ b/package.json @@ -15,8 +15,8 @@ "build:release-candidate": "corepack pnpm build && corepack pnpm generate:supply-chain && corepack pnpm scan:security && corepack pnpm verify:release && node scripts/verify-supply-chain-artifacts.ts && node scripts/create-release-candidate.ts", "preview": "vite preview", "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:design-system": "node scripts/check-design-system.ts", + "check:architecture": "node scripts/check-architecture.ts && node scripts/check-memento-assurance.ts", + "check:design-system": "node scripts/check-design-system.ts && node scripts/check-design-system-fixtures.ts", "check:design-system:fixture": "node scripts/check-design-system.ts --fixture", "check:i18n": "node scripts/check-i18n.ts", "check:i18n:fixture": "node scripts/check-i18n.ts --fixture", @@ -56,13 +56,15 @@ "test:http-scenario-evidence": "node scripts/run-http-scenario-evidence.ts", "test:recipes": "node scripts/run-vitest.ts run tests/recipes --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/optional-recipes.xml --passWithNoTests", "test:e2e": "playwright test", + "test:e2e:memento-api": "playwright test --config playwright.memento-api.config.ts", "test:e2e:dev": "playwright test --config playwright.dev.config.ts", "test:browser-capabilities": "playwright test --config playwright.capabilities.config.ts", "verify:browser-capability-evidence": "node scripts/verify-browser-capability-evidence.ts", "storybook": "storybook dev -p 6006", "build:storybook": "storybook build -o artifacts/storybook/static", "test:storybook": "playwright test --config playwright.storybook.config.ts", - "test:visual": "playwright test --config playwright.visual.config.ts", + "test:visual": "playwright test --config playwright.visual.config.ts && playwright test --config playwright.memento-legacy.config.ts", + "test:visual:memento-legacy": "playwright test --config playwright.memento-legacy.config.ts", "test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots", "check:test-evidence": "node scripts/check-test-evidence.ts", "check:test-evidence:browser": "node scripts/check-test-evidence.ts --skip-scenario-executions", @@ -135,7 +137,9 @@ "dev:local": "vite", "dev:api": "APP_PROFILE=development vite", "build:dev": "APP_PROFILE=development node scripts/build-frontend.ts", - "build:prod": "APP_PROFILE=production node scripts/build-frontend.ts" + "build:prod": "APP_PROFILE=production node scripts/build-frontend.ts", + "check:memento-assurance": "node scripts/check-memento-assurance.ts", + "check:design-system:fixtures": "node scripts/check-design-system-fixtures.ts" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/playwright.config.ts b/playwright.config.ts index 83fe081..12cec15 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -22,17 +22,17 @@ export default defineConfig({ projects: [ { name: "chromium", - testIgnore: "**/compact-smoke.spec.ts", + testIgnore: ["**/compact-smoke.spec.ts", "**/memento-api-mode.spec.ts"], use: { ...devices["Desktop Chrome"] }, }, { name: "firefox", - testIgnore: "**/compact-smoke.spec.ts", + testIgnore: ["**/compact-smoke.spec.ts", "**/memento-api-mode.spec.ts"], use: { ...devices["Desktop Firefox"] }, }, { name: "webkit", - testIgnore: "**/compact-smoke.spec.ts", + testIgnore: ["**/compact-smoke.spec.ts", "**/memento-api-mode.spec.ts"], use: { ...devices["Desktop Safari"] }, }, { diff --git a/playwright.memento-api.config.ts b/playwright.memento-api.config.ts new file mode 100644 index 0000000..1169d24 --- /dev/null +++ b/playwright.memento-api.config.ts @@ -0,0 +1,21 @@ +import { defineConfig, devices } from "@playwright/test"; + +export default defineConfig({ + testDir: "./tests/e2e", + testMatch: "memento-api-mode.spec.ts", + outputDir: "./artifacts/tests/e2e-api/results", + reporter: [["list"]], + use: { + ...devices["Desktop Chrome"], + baseURL: "http://127.0.0.1:4176", + trace: "retain-on-failure", + screenshot: "only-on-failure", + }, + webServer: { + command: + "APP_PROFILE=development RUNTIME_API_BASE_URL=http://127.0.0.1:4176/ corepack pnpm exec vite --host 127.0.0.1 --port 4176 --strictPort", + url: "http://127.0.0.1:4176", + reuseExistingServer: false, + }, + projects: [{ name: "chromium-api-mode" }], +}); diff --git a/playwright.memento-legacy.config.ts b/playwright.memento-legacy.config.ts new file mode 100644 index 0000000..65a1050 --- /dev/null +++ b/playwright.memento-legacy.config.ts @@ -0,0 +1,29 @@ +import { defineConfig, devices } from "@playwright/test"; + +export default defineConfig({ + testDir: "./tests/visual", + testMatch: "memento-legacy-parity.visual.spec.ts", + outputDir: "./artifacts/tests/visual-legacy/results", + reporter: [["list"]], + use: { + ...devices["Desktop Chrome"], + baseURL: "http://127.0.0.1:4174", + colorScheme: "light", + locale: "en-US", + trace: "retain-on-failure", + }, + webServer: [ + { + command: + "corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port 4174", + url: "http://127.0.0.1:4174", + reuseExistingServer: false, + }, + { + command: "node scripts/serve-memento-legacy-visual.ts 4195", + url: "http://127.0.0.1:4195", + reuseExistingServer: false, + }, + ], + projects: [{ name: "chromium-legacy-parity" }], +}); diff --git a/playwright.visual.config.ts b/playwright.visual.config.ts index f66f996..61b4e3c 100644 --- a/playwright.visual.config.ts +++ b/playwright.visual.config.ts @@ -2,6 +2,7 @@ import { defineConfig, devices } from "@playwright/test"; export default defineConfig({ testDir: "./tests/visual", + testIgnore: ["memento-legacy-parity.visual.spec.ts"], snapshotDir: "./tests/visual/__snapshots__", outputDir: "./artifacts/tests/visual/results", reporter: [ diff --git a/scripts/check-architecture.ts b/scripts/check-architecture.ts index ee4c14f..5fdd312 100644 --- a/scripts/check-architecture.ts +++ b/scripts/check-architecture.ts @@ -981,9 +981,16 @@ async function inspectTypeScriptOnlyPolicy(): Promise { /\.config\.(?:js|jsx|mjs|cjs)$/u.test(entry.name), ) .map((entry) => resolve(projectRoot, entry.name)); + const nonExecutableEvidenceRoots = [ + "tests/fixtures/memento-visual-baseline/legacy/", + ] as const; const candidates = [...files, ...rootConfigFiles] .filter((file) => forbiddenJavaScriptExtensionPattern.test(file)) .map((file) => reportPath(file, projectRoot, "")) + .filter( + (file) => + !nonExecutableEvidenceRoots.some((root) => file.startsWith(root)), + ) .sort(); const violations = candidates; return { diff --git a/scripts/check-design-system-fixtures.ts b/scripts/check-design-system-fixtures.ts new file mode 100644 index 0000000..d857cbe --- /dev/null +++ b/scripts/check-design-system-fixtures.ts @@ -0,0 +1,30 @@ +import { spawnSync } from "node:child_process"; + +const result = spawnSync( + process.execPath, + ["scripts/check-design-system.ts", "--fixture"], + { + cwd: process.cwd(), + encoding: "utf8", + }, +); + +const output = `${result.stdout ?? ""} +${result.stderr ?? ""}`; +if (result.status === 0) { + process.stderr.write( + "Design-system negative fixture unexpectedly passed; raw product palette regression is not protected.\n", + ); + process.exit(1); +} +if (!output.includes("raw product palette value in tests/fixtures/design-system/forbidden/memento-raw-product.css")) { + process.stderr.write( + "Design-system negative fixture failed, but not because the Memento raw palette was rejected.\n", + ); + process.stderr.write(output); + process.exit(1); +} + +process.stdout.write( + "Design-system fixtures: Memento raw product palette rejected PASS\n", +); diff --git a/scripts/check-design-system.ts b/scripts/check-design-system.ts index 22ce4a8..0201f24 100644 --- a/scripts/check-design-system.ts +++ b/scripts/check-design-system.ts @@ -13,6 +13,11 @@ const tokenFiles = { semantic: "src/presentation/design-system/tokens/semantic.css", component: "src/presentation/design-system/tokens/component.css", }; +const productDesignSources = [ + "src/presentation/design-system/memento/memento.css", +] as const; +const rawPalettePattern = /(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i; + const tokenLayers: Array = [ ["primitive", tokenFiles.primitive, REQUIRED_PRIMITIVE_TOKENS], ["semantic", tokenFiles.semantic, REQUIRED_SEMANTIC_TOKENS], @@ -29,9 +34,11 @@ for (const [layer, file, tokens] of tokenLayers) { } const cssSources = await Promise.all( - [...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map( - async (file) => ({ file, source: await readFile(file, "utf8") }), - ), + [ + ...Object.values(tokenFiles), + "src/presentation/styles/theme.css", + ...productDesignSources, + ].map(async (file) => ({ file, source: await readFile(file, "utf8") })), ); const definitions = new Set( cssSources.flatMap(({ source }) => @@ -109,7 +116,7 @@ for (const file of sources) { } if ( !file.includes("src/presentation/design-system/tokens/") && - /(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source) + rawPalettePattern.test(source) ) { failures.push(`raw palette value in ${file}`); } @@ -121,6 +128,16 @@ for (const file of sources) { } } +const productStyles = fixtureMode + ? ["tests/fixtures/design-system/forbidden/memento-raw-product.css"] + : [...productDesignSources]; +for (const file of productStyles) { + const source = await readFile(file, "utf8"); + if (rawPalettePattern.test(source)) { + failures.push(`raw product palette value in ${file}`); + } +} + const report = designSystemReportArtifactSchema.parse({ schemaVersion: 1, mode: fixtureMode ? "negative-fixture" : "source", diff --git a/scripts/check-memento-assurance.ts b/scripts/check-memento-assurance.ts new file mode 100644 index 0000000..ea7cb4e --- /dev/null +++ b/scripts/check-memento-assurance.ts @@ -0,0 +1,322 @@ +import { createHash } from "node:crypto"; +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; + +const root = process.cwd(); +const failures: string[] = []; + +async function text(relativePath: string): Promise { + return readFile(path.join(root, relativePath), "utf8"); +} + +async function exists(relativePath: string): Promise { + try { + await stat(path.join(root, relativePath)); + return true; + } catch { + return false; + } +} + +async function sha256(relativePath: string): Promise { + return createHash("sha256") + .update(await readFile(path.join(root, relativePath))) + .digest("hex"); +} + +async function walk(relativeDirectory: string): Promise { + const absolute = path.join(root, relativeDirectory); + const entries = await readdir(absolute, { withFileTypes: true }); + const files: string[] = []; + for (const entry of entries) { + const relative = path.join(relativeDirectory, entry.name); + if (entry.isDirectory()) { + files.push(...(await walk(relative))); + } else if (entry.isFile()) { + files.push(relative); + } + } + return files; +} + +function fail(message: string): void { + failures.push(message); +} + +const indexHtml = await text("index.html"); +for (const [id, pattern] of [ + ["STATIC_PAGE_MARKUP", /class=["'][^"']*\bpage\b/u], + ["STATIC_MODAL_MARKUP", /class=["'][^"']*\bmodal\b/u], + ["BETA_SCRIPT", /beta\.js/u], + ["BETA_STYLESHEET", /beta\.css/u], + ["STATIC_LOGIN", /login-v2\.html/u], + ["STATIC_REGISTER", /register-v2\.html/u], +] as const) { + if (pattern.test(indexHtml)) { + fail(`${id}: index.html contains product prototype markup/assets`); + } +} + +for (const obsolete of [ + "public/beta.js", + "public/beta.css", + "public/login-v2.html", + "public/register-v2.html", + "src/features/memento-web/presentation/memento-runtime-bridge.tsx", + "src/features/memento-web/presentation/memento-prototype-integration.ts", + "src/features/memento-web/adapters/http-memento-gateway.ts", + "src/features/memento-web/adapters/create-memento-gateway.ts", +] as const) { + if (await exists(obsolete)) { + fail(`OBSOLETE_ASSET: ${obsolete} must not return`); + } +} + +const presentationRoot = "src/features/memento-web/presentation"; +for (const relative of await walk(presentationRoot)) { + if (!/\.(?:ts|tsx)$/u.test(relative)) continue; + const source = await text(relative); + for (const [id, pattern] of [ + ["DOM_QUERY", /\b(?:document\.)?(?:querySelector|querySelectorAll|getElementById)\s*\(/u], + ["GLOBAL_CLICK_HANDLER", /\bdocument\.addEventListener\s*\(\s*["']click["']/u], + ["DIRECT_FETCH", /\b(?:globalThis\.)?fetch\s*\(/u], + ] as const) { + if (pattern.test(source)) { + fail(`${id}: ${relative}`); + } + } + + for (const match of source.matchAll(/from\s+["']([^"']*presentation\/design-system\/[^"']+)["']/gu)) { + const imported = match[1] ?? ""; + if (!imported.endsWith("/design-system/index.ts")) { + fail(`DESIGN_SYSTEM_DEEP_IMPORT: ${relative} -> ${imported}`); + } + } +} + +const featureRoot = "src/features/memento-web"; +for (const relative of await walk(featureRoot)) { + if (!/\.(?:ts|tsx)$/u.test(relative)) continue; + const source = await text(relative); + if (/\b(?:globalThis\.)?fetch\s*\(/u.test(source)) { + fail(`FEATURE_DIRECT_FETCH: ${relative}`); + } +} + +for (const relative of (await walk("public")).filter((file) => file.endsWith(".js"))) { + const source = await text(relative); + if ( + /\b(?:querySelector|querySelectorAll|getElementById|classList|onclick|addEventListener)\b/u.test( + source, + ) + ) { + fail(`PUBLIC_IMPERATIVE_UI_JS: ${relative}`); + } +} + +const serviceWorkerGenerator = await text("scripts/generate-service-worker-assets.ts"); +if (/beta\.(?:js|css)/u.test(serviceWorkerGenerator)) { + fail("SERVICE_WORKER_BETA_ASSET: beta asset remains in service-worker generator"); +} + +const contractSource = await text( + "src/features/memento-web/contracts/memento-feature-contract.ts", +); +const runtimeSource = await text( + "src/features/memento-web/presentation/memento-feature-runtime.tsx", +); +for (const routeId of [ + "APP_HOME", + "MEMENTO_LIBRARY", + "MEMENTO_MEMORIES", + "MEMENTO_MEMORY_DETAIL", + "MEMENTO_ALBUMS", + "MEMENTO_ALBUM_DETAIL", + "MEMENTO_SEARCH", + "MEMENTO_PEOPLE", + "MEMENTO_PERSON_DETAIL", + "MEMENTO_PLACES", + "MEMENTO_PLACE_DETAIL", + "MEMENTO_SETTINGS", + "MEMENTO_LOGIN", + "MEMENTO_REGISTER", +] as const) { + if (!contractSource.includes(`${routeId}: route({`)) { + fail(`ROUTE_CONTRACT_MISSING: ${routeId}`); + } + if (!runtimeSource.includes(`${routeId}: Object.freeze({`)) { + fail(`ROUTE_RUNTIME_MISSING: ${routeId}`); + } +} + + +const approvedLegacyFixture = Object.freeze({ + "tests/fixtures/memento-visual-baseline/legacy/index.html": + "d4ec52fcb9092468f18da4f13b462ac85bc60eef89fcfaabb31a5493387f9cde", + "tests/fixtures/memento-visual-baseline/legacy/beta.css": + "83476b0b188a8c89e64b693f33714f244e0ec30d107fc2485eb4e61ff40de420", + "tests/fixtures/memento-visual-baseline/legacy/beta.js": + "74790fa2dbb07de3c95eaeba709e2477d6710a2a8fbac4f07ca19b078b39a689", + "tests/fixtures/memento-visual-baseline/legacy/login-v2.html": + "891c3b05153a4a3c97f68c5cb19fc954884457a4b24b30e310ec61f073f8bf98", + "tests/fixtures/memento-visual-baseline/legacy/register-v2.html": + "53ce076096589408e9ccda0f856e96b974b82a0a0ab2d1fdde6bf3aea8e739c2", +} as const); + +for (const [fixture, expectedHash] of Object.entries(approvedLegacyFixture)) { + if (!(await exists(fixture))) { + fail(`LEGACY_VISUAL_FIXTURE_MISSING: ${fixture}`); + continue; + } + const actualHash = await sha256(fixture); + if (actualHash !== expectedHash) { + fail( + `LEGACY_VISUAL_FIXTURE_CHANGED: ${fixture} expected ${expectedHash} got ${actualHash}`, + ); + } +} + +for (const evidence of [ + "tests/fixtures/memento-visual-baseline/README.md", + "tests/visual/MEMENTO_VISUAL_BASELINE.md", + "tests/visual/memento-legacy-parity.visual.spec.ts", + "playwright.memento-legacy.config.ts", +] as const) { + if (!(await exists(evidence))) { + fail(`LEGACY_VISUAL_EVIDENCE_MISSING: ${evidence}`); + } +} + + +function splitSelectorList(prelude: string): string[] { + const selectors: string[] = []; + let buffer = ""; + let parentheses = 0; + let brackets = 0; + let quote: "'" | '"' | null = null; + for (let index = 0; index < prelude.length; index += 1) { + const character = prelude[index]!; + if (quote) { + buffer += character; + if (character === "\\") { + buffer += prelude[index + 1] ?? ""; + index += 1; + } else if (character === quote) { + quote = null; + } + continue; + } + if (character === "'" || character === '"') { + quote = character; + buffer += character; + continue; + } + if (character === "(") parentheses += 1; + else if (character === ")") parentheses -= 1; + else if (character === "[") brackets += 1; + else if (character === "]") brackets -= 1; + if (character === "," && parentheses === 0 && brackets === 0) { + selectors.push(buffer.trim()); + buffer = ""; + continue; + } + buffer += character; + } + if (buffer.trim()) selectors.push(buffer.trim()); + return selectors; +} + +function matchingCssBrace(source: string, openIndex: number): number { + let depth = 0; + let quote: "'" | '"' | null = null; + for (let index = openIndex; index < source.length; index += 1) { + const character = source[index]!; + if (quote) { + if (character === "\\") index += 1; + else if (character === quote) quote = null; + continue; + } + if (character === "'" || character === '"') { + quote = character; + continue; + } + if (source.startsWith("/*", index)) { + const end = source.indexOf("*/", index + 2); + if (end < 0) return source.length - 1; + index = end + 1; + continue; + } + if (character === "{") depth += 1; + else if (character === "}") { + depth -= 1; + if (depth === 0) return index; + } + } + throw new Error("Unbalanced Memento CSS"); +} + +function collectCssSelectors(source: string): string[] { + const selectors: string[] = []; + let index = 0; + while (index < source.length) { + while (index < source.length && /\s/u.test(source[index]!)) index += 1; + if (source.startsWith("/*", index)) { + const end = source.indexOf("*/", index + 2); + index = end < 0 ? source.length : end + 2; + continue; + } + const open = source.indexOf("{", index); + if (open < 0) break; + const prelude = source.slice(index, open).trim(); + const close = matchingCssBrace(source, open); + const body = source.slice(open + 1, close); + if (/^@(?:media|supports|layer|container)\b/u.test(prelude)) { + selectors.push(...collectCssSelectors(body)); + } else if (!prelude.startsWith("@")) { + selectors.push(...splitSelectorList(prelude)); + } + index = close + 1; + } + return selectors; +} + +const mementoStylesheet = await text( + "src/presentation/design-system/memento/memento.css", +); +for (const selector of collectCssSelectors(mementoStylesheet)) { + if ( + !selector.includes(".memento-app") && + !selector.includes(".memento-auth-") + ) { + fail(`MEMENTO_CSS_UNSCOPED: ${selector}`); + } +} + +const visualSpec = "tests/visual/memento-prototype.visual.spec.ts"; +if (!(await exists(visualSpec))) { + fail("VISUAL_SPEC_MISSING: Memento visual regression spec is required"); +} +const snapshotDirectory = + "tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots"; +if (!(await exists(snapshotDirectory))) { + fail("VISUAL_BASELINE_MISSING: Memento snapshot directory is required"); +} else { + const snapshots = (await readdir(path.join(root, snapshotDirectory))).filter( + (name) => name.endsWith(".png"), + ); + if (snapshots.length < 26) { + fail( + `VISUAL_BASELINE_INCOMPLETE: expected at least 26 snapshots, found ${snapshots.length}`, + ); + } +} + +if (failures.length > 0) { + console.error("Memento assurance gate: FAIL"); + for (const failure of failures) console.error(`- ${failure}`); + process.exitCode = 1; +} else { + console.log( + "Memento assurance gate: PASS (React ownership, route/runtime, HTTP boundary, prototype removal, visual baseline)", + ); +} diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index a2dc976..8a8b958 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -38,15 +38,13 @@ const EXCLUDED_FILES: ReadonlySet = new Set([ ]); /** - * Memento's visible Beta shell is intentionally copied byte-for-byte from the - * approved design prototype. These stable URLs are still safe to pre-cache: - * every row is digest-verified during install and lives in a release-specific - * cache. API responses and private originals are never added here. + * Memento's React shell keeps the approved prototype media assets on stable + * product URLs. Those URLs are still safe to pre-cache because every row is + * digest-verified during install and lives in a release-specific cache. API + * responses and private originals are never added here. */ const MEMENTO_SHELL_FILES: ReadonlySet = new Set([ "index.html", - "beta.css", - "beta.js", ...Array.from({ length: 11 }, (_, index) => `assets/photo-${index + 1}.jpg`), ]); diff --git a/scripts/serve-memento-legacy-visual.ts b/scripts/serve-memento-legacy-visual.ts new file mode 100644 index 0000000..1d91c0c --- /dev/null +++ b/scripts/serve-memento-legacy-visual.ts @@ -0,0 +1,49 @@ +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { createServer } from "node:http"; +import path from "node:path"; + +const port = Number(process.argv[2] ?? "4175"); +const root = path.resolve("tests/fixtures/memento-visual-baseline/legacy"); +const publicRoot = path.resolve("public"); + +const MIME = Object.freeze({ + ".css": "text/css; charset=utf-8", + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".jpg": "image/jpeg", + ".json": "application/json; charset=utf-8", + ".png": "image/png", + ".svg": "image/svg+xml", +}); + +function candidatePath(urlPath: string): string { + const clean = decodeURIComponent(urlPath.split("?")[0] ?? "/"); + const relative = clean === "/" ? "index.html" : clean.replace(/^\/+/, ""); + const base = relative.startsWith("assets/") ? publicRoot : root; + const resolved = path.resolve(base, relative); + if (!resolved.startsWith(base + path.sep) && resolved !== base) { + throw new Error("path traversal"); + } + return resolved; +} + +const server = createServer(async (request, response) => { + try { + const file = candidatePath(request.url ?? "/"); + const metadata = await stat(file); + if (!metadata.isFile()) throw new Error("not a file"); + const extension = path.extname(file) as keyof typeof MIME; + response.statusCode = 200; + response.setHeader("Content-Type", MIME[extension] ?? "application/octet-stream"); + response.setHeader("Cache-Control", "no-store"); + createReadStream(file).pipe(response); + } catch { + response.statusCode = 404; + response.end("Not found"); + } +}); + +server.listen(port, "127.0.0.1", () => { + process.stdout.write(`Memento legacy visual fixture: http://127.0.0.1:${port}\n`); +}); diff --git a/src/adapters/http/http-contract-bridge.ts b/src/adapters/http/http-contract-bridge.ts index 662143c..ce4b60e 100644 --- a/src/adapters/http/http-contract-bridge.ts +++ b/src/adapters/http/http-contract-bridge.ts @@ -111,6 +111,11 @@ const TRANSPORT_OWNED_HEADERS: ReadonlySet = new Set([ "idempotency-key", ]); +const DESCRIPTOR_OWNED_HEADERS: ReadonlySet = new Set([ + "if-match", +]); +const MAX_DESCRIPTOR_HEADER_VALUE_BYTES = 8_192; + const FORBIDDEN_REQUEST_HEADERS: ReadonlySet = new Set([ "host", "origin", @@ -137,6 +142,7 @@ export type RequestProjectionFailure = export type ProjectedRequest = Readonly<{ url: string; method: string; + headers: Readonly>; bodyBytes: Uint8Array | null; }>; @@ -237,11 +243,28 @@ function projectRequestChecked( return failure("REQUEST_BODY_UNEXPECTED"); } + const descriptorHeaders: Record = {}; + for (const entry of projection.headerEntries ?? []) { + const [rawName, rawValue] = entry; + const name = rawName.toLowerCase(); + if ( + !DESCRIPTOR_OWNED_HEADERS.has(name) || + Object.hasOwn(descriptorHeaders, name) || + rawValue.length === 0 || + /[\r\n]/.test(rawValue) || + encoder.encode(rawValue).byteLength > MAX_DESCRIPTOR_HEADER_VALUE_BYTES + ) { + return failure("PROJECTION_INVALID"); + } + descriptorHeaders[name] = rawValue; + } + return Object.freeze({ ok: true as const, request: Object.freeze({ url: url.href, method: contract.method, + headers: Object.freeze(descriptorHeaders), bodyBytes, }), }); @@ -255,7 +278,12 @@ function isValidProjection( if (!value || typeof value !== "object" || Array.isArray(value)) return false; const candidate = value as Record; const keys = Object.keys(candidate).sort(); - if (keys.join("|") !== "body|pathValues|queryEntries") return false; + if ( + keys.join("|") !== "body|pathValues|queryEntries" && + keys.join("|") !== "body|headerEntries|pathValues|queryEntries" + ) { + return false; + } const pathValues = candidate.pathValues; if (!pathValues || typeof pathValues !== "object" || Array.isArray(pathValues)) { @@ -276,6 +304,21 @@ function isValidProjection( } } + const headerEntries = candidate.headerEntries; + if (headerEntries !== undefined) { + if (!Array.isArray(headerEntries) || headerEntries.length > 16) return false; + for (const entry of headerEntries) { + if ( + !Array.isArray(entry) || + entry.length !== 2 || + typeof entry[0] !== "string" || + typeof entry[1] !== "string" + ) { + return false; + } + } + } + const queryEntries = candidate.queryEntries; if (!Array.isArray(queryEntries) || queryEntries.length > 256) return false; for (const entry of queryEntries) { @@ -357,6 +400,7 @@ export function checkFinalInvariants( const lower = name.toLowerCase(); if (FORBIDDEN_REQUEST_HEADERS.has(lower)) return "FORBIDDEN_HEADER"; if (TRANSPORT_OWNED_HEADERS.has(lower)) continue; + if (DESCRIPTOR_OWNED_HEADERS.has(lower)) continue; if (!ALLOWED_CREDENTIAL_HEADERS.has(lower)) return "HEADER_NOT_ALLOWED"; if ( !input.authProfile.allowedCredentialHeaders.includes( diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 74d6d3e..4791428 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -679,6 +679,7 @@ export function createContractHttpExecutor( // Transport-owned headers are written last so no credential entry can // shadow Accept or Content-Type through key ordering. const headers: Record = { + ...projected.request.headers, ...admission.headers, Accept: "application/json", }; diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts index 626f326..ed1b9aa 100644 --- a/src/adapters/http/index.ts +++ b/src/adapters/http/index.ts @@ -53,3 +53,10 @@ export { } from "./client.ts"; /** V2 `HttpClient.execute`의 첫 인자 타입. */ export type { OperationRequestInput } from "./request-builder.ts"; + +export { + createOffsetUploadExecutor, + type OffsetUploadExecutionInput, + type OffsetUploadExecutor, + type OffsetUploadExecutorDependencies, +} from "./offset-upload.ts"; diff --git a/src/adapters/http/offset-upload.ts b/src/adapters/http/offset-upload.ts new file mode 100644 index 0000000..1711948 --- /dev/null +++ b/src/adapters/http/offset-upload.ts @@ -0,0 +1,172 @@ +import { + createFailure, + kindForStatus, + type AppFailure, +} from "../../contracts/errors.ts"; +import type { Result } from "../../contracts/result.ts"; + +export type OffsetUploadExecutionInput = Readonly<{ + path: string; + offset: number; + chunk: Blob; + signal?: AbortSignal; +}>; + +export type OffsetUploadExecutor = Readonly<{ + append( + input: OffsetUploadExecutionInput, + ): Promise>; +}>; + +export type OffsetUploadExecutorDependencies = Readonly<{ + baseUrl: string; + timeoutMs: number; + fetcher?: typeof fetch; + credentialHeaders(): Readonly> | null; +}>; + +const OPERATION_ID = "OFFSET_UPLOAD_APPEND"; + +export function createOffsetUploadExecutor( + dependencies: OffsetUploadExecutorDependencies, +): OffsetUploadExecutor { + const fetcher = dependencies.fetcher ?? fetch; + const baseUrl = new URL(ensureTrailingSlash(dependencies.baseUrl)); + + return Object.freeze({ + async append( + input: OffsetUploadExecutionInput, + ): Promise> { + if ( + typeof input.path !== "string" || + input.path.length === 0 || + !Number.isSafeInteger(input.offset) || + input.offset < 0 || + typeof input.chunk.size !== "number" || + !Number.isSafeInteger(input.chunk.size) || + input.chunk.size < 0 + ) { + return failure( + "VALIDATION_REJECTED", + "OFFSET_UPLOAD_INPUT_INVALID", + "NOT_STARTED", + ); + } + + let url: URL; + try { + url = new URL(input.path, baseUrl); + } catch { + return failure( + "VALIDATION_REJECTED", + "OFFSET_UPLOAD_PATH_INVALID", + "NOT_STARTED", + ); + } + if (url.origin !== baseUrl.origin) { + return failure( + "VALIDATION_REJECTED", + "OFFSET_UPLOAD_ORIGIN_MISMATCH", + "NOT_STARTED", + ); + } + + const credentialHeaders = dependencies.credentialHeaders(); + if (credentialHeaders === null) { + return failure( + "AUTH_INTEGRATION_FAILURE", + "OFFSET_UPLOAD_CREDENTIALS_UNAVAILABLE", + "NOT_STARTED", + ); + } + + const controller = new AbortController(); + let timedOut = false; + let dispatched = false; + const timeout = globalThis.setTimeout(() => { + timedOut = true; + controller.abort(); + }, dependencies.timeoutMs); + const externalAbort = () => controller.abort(); + input.signal?.addEventListener("abort", externalAbort, { once: true }); + if (input.signal?.aborted) externalAbort(); + + try { + dispatched = true; + const response = await fetcher(url, { + method: "PATCH", + body: input.chunk, + headers: { + ...credentialHeaders, + "Content-Type": "application/offset+octet-stream", + "Upload-Offset": String(input.offset), + }, + credentials: "include", + redirect: "error", + referrerPolicy: "no-referrer", + cache: "no-store", + signal: controller.signal, + }); + + if (!response.ok) { + return failure( + kindForStatus(response.status), + "OFFSET_UPLOAD_HTTP_FAILURE", + response.status >= 500 ? "MAYBE_APPLIED" : "NOT_APPLIED", + response.status, + ); + } + + const nextOffset = Number(response.headers.get("Upload-Offset")); + if (!Number.isSafeInteger(nextOffset) || nextOffset < input.offset) { + return failure( + "SCHEMA_MISMATCH", + "UPLOAD_OFFSET_INVALID", + "MAYBE_APPLIED", + response.status, + ); + } + + return Object.freeze({ ok: true as const, value: nextOffset }); + } catch { + if (input.signal?.aborted && !timedOut) { + return failure( + "REQUEST_ABORTED", + "OFFSET_UPLOAD_ABORTED", + dispatched ? "MAYBE_APPLIED" : "NOT_STARTED", + ); + } + return failure( + timedOut ? "REQUEST_TIMEOUT" : "NETWORK_UNREACHABLE", + timedOut + ? "OFFSET_UPLOAD_TIMEOUT" + : "OFFSET_UPLOAD_NETWORK_FAILURE", + dispatched ? "MAYBE_APPLIED" : "NOT_STARTED", + ); + } finally { + globalThis.clearTimeout(timeout); + input.signal?.removeEventListener("abort", externalAbort); + } + }, + }); +} + +function failure( + kind: Parameters[0], + code: string, + effect: NonNullable, + httpStatus?: number, +): Result { + return Object.freeze({ + ok: false as const, + error: createFailure(kind, OPERATION_ID, 0, { + code, + effect, + ...(httpStatus === undefined ? {} : { httpStatus }), + }), + }); +} + +function ensureTrailingSlash(value: string): string { + return value.endsWith("/") ? value : `${value}/`; +} diff --git a/src/bootstrap/create-runtime-composition.ts b/src/bootstrap/create-runtime-composition.ts index d3c3375..8d1b712 100644 --- a/src/bootstrap/create-runtime-composition.ts +++ b/src/bootstrap/create-runtime-composition.ts @@ -1,6 +1,5 @@ import { resolveRuntimeCapabilities } from "../contracts/runtime-capabilities.ts"; import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts"; -import { createMementoGateway } from "../features/memento-web/adapters/create-memento-gateway.ts"; import { createCompositionRoot } from "./composition-root.ts"; import { loadReleaseManifest } from "./load-release-manifest.ts"; import { loadRuntimeConfig } from "./load-runtime-config.ts"; @@ -54,13 +53,10 @@ export async function createRuntimeComposition( : {}), }); - const mementoGateway = createMementoGateway(root.config.config); - return Object.freeze({ ...root, capabilities, optional, - mementoGateway, async dispose(): Promise { // §20.3. Optional runtime first, then the base infrastructure: the query // cache is cleared only after realtime and worker admission has closed, diff --git a/src/bootstrap/main.tsx b/src/bootstrap/main.tsx index f24c2eb..d741772 100644 --- a/src/bootstrap/main.tsx +++ b/src/bootstrap/main.tsx @@ -1,8 +1,8 @@ import { createRoot } from "react-dom/client"; import { recordBootFailure } from "../adapters/diagnostics/index.ts"; -import { ROUTE_RUNTIME } from "../features/installed-feature-runtimes.tsx"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; +import "../presentation/styles/theme.css"; import { createRuntimeComposition } from "./create-runtime-composition.ts"; import { initializeColorScheme } from "./initialize-color-scheme.ts"; import { ReleaseManifestError } from "./load-release-manifest.ts"; @@ -15,14 +15,6 @@ if (!rootElement) { throw new Error("Missing #root mount element"); } -// Memento owns the visible static Beta shell, but the inherited frontend -// foundation still publishes route chunks in its release manifest. Touching the -// runtime catalog here keeps those lazy chunks in the build without mounting or -// executing the platform router. -document.documentElement.dataset.registeredRouteRuntimeCount = String( - Object.keys(ROUTE_RUNTIME).length, -); - const root = createRoot(rootElement); async function boot(): Promise { diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 06e1672..de05bff 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -8,6 +8,7 @@ import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts"; import { createContractHttpExecutor, createHttpClient, + createOffsetUploadExecutor, type HttpExecutionObservation, type InstalledHttpOperationExecutor, } from "../adapters/http/index.ts"; @@ -158,6 +159,29 @@ function hostValue( } } +function cookieValueFromHost( + host: Record, + name: string, +): string | undefined { + const documentValue = hostValue(host, "document"); + if (!documentValue || typeof documentValue !== "object") return undefined; + let cookie: unknown; + try { + cookie = Reflect.get(documentValue, "cookie"); + } catch { + return undefined; + } + if (typeof cookie !== "string") return undefined; + const encoded = encodeURIComponent(name); + const match = cookie + .split(";") + .map((part) => part.trim()) + .find((part) => part.startsWith(`${encoded}=`)); + return match + ? decodeURIComponent(match.slice(encoded.length + 1)) + : undefined; +} + function storageOrUndefined(value: unknown): Storage | undefined { if (!value || typeof value !== "object") return undefined; const candidate = value as Record; @@ -452,6 +476,24 @@ export async function createRuntimeAdapters( if (serverStateScope.getPhase() !== "READY") { return Object.freeze({ kind: "SCOPE_FENCED" as const }); } + + if (operation.authProfileId === "MEMENTO_BFF_READ") { + return Object.freeze({ + kind: "READY" as const, + headers: Object.freeze({}), + }); + } + + if (operation.authProfileId === "MEMENTO_BFF_WRITE") { + const token = cookieValueFromHost(host, "XSRF-TOKEN"); + return token + ? Object.freeze({ + kind: "READY" as const, + headers: Object.freeze({ "x-xsrf-token": token }), + }) + : Object.freeze({ kind: "UNAVAILABLE" as const }); + } + const state = authSession.getState(); if (state === "integration-failed") { return Object.freeze({ kind: "UNAVAILABLE" as const }); @@ -517,8 +559,27 @@ export async function createRuntimeAdapters( return outcome; }, }); + const offsetUpload = createOffsetUploadExecutor({ + baseUrl: config.API_BASE_URL, + timeoutMs: config.REQUEST_TIMEOUT_MS, + fetcher: context.fetcher, + credentialHeaders() { + if (serverStateScope.getPhase() !== "READY") return null; + const token = cookieValueFromHost(host, "XSRF-TOKEN"); + return token + ? Object.freeze({ "X-XSRF-TOKEN": token }) + : null; + }, + }); + const featureInputs = createInstalledFeatureInputs({ http: contractOperations, + offsetUpload, + runtime: Object.freeze({ + appEnvironment: config.APP_ENV, + apiBaseUrl: config.API_BASE_URL, + requestTimeoutMs: config.REQUEST_TIMEOUT_MS, + }), }); return Object.freeze({ diff --git a/src/bootstrap/runtime-application.tsx b/src/bootstrap/runtime-application.tsx index 5eb1d9c..475eeed 100644 --- a/src/bootstrap/runtime-application.tsx +++ b/src/bootstrap/runtime-application.tsx @@ -2,7 +2,7 @@ import { StrictMode, useEffect } from "react"; import { ApplicationProvider } from "../presentation/providers/application-provider.tsx"; import { ServerStateGenerationProvider } from "../presentation/adapters/query/server-state-generation-provider.tsx"; -import { MementoRuntimeBridge } from "../features/memento-web/presentation/memento-runtime-bridge.tsx"; +import { AppRouter } from "../presentation/routes/app-router.tsx"; import type { RuntimeComposition } from "./create-runtime-composition.ts"; /** @@ -44,7 +44,10 @@ export function RuntimeApplication({ > - + diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 7ed430c..e839650 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -160,6 +160,11 @@ export type HttpRequestProjection = Readonly<{ pathValues: Readonly>; /** Descriptor-generated query entry order; array encoding is descriptor-owned. */ queryEntries: readonly (readonly [string, string])[]; + /** + * Narrow descriptor-owned conditional headers. Transport and credential + * headers remain outside this projection and cannot be overridden here. + */ + headerEntries?: readonly (readonly [string, string])[]; /** Canonical JSON body value, or `null` when `requestBody` is `NONE`. */ body: unknown; }>; @@ -183,6 +188,11 @@ export type ContractContributionSource = kind: "EXTERNAL_PACKAGE"; package: InstalledContractPackageIdentity; }> + | Readonly<{ + kind: "PRODUCT_LOCAL_CONTRACT"; + contractId: string; + revision: number; + }> | Readonly<{ kind: "TEMPLATE_FIXTURE"; fixtureId: "REFERENCE_FEATURE_V1"; @@ -691,6 +701,27 @@ export function composeContractContributions( ); } packagesById.set(identity.packageId, identity); + } else if (rawSource.kind === "PRODUCT_LOCAL_CONTRACT") { + const local = exactOwnDataSnapshot< + Readonly<{ + kind: "PRODUCT_LOCAL_CONTRACT"; + contractId: string; + revision: number; + }> + >( + rawSource, + ["kind", "contractId", "revision"], + ["kind", "contractId", "revision"], + rejectSource, + ); + if ( + !CONTRIBUTION_ID.test(local.contractId) || + !Number.isSafeInteger(local.revision) || + local.revision < 1 + ) { + fail(`${featureId}: local product contract identity`); + } + source = Object.freeze({ ...local }); } else if (rawSource.kind === "TEMPLATE_FIXTURE") { const fixture = exactOwnDataSnapshot< Readonly<{ diff --git a/src/contracts/rest-profiles.ts b/src/contracts/rest-profiles.ts index 317f3b0..3f1879a 100644 --- a/src/contracts/rest-profiles.ts +++ b/src/contracts/rest-profiles.ts @@ -21,6 +21,7 @@ export type RestProviderProfile = Readonly<{ export const CREDENTIAL_HEADER_NAMES = Object.freeze([ "authorization", "x-csrf-token", + "x-xsrf-token", "x-tenant-context", ] as const); @@ -70,6 +71,20 @@ export const REST_AUTH_PROFILES = Object.freeze({ allowedCredentialHeaders: Object.freeze([]), requiredCredentialHeaders: Object.freeze([]), }), + MEMENTO_BFF_READ: Object.freeze({ + authProfileId: "MEMENTO_BFF_READ", + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + allowedCredentialHeaders: Object.freeze([]), + requiredCredentialHeaders: Object.freeze([]), + }), + MEMENTO_BFF_WRITE: Object.freeze({ + authProfileId: "MEMENTO_BFF_WRITE", + transport: "SAME_ORIGIN_COOKIE", + credentials: "include", + allowedCredentialHeaders: Object.freeze(["x-xsrf-token"] as const), + requiredCredentialHeaders: Object.freeze(["x-xsrf-token"] as const), + }), } satisfies Readonly>); function isCredentialHeaderName(value: unknown): value is CredentialHeaderName { diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts index 46cdafc..8b2793d 100644 --- a/src/features/feature-adapter-contribution.ts +++ b/src/features/feature-adapter-contribution.ts @@ -4,6 +4,7 @@ import type { } from "../application/ports/in/application-api.ts"; import type { InstalledHttpOperationExecutor, + OffsetUploadExecutor, } from "../adapters/http/index.ts"; /** @@ -44,7 +45,13 @@ export function createIndexedDbRepositoryProvider( export type FeaturePlatformCapabilities = Readonly<{ http: InstalledHttpOperationExecutor; + offsetUpload: OffsetUploadExecutor; indexedDb: IndexedDbRepositoryProvider; + runtime: Readonly<{ + appEnvironment: "local" | "development" | "staging" | "production"; + apiBaseUrl: string; + requestTimeoutMs: number; + }>; }>; export type FeaturePlatformCapabilityId = diff --git a/src/features/installed-contract-contributions.ts b/src/features/installed-contract-contributions.ts index 5c3d44c..c061acf 100644 --- a/src/features/installed-contract-contributions.ts +++ b/src/features/installed-contract-contributions.ts @@ -4,9 +4,11 @@ import { type InstalledContractPackageIdentity, } from "../contracts/external-contract-runtime.ts"; import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; +import { MEMENTO_CONTRACT_CONTRIBUTION } from "./memento-web/contracts/memento-http-contract-contribution.ts"; import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./reference-feature/contracts/reference-feature-contract-contribution.ts"; const COMPILED_CONTRACT_CONTRIBUTIONS = Object.freeze([ + MEMENTO_CONTRACT_CONTRIBUTION, REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, ] as const); diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts index 303941e..e7eeee3 100644 --- a/src/features/installed-feature-adapters.ts +++ b/src/features/installed-feature-adapters.ts @@ -3,10 +3,12 @@ import { type ContributionsCapabilityContext, type InstalledFeatureInputs, } from "./feature-adapter-contribution.ts"; +import { MEMENTO_FEATURE_ADAPTER_CONTRIBUTION } from "./memento-web/adapters/create-memento-feature-input.ts"; import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./reference-feature/adapters/create-reference-feature-input.ts"; import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([ + MEMENTO_FEATURE_ADAPTER_CONTRIBUTION, REFERENCE_FEATURE_ADAPTER_CONTRIBUTION, ] as const); diff --git a/src/features/installed-feature-contracts.ts b/src/features/installed-feature-contracts.ts index 767a270..e066c5e 100644 --- a/src/features/installed-feature-contracts.ts +++ b/src/features/installed-feature-contracts.ts @@ -22,20 +22,33 @@ import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts"; */ export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES; +type UnionToIntersection = + (Union extends unknown ? (value: Union) => void : never) extends + (value: infer Intersection) => void + ? Intersection + : never; + +type InstalledFeatureRoutes = UnionToIntersection< + (typeof INSTALLED_PRODUCT_FEATURES)[number]["routes"] +>; + +type InstalledFeatureRouteRuntimeContracts = UnionToIntersection< + (typeof INSTALLED_PRODUCT_FEATURES)[number]["routeRuntimeContracts"] +>; + export const ROUTE_REGISTRY = Object.freeze( INSTALLED_FEATURE_CONTRACTS.reduce( (registry, contract) => ({ ...registry, ...contract.routes }), { ...PLATFORM_ROUTE_REGISTRY }, ), -) as typeof PLATFORM_ROUTE_REGISTRY & - (typeof INSTALLED_PRODUCT_FEATURES)[number]["routes"]; +) as typeof PLATFORM_ROUTE_REGISTRY & InstalledFeatureRoutes; export const ROUTE_RUNTIME_CONTRACT = Object.freeze( INSTALLED_FEATURE_CONTRACTS.reduce( (registry, contract) => ({ ...registry, ...contract.routeRuntimeContracts }), { ...PLATFORM_ROUTE_RUNTIME_CONTRACT }, ), ) as typeof PLATFORM_ROUTE_RUNTIME_CONTRACT & - (typeof INSTALLED_PRODUCT_FEATURES)[number]["routeRuntimeContracts"]; + InstalledFeatureRouteRuntimeContracts; export const API_OPERATIONS = composeApiOperations( INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.apiOperations), ); @@ -46,22 +59,22 @@ export const REST_PROFILE_BINDINGS_VALID = validateRestProfileBindings( export const INVALIDATION_REGISTRY = Object.freeze({ topics: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.topics, + (contract) => [...contract.invalidation.topics], ), ), namespaces: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.namespaces, + (contract) => [...contract.invalidation.namespaces], ), ), edges: Object.freeze( INSTALLED_FEATURE_CONTRACTS.flatMap( - (contract) => contract.invalidation.edges, + (contract) => [...contract.invalidation.edges], ), ), }); export const INVALIDATION_TOPIC_VERSIONS = Object.freeze( - INSTALLED_FEATURE_CONTRACTS.flatMap((contract) => contract.topicVersions), + INSTALLED_FEATURE_CONTRACTS.flatMap((contract) => [...contract.topicVersions]), ); export const SCHEMA_REGISTRY = composeSchemaRegistry([ PLATFORM_SCHEMA_REGISTRY, diff --git a/src/features/installed-feature-runtimes.tsx b/src/features/installed-feature-runtimes.tsx index dc53a8c..29167d2 100644 --- a/src/features/installed-feature-runtimes.tsx +++ b/src/features/installed-feature-runtimes.tsx @@ -1,9 +1,13 @@ +import type { ComponentType } from "react"; + import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.ts"; import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx"; +import { MEMENTO_FEATURE_RUNTIME_CONTRIBUTION } from "./memento-web/presentation/memento-feature-runtime.tsx"; import { REFERENCE_FEATURE_RUNTIME_CONTRIBUTION } from "./reference-feature/presentation/reference-feature-runtime.tsx"; import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; const COMPILED_FEATURE_RUNTIME_CONTRIBUTIONS = Object.freeze([ + MEMENTO_FEATURE_RUNTIME_CONTRIBUTION, REFERENCE_FEATURE_RUNTIME_CONTRIBUTION, ] as const); @@ -36,3 +40,14 @@ export const ROUTE_RUNTIME = Object.freeze( ), ), ); + +export const FEATURE_SHELL_RUNTIME: Readonly> = + Object.freeze( + Object.fromEntries( + INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS.flatMap((contribution) => + "Shell" in contribution + ? [[contribution.featureId, contribution.Shell] as const] + : [], + ), + ), + ); diff --git a/src/features/installed-product-manifest.ts b/src/features/installed-product-manifest.ts index 842f4c0..2d452d8 100644 --- a/src/features/installed-product-manifest.ts +++ b/src/features/installed-product-manifest.ts @@ -2,6 +2,7 @@ import { selectCompiledProductFeatures, type SelectableProductFeature, } from "../contracts/product-features.ts"; +import { MEMENTO_FEATURE_CONTRACT } from "./memento-web/contracts/memento-feature-contract.ts"; import { REFERENCE_FEATURE_CONTRACT } from "./reference-feature/contracts/reference-feature-contract.ts"; /** @@ -26,6 +27,7 @@ import { REFERENCE_FEATURE_CONTRACT } from "./reference-feature/contracts/refere */ const COMPILED_PRODUCT_FEATURES = Object.freeze([ + MEMENTO_FEATURE_CONTRACT, REFERENCE_FEATURE_CONTRACT, ] as const); diff --git a/src/features/memento-web/adapters/create-memento-feature-input.ts b/src/features/memento-web/adapters/create-memento-feature-input.ts new file mode 100644 index 0000000..06ed6e1 --- /dev/null +++ b/src/features/memento-web/adapters/create-memento-feature-input.ts @@ -0,0 +1,54 @@ +import { + createFeatureHttpBinding, + type InstalledHttpOperationExecutor, +} from "../../../adapters/http/index.ts"; +import { + defineFeatureAdapterContribution, +} from "../../feature-adapter-contribution.ts"; +import { createMementoFeatureInput } from "../application/memento-application.ts"; +import { MEMENTO_FEATURE_ID } from "../contracts/memento-feature-contract.ts"; +import { MEMENTO_HTTP_OPERATIONS } from "./memento-http-binding.ts"; +import { createMementoHttpFeatureInput } from "./memento-http-feature-input.ts"; +import { createMockMementoGateway } from "./mock-memento-gateway.ts"; +import { createMementoOffsetUpload } from "./memento-offset-upload.ts"; + +export type MementoRuntimeCapability = Readonly<{ + appEnvironment: "local" | "development" | "staging" | "production"; + apiBaseUrl: string; + requestTimeoutMs: number; +}>; + +export function resolveMementoDataMode( + runtime: MementoRuntimeCapability, +): "mock" | "api" { + return runtime.appEnvironment === "local" ? "mock" : "api"; +} + +export function createMementoFeatureInstalledInput(context: Readonly<{ + http: InstalledHttpOperationExecutor; + offsetUpload: import("../../../adapters/http/index.ts").OffsetUploadExecutor; + runtime: MementoRuntimeCapability; +}>) { + const input = + resolveMementoDataMode(context.runtime) === "mock" + ? createMementoFeatureInput(createMockMementoGateway()) + : createMementoHttpFeatureInput( + createFeatureHttpBinding( + context.http, + MEMENTO_HTTP_OPERATIONS, + ), + createMementoOffsetUpload(context.offsetUpload), + ); + + return Object.freeze({ + featureId: MEMENTO_FEATURE_ID, + input, + }); +} + +export const MEMENTO_FEATURE_ADAPTER_CONTRIBUTION = + defineFeatureAdapterContribution({ + featureId: MEMENTO_FEATURE_ID, + needs: ["http", "offsetUpload", "runtime"] as const, + createInput: createMementoFeatureInstalledInput, + }); diff --git a/src/features/memento-web/adapters/create-memento-gateway.ts b/src/features/memento-web/adapters/create-memento-gateway.ts deleted file mode 100644 index ea7c74f..0000000 --- a/src/features/memento-web/adapters/create-memento-gateway.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { MementoGateway } from "../application/memento-gateway.ts"; -import type { MementoRuntimeConfig } from "../contracts/memento-api.ts"; -import { createHttpMementoGateway } from "./http-memento-gateway.ts"; -import { createMockMementoGateway } from "./mock-memento-gateway.ts"; - -/** - * Memento product environment boundary. - * - * local -> deterministic mock gateway - * development -> real BFF/API gateway - * staging -> real BFF/API gateway - * production -> real BFF/API gateway - * - * Presentation code never branches on the environment. - */ -export function createMementoGateway( - config: MementoRuntimeConfig, -): MementoGateway { - if (config.APP_ENV === "local") { - return createMockMementoGateway(); - } - - return createHttpMementoGateway({ - apiBaseUrl: config.API_BASE_URL, - timeoutMs: config.REQUEST_TIMEOUT_MS, - }); -} diff --git a/src/features/memento-web/adapters/http-memento-gateway.ts b/src/features/memento-web/adapters/http-memento-gateway.ts deleted file mode 100644 index c69ecdf..0000000 --- a/src/features/memento-web/adapters/http-memento-gateway.ts +++ /dev/null @@ -1,469 +0,0 @@ -import type { - AlbumQuery, - CreateAlbumInput, - CreateShareInput, - LibraryQuery, - MementoGateway, - MemoryQuery, - ShareTarget, - UpdateAlbumInput, - UpdateMediaMetadataInput, - UpdateMemoryInput, -} from "../application/memento-gateway.ts"; -import type { - AccountSettings, - AlbumDetail, - AlbumSummary, - ApiErrorPayload, - BackupSummary, - CursorPage, - DeviceBackupPolicy, - DeviceSummary, - DuplicateGroup, - DuplicateResolutionInput, - HomeResponse, - LibraryItem, - MediaDetail, - MemoryCandidate, - MemoryDetail, - MemorySummary, - MementoCapabilities, - PersonSummary, - PlaceSummary, - PublicShare, - SearchResponse, - ShareCreateResult, - StorageSettings, - UploadCommitResult, - UploadPreflightInput, - UploadPreflightResponse, - UploadSession, -} from "../contracts/memento-api.ts"; - -export class MementoApiError extends Error { - readonly status: number; - readonly code?: string; - readonly traceId?: string; - - constructor( - message: string, - input: Readonly<{ status: number; code?: string; traceId?: string }>, - ) { - super(message); - this.name = "MementoApiError"; - this.status = input.status; - this.code = input.code; - this.traceId = input.traceId; - } -} - -type HttpGatewayOptions = Readonly<{ - apiBaseUrl: string; - timeoutMs: number; - fetcher?: typeof fetch; -}>; - -type RequestOptions = Readonly<{ - idempotentCommand?: boolean; - expectJson?: boolean; - root?: URL; -}>; - -const APP_API_PREFIX = "app-api/v1/"; -const SHARE_API_PREFIX = "share-api/v1/"; - -function readCookie(name: string): string | undefined { - if (typeof document === "undefined") return undefined; - const encoded = encodeURIComponent(name); - const match = document.cookie - .split(";") - .map((part) => part.trim()) - .find((part) => part.startsWith(`${encoded}=`)); - return match - ? decodeURIComponent(match.slice(encoded.length + 1)) - : undefined; -} - -function idempotencyKey(): string { - if (typeof crypto !== "undefined" && "randomUUID" in crypto) { - return crypto.randomUUID(); - } - return `web-${Date.now()}-${Math.random().toString(16).slice(2)}`; -} - -function queryString(input: object): string { - const search = new URLSearchParams(); - for (const [key, value] of Object.entries(input)) { - if (value === undefined || value === null || value === "") continue; - search.set(key, String(value)); - } - const encoded = search.toString(); - return encoded ? `?${encoded}` : ""; -} - -function versionHeaders(expectedVersion?: number): HeadersInit | undefined { - return Number.isSafeInteger(expectedVersion) - ? { "If-Match": String(expectedVersion) } - : undefined; -} - -function withoutVersion>( - input: T, -): Omit { - const { expectedVersion: _expectedVersion, ...body } = input; - return body; -} - -export function createHttpMementoGateway( - options: HttpGatewayOptions, -): MementoGateway { - const fetcher = options.fetcher ?? fetch; - const base = ensureTrailingSlash(options.apiBaseUrl); - const apiRoot = new URL(APP_API_PREFIX, base); - const shareRoot = new URL(SHARE_API_PREFIX, base); - - async function request( - path: string, - init: RequestInit = {}, - requestOptions: RequestOptions = {}, - ): Promise { - const controller = new AbortController(); - const timeout = globalThis.setTimeout( - () => controller.abort(), - options.timeoutMs, - ); - const method = (init.method ?? "GET").toUpperCase(); - const headers = new Headers(init.headers); - const isUnsafe = !["GET", "HEAD", "OPTIONS"].includes(method); - - if (isUnsafe) { - const csrf = readCookie("XSRF-TOKEN"); - if (csrf) headers.set("X-XSRF-TOKEN", csrf); - } - if (requestOptions.idempotentCommand) { - headers.set("Idempotency-Key", idempotencyKey()); - } - if (init.body !== undefined && !headers.has("Content-Type")) { - headers.set("Content-Type", "application/json"); - } - - try { - const response = await fetcher( - new URL(path.replace(/^\//, ""), requestOptions.root ?? apiRoot), - { - ...init, - headers, - credentials: "include", - signal: controller.signal, - }, - ); - - if (!response.ok) { - let payload: ApiErrorPayload = {}; - const contentType = response.headers.get("content-type") ?? ""; - if (contentType.includes("application/json")) { - try { - payload = (await response.json()) as ApiErrorPayload; - } catch { - payload = {}; - } - } - throw new MementoApiError( - payload.message ?? `Memento API request failed (${response.status})`, - { - status: response.status, - ...(payload.code ? { code: payload.code } : {}), - ...(payload.traceId ? { traceId: payload.traceId } : {}), - }, - ); - } - - if (response.status === 204 || requestOptions.expectJson === false) { - return undefined as T; - } - return (await response.json()) as T; - } finally { - globalThis.clearTimeout(timeout); - } - } - - async function appendUploadChunk( - uploadSessionId: string, - offset: number, - chunk: Blob, - ): Promise { - const controller = new AbortController(); - const timeout = globalThis.setTimeout( - () => controller.abort(), - options.timeoutMs, - ); - const headers = new Headers({ - "Content-Type": "application/offset+octet-stream", - "Upload-Offset": String(offset), - }); - const csrf = readCookie("XSRF-TOKEN"); - if (csrf) headers.set("X-XSRF-TOKEN", csrf); - - try { - const response = await fetcher( - new URL(`uploads/${encodeURIComponent(uploadSessionId)}`, apiRoot), - { - method: "PATCH", - body: chunk, - headers, - credentials: "include", - signal: controller.signal, - }, - ); - - if (!response.ok) { - let payload: ApiErrorPayload = {}; - try { - payload = (await response.json()) as ApiErrorPayload; - } catch { - payload = {}; - } - throw new MementoApiError( - payload.message ?? `Upload chunk failed (${response.status})`, - { - status: response.status, - ...(payload.code ? { code: payload.code } : {}), - ...(payload.traceId ? { traceId: payload.traceId } : {}), - }, - ); - } - - const nextOffset = Number(response.headers.get("Upload-Offset")); - if (!Number.isFinite(nextOffset)) { - throw new Error("Upload response did not include a valid Upload-Offset"); - } - return nextOffset; - } finally { - globalThis.clearTimeout(timeout); - } - } - - const gateway: MementoGateway = { - mode: "api", - - getCapabilities: () => request("capabilities"), - getHome: () => request("home"), - - getLibrary: (query: LibraryQuery = {}) => - request>(`library${queryString(query)}`), - getMedia: (mediaId) => - request(`media/${encodeURIComponent(mediaId)}`), - setMediaFavorite: (mediaId, favorite) => - request( - `media/${encodeURIComponent(mediaId)}/favorite`, - { method: "PUT", body: JSON.stringify({ favorite }) }, - { idempotentCommand: true }, - ), - trashMedia: (mediaId) => - request( - `media/${encodeURIComponent(mediaId)}/trash`, - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - restoreMedia: (mediaId) => - request( - `media/${encodeURIComponent(mediaId)}/restore`, - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - updateMediaMetadata: (mediaId, input: UpdateMediaMetadataInput) => - request( - `media/${encodeURIComponent(mediaId)}/metadata`, - { - method: "PATCH", - headers: versionHeaders(input.expectedVersion), - body: JSON.stringify(withoutVersion(input)), - }, - ), - - getAlbums: (query: AlbumQuery = {}) => - request>(`albums${queryString(query)}`), - getAlbum: (albumId) => - request(`albums/${encodeURIComponent(albumId)}`), - createAlbum: (input: CreateAlbumInput) => - request>( - "albums", - { method: "POST", body: JSON.stringify(input) }, - { idempotentCommand: true }, - ), - updateAlbum: (albumId, input: UpdateAlbumInput) => - request( - `albums/${encodeURIComponent(albumId)}`, - { - method: "PATCH", - headers: versionHeaders(input.expectedVersion), - body: JSON.stringify(withoutVersion(input)), - }, - ), - deleteAlbum: (albumId, expectedVersion) => - request( - `albums/${encodeURIComponent(albumId)}`, - { method: "DELETE", headers: versionHeaders(expectedVersion) }, - { expectJson: false }, - ), - addAlbumItems: (albumId, mediaIds) => - request( - `albums/${encodeURIComponent(albumId)}/items`, - { method: "POST", body: JSON.stringify({ mediaIds }) }, - { idempotentCommand: true, expectJson: false }, - ), - removeAlbumItem: (albumId, mediaId) => - request( - `albums/${encodeURIComponent(albumId)}/items/${encodeURIComponent(mediaId)}`, - { method: "DELETE" }, - { expectJson: false }, - ), - reorderAlbumItems: (albumId, mediaIds) => - request( - `albums/${encodeURIComponent(albumId)}/order`, - { method: "PUT", body: JSON.stringify({ mediaIds }) }, - { expectJson: false }, - ), - getAlbumStory: (albumId) => - request( - `albums/${encodeURIComponent(albumId)}/story`, - ), - - getMemories: (query: MemoryQuery = {}) => - request>(`memories${queryString(query)}`), - getMemory: (memoryId) => - request(`memories/${encodeURIComponent(memoryId)}`), - updateMemory: (memoryId, input: UpdateMemoryInput) => - request( - `memories/${encodeURIComponent(memoryId)}`, - { - method: "PATCH", - headers: versionHeaders(input.expectedVersion), - body: JSON.stringify(withoutVersion(input)), - }, - ), - getMemoryCandidates: () => - request>("memory-candidates?status=SUGGESTED"), - saveMemoryCandidate: (candidateId) => - request>( - `memory-candidates/${encodeURIComponent(candidateId)}/save`, - { method: "POST" }, - { idempotentCommand: true }, - ), - dismissMemoryCandidate: (candidateId) => - request( - `memory-candidates/${encodeURIComponent(candidateId)}/dismiss`, - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - regenerateMemory: (memoryId) => - request( - `memories/${encodeURIComponent(memoryId)}/regenerate`, - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - getMemoryStory: (memoryId) => - request( - `memories/${encodeURIComponent(memoryId)}/story`, - ), - - getDuplicateGroups: () => - request>("duplicates/groups"), - resolveDuplicateGroup: (groupId, input: DuplicateResolutionInput) => - request( - `duplicates/groups/${encodeURIComponent(groupId)}/resolve`, - { method: "POST", body: JSON.stringify(input) }, - { idempotentCommand: true, expectJson: false }, - ), - - search: (query: string) => - request(`search${queryString({ q: query })}`), - getPeople: () => request>("people"), - getPlaces: () => request>("places"), - - getDevices: () => request>("devices"), - getDeviceBackupPolicy: (deviceId) => - request( - `devices/${encodeURIComponent(deviceId)}/backup-policy`, - ), - updateDeviceBackupPolicy: (deviceId, policy) => - request( - `devices/${encodeURIComponent(deviceId)}/backup-policy`, - { method: "PUT", body: JSON.stringify(policy) }, - ), - disconnectDevice: (deviceId) => - request( - `devices/${encodeURIComponent(deviceId)}/disconnect`, - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - getBackupSummary: (deviceId) => - request( - `devices/${encodeURIComponent(deviceId)}/backup-summary`, - ), - - getStorageSettings: () => request("settings/storage"), - getAccount: () => request("account"), - updateAccount: (input) => - request("account", { - method: "PATCH", - body: JSON.stringify(input), - }), - runStorageIntegrityScan: () => - request( - "settings/storage/integrity-scan", - { method: "POST" }, - { idempotentCommand: true, expectJson: false }, - ), - - createShare: (target: ShareTarget, input: CreateShareInput) => - request( - `${target.type === "album" ? "albums" : "memories"}/${encodeURIComponent(target.id)}/shares`, - { method: "POST", body: JSON.stringify(input) }, - { idempotentCommand: true }, - ), - revokeShare: (shareId) => - request( - `shares/${encodeURIComponent(shareId)}`, - { method: "DELETE" }, - { expectJson: false }, - ), - getPublicShare: (token) => - request( - encodeURIComponent(token), - {}, - { root: shareRoot }, - ), - - preflightUpload: (input: UploadPreflightInput) => - request("uploads/preflight", { - method: "POST", - body: JSON.stringify(input), - }), - createUploadSession: (input) => - request( - "uploads", - { method: "POST", body: JSON.stringify(input) }, - { idempotentCommand: true }, - ), - appendUploadChunk, - commitUpload: (uploadSessionId: string) => - request( - `uploads/${encodeURIComponent(uploadSessionId)}/commit`, - { method: "POST" }, - { idempotentCommand: true }, - ), - abortUpload: (uploadSessionId: string) => - request( - `uploads/${encodeURIComponent(uploadSessionId)}`, - { method: "DELETE" }, - { expectJson: false }, - ), - }; - - return Object.freeze(gateway); -} - -function ensureTrailingSlash(value: string): string { - return value.endsWith("/") ? value : `${value}/`; -} diff --git a/src/features/memento-web/adapters/memento-http-binding.ts b/src/features/memento-web/adapters/memento-http-binding.ts new file mode 100644 index 0000000..8447bf8 --- /dev/null +++ b/src/features/memento-web/adapters/memento-http-binding.ts @@ -0,0 +1,169 @@ +import { + defineFeatureHttpOperationForRoutes, + type FeatureHttpBinding, +} from "../../../adapters/http/index.ts"; +import { mappingSuccess } from "../../../contracts/boundary-mapper.ts"; +import { + MEMENTO_HTTP_CONTRACTS, +} from "../contracts/memento-http-contract-contribution.ts"; +import { + MEMENTO_FEATURE_CONTRACT, +} from "../contracts/memento-feature-contract.ts"; + +export type MementoFeatureRouteId = + keyof typeof MEMENTO_FEATURE_CONTRACT.routes; + +const defineMementoHttpOperation = + defineFeatureHttpOperationForRoutes(); + +export const MEMENTO_HTTP_OPERATIONS = Object.freeze({ + MEMENTO_GET_HOME: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_HOME, + routeId: "APP_HOME", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_LIBRARY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_LIBRARY, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_MEMORIES: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_MEMORIES, + routeId: "MEMENTO_MEMORIES", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_MEMORY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_MEMORY, + routeId: "MEMENTO_MEMORY_DETAIL", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_MEMORY_CANDIDATES: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_MEMORY_CANDIDATES, + routeId: "MEMENTO_MEMORIES", + mapSuccess: mappingSuccess, + }), + MEMENTO_SAVE_MEMORY_CANDIDATE: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_SAVE_MEMORY_CANDIDATE, + routeId: "MEMENTO_MEMORIES", + mapSuccess: mappingSuccess, + }), + MEMENTO_UPDATE_MEMORY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_UPDATE_MEMORY, + routeId: "MEMENTO_MEMORY_DETAIL", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_ALBUMS: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_ALBUMS, + routeId: "MEMENTO_ALBUMS", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_ALBUM: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_ALBUM, + routeId: "MEMENTO_ALBUM_DETAIL", + mapSuccess: mappingSuccess, + }), + MEMENTO_CREATE_ALBUM: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_CREATE_ALBUM, + routeId: "MEMENTO_ALBUMS", + mapSuccess: mappingSuccess, + }), + MEMENTO_UPDATE_ALBUM: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_UPDATE_ALBUM, + routeId: "MEMENTO_ALBUM_DETAIL", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_PEOPLE: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_PEOPLE, + routeId: "MEMENTO_PEOPLE", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_PLACES: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_PLACES, + routeId: "MEMENTO_PLACES", + mapSuccess: mappingSuccess, + }), + MEMENTO_SEARCH: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_SEARCH, + routeId: "MEMENTO_SEARCH", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_DEVICES: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_DEVICES, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_DEVICE_BACKUP_POLICY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_DEVICE_BACKUP_POLICY, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_UPDATE_DEVICE_BACKUP_POLICY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_UPDATE_DEVICE_BACKUP_POLICY, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_DISCONNECT_DEVICE: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_DISCONNECT_DEVICE, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_BACKUP_SUMMARY: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_BACKUP_SUMMARY, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_STORAGE_SETTINGS: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_STORAGE_SETTINGS, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_ACCOUNT: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_ACCOUNT, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_RUN_INTEGRITY_SCAN: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_RUN_INTEGRITY_SCAN, + routeId: "MEMENTO_SETTINGS", + mapSuccess: mappingSuccess, + }), + MEMENTO_SET_MEDIA_FAVORITE: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_SET_MEDIA_FAVORITE, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_GET_DUPLICATES: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_GET_DUPLICATES, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_CREATE_SHARE: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_CREATE_SHARE, + routeId: "MEMENTO_MEMORY_DETAIL", + mapSuccess: mappingSuccess, + }), + MEMENTO_UPLOAD_PREFLIGHT: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_UPLOAD_PREFLIGHT, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_CREATE_UPLOAD_SESSION: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_CREATE_UPLOAD_SESSION, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_COMMIT_UPLOAD: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_COMMIT_UPLOAD, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), + MEMENTO_ABORT_UPLOAD: defineMementoHttpOperation({ + contract: MEMENTO_HTTP_CONTRACTS.MEMENTO_ABORT_UPLOAD, + routeId: "MEMENTO_LIBRARY", + mapSuccess: mappingSuccess, + }), +} as const); + +export type MementoHttpBinding = FeatureHttpBinding< + typeof MEMENTO_HTTP_OPERATIONS +>; diff --git a/src/features/memento-web/adapters/memento-http-feature-input.ts b/src/features/memento-web/adapters/memento-http-feature-input.ts new file mode 100644 index 0000000..c5ec6a1 --- /dev/null +++ b/src/features/memento-web/adapters/memento-http-feature-input.ts @@ -0,0 +1,244 @@ +import type { Result } from "../../../contracts/result.ts"; +import type { AppFailure } from "../../../contracts/errors.ts"; +import type { + MementoFeatureInput, + MementoMutationContext, + MementoQueryContext, +} from "../application/memento-application.ts"; +import type { + AlbumQuery, + CreateAlbumInput, + CreateShareInput, + LibraryQuery, + MemoryQuery, + ShareTarget, + UpdateAlbumInput, + UpdateMemoryInput, +} from "../application/memento-contracts.ts"; +import type { + DeviceBackupPolicy, + UploadPreflightInput, +} from "../contracts/memento-api.ts"; +import type { MementoHttpBinding } from "./memento-http-binding.ts"; + +const EMPTY = Object.freeze({}); + +export type MementoOffsetUpload = Readonly<{ + append( + uploadSessionId: string, + offset: number, + chunk: Blob, + context?: MementoMutationContext, + ): Promise>; +}>; + +function queryContext(context?: MementoQueryContext) { + return context?.signal === undefined + ? undefined + : Object.freeze({ signal: context.signal }); +} + +function mutationContext(context?: MementoMutationContext) { + if (!context) return undefined; + return Object.freeze({ + ...(context.signal === undefined ? {} : { signal: context.signal }), + ...(context.intent === undefined ? {} : { intent: context.intent }), + }); +} + +export function createMementoHttpFeatureInput( + http: MementoHttpBinding, + offsetUpload: MementoOffsetUpload, +): MementoFeatureInput { + return Object.freeze({ + mode: "api" as const, + getHome: (context) => + http.execute("MEMENTO_GET_HOME", EMPTY, queryContext(context)), + getLibrary: (query: LibraryQuery = {}, context) => + http.execute( + "MEMENTO_GET_LIBRARY", + query, + queryContext(context), + ), + getMemories: (query: MemoryQuery = {}, context) => + http.execute( + "MEMENTO_GET_MEMORIES", + query, + queryContext(context), + ), + getMemory: (memoryId, context) => + http.execute( + "MEMENTO_GET_MEMORY", + Object.freeze({ memoryId }), + queryContext(context), + ), + getMemoryCandidates: (context) => + http.execute( + "MEMENTO_GET_MEMORY_CANDIDATES", + EMPTY, + queryContext(context), + ), + saveMemoryCandidate: (candidateId, context) => + http.execute( + "MEMENTO_SAVE_MEMORY_CANDIDATE", + Object.freeze({ candidateId }), + mutationContext(context), + ), + updateMemory: ( + memoryId: string, + input: UpdateMemoryInput, + context, + ) => + http.execute( + "MEMENTO_UPDATE_MEMORY", + Object.freeze({ memoryId, input }), + mutationContext(context), + ), + getAlbums: (query: AlbumQuery = {}, context) => + http.execute( + "MEMENTO_GET_ALBUMS", + query, + queryContext(context), + ), + getAlbum: (albumId, context) => + http.execute( + "MEMENTO_GET_ALBUM", + Object.freeze({ albumId }), + queryContext(context), + ), + createAlbum: (input: CreateAlbumInput, context) => + http.execute( + "MEMENTO_CREATE_ALBUM", + input, + mutationContext(context), + ), + updateAlbum: ( + albumId: string, + input: UpdateAlbumInput, + context, + ) => + http.execute( + "MEMENTO_UPDATE_ALBUM", + Object.freeze({ albumId, input }), + mutationContext(context), + ), + getPeople: (context) => + http.execute( + "MEMENTO_GET_PEOPLE", + EMPTY, + queryContext(context), + ), + getPlaces: (context) => + http.execute( + "MEMENTO_GET_PLACES", + EMPTY, + queryContext(context), + ), + search: (query: string, context) => + http.execute( + "MEMENTO_SEARCH", + Object.freeze({ query }), + queryContext(context), + ), + getDevices: (context) => + http.execute( + "MEMENTO_GET_DEVICES", + EMPTY, + queryContext(context), + ), + getDeviceBackupPolicy: (deviceId, context) => + http.execute( + "MEMENTO_GET_DEVICE_BACKUP_POLICY", + Object.freeze({ deviceId }), + queryContext(context), + ), + updateDeviceBackupPolicy: ( + deviceId: string, + policy: DeviceBackupPolicy, + context, + ) => + http.execute( + "MEMENTO_UPDATE_DEVICE_BACKUP_POLICY", + Object.freeze({ deviceId, policy }), + mutationContext(context), + ), + disconnectDevice: (deviceId, context) => + http.execute( + "MEMENTO_DISCONNECT_DEVICE", + Object.freeze({ deviceId }), + mutationContext(context), + ), + getBackupSummary: (deviceId, context) => + http.execute( + "MEMENTO_GET_BACKUP_SUMMARY", + Object.freeze({ deviceId }), + queryContext(context), + ), + getStorageSettings: (context) => + http.execute( + "MEMENTO_GET_STORAGE_SETTINGS", + EMPTY, + queryContext(context), + ), + getAccount: (context) => + http.execute( + "MEMENTO_GET_ACCOUNT", + EMPTY, + queryContext(context), + ), + runStorageIntegrityScan: (context) => + http.execute( + "MEMENTO_RUN_INTEGRITY_SCAN", + EMPTY, + mutationContext(context), + ), + setMediaFavorite: (mediaId, favorite, context) => + http.execute( + "MEMENTO_SET_MEDIA_FAVORITE", + Object.freeze({ mediaId, favorite }), + mutationContext(context), + ), + getDuplicateGroups: (context) => + http.execute( + "MEMENTO_GET_DUPLICATES", + EMPTY, + queryContext(context), + ), + createShare: ( + target: ShareTarget, + input: CreateShareInput, + context, + ) => + http.execute( + "MEMENTO_CREATE_SHARE", + Object.freeze({ target, input }), + mutationContext(context), + ), + preflightUpload: (input: UploadPreflightInput, context) => + http.execute( + "MEMENTO_UPLOAD_PREFLIGHT", + input, + mutationContext(context), + ), + createUploadSession: (input, context) => + http.execute( + "MEMENTO_CREATE_UPLOAD_SESSION", + input, + mutationContext(context), + ), + appendUploadChunk: (uploadSessionId, offset, chunk, context) => + offsetUpload.append(uploadSessionId, offset, chunk, context), + commitUpload: (uploadSessionId, context) => + http.execute( + "MEMENTO_COMMIT_UPLOAD", + Object.freeze({ uploadSessionId }), + mutationContext(context), + ), + abortUpload: (uploadSessionId, context) => + http.execute( + "MEMENTO_ABORT_UPLOAD", + Object.freeze({ uploadSessionId }), + mutationContext(context), + ), + }); +} diff --git a/src/features/memento-web/adapters/memento-offset-upload.ts b/src/features/memento-web/adapters/memento-offset-upload.ts new file mode 100644 index 0000000..b437798 --- /dev/null +++ b/src/features/memento-web/adapters/memento-offset-upload.ts @@ -0,0 +1,19 @@ +import type { OffsetUploadExecutor } from "../../../adapters/http/index.ts"; +import type { MementoOffsetUpload } from "./memento-http-feature-input.ts"; + +export function createMementoOffsetUpload( + offsetUpload: OffsetUploadExecutor, +): MementoOffsetUpload { + return Object.freeze({ + append(uploadSessionId, offset, chunk, context) { + return offsetUpload.append({ + path: `/app-api/v1/uploads/${encodeURIComponent(uploadSessionId)}`, + offset, + chunk, + ...(context?.signal === undefined + ? {} + : { signal: context.signal }), + }); + }, + }); +} diff --git a/src/features/memento-web/adapters/mock-memento-gateway.ts b/src/features/memento-web/adapters/mock-memento-gateway.ts index b26366d..d8973db 100644 --- a/src/features/memento-web/adapters/mock-memento-gateway.ts +++ b/src/features/memento-web/adapters/mock-memento-gateway.ts @@ -210,7 +210,10 @@ export function createMockMementoGateway(): MementoGateway { getAlbumStory: async () => Object.freeze([]), getMemories: async () => ({ items: MEMORIES, nextCursor: null }), getMemory: async (memoryId) => { - const item = MEMORIES.find((memoryItem) => memoryItem.id === memoryId) ?? MEMORIES[0]!; + const item = + memoryId === "memory-jeju" + ? memory("memory-jeju", "제주, 여름의 끝", 84, PHOTOS[0]) + : (MEMORIES.find((memoryItem) => memoryItem.id === memoryId) ?? MEMORIES[0]!); return { ...item, description: "로컬 Mock Memory", diff --git a/src/features/memento-web/application/memento-application.ts b/src/features/memento-web/application/memento-application.ts new file mode 100644 index 0000000..90cb67a --- /dev/null +++ b/src/features/memento-web/application/memento-application.ts @@ -0,0 +1,150 @@ +import type {} from "../../../application/ports/in/application-api.ts"; +import { normalizeUnknownFailure } from "../../../contracts/errors.ts"; +import type { MutationIntent } from "../../../contracts/mutation-intent.ts"; +import type { Result } from "../../../contracts/result.ts"; +import type { + AccountSettings, + AlbumDetail, + AlbumSummary, + BackupSummary, + CursorPage, + DeviceBackupPolicy, + DeviceSummary, + DuplicateGroup, + HomeResponse, + LibraryItem, + MediaDetail, + MemoryCandidate, + MemoryDetail, + MemorySummary, + MementoDataMode, + PersonSummary, + PlaceSummary, + SearchResponse, + ShareCreateResult, + StorageSettings, + UploadCommitResult, + UploadPreflightInput, + UploadPreflightResponse, + UploadSession, +} from "../contracts/memento-api.ts"; +import type { + AlbumQuery, + CreateAlbumInput, + CreateShareInput, + LibraryQuery, + MemoryQuery, + ShareTarget, + UpdateAlbumInput, + UpdateMemoryInput, +} from "./memento-contracts.ts"; +import type { MementoGateway } from "./memento-gateway.ts"; + +export type MementoResult = Result; + +export type MementoQueryContext = Readonly<{ signal?: AbortSignal }>; +export type MementoMutationContext = Readonly<{ + signal?: AbortSignal; + intent?: MutationIntent; +}>; + +export type MementoFeatureInput = Readonly<{ + mode: MementoDataMode; + getHome(context?: MementoQueryContext): Promise>; + getLibrary(query?: LibraryQuery, context?: MementoQueryContext): Promise>>; + getMemories(query?: MemoryQuery, context?: MementoQueryContext): Promise>>; + getMemory(memoryId: string, context?: MementoQueryContext): Promise>; + getMemoryCandidates(context?: MementoQueryContext): Promise>>; + saveMemoryCandidate(candidateId: string, context?: MementoMutationContext): Promise>>; + updateMemory(memoryId: string, input: UpdateMemoryInput, context?: MementoMutationContext): Promise>; + getAlbums(query?: AlbumQuery, context?: MementoQueryContext): Promise>>; + getAlbum(albumId: string, context?: MementoQueryContext): Promise>; + createAlbum(input: CreateAlbumInput, context?: MementoMutationContext): Promise>>; + updateAlbum(albumId: string, input: UpdateAlbumInput, context?: MementoMutationContext): Promise>; + getPeople(context?: MementoQueryContext): Promise>>; + getPlaces(context?: MementoQueryContext): Promise>>; + search(query: string, context?: MementoQueryContext): Promise>; + getDevices(context?: MementoQueryContext): Promise>>; + getDeviceBackupPolicy(deviceId: string, context?: MementoQueryContext): Promise>; + updateDeviceBackupPolicy(deviceId: string, policy: DeviceBackupPolicy, context?: MementoMutationContext): Promise>; + disconnectDevice(deviceId: string, context?: MementoMutationContext): Promise>; + getBackupSummary(deviceId: string, context?: MementoQueryContext): Promise>; + getStorageSettings(context?: MementoQueryContext): Promise>; + getAccount(context?: MementoQueryContext): Promise>; + runStorageIntegrityScan(context?: MementoMutationContext): Promise>; + setMediaFavorite(mediaId: string, favorite: boolean, context?: MementoMutationContext): Promise>; + getDuplicateGroups(context?: MementoQueryContext): Promise>>; + createShare(target: ShareTarget, input: CreateShareInput, context?: MementoMutationContext): Promise>; + preflightUpload(input: UploadPreflightInput, context?: MementoMutationContext): Promise>; + createUploadSession( + input: Readonly<{ + deviceId?: string | null; + deviceLocalAssetId: string; + sourceType: "WEB_MANUAL"; + filename: string; + expectedSize: number; + mimeType: string; + clientSha256?: string | null; + }>, + context?: MementoMutationContext, + ): Promise>; + appendUploadChunk(uploadSessionId: string, offset: number, chunk: Blob, context?: MementoMutationContext): Promise>; + commitUpload(uploadSessionId: string, context?: MementoMutationContext): Promise>; + abortUpload(uploadSessionId: string, context?: MementoMutationContext): Promise>; +}>; + +declare module "../../../application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "memento-web": MementoFeatureInput; + } +} + +function result( + operationId: string, + execute: () => Promise, +): Promise> { + return execute() + .then((value) => Object.freeze({ ok: true as const, value })) + .catch((error: unknown) => + Object.freeze({ + ok: false as const, + error: normalizeUnknownFailure(error, { operationId }), + }), + ); +} + +export function createMementoFeatureInput(gateway: MementoGateway): MementoFeatureInput { + return Object.freeze({ + mode: gateway.mode, + getHome: () => result("MEMENTO_GET_HOME", () => gateway.getHome()), + getLibrary: (query) => result("MEMENTO_GET_LIBRARY", () => gateway.getLibrary(query)), + getMemories: (query) => result("MEMENTO_GET_MEMORIES", () => gateway.getMemories(query)), + getMemory: (id) => result("MEMENTO_GET_MEMORY", () => gateway.getMemory(id)), + getMemoryCandidates: () => result("MEMENTO_GET_MEMORY_CANDIDATES", () => gateway.getMemoryCandidates()), + saveMemoryCandidate: (id) => result("MEMENTO_SAVE_MEMORY_CANDIDATE", () => gateway.saveMemoryCandidate(id)), + updateMemory: (id, input) => result("MEMENTO_UPDATE_MEMORY", () => gateway.updateMemory(id, input)), + getAlbums: (query) => result("MEMENTO_GET_ALBUMS", () => gateway.getAlbums(query)), + getAlbum: (id) => result("MEMENTO_GET_ALBUM", () => gateway.getAlbum(id)), + createAlbum: (input) => result("MEMENTO_CREATE_ALBUM", () => gateway.createAlbum(input)), + updateAlbum: (id, input) => result("MEMENTO_UPDATE_ALBUM", () => gateway.updateAlbum(id, input)), + getPeople: () => result("MEMENTO_GET_PEOPLE", () => gateway.getPeople()), + getPlaces: () => result("MEMENTO_GET_PLACES", () => gateway.getPlaces()), + search: (query) => result("MEMENTO_SEARCH", () => gateway.search(query)), + getDevices: () => result("MEMENTO_GET_DEVICES", () => gateway.getDevices()), + getDeviceBackupPolicy: (id) => result("MEMENTO_GET_BACKUP_POLICY", () => gateway.getDeviceBackupPolicy(id)), + updateDeviceBackupPolicy: (id, policy) => result("MEMENTO_UPDATE_BACKUP_POLICY", () => gateway.updateDeviceBackupPolicy(id, policy)), + disconnectDevice: (id) => result("MEMENTO_DISCONNECT_DEVICE", () => gateway.disconnectDevice(id)), + getBackupSummary: (id) => result("MEMENTO_GET_BACKUP_SUMMARY", () => gateway.getBackupSummary(id)), + getStorageSettings: () => result("MEMENTO_GET_STORAGE_SETTINGS", () => gateway.getStorageSettings()), + getAccount: () => result("MEMENTO_GET_ACCOUNT", () => gateway.getAccount()), + runStorageIntegrityScan: () => result("MEMENTO_RUN_INTEGRITY_SCAN", () => gateway.runStorageIntegrityScan()), + setMediaFavorite: (id, favorite) => result("MEMENTO_SET_MEDIA_FAVORITE", () => gateway.setMediaFavorite(id, favorite)), + getDuplicateGroups: () => result("MEMENTO_GET_DUPLICATES", () => gateway.getDuplicateGroups()), + createShare: (target, input) => result("MEMENTO_CREATE_SHARE", () => gateway.createShare(target, input)), + preflightUpload: (input) => result("MEMENTO_UPLOAD_PREFLIGHT", () => gateway.preflightUpload(input)), + createUploadSession: (input) => result("MEMENTO_CREATE_UPLOAD_SESSION", () => gateway.createUploadSession(input)), + appendUploadChunk: (id, offset, chunk) => result("MEMENTO_APPEND_UPLOAD_CHUNK", () => gateway.appendUploadChunk(id, offset, chunk)), + commitUpload: (id) => result("MEMENTO_COMMIT_UPLOAD", () => gateway.commitUpload(id)), + abortUpload: (id) => result("MEMENTO_ABORT_UPLOAD", () => gateway.abortUpload(id)), + }); +} diff --git a/src/features/memento-web/application/memento-contracts.ts b/src/features/memento-web/application/memento-contracts.ts new file mode 100644 index 0000000..986b755 --- /dev/null +++ b/src/features/memento-web/application/memento-contracts.ts @@ -0,0 +1,65 @@ +export type LibraryQuery = Readonly<{ + cursor?: string; + limit?: number; + dateFrom?: string; + dateTo?: string; + mediaType?: string; + state?: string; + favorite?: boolean; + year?: number; + search?: string; + sort?: string; +}>; + +export type AlbumQuery = Readonly<{ + cursor?: string; + limit?: number; + search?: string; + shared?: boolean; + sort?: string; +}>; + +export type MemoryQuery = Readonly<{ + cursor?: string; + limit?: number; + sort?: string; + state?: string; + search?: string; +}>; + +export type CreateAlbumInput = Readonly<{ + title: string; + description?: string | null; + coverMediaId?: string | null; + sortMode?: "MANUAL" | "CAPTURE_TIME" | string; + mediaIds?: readonly string[]; +}>; + +export type UpdateAlbumInput = Readonly<{ + title?: string; + description?: string | null; + sortMode?: string; + expectedVersion?: number; +}>; + +export type UpdateMemoryInput = Readonly<{ + title?: string; + coverMediaId?: string | null; + autoUpdate?: boolean; + expectedVersion?: number; +}>; + +export type UpdateMediaMetadataInput = Readonly<{ + takenAt?: string | null; + description?: string | null; + expectedVersion?: number; +}>; + +export type CreateShareInput = Readonly<{ + allowDownload: boolean; + expiresAt?: string | null; +}>; + +export type ShareTarget = + | Readonly<{ type: "album"; id: string }> + | Readonly<{ type: "memory"; id: string }>; diff --git a/src/features/memento-web/application/memento-gateway.ts b/src/features/memento-web/application/memento-gateway.ts index 535350c..d356ff2 100644 --- a/src/features/memento-web/application/memento-gateway.ts +++ b/src/features/memento-web/application/memento-gateway.ts @@ -28,71 +28,17 @@ import type { UploadSession, } from "../contracts/memento-api.ts"; -export type LibraryQuery = Readonly<{ - cursor?: string; - limit?: number; - dateFrom?: string; - dateTo?: string; - mediaType?: string; - state?: string; - favorite?: boolean; - year?: number; - search?: string; - sort?: string; -}>; - -export type AlbumQuery = Readonly<{ - cursor?: string; - limit?: number; - search?: string; - shared?: boolean; - sort?: string; -}>; - -export type MemoryQuery = Readonly<{ - cursor?: string; - limit?: number; - sort?: string; - state?: string; - search?: string; -}>; - -export type CreateAlbumInput = Readonly<{ - title: string; - description?: string | null; - coverMediaId?: string | null; - sortMode?: "MANUAL" | "CAPTURE_TIME" | string; - mediaIds?: readonly string[]; -}>; - -export type UpdateAlbumInput = Readonly<{ - title?: string; - description?: string | null; - sortMode?: string; - expectedVersion?: number; -}>; - -export type UpdateMemoryInput = Readonly<{ - title?: string; - coverMediaId?: string | null; - autoUpdate?: boolean; - expectedVersion?: number; -}>; - -export type UpdateMediaMetadataInput = Readonly<{ - takenAt?: string | null; - description?: string | null; - expectedVersion?: number; -}>; - -export type CreateShareInput = Readonly<{ - allowDownload: boolean; - expiresAt?: string | null; -}>; - -export type ShareTarget = - | Readonly<{ type: "album"; id: string }> - | Readonly<{ type: "memory"; id: string }>; +import type { + AlbumQuery, + CreateAlbumInput, + CreateShareInput, + LibraryQuery, + MemoryQuery, + ShareTarget, + UpdateAlbumInput, + UpdateMediaMetadataInput, + UpdateMemoryInput, +} from "./memento-contracts.ts"; export interface MementoGateway { readonly mode: MementoDataMode; diff --git a/src/features/memento-web/contracts/memento-feature-contract.ts b/src/features/memento-web/contracts/memento-feature-contract.ts new file mode 100644 index 0000000..00305a2 --- /dev/null +++ b/src/features/memento-web/contracts/memento-feature-contract.ts @@ -0,0 +1,302 @@ +import { MEMENTO_RUNTIME_SCHEMA_CODECS } from "./memento-route-schemas.ts"; + +export const MEMENTO_FEATURE_ID = "memento-web"; + +const route = >(definition: Definition) => Object.freeze(definition); + +const runtime = >(definition: Definition) => Object.freeze(definition); + +export const MEMENTO_FEATURE_CONTRACT = Object.freeze({ + featureId: MEMENTO_FEATURE_ID, + runtimeSchemas: MEMENTO_RUNTIME_SCHEMA_CODECS, + mappers: Object.freeze({}), + schemas: Object.freeze({ + MementoLibrarySearch: Object.freeze({ + schemaId: "MementoLibrarySearch", + boundary: "route-search", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoDetailSearch: Object.freeze({ + schemaId: "MementoDetailSearch", + boundary: "route-search", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoMemoryParams: Object.freeze({ + schemaId: "MementoMemoryParams", + boundary: "route-params", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoAlbumParams: Object.freeze({ + schemaId: "MementoAlbumParams", + boundary: "route-params", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoPersonParams: Object.freeze({ + schemaId: "MementoPersonParams", + boundary: "route-params", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoPlaceParams: Object.freeze({ + schemaId: "MementoPlaceParams", + boundary: "route-params", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + MementoSettingsSearch: Object.freeze({ + schemaId: "MementoSettingsSearch", + boundary: "route-search", + owner: "feature-memento-web", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + }), + routes: Object.freeze({ + APP_HOME: route({ + routeId: "APP_HOME", + path: "/", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-home", + errorSurface: "feature-boundary", + chunkId: "route-memento-home", + title: "Memento", + navigationLabel: "홈", + navigationOrder: 10, + }), + MEMENTO_LIBRARY: route({ + routeId: "MEMENTO_LIBRARY", + path: "/library", + paramsSchema: null, + searchSchema: "MementoLibrarySearch", + access: "public", + loadingSurface: "memento-library", + errorSurface: "feature-boundary", + chunkId: "route-memento-library", + title: "라이브러리", + navigationLabel: "라이브러리", + navigationOrder: 20, + }), + MEMENTO_MEMORIES: route({ + routeId: "MEMENTO_MEMORIES", + path: "/memories", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-memories", + errorSurface: "feature-boundary", + chunkId: "route-memento-memories", + title: "Memories", + navigationLabel: "Memories", + navigationOrder: 30, + }), + MEMENTO_MEMORY_DETAIL: route({ + routeId: "MEMENTO_MEMORY_DETAIL", + path: "/memories/:memoryId", + paramsSchema: "MementoMemoryParams", + searchSchema: "MementoDetailSearch", + access: "public", + loadingSurface: "memento-memory-detail", + errorSurface: "feature-boundary", + chunkId: "route-memento-memory-detail", + title: "Memory", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_ALBUMS: route({ + routeId: "MEMENTO_ALBUMS", + path: "/albums", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-albums", + errorSurface: "feature-boundary", + chunkId: "route-memento-albums", + title: "Albums", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_ALBUM_DETAIL: route({ + routeId: "MEMENTO_ALBUM_DETAIL", + path: "/albums/:albumId", + paramsSchema: "MementoAlbumParams", + searchSchema: "MementoDetailSearch", + access: "public", + loadingSurface: "memento-album-detail", + errorSurface: "feature-boundary", + chunkId: "route-memento-album-detail", + title: "Album", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_SEARCH: route({ + routeId: "MEMENTO_SEARCH", + path: "/search", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-search", + errorSurface: "feature-boundary", + chunkId: "route-memento-search", + title: "검색", + navigationLabel: "검색", + navigationOrder: 40, + }), + MEMENTO_PEOPLE: route({ + routeId: "MEMENTO_PEOPLE", + path: "/people", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-people", + errorSurface: "feature-boundary", + chunkId: "route-memento-people", + title: "사람", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_PERSON_DETAIL: route({ + routeId: "MEMENTO_PERSON_DETAIL", + path: "/people/:personId", + paramsSchema: "MementoPersonParams", + searchSchema: null, + access: "public", + loadingSurface: "memento-person-detail", + errorSurface: "feature-boundary", + chunkId: "route-memento-person-detail", + title: "사람", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_PLACES: route({ + routeId: "MEMENTO_PLACES", + path: "/places", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-places", + errorSurface: "feature-boundary", + chunkId: "route-memento-places", + title: "장소 지도", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_PLACE_DETAIL: route({ + routeId: "MEMENTO_PLACE_DETAIL", + path: "/places/:placeId", + paramsSchema: "MementoPlaceParams", + searchSchema: null, + access: "public", + loadingSurface: "memento-place-detail", + errorSurface: "feature-boundary", + chunkId: "route-memento-place-detail", + title: "장소", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_LOGIN: route({ + routeId: "MEMENTO_LOGIN", + path: "/login", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-login", + errorSurface: "feature-boundary", + chunkId: "route-memento-login", + title: "로그인", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_REGISTER: route({ + routeId: "MEMENTO_REGISTER", + path: "/register", + paramsSchema: null, + searchSchema: null, + access: "public", + loadingSurface: "memento-register", + errorSurface: "feature-boundary", + chunkId: "route-memento-register", + title: "회원가입", + navigationLabel: null, + navigationOrder: null, + }), + MEMENTO_SETTINGS: route({ + routeId: "MEMENTO_SETTINGS", + path: "/settings", + paramsSchema: null, + searchSchema: "MementoSettingsSearch", + access: "public", + loadingSurface: "memento-settings", + errorSurface: "feature-boundary", + chunkId: "route-memento-settings", + title: "설정", + navigationLabel: null, + navigationOrder: null, + }), + }), + routeRuntimeContracts: Object.freeze({ + APP_HOME: runtime({ routeId: "APP_HOME", moduleId: "memento-home-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_LIBRARY: runtime({ routeId: "MEMENTO_LIBRARY", moduleId: "memento-library-page", paramsCodec: "none", searchCodec: "MementoLibrarySearch" }), + MEMENTO_MEMORIES: runtime({ routeId: "MEMENTO_MEMORIES", moduleId: "memento-memories-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_MEMORY_DETAIL: runtime({ routeId: "MEMENTO_MEMORY_DETAIL", moduleId: "memento-memory-detail-page", paramsCodec: "MementoMemoryParams", searchCodec: "MementoDetailSearch" }), + MEMENTO_ALBUMS: runtime({ routeId: "MEMENTO_ALBUMS", moduleId: "memento-albums-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_ALBUM_DETAIL: runtime({ routeId: "MEMENTO_ALBUM_DETAIL", moduleId: "memento-album-detail-page", paramsCodec: "MementoAlbumParams", searchCodec: "MementoDetailSearch" }), + MEMENTO_SEARCH: runtime({ routeId: "MEMENTO_SEARCH", moduleId: "memento-search-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_PEOPLE: runtime({ routeId: "MEMENTO_PEOPLE", moduleId: "memento-people-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_PERSON_DETAIL: runtime({ routeId: "MEMENTO_PERSON_DETAIL", moduleId: "memento-person-detail-page", paramsCodec: "MementoPersonParams", searchCodec: "none" }), + MEMENTO_PLACES: runtime({ routeId: "MEMENTO_PLACES", moduleId: "memento-places-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_PLACE_DETAIL: runtime({ routeId: "MEMENTO_PLACE_DETAIL", moduleId: "memento-place-detail-page", paramsCodec: "MementoPlaceParams", searchCodec: "none" }), + MEMENTO_LOGIN: runtime({ routeId: "MEMENTO_LOGIN", moduleId: "memento-login-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_REGISTER: runtime({ routeId: "MEMENTO_REGISTER", moduleId: "memento-register-page", paramsCodec: "none", searchCodec: "none" }), + MEMENTO_SETTINGS: runtime({ routeId: "MEMENTO_SETTINGS", moduleId: "memento-settings-page", paramsCodec: "none", searchCodec: "MementoSettingsSearch" }), + }), + apiOperations: Object.freeze({}), + invalidation: Object.freeze({ + topics: Object.freeze([]), + namespaces: Object.freeze([]), + edges: Object.freeze([]), + }), + topicVersions: Object.freeze([]), +} as const); diff --git a/src/features/memento-web/contracts/memento-http-contract-contribution.ts b/src/features/memento-web/contracts/memento-http-contract-contribution.ts new file mode 100644 index 0000000..ea89e46 --- /dev/null +++ b/src/features/memento-web/contracts/memento-http-contract-contribution.ts @@ -0,0 +1,702 @@ +import type { + CommandEffectDescriptor, + InstalledContractContribution, + InstalledHttpContract, + RuntimeValidator, +} from "../../../contracts/external-contract-runtime.ts"; +import type { + AlbumQuery, + CreateAlbumInput, + CreateShareInput, + LibraryQuery, + MemoryQuery, + ShareTarget, + UpdateAlbumInput, + UpdateMemoryInput, +} from "../application/memento-contracts.ts"; +import type { + AccountSettings, + AlbumDetail, + AlbumSummary, + ApiErrorPayload, + BackupSummary, + CursorPage, + DeviceBackupPolicy, + DeviceSummary, + DuplicateGroup, + HomeResponse, + LibraryItem, + MediaDetail, + MemoryCandidate, + MemoryDetail, + MemorySummary, + PersonSummary, + PlaceSummary, + SearchResponse, + ShareCreateResult, + StorageSettings, + UploadCommitResult, + UploadPreflightInput, + UploadPreflightResponse, + UploadSession, +} from "./memento-api.ts"; +import { MEMENTO_FEATURE_ID } from "./memento-feature-contract.ts"; + +type NoInput = Readonly>; +type IdInput = Readonly<{ id: string }>; +type DeviceInput = Readonly<{ deviceId: string }>; + +export type MementoHttpContractInput = { + MEMENTO_GET_HOME: NoInput; + MEMENTO_GET_LIBRARY: LibraryQuery; + MEMENTO_GET_MEMORIES: MemoryQuery; + MEMENTO_GET_MEMORY: Readonly<{ memoryId: string }>; + MEMENTO_GET_MEMORY_CANDIDATES: NoInput; + MEMENTO_SAVE_MEMORY_CANDIDATE: Readonly<{ candidateId: string }>; + MEMENTO_UPDATE_MEMORY: Readonly<{ memoryId: string; input: UpdateMemoryInput }>; + MEMENTO_GET_ALBUMS: AlbumQuery; + MEMENTO_GET_ALBUM: Readonly<{ albumId: string }>; + MEMENTO_CREATE_ALBUM: CreateAlbumInput; + MEMENTO_UPDATE_ALBUM: Readonly<{ albumId: string; input: UpdateAlbumInput }>; + MEMENTO_GET_PEOPLE: NoInput; + MEMENTO_GET_PLACES: NoInput; + MEMENTO_SEARCH: Readonly<{ query: string }>; + MEMENTO_GET_DEVICES: NoInput; + MEMENTO_GET_DEVICE_BACKUP_POLICY: DeviceInput; + MEMENTO_UPDATE_DEVICE_BACKUP_POLICY: Readonly<{ + deviceId: string; + policy: DeviceBackupPolicy; + }>; + MEMENTO_DISCONNECT_DEVICE: DeviceInput; + MEMENTO_GET_BACKUP_SUMMARY: DeviceInput; + MEMENTO_GET_STORAGE_SETTINGS: NoInput; + MEMENTO_GET_ACCOUNT: NoInput; + MEMENTO_RUN_INTEGRITY_SCAN: NoInput; + MEMENTO_SET_MEDIA_FAVORITE: Readonly<{ mediaId: string; favorite: boolean }>; + MEMENTO_GET_DUPLICATES: NoInput; + MEMENTO_CREATE_SHARE: Readonly<{ + target: ShareTarget; + input: CreateShareInput; + }>; + MEMENTO_UPLOAD_PREFLIGHT: UploadPreflightInput; + MEMENTO_CREATE_UPLOAD_SESSION: Readonly<{ + deviceId?: string | null; + deviceLocalAssetId: string; + sourceType: "WEB_MANUAL"; + filename: string; + expectedSize: number; + mimeType: string; + clientSha256?: string | null; + }>; + MEMENTO_COMMIT_UPLOAD: Readonly<{ uploadSessionId: string }>; + MEMENTO_ABORT_UPLOAD: Readonly<{ uploadSessionId: string }>; +}; + +export type MementoHttpContractOutput = { + MEMENTO_GET_HOME: HomeResponse; + MEMENTO_GET_LIBRARY: CursorPage; + MEMENTO_GET_MEMORIES: CursorPage; + MEMENTO_GET_MEMORY: MemoryDetail; + MEMENTO_GET_MEMORY_CANDIDATES: CursorPage; + MEMENTO_SAVE_MEMORY_CANDIDATE: Readonly<{ memoryId: string; version?: number }>; + MEMENTO_UPDATE_MEMORY: MemoryDetail; + MEMENTO_GET_ALBUMS: CursorPage; + MEMENTO_GET_ALBUM: AlbumDetail; + MEMENTO_CREATE_ALBUM: Readonly<{ id: string; title: string; version?: number }>; + MEMENTO_UPDATE_ALBUM: AlbumDetail; + MEMENTO_GET_PEOPLE: CursorPage; + MEMENTO_GET_PLACES: CursorPage; + MEMENTO_SEARCH: SearchResponse; + MEMENTO_GET_DEVICES: CursorPage; + MEMENTO_GET_DEVICE_BACKUP_POLICY: DeviceBackupPolicy; + MEMENTO_UPDATE_DEVICE_BACKUP_POLICY: DeviceBackupPolicy; + MEMENTO_DISCONNECT_DEVICE: void; + MEMENTO_GET_BACKUP_SUMMARY: BackupSummary; + MEMENTO_GET_STORAGE_SETTINGS: StorageSettings; + MEMENTO_GET_ACCOUNT: AccountSettings; + MEMENTO_RUN_INTEGRITY_SCAN: void; + MEMENTO_SET_MEDIA_FAVORITE: MediaDetail; + MEMENTO_GET_DUPLICATES: CursorPage; + MEMENTO_CREATE_SHARE: ShareCreateResult; + MEMENTO_UPLOAD_PREFLIGHT: UploadPreflightResponse; + MEMENTO_CREATE_UPLOAD_SESSION: UploadSession; + MEMENTO_COMMIT_UPLOAD: UploadCommitResult; + MEMENTO_ABORT_UPLOAD: void; +}; + +export type MementoHttpOperationId = keyof MementoHttpContractInput & + keyof MementoHttpContractOutput; + +function isRecord(value: unknown): value is Readonly> { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function runtimeValidator( + schemaId: string, + accept: (value: unknown) => boolean, +): RuntimeValidator { + return Object.freeze({ + schemaId, + safeParse(value: unknown) { + return accept(value) + ? Object.freeze({ + success: true as const, + data: structuredClone(value) as T, + }) + : Object.freeze({ + success: false as const, + issues: Object.freeze([ + Object.freeze({ path: Object.freeze([]), code: "INVALID_VALUE" }), + ]), + }); + }, + }); +} + +const noInputValidator = runtimeValidator( + "MementoNoInput", + (value) => isRecord(value) && Object.keys(value).length === 0, +); +const objectInputValidator = (schemaId: string) => + runtimeValidator(schemaId, isRecord); +const objectOutputValidator = (schemaId: string) => + runtimeValidator(schemaId, isRecord); +const cursorOutputValidator = (schemaId: string) => + runtimeValidator>( + schemaId, + (value) => isRecord(value) && Array.isArray(value.items), + ); +const voidOutputValidator = runtimeValidator( + "MementoVoid", + (value) => value === undefined || value === null, +); +const problemValidator = runtimeValidator( + "MementoProblem", + (value) => isRecord(value), +); + +const COMMAND_EFFECT: CommandEffectDescriptor = Object.freeze({ + successEffect: "APPLIED_CONFIRMED", + classifyProblem({ + status, + }: Readonly<{ status: number; problem: ApiErrorPayload }>) { + return status >= 400 && status < 500 ? "NOT_APPLIED" : "MAYBE_APPLIED"; + }, +}); + +type ContractSpec = Readonly<{ + operationId: OperationId; + method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + pathTemplate: string; + inputValidator: RuntimeValidator; + outputValidator: RuntimeValidator; + projectRequest(input: Input): Readonly<{ + pathValues: Readonly>; + queryEntries: readonly (readonly [string, string])[]; + headerEntries?: readonly (readonly [string, string])[]; + body: unknown; + }>; + responseBody?: "REQUIRED_JSON" | "NONE"; + acceptedStatuses?: readonly number[]; + retrySemantics?: "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER"; +}>; + +type MementoInstalledHttpContract< + OperationId extends MementoHttpOperationId, + Input, + Output, +> = InstalledHttpContract & + Readonly<{ + contract: InstalledHttpContract< + Input, + Output, + ApiErrorPayload + >["contract"] & + Readonly<{ operationId: OperationId }>; + }>; + +function contract< + Input, + Output, + const OperationId extends MementoHttpOperationId = MementoHttpOperationId, +>( + spec: ContractSpec, +): MementoInstalledHttpContract { + const isRead = spec.method === "GET"; + const retrySemantics = + spec.retrySemantics ?? (isRead ? "SAFE" : "NEVER"); + const keyed = retrySemantics === "KEYED"; + const responseBody = spec.responseBody ?? "REQUIRED_JSON"; + const acceptedStatuses = + spec.acceptedStatuses ?? + (responseBody === "NONE" ? Object.freeze([200, 204]) : Object.freeze([200])); + + return Object.freeze({ + contract: Object.freeze({ + operationId: spec.operationId, + method: spec.method, + pathTemplate: spec.pathTemplate, + inputValidator: spec.inputValidator, + outputValidator: spec.outputValidator, + problemValidator, + acceptedStatuses, + emptyBodyStatuses: + responseBody === "NONE" + ? Object.freeze([...acceptedStatuses]) + : Object.freeze([]), + retrySemantics, + requestBody: isRead ? "NONE" : "JSON", + responseBody, + commandRecovery: keyed + ? Object.freeze({ + mode: "IDEMPOTENCY_REPLAY" as const, + operationIdentityField: "idempotencyKey", + }) + : null, + commandEffect: isRead ? null : COMMAND_EFFECT, + projectRequest: spec.projectRequest, + }), + frontend: Object.freeze({ + policyId: `${spec.operationId}_V1`, + requestByteLimit: isRead ? 0 : 262_144, + responseByteLimit: 8_388_608, + totalDeadlineMs: 10_000, + retryBudget: (isRead || retrySemantics === "IDEMPOTENT" ? 2 : 0) as 0 | 1 | 2, + authProfileId: isRead ? "MEMENTO_BFF_READ" : "MEMENTO_BFF_WRITE", + diagnosticsOperation: spec.operationId.toLocaleLowerCase().replaceAll("_", "."), + }), + }) as MementoInstalledHttpContract; +} + +const EMPTY = Object.freeze({}); +const noBody = () => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([]), + body: null, +}); + +function queryEntries(input: Readonly>) { + const entries: (readonly [string, string])[] = []; + for (const [key, value] of Object.entries(input)) { + if (value === undefined || value === null || value === "") continue; + entries.push(Object.freeze([key, String(value)])); + } + return Object.freeze(entries); +} + +function versionHeader( + expectedVersion?: number, +): readonly (readonly [string, string])[] { + return Number.isSafeInteger(expectedVersion) + ? Object.freeze([ + Object.freeze(["if-match", String(expectedVersion)] as const), + ]) + : Object.freeze([]); +} + +function withoutExpectedVersion>( + input: T, +): Omit { + const { expectedVersion: _expectedVersion, ...rest } = input; + return rest; +} + +export const MEMENTO_HTTP_CONTRACTS = Object.freeze({ + MEMENTO_GET_HOME: contract({ + operationId: "MEMENTO_GET_HOME", + method: "GET", + pathTemplate: "/app-api/v1/home", + inputValidator: noInputValidator, + outputValidator: objectOutputValidator("MementoHomeResponse"), + projectRequest: noBody, + }), + MEMENTO_GET_LIBRARY: contract, "MEMENTO_GET_LIBRARY">({ + operationId: "MEMENTO_GET_LIBRARY", + method: "GET", + pathTemplate: "/app-api/v1/library", + inputValidator: objectInputValidator("MementoLibraryQuery"), + outputValidator: cursorOutputValidator("MementoLibraryPage"), + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: queryEntries(input), + body: null, + }), + }), + MEMENTO_GET_MEMORIES: contract, "MEMENTO_GET_MEMORIES">({ + operationId: "MEMENTO_GET_MEMORIES", + method: "GET", + pathTemplate: "/app-api/v1/memories", + inputValidator: objectInputValidator("MementoMemoryQuery"), + outputValidator: cursorOutputValidator("MementoMemoryPage"), + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: queryEntries(input), + body: null, + }), + }), + MEMENTO_GET_MEMORY: contract, MemoryDetail, "MEMENTO_GET_MEMORY">({ + operationId: "MEMENTO_GET_MEMORY", + method: "GET", + pathTemplate: "/app-api/v1/memories/{memoryId}", + inputValidator: objectInputValidator("MementoMemoryId"), + outputValidator: objectOutputValidator("MementoMemoryDetail"), + projectRequest: ({ memoryId }) => Object.freeze({ + pathValues: Object.freeze({ memoryId }), + queryEntries: Object.freeze([]), + body: null, + }), + }), + MEMENTO_GET_MEMORY_CANDIDATES: contract, "MEMENTO_GET_MEMORY_CANDIDATES">({ + operationId: "MEMENTO_GET_MEMORY_CANDIDATES", + method: "GET", + pathTemplate: "/app-api/v1/memory-candidates", + inputValidator: noInputValidator, + outputValidator: cursorOutputValidator("MementoMemoryCandidatePage"), + projectRequest: () => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([ + Object.freeze(["status", "SUGGESTED"] as const), + ]), + body: null, + }), + }), + MEMENTO_SAVE_MEMORY_CANDIDATE: contract< + Readonly<{ candidateId: string }>, + Readonly<{ memoryId: string; version?: number }> + , "MEMENTO_SAVE_MEMORY_CANDIDATE">({ + operationId: "MEMENTO_SAVE_MEMORY_CANDIDATE", + method: "POST", + pathTemplate: "/app-api/v1/memory-candidates/{candidateId}/save", + inputValidator: objectInputValidator("MementoMemoryCandidateId"), + outputValidator: objectOutputValidator("MementoSavedMemory"), + retrySemantics: "KEYED", + projectRequest: ({ candidateId }) => Object.freeze({ + pathValues: Object.freeze({ candidateId }), + queryEntries: Object.freeze([]), + body: EMPTY, + }), + }), + MEMENTO_UPDATE_MEMORY: contract< + Readonly<{ memoryId: string; input: UpdateMemoryInput }>, + MemoryDetail + , "MEMENTO_UPDATE_MEMORY">({ + operationId: "MEMENTO_UPDATE_MEMORY", + method: "PATCH", + pathTemplate: "/app-api/v1/memories/{memoryId}", + inputValidator: objectInputValidator("MementoUpdateMemory"), + outputValidator: objectOutputValidator("MementoMemoryDetail"), + projectRequest: ({ memoryId, input }) => Object.freeze({ + pathValues: Object.freeze({ memoryId }), + queryEntries: Object.freeze([]), + headerEntries: versionHeader(input.expectedVersion), + body: Object.freeze(withoutExpectedVersion(input)), + }), + }), + MEMENTO_GET_ALBUMS: contract, "MEMENTO_GET_ALBUMS">({ + operationId: "MEMENTO_GET_ALBUMS", + method: "GET", + pathTemplate: "/app-api/v1/albums", + inputValidator: objectInputValidator("MementoAlbumQuery"), + outputValidator: cursorOutputValidator("MementoAlbumPage"), + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: queryEntries(input), + body: null, + }), + }), + MEMENTO_GET_ALBUM: contract, AlbumDetail, "MEMENTO_GET_ALBUM">({ + operationId: "MEMENTO_GET_ALBUM", + method: "GET", + pathTemplate: "/app-api/v1/albums/{albumId}", + inputValidator: objectInputValidator("MementoAlbumId"), + outputValidator: objectOutputValidator("MementoAlbumDetail"), + projectRequest: ({ albumId }) => Object.freeze({ + pathValues: Object.freeze({ albumId }), + queryEntries: Object.freeze([]), + body: null, + }), + }), + MEMENTO_CREATE_ALBUM: contract, "MEMENTO_CREATE_ALBUM">({ + operationId: "MEMENTO_CREATE_ALBUM", + method: "POST", + pathTemplate: "/app-api/v1/albums", + inputValidator: objectInputValidator("MementoCreateAlbum"), + outputValidator: objectOutputValidator("MementoCreatedAlbum"), + acceptedStatuses: Object.freeze([200, 201]), + retrySemantics: "KEYED", + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([]), + body: input, + }), + }), + MEMENTO_UPDATE_ALBUM: contract< + Readonly<{ albumId: string; input: UpdateAlbumInput }>, + AlbumDetail + , "MEMENTO_UPDATE_ALBUM">({ + operationId: "MEMENTO_UPDATE_ALBUM", + method: "PATCH", + pathTemplate: "/app-api/v1/albums/{albumId}", + inputValidator: objectInputValidator("MementoUpdateAlbum"), + outputValidator: objectOutputValidator("MementoAlbumDetail"), + projectRequest: ({ albumId, input }) => Object.freeze({ + pathValues: Object.freeze({ albumId }), + queryEntries: Object.freeze([]), + headerEntries: versionHeader(input.expectedVersion), + body: Object.freeze(withoutExpectedVersion(input)), + }), + }), + MEMENTO_GET_PEOPLE: contract, "MEMENTO_GET_PEOPLE">({ + operationId: "MEMENTO_GET_PEOPLE", + method: "GET", + pathTemplate: "/app-api/v1/people", + inputValidator: noInputValidator, + outputValidator: cursorOutputValidator("MementoPeoplePage"), + projectRequest: noBody, + }), + MEMENTO_GET_PLACES: contract, "MEMENTO_GET_PLACES">({ + operationId: "MEMENTO_GET_PLACES", + method: "GET", + pathTemplate: "/app-api/v1/places", + inputValidator: noInputValidator, + outputValidator: cursorOutputValidator("MementoPlacesPage"), + projectRequest: noBody, + }), + MEMENTO_SEARCH: contract, SearchResponse, "MEMENTO_SEARCH">({ + operationId: "MEMENTO_SEARCH", + method: "GET", + pathTemplate: "/app-api/v1/search", + inputValidator: objectInputValidator("MementoSearchQuery"), + outputValidator: objectOutputValidator("MementoSearchResponse"), + projectRequest: ({ query }) => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([ + Object.freeze(["q", query] as const), + ]), + body: null, + }), + }), + MEMENTO_GET_DEVICES: contract, "MEMENTO_GET_DEVICES">({ + operationId: "MEMENTO_GET_DEVICES", + method: "GET", + pathTemplate: "/app-api/v1/devices", + inputValidator: noInputValidator, + outputValidator: cursorOutputValidator("MementoDevicePage"), + projectRequest: noBody, + }), + MEMENTO_GET_DEVICE_BACKUP_POLICY: contract({ + operationId: "MEMENTO_GET_DEVICE_BACKUP_POLICY", + method: "GET", + pathTemplate: "/app-api/v1/devices/{deviceId}/backup-policy", + inputValidator: objectInputValidator("MementoDeviceId"), + outputValidator: objectOutputValidator("MementoDeviceBackupPolicy"), + projectRequest: ({ deviceId }) => Object.freeze({ + pathValues: Object.freeze({ deviceId }), + queryEntries: Object.freeze([]), + body: null, + }), + }), + MEMENTO_UPDATE_DEVICE_BACKUP_POLICY: contract< + Readonly<{ deviceId: string; policy: DeviceBackupPolicy }>, + DeviceBackupPolicy + , "MEMENTO_UPDATE_DEVICE_BACKUP_POLICY">({ + operationId: "MEMENTO_UPDATE_DEVICE_BACKUP_POLICY", + method: "PUT", + pathTemplate: "/app-api/v1/devices/{deviceId}/backup-policy", + inputValidator: objectInputValidator("MementoUpdateBackupPolicy"), + outputValidator: objectOutputValidator("MementoDeviceBackupPolicy"), + retrySemantics: "IDEMPOTENT", + projectRequest: ({ deviceId, policy }) => Object.freeze({ + pathValues: Object.freeze({ deviceId }), + queryEntries: Object.freeze([]), + body: policy, + }), + }), + MEMENTO_DISCONNECT_DEVICE: contract({ + operationId: "MEMENTO_DISCONNECT_DEVICE", + method: "POST", + pathTemplate: "/app-api/v1/devices/{deviceId}/disconnect", + inputValidator: objectInputValidator("MementoDeviceId"), + outputValidator: voidOutputValidator, + responseBody: "NONE", + retrySemantics: "KEYED", + projectRequest: ({ deviceId }) => Object.freeze({ + pathValues: Object.freeze({ deviceId }), + queryEntries: Object.freeze([]), + body: EMPTY, + }), + }), + MEMENTO_GET_BACKUP_SUMMARY: contract({ + operationId: "MEMENTO_GET_BACKUP_SUMMARY", + method: "GET", + pathTemplate: "/app-api/v1/devices/{deviceId}/backup-summary", + inputValidator: objectInputValidator("MementoDeviceId"), + outputValidator: objectOutputValidator("MementoBackupSummary"), + projectRequest: ({ deviceId }) => Object.freeze({ + pathValues: Object.freeze({ deviceId }), + queryEntries: Object.freeze([]), + body: null, + }), + }), + MEMENTO_GET_STORAGE_SETTINGS: contract({ + operationId: "MEMENTO_GET_STORAGE_SETTINGS", + method: "GET", + pathTemplate: "/app-api/v1/settings/storage", + inputValidator: noInputValidator, + outputValidator: objectOutputValidator("MementoStorageSettings"), + projectRequest: noBody, + }), + MEMENTO_GET_ACCOUNT: contract({ + operationId: "MEMENTO_GET_ACCOUNT", + method: "GET", + pathTemplate: "/app-api/v1/account", + inputValidator: noInputValidator, + outputValidator: objectOutputValidator("MementoAccountSettings"), + projectRequest: noBody, + }), + MEMENTO_RUN_INTEGRITY_SCAN: contract({ + operationId: "MEMENTO_RUN_INTEGRITY_SCAN", + method: "POST", + pathTemplate: "/app-api/v1/settings/storage/integrity-scan", + inputValidator: noInputValidator, + outputValidator: voidOutputValidator, + responseBody: "NONE", + retrySemantics: "KEYED", + projectRequest: () => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([]), + body: EMPTY, + }), + }), + MEMENTO_SET_MEDIA_FAVORITE: contract< + Readonly<{ mediaId: string; favorite: boolean }>, + MediaDetail + , "MEMENTO_SET_MEDIA_FAVORITE">({ + operationId: "MEMENTO_SET_MEDIA_FAVORITE", + method: "PUT", + pathTemplate: "/app-api/v1/media/{mediaId}/favorite", + inputValidator: objectInputValidator("MementoSetMediaFavorite"), + outputValidator: objectOutputValidator("MementoMediaDetail"), + retrySemantics: "IDEMPOTENT", + projectRequest: ({ mediaId, favorite }) => Object.freeze({ + pathValues: Object.freeze({ mediaId }), + queryEntries: Object.freeze([]), + body: Object.freeze({ favorite }), + }), + }), + MEMENTO_GET_DUPLICATES: contract, "MEMENTO_GET_DUPLICATES">({ + operationId: "MEMENTO_GET_DUPLICATES", + method: "GET", + pathTemplate: "/app-api/v1/duplicates/groups", + inputValidator: noInputValidator, + outputValidator: cursorOutputValidator("MementoDuplicatePage"), + projectRequest: noBody, + }), + MEMENTO_CREATE_SHARE: contract< + Readonly<{ target: ShareTarget; input: CreateShareInput }>, + ShareCreateResult + , "MEMENTO_CREATE_SHARE">({ + operationId: "MEMENTO_CREATE_SHARE", + method: "POST", + pathTemplate: "/app-api/v1/{targetType}/{targetId}/shares", + inputValidator: objectInputValidator("MementoCreateShare"), + outputValidator: objectOutputValidator("MementoShareCreateResult"), + acceptedStatuses: Object.freeze([200, 201]), + retrySemantics: "KEYED", + projectRequest: ({ target, input }) => Object.freeze({ + pathValues: Object.freeze({ + targetType: target.type === "album" ? "albums" : "memories", + targetId: target.id, + }), + queryEntries: Object.freeze([]), + body: input, + }), + }), + MEMENTO_UPLOAD_PREFLIGHT: contract({ + operationId: "MEMENTO_UPLOAD_PREFLIGHT", + method: "POST", + pathTemplate: "/app-api/v1/uploads/preflight", + inputValidator: objectInputValidator("MementoUploadPreflightInput"), + outputValidator: objectOutputValidator("MementoUploadPreflightResponse"), + retrySemantics: "IDEMPOTENT", + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([]), + body: input, + }), + }), + MEMENTO_CREATE_UPLOAD_SESSION: contract< + MementoHttpContractInput["MEMENTO_CREATE_UPLOAD_SESSION"], + UploadSession + , "MEMENTO_CREATE_UPLOAD_SESSION">({ + operationId: "MEMENTO_CREATE_UPLOAD_SESSION", + method: "POST", + pathTemplate: "/app-api/v1/uploads", + inputValidator: objectInputValidator("MementoCreateUploadSession"), + outputValidator: objectOutputValidator("MementoUploadSession"), + acceptedStatuses: Object.freeze([200, 201]), + retrySemantics: "KEYED", + projectRequest: (input) => Object.freeze({ + pathValues: EMPTY, + queryEntries: Object.freeze([]), + body: input, + }), + }), + MEMENTO_COMMIT_UPLOAD: contract< + Readonly<{ uploadSessionId: string }>, + UploadCommitResult + , "MEMENTO_COMMIT_UPLOAD">({ + operationId: "MEMENTO_COMMIT_UPLOAD", + method: "POST", + pathTemplate: "/app-api/v1/uploads/{uploadSessionId}/commit", + inputValidator: objectInputValidator("MementoUploadSessionId"), + outputValidator: objectOutputValidator("MementoUploadCommitResult"), + retrySemantics: "KEYED", + projectRequest: ({ uploadSessionId }) => Object.freeze({ + pathValues: Object.freeze({ uploadSessionId }), + queryEntries: Object.freeze([]), + body: EMPTY, + }), + }), + MEMENTO_ABORT_UPLOAD: contract, void, "MEMENTO_ABORT_UPLOAD">({ + operationId: "MEMENTO_ABORT_UPLOAD", + method: "DELETE", + pathTemplate: "/app-api/v1/uploads/{uploadSessionId}", + inputValidator: objectInputValidator("MementoUploadSessionId"), + outputValidator: voidOutputValidator, + responseBody: "NONE", + retrySemantics: "IDEMPOTENT", + projectRequest: ({ uploadSessionId }) => Object.freeze({ + pathValues: Object.freeze({ uploadSessionId }), + queryEntries: Object.freeze([]), + body: EMPTY, + }), + }), +} satisfies Readonly<{ + [OperationId in MementoHttpOperationId]: InstalledHttpContract< + MementoHttpContractInput[OperationId], + MementoHttpContractOutput[OperationId], + ApiErrorPayload + >; +}>); + +export const MEMENTO_CONTRACT_CONTRIBUTION: InstalledContractContribution = + Object.freeze({ + contributionId: "memento-web-http-v1", + featureId: MEMENTO_FEATURE_ID, + source: Object.freeze({ + kind: "PRODUCT_LOCAL_CONTRACT" as const, + contractId: "memento-web-http-v1", + revision: 1, + }), + http: Object.freeze(Object.values(MEMENTO_HTTP_CONTRACTS)) as readonly InstalledHttpContract< + unknown, + unknown, + unknown + >[], + events: Object.freeze([]), + }); diff --git a/src/features/memento-web/contracts/memento-route-schemas.ts b/src/features/memento-web/contracts/memento-route-schemas.ts new file mode 100644 index 0000000..f42fb88 --- /dev/null +++ b/src/features/memento-web/contracts/memento-route-schemas.ts @@ -0,0 +1,61 @@ +import { z } from "zod"; +import type { RuntimeSchemaCodec } from "../../../contracts/schema-registry.ts"; + +export const mementoMemoryParamsSchema = z.object({ + memoryId: z.string().trim().min(1).max(120), +}).strict(); + +export const mementoAlbumParamsSchema = z.object({ + albumId: z.string().trim().min(1).max(120), +}).strict(); + +export const mementoPersonParamsSchema = z.object({ + personId: z.string().trim().min(1).max(120), +}).strict(); + +export const mementoPlaceParamsSchema = z.object({ + placeId: z.string().trim().min(1).max(120), +}).strict(); + +export const mementoLibrarySearchSchema = z.object({ + filter: z.enum(["date", "type", "unorganized", "duplicate"]).optional(), + q: z.string().trim().max(200).optional(), + view: z.enum(["mosaic", "dense"]).optional(), +}).strict(); + +export const mementoDetailSearchSchema = z.object({ + tab: z.enum(["story", "photos", "info"]).optional(), +}).strict(); + +export const mementoSettingsSearchSchema = z.object({ + section: z.enum(["devices", "backup-settings", "storage", "account"]).optional(), +}).strict(); + +function project(result: z.ZodSafeParseResult) { + return result.success + ? ({ success: true as const, data: structuredClone(result.data) }) + : ({ + success: false as const, + issues: result.error.issues.map((issue) => ({ + path: issue.path.join("."), + code: issue.code, + })), + }); +} + +function codec(schemaId: string, schema: z.ZodType): RuntimeSchemaCodec { + return Object.freeze({ + schemaId, + parse: (value: unknown) => project(schema.safeParse(value)), + }); +} + +export const MEMENTO_RUNTIME_SCHEMA_CODECS = Object.freeze({ + MementoLibrarySearch: codec("MementoLibrarySearch", mementoLibrarySearchSchema), + MementoDetailSearch: codec("MementoDetailSearch", mementoDetailSearchSchema), + MementoMemoryParams: codec("MementoMemoryParams", mementoMemoryParamsSchema), + MementoAlbumParams: codec("MementoAlbumParams", mementoAlbumParamsSchema), + MementoPersonParams: codec("MementoPersonParams", mementoPersonParamsSchema), + MementoPlaceParams: codec("MementoPlaceParams", mementoPlaceParamsSchema), + MementoSettingsSearch: codec("MementoSettingsSearch", mementoSettingsSearchSchema), +}); diff --git a/src/features/memento-web/presentation/components/icons.tsx b/src/features/memento-web/presentation/components/icons.tsx new file mode 100644 index 0000000..98d74af --- /dev/null +++ b/src/features/memento-web/presentation/components/icons.tsx @@ -0,0 +1,33 @@ +import type { ReactNode } from "react"; + +type IconName = "home" | "grid" | "spark" | "search" | "plus" | "back"; + +const paths: Readonly> = { + home: , + grid: ( + <> + + + + + + ), + spark: ( + <> + + + + ), + search: ( + <> + + + + ), + plus: , + back: , +}; + +export function MementoIcon({ name }: Readonly<{ name: IconName }>) { + return ; +} diff --git a/src/features/memento-web/presentation/components/media-components.tsx b/src/features/memento-web/presentation/components/media-components.tsx new file mode 100644 index 0000000..81863f0 --- /dev/null +++ b/src/features/memento-web/presentation/components/media-components.tsx @@ -0,0 +1,85 @@ +import { useMementoUi } from "../memento-ui-context.tsx"; +import { LIBRARY_LAYOUT, PHOTO_URLS } from "../memento-demo-model.ts"; + +export function PhotoGrid({ + id, + offset = 0, + count = 15, + selectable = false, + selected = new Set(), + onToggle, +}: Readonly<{ + id?: string; + offset?: number; + count?: number; + selectable?: boolean; + selected?: ReadonlySet; + onToggle?: (key: string) => void; +}>) { + const ui = useMementoUi(); + return ( +
+ {Array.from({ length: count }, (_, index) => { + const src = PHOTO_URLS[(index + offset) % PHOTO_URLS.length]!; + const key = `${offset}-${index}`; + return ( +
selectable ? onToggle?.(key) : ui.openViewer(src)} + > + +
+ ); + })} +
+ ); +} + +export function LibraryMediaGrid({ + group, + offset, + hiddenMode, + selected, + onToggle, +}: Readonly<{ + group: number; + offset: number; + hiddenMode: "none" | "duplicate" | "unorganized"; + selected: ReadonlySet; + onToggle(key: string): void; +}>) { + return ( +
+ {Array.from({ length: 12 }, (_, index) => { + const className = LIBRARY_LAYOUT[(index + group) % LIBRARY_LAYOUT.length] ?? ""; + const key = `${group}-${index}`; + const hidden = + hiddenMode === "duplicate" + ? index % 6 !== 0 + : hiddenMode === "unorganized" + ? index % 4 === 0 + : false; + const src = PHOTO_URLS[(offset + index) % PHOTO_URLS.length]!; + return ( +
onToggle(key)} + > + + ✓ + + {index === 3 ? ▶ 0:18 : null} + {index === 6 ? 중복 후보 : null} + {index === 8 ? ✓ 서버 : null} + +
+ ); + })} +
+ ); +} diff --git a/src/features/memento-web/presentation/components/memory-components.tsx b/src/features/memento-web/presentation/components/memory-components.tsx new file mode 100644 index 0000000..234edce --- /dev/null +++ b/src/features/memento-web/presentation/components/memory-components.tsx @@ -0,0 +1,69 @@ +import { useNavigate } from "react-router-dom"; + +import { MementoBadge } from "../../../../presentation/design-system/index.ts"; +import { Photo } from "./photo.tsx"; + +export function ResurfacedMemoryCard({ + title, + meta, + photo, + memoryId, +}: Readonly<{ + title: string; + meta: string; + photo: number; + memoryId?: string; +}>) { + const navigate = useNavigate(); + return ( +
memoryId && void navigate(`/memories/${memoryId}`)} + > + +
{meta}{title}
+
+ ); +} + +export function MemoryItem({ + id, + title, + meta, + photo, + count, + type = "Memory", + album = false, + shared = false, + showType = true, +}: Readonly<{ + id: string; + title: string; + meta: string; + photo: number; + count: number; + type?: string; + album?: boolean; + shared?: boolean; + showType?: boolean; +}>) { + const navigate = useNavigate(); + return ( +
void navigate(album ? `/albums/${id}` : `/memories/${id}`)} + > +
+ + {showType ? ( + + {album && shared ? "공유 Album" : type} + + ) : null} + {count} +
+
{title}{meta}
+
+ ); +} diff --git a/src/features/memento-web/presentation/components/page-head.tsx b/src/features/memento-web/presentation/components/page-head.tsx new file mode 100644 index 0000000..26b2170 --- /dev/null +++ b/src/features/memento-web/presentation/components/page-head.tsx @@ -0,0 +1,45 @@ +import type { ReactNode } from "react"; + +export function PageHead({ + eyebrow, + title, + actions, +}: Readonly<{ + eyebrow?: string; + title: string; + actions?: ReactNode; +}>) { + return ( +
+
+ {eyebrow ?
{eyebrow}
: null} +

{title}

+
+ {actions ?
{actions}
: null} +
+ ); +} + +export function SectionHead({ + title, + note, + action, +}: Readonly<{ + title: string; + note?: string; + action?: ReactNode; +}>) { + return ( +
+ {note ? ( +
+

{title}

+

{note}

+
+ ) : ( +

{title}

+ )} + {action} +
+ ); +} diff --git a/src/features/memento-web/presentation/components/photo.tsx b/src/features/memento-web/presentation/components/photo.tsx new file mode 100644 index 0000000..57347af --- /dev/null +++ b/src/features/memento-web/presentation/components/photo.tsx @@ -0,0 +1,6 @@ +export function Photo({ + index, + alt = "", +}: Readonly<{ index: number; alt?: string }>) { + return {alt}; +} diff --git a/src/features/memento-web/presentation/hooks/use-memento.ts b/src/features/memento-web/presentation/hooks/use-memento.ts new file mode 100644 index 0000000..d93ff07 --- /dev/null +++ b/src/features/memento-web/presentation/hooks/use-memento.ts @@ -0,0 +1,299 @@ +import { useApplicationFeature } from "../../../../presentation/providers/application-provider.tsx"; +import { + useApplicationMutation, + useApplicationQuery, +} from "../../../../presentation/adapters/query/application-query.ts"; +import { useServerStateScope } from "../../../../presentation/adapters/query/server-state-scope-provider.tsx"; +import type { + AlbumQuery, + CreateAlbumInput, + CreateShareInput, + LibraryQuery, + MemoryQuery, + ShareTarget, + UpdateAlbumInput, + UpdateMemoryInput, +} from "../../application/memento-contracts.ts"; +import { MEMENTO_FEATURE_ID } from "../../contracts/memento-feature-contract.ts"; + +export function useMementoInput() { + return useApplicationFeature(MEMENTO_FEATURE_ID); +} + +export function useMementoMode() { + return useMementoInput().mode; +} + +export function useMementoHome() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "home"], + execute: ({ signal }) => input.getHome({ signal }), + }); +} + +export function useLibrary(query: LibraryQuery = {}) { + const input = useMementoInput(); + const stable = query; + return useApplicationQuery({ + queryKey: ["memento", "library", stable], + execute: ({ signal }) => input.getLibrary(stable, { signal }), + }); +} + +export function useMemories(query: MemoryQuery = {}) { + const input = useMementoInput(); + const stable = query; + return useApplicationQuery({ + queryKey: ["memento", "memories", stable], + execute: ({ signal }) => input.getMemories(stable, { signal }), + }); +} + +export function useMemory(memoryId: string) { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "memory", memoryId], + execute: ({ signal }) => input.getMemory(memoryId, { signal }), + enabled: memoryId.length > 0, + }); +} + +export function useMemoryCandidates() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "memory-candidates"], + execute: ({ signal }) => input.getMemoryCandidates({ signal }), + }); +} + +export function useAlbums(query: AlbumQuery = {}) { + const input = useMementoInput(); + const stable = query; + return useApplicationQuery({ + queryKey: ["memento", "albums", stable], + execute: ({ signal }) => input.getAlbums(stable, { signal }), + }); +} + +export function useAlbum(albumId: string) { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "album", albumId], + execute: ({ signal }) => input.getAlbum(albumId, { signal }), + enabled: albumId.length > 0, + }); +} + +export function useSearch(query: string) { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "search", query], + execute: ({ signal }) => input.search(query, { signal }), + enabled: query.trim().length > 0, + }); +} + +export function usePeople() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "people"], + execute: ({ signal }) => input.getPeople({ signal }), + }); +} + +export function usePlaces() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "places"], + execute: ({ signal }) => input.getPlaces({ signal }), + }); +} + +export function useDevices() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "devices"], + execute: ({ signal }) => input.getDevices({ signal }), + }); +} + +export function useStorageSettings() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "storage-settings"], + execute: () => input.getStorageSettings(), + }); +} + +export function useAccount() { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "account"], + execute: () => input.getAccount(), + }); +} + +export function useDeviceBackupPolicy(deviceId: string) { + const input = useMementoInput(); + return useApplicationQuery({ + queryKey: ["memento", "device-backup-policy", deviceId], + execute: () => input.getDeviceBackupPolicy(deviceId), + enabled: deviceId.length > 0, + }); +} + +export function useUpdateDeviceBackupPolicy() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-update-device-backup-policy-v1", + definitionVersion: 1, + operationId: "MEMENTO_UPDATE_DEVICE_BACKUP_POLICY", + requiresIdempotencyKey: false, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: ( + command: Readonly<{ + deviceId: string; + policy: Parameters[1]; + }>, + context, + ) => + input.updateDeviceBackupPolicy( + command.deviceId, + command.policy, + context, + ), + }); +} + +export function useDisconnectDevice() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-disconnect-device-v1", + definitionVersion: 1, + operationId: "MEMENTO_DISCONNECT_DEVICE", + requiresIdempotencyKey: true, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: (deviceId: string, context) => + input.disconnectDevice(deviceId, context), + }); +} + +export function useRunStorageIntegrityScan() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-storage-integrity-scan-v1", + definitionVersion: 1, + operationId: "MEMENTO_RUN_INTEGRITY_SCAN", + requiresIdempotencyKey: true, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: (_: undefined, context) => + input.runStorageIntegrityScan(context), + }); +} + +export function useSaveMemoryCandidate() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-save-memory-candidate-v1", + definitionVersion: 1, + operationId: "MEMENTO_SAVE_MEMORY_CANDIDATE", + requiresIdempotencyKey: true, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: (candidateId: string, context) => + input.saveMemoryCandidate(candidateId, context), + }); +} + +export function useCreateAlbum() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-create-album-v1", + definitionVersion: 1, + operationId: "MEMENTO_CREATE_ALBUM", + requiresIdempotencyKey: true, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: (command: CreateAlbumInput, context) => + input.createAlbum(command, context), + }); +} + +export function useUpdateMemory() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-update-memory-v1", + definitionVersion: 1, + operationId: "MEMENTO_UPDATE_MEMORY", + requiresIdempotencyKey: false, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: ( + command: Readonly<{ id: string; input: UpdateMemoryInput }>, + context, + ) => input.updateMemory(command.id, command.input, context), + }); +} + +export function useUpdateAlbum() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-update-album-v1", + definitionVersion: 1, + operationId: "MEMENTO_UPDATE_ALBUM", + requiresIdempotencyKey: false, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: ( + command: Readonly<{ id: string; input: UpdateAlbumInput }>, + context, + ) => input.updateAlbum(command.id, command.input, context), + }); +} + +export function useCreateShare() { + const input = useMementoInput(); + const scope = useServerStateScope(); + return useApplicationMutation({ + definitionId: "memento-create-share-v1", + definitionVersion: 1, + operationId: "MEMENTO_CREATE_SHARE", + requiresIdempotencyKey: true, + owner: MEMENTO_FEATURE_ID, + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + invalidate: Object.freeze([]), + execute: ( + command: Readonly<{ + target: ShareTarget; + input: CreateShareInput; + }>, + context, + ) => input.createShare(command.target, command.input, context), + }); +} diff --git a/src/features/memento-web/presentation/layouts/memento-app-shell.tsx b/src/features/memento-web/presentation/layouts/memento-app-shell.tsx new file mode 100644 index 0000000..bb3da9c --- /dev/null +++ b/src/features/memento-web/presentation/layouts/memento-app-shell.tsx @@ -0,0 +1,111 @@ +import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom"; +import { MementoIcon } from "../components/icons.tsx"; +import { MementoOverlays } from "../overlays/memento-overlays.tsx"; +import { MementoUiProvider, useMementoUi } from "../memento-ui-context.tsx"; + +const primary = [ + { to: "/", label: "홈", icon: "home" as const, end: true }, + { to: "/library", label: "라이브러리", icon: "grid" as const, end: false }, + { to: "/memories", label: "Memories", icon: "spark" as const, end: false }, + { to: "/search", label: "검색", icon: "search" as const, end: false }, +] as const; + +export function MementoAppShell() { + return ( + + + + ); +} + +function MementoShellContent() { + const ui = useMementoUi(); + const location = useLocation(); + const navigate = useNavigate(); + const authSurface = + location.pathname === "/login" || location.pathname === "/register"; + + if (authSurface) { + return ( +
+ +
+ ); + } + + return ( +
+ + +
+ + + Memento + + +
+ +
+ +
+ + + + +
+ ); +} diff --git a/src/features/memento-web/presentation/memento-demo-model.ts b/src/features/memento-web/presentation/memento-demo-model.ts new file mode 100644 index 0000000..4e619e3 --- /dev/null +++ b/src/features/memento-web/presentation/memento-demo-model.ts @@ -0,0 +1,53 @@ +export const PHOTO_URLS = Object.freeze( + Array.from({ length: 11 }, (_, index) => `/assets/photo-${index + 1}.jpg`), +); + +export const DEMO_MEMORY_CARDS = Object.freeze([ + { id: "memory-gangneung", title: "강릉에서 보낸 주말", meta: "1년 전 오늘", photo: 2, count: 67 }, + { id: "memory-gapyeong", title: "가평 드라이브", meta: "지난 가을", photo: 3, count: 41 }, + { id: "memory-busan", title: "처음 떠난 부산", meta: "3년 전", photo: 4, count: 108 }, +]); + +export const DEMO_MEMORIES = Object.freeze([ + { id: "memory-gangneung", title: "강릉에서 보낸 주말", meta: "1년 전 오늘 · 67개", photo: 2, count: 67, type: "Memory" }, + { id: "memory-gapyeong", title: "가평 드라이브", meta: "2025.10.03 · 41개", photo: 3, count: 41, type: "자동 Memory" }, + { id: "memory-seoul", title: "서울의 겨울", meta: "2025.12 — 2026.02 · 123개", photo: 5, count: 123, type: "자동 Memory" }, + { id: "memory-busan", title: "처음 떠난 부산", meta: "2023.08.18 — 08.21 · 108개", photo: 8, count: 108, type: "자동 Memory" }, +]); + +export const DEMO_MANUAL_ALBUMS = Object.freeze([ + { id: "album-spring", title: "평범했던 봄", meta: "2025.03 — 05 · 96개", photo: 10, count: 96, type: "Album" }, + { id: "album-mountain", title: "산으로 간 날", meta: "2024.11.02 · 34개", photo: 11, count: 34, type: "Album" }, +]); + +export const DEMO_ALBUMS = Object.freeze([ + { id: "album-family", title: "가족 사진", meta: "124개 · 최근 수정 9월 14일", photo: 6, count: 124, shared: false }, + { id: "album-profile", title: "프로필 후보", meta: "48개 · 최근 수정 9월 10일", photo: 9, count: 48, shared: false }, + { id: "album-jeju", title: "2026 제주 베스트", meta: "36개 · 공유 중", photo: 1, count: 36, shared: true }, + { id: "album-dog", title: "강아지", meta: "82개 · 최근 수정 8월 21일", photo: 11, count: 82, shared: false }, + { id: "album-interior", title: "인테리어 참고", meta: "64개 · 최근 수정 8월 08일", photo: 5, count: 64, shared: false }, + { id: "album-friends", title: "친구들과", meta: "91개 · 공유 중", photo: 3, count: 91, shared: true }, +]); + +export const LIBRARY_GROUPS = Object.freeze([ + { label: "9월 15일", meta: "오늘 · Galaxy에서 42개 동기화됨", offset: 0 }, + { label: "9월 13일", meta: "서울 · 24개 항목", offset: 4 }, + { label: "8월 29일", meta: "강릉 · 18개 항목", offset: 7 }, +]); + +export const LIBRARY_LAYOUT = Object.freeze([ + "large", "wide", "tall", "", "wide", "", "tall", "", "", "wide", "", "", +]); + +export const PEOPLE = Object.freeze([ + { id: "person-me", name: "나", initial: "나", media: 842, memories: 18, tone: "tone-a" }, + { id: "person-family", name: "가족", initial: "가", media: 381, memories: 12, tone: "tone-b" }, + { id: "person-friends", name: "친구", initial: "친", media: 264, memories: 8, tone: "tone-c" }, +]); + +export const PLACES = Object.freeze([ + { id: "place-jeju", name: "제주도", media: 168, visits: 4, photo: 1, bbox: "126.13%2C33.15%2C126.95%2C33.58" }, + { id: "place-seoul", name: "서울", media: 624, visits: 38, photo: 5, bbox: "126.76%2C37.42%2C127.18%2C37.70" }, + { id: "place-gangneung", name: "강릉", media: 91, visits: 3, photo: 2, bbox: "128.78%2C37.65%2C129.12%2C37.86" }, + { id: "place-busan", name: "부산", media: 108, visits: 2, photo: 8, bbox: "128.85%2C35.02%2C129.30%2C35.30" }, +]); diff --git a/src/features/memento-web/presentation/memento-feature-runtime.tsx b/src/features/memento-web/presentation/memento-feature-runtime.tsx new file mode 100644 index 0000000..c68162b --- /dev/null +++ b/src/features/memento-web/presentation/memento-feature-runtime.tsx @@ -0,0 +1,89 @@ +import { lazy } from "react"; + +import { MEMENTO_FEATURE_ID } from "../contracts/memento-feature-contract.ts"; +import { + mementoAlbumParamsSchema, + mementoDetailSearchSchema, + mementoLibrarySearchSchema, + mementoMemoryParamsSchema, + mementoPersonParamsSchema, + mementoPlaceParamsSchema, + mementoSettingsSearchSchema, +} from "../contracts/memento-route-schemas.ts"; +import { MementoAppShell } from "./layouts/memento-app-shell.tsx"; + +export const MEMENTO_FEATURE_ROUTE_CODECS = { + MementoLibrarySearch: mementoLibrarySearchSchema, + MementoDetailSearch: mementoDetailSearchSchema, + MementoMemoryParams: mementoMemoryParamsSchema, + MementoAlbumParams: mementoAlbumParamsSchema, + MementoPersonParams: mementoPersonParamsSchema, + MementoPlaceParams: mementoPlaceParamsSchema, + MementoSettingsSearch: mementoSettingsSearchSchema, +} as const; + +export const MEMENTO_FEATURE_ROUTE_RUNTIME = { + APP_HOME: Object.freeze({ + moduleId: "memento-home-page", + Component: lazy(() => import("./pages/memento-home-page.tsx")), + }), + MEMENTO_LIBRARY: Object.freeze({ + moduleId: "memento-library-page", + Component: lazy(() => import("./pages/memento-library-page.tsx")), + }), + MEMENTO_MEMORIES: Object.freeze({ + moduleId: "memento-memories-page", + Component: lazy(() => import("./pages/memento-memories-page.tsx")), + }), + MEMENTO_MEMORY_DETAIL: Object.freeze({ + moduleId: "memento-memory-detail-page", + Component: lazy(() => import("./pages/memento-memory-detail-page.tsx")), + }), + MEMENTO_ALBUMS: Object.freeze({ + moduleId: "memento-albums-page", + Component: lazy(() => import("./pages/memento-albums-page.tsx")), + }), + MEMENTO_ALBUM_DETAIL: Object.freeze({ + moduleId: "memento-album-detail-page", + Component: lazy(() => import("./pages/memento-album-detail-page.tsx")), + }), + MEMENTO_SEARCH: Object.freeze({ + moduleId: "memento-search-page", + Component: lazy(() => import("./pages/memento-search-page.tsx")), + }), + MEMENTO_PEOPLE: Object.freeze({ + moduleId: "memento-people-page", + Component: lazy(() => import("./pages/memento-people-page.tsx")), + }), + MEMENTO_PERSON_DETAIL: Object.freeze({ + moduleId: "memento-person-detail-page", + Component: lazy(() => import("./pages/memento-person-detail-page.tsx")), + }), + MEMENTO_PLACES: Object.freeze({ + moduleId: "memento-places-page", + Component: lazy(() => import("./pages/memento-places-page.tsx")), + }), + MEMENTO_PLACE_DETAIL: Object.freeze({ + moduleId: "memento-place-detail-page", + Component: lazy(() => import("./pages/memento-place-detail-page.tsx")), + }), + MEMENTO_LOGIN: Object.freeze({ + moduleId: "memento-login-page", + Component: lazy(() => import("./pages/memento-login-page.tsx")), + }), + MEMENTO_REGISTER: Object.freeze({ + moduleId: "memento-register-page", + Component: lazy(() => import("./pages/memento-register-page.tsx")), + }), + MEMENTO_SETTINGS: Object.freeze({ + moduleId: "memento-settings-page", + Component: lazy(() => import("./pages/memento-settings-page.tsx")), + }), +} as const; + +export const MEMENTO_FEATURE_RUNTIME_CONTRIBUTION = Object.freeze({ + featureId: MEMENTO_FEATURE_ID, + routeCodecs: MEMENTO_FEATURE_ROUTE_CODECS, + routeRuntime: MEMENTO_FEATURE_ROUTE_RUNTIME, + Shell: MementoAppShell, +}); diff --git a/src/features/memento-web/presentation/memento-prototype-integration.ts b/src/features/memento-web/presentation/memento-prototype-integration.ts deleted file mode 100644 index f592fb7..0000000 --- a/src/features/memento-web/presentation/memento-prototype-integration.ts +++ /dev/null @@ -1,1124 +0,0 @@ -import type { MementoGateway } from "../application/memento-gateway.ts"; -import type { - AlbumDetail, - AlbumSummary, - DeviceBackupPolicy, - DeviceSummary, - LibraryItem, - MemoryCandidate, - MemoryDetail, - MemorySummary, - PersonSummary, - PlaceSummary, - StorageSettings, -} from "../contracts/memento-api.ts"; - -type Cleanup = () => void; -type Run = ( - task: Promise, - onSuccess?: (value: T) => void, -) => void; - -export function installMementoPrototypeIntegration( - root: HTMLElement, - gateway: MementoGateway, -): Cleanup { - let disposed = false; - let primaryDeviceId: string | null = null; - let backupPolicy: DeviceBackupPolicy | null = null; - let albumSearchTimer: ReturnType | undefined; - const cleanups: Cleanup[] = []; - const pending = new Set>(); - - const run: Run = (task: Promise, onSuccess?: (value: T) => void) => { - const guarded = task - .then((value) => { - if (!disposed) onSuccess?.(value); - }) - .catch((error: unknown) => { - if (!disposed && gateway.mode === "api") { - showToast(root, apiFailureMessage(error)); - } - }) - .finally(() => pending.delete(guarded)); - pending.add(guarded); - }; - - if (gateway.mode === "api") { - root.dataset.mementoConnectivity = - navigator.onLine === false ? "offline" : "online"; - hydrateInitialApiState(root, gateway, run); - } - - const onCommandCapture = (event: Event) => { - if (gateway.mode !== "api") return; - const target = event.target; - if (!(target instanceof Element)) return; - - const commandTarget = findApiCommandTarget(target, root); - if (!commandTarget) return; - - stopPrototypeCommand(event); - - if (navigator.onLine === false) { - showToast(root, "오프라인 · 지금은 읽기 전용으로 사용할 수 있습니다."); - return; - } - - if (commandTarget.matches("#fakeChoose")) { - root.querySelector( - '[data-memento-upload-input="files"]', - )?.click(); - return; - } - if (commandTarget.matches("[data-folder-upload]")) { - root.querySelector( - '[data-memento-upload-input="folder"]', - )?.click(); - return; - } - - if ( - commandTarget.matches("#saveSuggested") || - commandTarget.matches("[data-save-memory]") - ) { - const candidateId = - (commandTarget as HTMLElement).dataset.candidateId ?? - root.dataset.suggestedCandidateId; - if (!candidateId) { - showToast(root, "추천 Memory 정보를 불러오는 중입니다."); - return; - } - run(gateway.saveMemoryCandidate(candidateId), () => { - if (commandTarget instanceof HTMLButtonElement) { - commandTarget.textContent = "보관됨 ✓"; - commandTarget.disabled = true; - } - showToast(root, "Memory에 보관했습니다."); - loadMemories(root, gateway, run); - }); - return; - } - - if (commandTarget.matches("#confirmCreateAlbum")) { - const title = - root.querySelector("#newAlbumName")?.value.trim() || - "새로운 Album"; - run( - gateway.createAlbum({ - title, - description: null, - coverMediaId: null, - sortMode: "MANUAL", - mediaIds: [], - }), - () => { - closePrototypeOverlay(root); - navigatePrototype(root, "albums"); - loadAlbums(root, gateway, run); - showToast(root, `${title} Album을 만들었습니다.`); - }, - ); - return; - } - - if (commandTarget.matches("#applyShare")) { - const targetShare = activeShareTarget(root); - if (!targetShare) { - showToast(root, "공유할 Memory 또는 Album을 먼저 선택하세요."); - return; - } - const checks = root.querySelectorAll( - "#shareModal .check-row input[type=checkbox]", - ); - const allowDownload = checks[0]?.checked ?? false; - const useExpiry = checks[1]?.checked ?? false; - run( - gateway.createShare(targetShare, { - allowDownload, - expiresAt: useExpiry - ? new Date(Date.now() + 7 * 86_400_000).toISOString() - : null, - }), - (share) => { - root.dataset.activeShareId = share.shareId; - const shareText = - root.querySelector("#shareModal .share-link span"); - if (shareText) shareText.textContent = share.url; - closePrototypeOverlay(root); - showToast(root, "공유 설정을 저장했습니다."); - }, - ); - return; - } - - if (commandTarget.matches("#copyShare")) { - const value = - root.querySelector("#shareModal .share-link span") - ?.textContent?.trim() ?? ""; - if (!value) return; - void navigator.clipboard - .writeText(value) - .then(() => showToast(root, "공유 링크를 복사했습니다.")) - .catch(() => showToast(root, "공유 링크를 복사하지 못했습니다.")); - return; - } - - if (commandTarget.matches("#saveMemoryEdit")) { - const memoryId = root.dataset.activeMemoryId; - if (!memoryId) { - showToast(root, "편집할 Memory를 먼저 선택하세요."); - return; - } - const title = - root - .querySelector("#editMemoryModal .text-input") - ?.value.trim() || undefined; - const autoUpdate = - root.querySelector( - "#editMemoryModal .check-row input[type=checkbox]", - )?.checked ?? true; - run(gateway.updateMemory(memoryId, { title, autoUpdate }), (memory) => { - hydrateMemoryDetail(root, memory); - closePrototypeOverlay(root); - loadMemories(root, gateway, run); - showToast(root, "Memory 편집 내용을 저장했습니다."); - }); - return; - } - - if (commandTarget.matches("#actionConfirm")) { - const action = root - .querySelector("#actionTitle") - ?.textContent?.trim(); - if (action === "Album 편집") { - const albumId = root.dataset.activeAlbumId; - if (!albumId) { - showToast(root, "편집할 Album을 먼저 선택하세요."); - return; - } - const fields = root.querySelectorAll( - "#actionBody .text-input", - ); - const title = fields[0]?.value.trim() || undefined; - const description = fields[1]?.value.trim() || null; - run( - gateway.updateAlbum(albumId, { title, description }), - (album) => { - hydrateAlbumDetail(root, album); - closePrototypeOverlay(root); - loadAlbums(root, gateway, run); - showToast(root, "Album 정보를 저장했습니다."); - }, - ); - return; - } - // Album management prototype contains no concrete choice control yet. - // Do not report a fake successful mutation in API mode. - showToast(root, "적용할 Album 관리 작업을 먼저 선택하세요."); - return; - } - - if (commandTarget.matches("[data-album-order]")) { - const albumId = root.dataset.activeAlbumId; - if (!albumId) return; - const button = commandTarget as HTMLElement; - const nextManual = button.textContent?.trim() !== "직접 설정"; - run( - gateway.updateAlbum(albumId, { - sortMode: nextManual ? "MANUAL" : "CAPTURE_TIME", - }), - () => { - button.textContent = nextManual ? "직접 설정" : "촬영일 순"; - showToast(root, `Album 정렬 방식을 ${button.textContent}으로 변경했습니다.`); - }, - ); - return; - } - - if ( - commandTarget.matches("[data-toast]") && - (commandTarget as HTMLElement).dataset.toast?.includes("무결성 검사를 시작") - ) { - run(gateway.runStorageIntegrityScan(), () => - showToast(root, "무결성 검사를 시작했습니다."), - ); - return; - } - - if (commandTarget.matches("[data-device-disconnect]")) { - const deviceId = (commandTarget as HTMLElement).dataset.deviceId; - if (!deviceId) return; - run(gateway.disconnectDevice(deviceId), () => { - showToast(root, "기기 연결을 해제했습니다."); - loadDevices(root, gateway, run, (id) => { - primaryDeviceId = id; - }); - }); - return; - } - - if (commandTarget.matches("#settingsContent [data-toggle]")) { - if (!primaryDeviceId || !backupPolicy) { - showToast(root, "백업 설정을 불러오는 중입니다."); - return; - } - const toggles = Array.from( - root.querySelectorAll("#settingsContent [data-toggle]"), - ); - const index = toggles.indexOf(commandTarget as HTMLElement); - const current = backupPolicy; - const next: DeviceBackupPolicy = { - ...current, - enabled: index === 0 ? !current.enabled : current.enabled, - wifiOnly: index === 1 ? !current.wifiOnly : current.wifiOnly, - includeVideos: - index === 2 ? !current.includeVideos : current.includeVideos, - }; - run(gateway.updateDeviceBackupPolicy(primaryDeviceId, next), (saved) => { - backupPolicy = saved; - applyBackupToggleState(root, saved); - showToast(root, "모바일 백업 설정을 저장했습니다."); - }); - return; - } - - if ( - commandTarget.matches(".selection-bar button") && - commandTarget.textContent?.includes("즐겨찾기") - ) { - const selected = selectedMediaIds(root); - if (selected.length === 0) return; - run( - Promise.all( - selected.map((mediaId) => gateway.setMediaFavorite(mediaId, true)), - ), - () => { - root.querySelector("#clearSelection")?.click(); - showToast(root, `${selected.length}개 항목을 즐겨찾기에 추가했습니다.`); - }, - ); - } - }; - - root.addEventListener("click", onCommandCapture, true); - cleanups.push(() => - root.removeEventListener("click", onCommandCapture, true), - ); - - const onClick = (event: Event) => { - const target = event.target; - if (!(target instanceof Element)) return; - - const pageButton = target.closest("[data-page]"); - if (pageButton?.dataset.page && gateway.mode === "api") { - loadPage(root, gateway, pageButton.dataset.page, run, { - onPrimaryDevice: (id) => { - primaryDeviceId = id; - }, - onBackupPolicy: (policy) => { - backupPolicy = policy; - }, - }); - } - - const memoryCard = target.closest("[data-open-memory]"); - if (memoryCard?.dataset.memoryId) { - root.dataset.activeMemoryId = memoryCard.dataset.memoryId; - if (gateway.mode === "api") { - run(gateway.getMemory(memoryCard.dataset.memoryId), (memory) => - hydrateMemoryDetail(root, memory), - ); - } - } - - const albumCard = target.closest("[data-open-album]"); - if (albumCard?.dataset.albumId) { - root.dataset.activeAlbumId = albumCard.dataset.albumId; - if (gateway.mode === "api") { - run(gateway.getAlbum(albumCard.dataset.albumId), (album) => - hydrateAlbumDetail(root, album), - ); - } - } - - const media = target.closest("[data-media-id]"); - if (media?.dataset.mediaId) { - root.dataset.activeMediaId = media.dataset.mediaId; - } - - if (gateway.mode !== "api") return; - - const filter = target.closest("[data-filter]"); - if (filter?.dataset.filter === "duplicate") { - run(gateway.getDuplicateGroups()); - run(gateway.getLibrary({ state: "DUPLICATE_CANDIDATE" }), (page) => - hydrateLibrary(root, page.items), - ); - } else if (filter?.dataset.filter === "unorganized") { - run(gateway.getLibrary({ state: "UNORGANIZED" }), (page) => - hydrateLibrary(root, page.items), - ); - } - - if (target.closest("[data-duplicate]")) { - run(gateway.getDuplicateGroups()); - run(gateway.getLibrary({ state: "DUPLICATE_CANDIDATE" }), (page) => - hydrateLibrary(root, page.items), - ); - } - - const mediaType = target.closest("[data-media-type]"); - if (mediaType?.dataset.mediaType) { - const value = mediaType.dataset.mediaType; - if (value === "즐겨찾기") { - run(gateway.getLibrary({ favorite: true }), (page) => - hydrateLibrary(root, page.items), - ); - } else { - run( - gateway.getLibrary({ - mediaType: value === "동영상" ? "VIDEO" : value, - }), - (page) => hydrateLibrary(root, page.items), - ); - } - } - - const year = target.closest("[data-year]")?.dataset.year; - if (year) { - run(gateway.getLibrary({ year: Number(year) }), (page) => - hydrateLibrary(root, page.items), - ); - } - - const albumFilter = - target.closest("[data-album-filter]")?.dataset.albumFilter; - if (albumFilter) { - run( - gateway.getAlbums({ - limit: 50, - ...(albumFilter === "shared" ? { shared: true } : {}), - }), - (page) => hydrateAlbums(root, page.items), - ); - } - - const settingsButton = target.closest( - "[data-settings],[data-profile-page]", - ); - const settingsKind = - settingsButton?.dataset.settings ?? settingsButton?.dataset.profilePage; - if (settingsKind === "devices") { - loadDevices(root, gateway, run, (id) => { - primaryDeviceId = id; - }); - } else if (settingsKind === "backup-settings") { - loadDevices(root, gateway, run, (id) => { - primaryDeviceId = id; - if (id) { - run(gateway.getDeviceBackupPolicy(id), (policy) => { - backupPolicy = policy; - applyBackupToggleState(root, policy); - }); - } - }); - } else if (settingsKind === "storage") { - run(gateway.getStorageSettings(), (settings) => - hydrateStorageSettings(root, settings), - ); - } else if (settingsKind === "account") { - run(gateway.getAccount(), (account) => hydrateAccount(root, account)); - } - }; - - root.addEventListener("click", onClick); - cleanups.push(() => root.removeEventListener("click", onClick)); - - const onKeyDown = (event: KeyboardEvent) => { - if (event.key !== "Enter" || gateway.mode !== "api") return; - const input = event.target; - if (!(input instanceof HTMLInputElement)) return; - - if (input.closest(".big-search")) { - const query = input.value.trim(); - if (query) { - run(gateway.search(query), (result) => { - hydratePeople(root, result.people); - hydratePlaces(root, result.places); - hydrateAlbums(root, result.albums); - hydrateMemories(root, result.memories); - hydrateLibrary(root, result.media); - }); - } - return; - } - - if (input.closest("#page-library")) { - const query = input.value.trim(); - if (query) { - run(gateway.getLibrary({ search: query }), (page) => - hydrateLibrary(root, page.items), - ); - } - } - }; - - root.addEventListener("keydown", onKeyDown); - cleanups.push(() => root.removeEventListener("keydown", onKeyDown)); - - const albumSearch = root.querySelector("#albumSearch"); - if (albumSearch && gateway.mode === "api") { - const onAlbumSearch = () => { - if (albumSearchTimer !== undefined) clearTimeout(albumSearchTimer); - albumSearchTimer = setTimeout(() => { - run(gateway.getAlbums({ search: albumSearch.value.trim(), limit: 50 }), (page) => - hydrateAlbums(root, page.items), - ); - }, 200); - }; - albumSearch.addEventListener("input", onAlbumSearch); - cleanups.push(() => { - albumSearch.removeEventListener("input", onAlbumSearch); - if (albumSearchTimer !== undefined) clearTimeout(albumSearchTimer); - }); - } - - if (gateway.mode === "api") { - cleanups.push(installUploadPicker(root, gateway, run)); - cleanups.push(installConnectivityBoundary(root)); - } - - return () => { - disposed = true; - for (const cleanup of cleanups.reverse()) cleanup(); - pending.clear(); - }; -} - -function hydrateInitialApiState( - root: HTMLElement, - gateway: MementoGateway, - run: Run, -): void { - run(gateway.getCapabilities()); - run(gateway.getHome(), (home) => { - root.dataset.suggestedCandidateId = - home.suggestedMemory?.candidateId ?? ""; - root - .querySelectorAll("#saveSuggested,[data-save-memory]") - .forEach((button) => { - if (home.suggestedMemory) { - button.dataset.candidateId = home.suggestedMemory.candidateId; - } - }); - const unorganized = root.querySelector("[data-unorganized]"); - const duplicate = root.querySelector("[data-duplicate]"); - if (unorganized) { - unorganized.dataset.count = String(home.repository.unorganizedCount); - } - if (duplicate) { - duplicate.dataset.count = String(home.repository.duplicateCandidateCount); - } - }); - loadLibrary(root, gateway, run); - loadMemories(root, gateway, run); - loadAlbums(root, gateway, run); -} - -function findApiCommandTarget( - target: Element, - root: HTMLElement, -): HTMLElement | null { - const direct = target.closest( - [ - "#saveSuggested", - "[data-save-memory]", - "#confirmCreateAlbum", - "#applyShare", - "#copyShare", - "#saveMemoryEdit", - "#fakeChoose", - "[data-folder-upload]", - "[data-album-order]", - "[data-device-disconnect]", - "#settingsContent [data-toggle]", - ".selection-bar button", - ].join(","), - ); - if (direct) return direct; - - const actionConfirm = target.closest("#actionConfirm"); - if (actionConfirm && root.querySelector("#actionModal.show")) { - return actionConfirm; - } - - const toastAction = target.closest("[data-toast]"); - if (toastAction?.dataset.toast?.includes("무결성 검사를 시작")) { - return toastAction; - } - return null; -} - -function stopPrototypeCommand(event: Event): void { - event.preventDefault(); - event.stopPropagation(); -} - -function loadPage( - root: HTMLElement, - gateway: MementoGateway, - page: string, - run: Run, - state: Readonly<{ - onPrimaryDevice(id: string | null): void; - onBackupPolicy(policy: DeviceBackupPolicy): void; - }>, -): void { - if (page === "home") { - run(gateway.getHome()); - } else if (page === "library") { - loadLibrary(root, gateway, run); - } else if (page === "memories") { - loadMemories(root, gateway, run); - } else if (page === "albums") { - loadAlbums(root, gateway, run); - } else if (page === "search") { - run(gateway.getPeople(), (result) => hydratePeople(root, result.items)); - run(gateway.getPlaces(), (result) => hydratePlaces(root, result.items)); - } else if (page === "people") { - run(gateway.getPeople(), (result) => hydratePeople(root, result.items)); - } else if (page === "places-map") { - run(gateway.getPlaces(), (result) => hydratePlaces(root, result.items)); - } else if (page === "settings") { - loadDevices(root, gateway, run, (id) => { - state.onPrimaryDevice(id); - if (id) { - run(gateway.getDeviceBackupPolicy(id), state.onBackupPolicy); - } - }); - } -} - -function loadLibrary( - root: HTMLElement, - gateway: MementoGateway, - run: Run, -): void { - run(gateway.getLibrary({ limit: 50 }), (result) => - hydrateLibrary(root, result.items), - ); -} - -function loadAlbums( - root: HTMLElement, - gateway: MementoGateway, - run: Run, -): void { - run(gateway.getAlbums({ limit: 50 }), (result) => - hydrateAlbums(root, result.items), - ); -} - -function loadMemories( - root: HTMLElement, - gateway: MementoGateway, - run: Run, -): void { - run(gateway.getMemories({ limit: 50 }), (result) => - hydrateMemories(root, result.items), - ); - run(gateway.getMemoryCandidates(), (result) => - hydrateCandidates(root, result.items), - ); -} - -function loadDevices( - root: HTMLElement, - gateway: MementoGateway, - run: Run, - onPrimaryDevice: (id: string | null) => void, -): void { - run(gateway.getDevices(), (result) => { - onPrimaryDevice(result.items[0]?.id ?? null); - hydrateDevices(root, result.items); - }); -} - -function hydrateLibrary(root: HTMLElement, items: readonly LibraryItem[]): void { - const tiles = Array.from(root.querySelectorAll(".media-tile")); - tiles.forEach((tile, index) => { - const item = items[index]; - if (!item) return; - tile.dataset.mediaId = item.id; - const image = tile.querySelector("img"); - if (image && item.thumbnailUrl) image.src = item.thumbnailUrl; - }); - - const today = Array.from( - root.querySelectorAll("#todayGrid .viewable"), - ); - today.forEach((tile, index) => { - const item = items[index]; - const image = tile.querySelector("img"); - if (item) { - tile.dataset.mediaId = item.id; - if (image && item.thumbnailUrl) image.src = item.thumbnailUrl; - } - }); -} - -function hydrateAlbums(root: HTMLElement, items: readonly AlbumSummary[]): void { - bindCards( - Array.from( - root.querySelectorAll( - "#albumsPageGrid [data-open-album]", - ), - ), - items, - "albumId", - (item) => item.title, - (item) => `${item.mediaCount}개${item.shared ? " · 공유 중" : ""}`, - (item) => item.cover?.thumbnailUrl, - ); - bindCards( - Array.from( - root.querySelectorAll("#manualAlbums [data-open-album]"), - ), - items, - "albumId", - (item) => item.title, - (item) => `${item.mediaCount}개`, - (item) => item.cover?.thumbnailUrl, - ); -} - -function hydrateAlbumDetail(root: HTMLElement, album: AlbumDetail): void { - root.dataset.activeAlbumId = album.id; - const title = root.querySelector("#albumDetailTitle"); - const meta = root.querySelector("#albumDetailMeta"); - const cover = root.querySelector("#albumDetailCover"); - if (title) title.textContent = album.title; - if (meta) { - meta.textContent = `${album.mediaCount}개의 사진과 영상${album.updatedAt ? ` · 최근 수정 ${formatShortDate(album.updatedAt)}` : ""}`; - } - if (cover && album.cover?.thumbnailUrl) cover.src = album.cover.thumbnailUrl; - const tiles = Array.from( - root.querySelectorAll("#albumPhotos .viewable"), - ); - album.items?.forEach((item, index) => { - const tile = tiles[index]; - if (!tile) return; - tile.dataset.mediaId = item.id; - const image = tile.querySelector("img"); - if (image && item.thumbnailUrl) image.src = item.thumbnailUrl; - }); -} - -function hydrateMemories( - root: HTMLElement, - items: readonly MemorySummary[], -): void { - bindCards( - Array.from( - root.querySelectorAll( - "#savedMemories [data-open-memory]", - ), - ), - items, - "memoryId", - (item) => item.title, - (item) => (item.mediaCount ? `${item.mediaCount}개` : ""), - (item) => item.cover?.thumbnailUrl, - ); -} - -function hydrateMemoryDetail(root: HTMLElement, memory: MemoryDetail): void { - root.dataset.activeMemoryId = memory.id; - const title = root.querySelector("#memoryDetailTitle"); - const meta = root.querySelector("#memoryDetailMeta"); - const cover = root.querySelector("#memoryDetailCover"); - if (title) title.textContent = memory.title; - if (meta) { - const places = memory.placeNames?.join(" · "); - meta.textContent = [ - memory.startAt && memory.endAt - ? `${formatShortDate(memory.startAt)} — ${formatShortDate(memory.endAt)}` - : null, - places || null, - memory.mediaCount ? `${memory.mediaCount}개의 사진과 영상` : null, - ] - .filter(Boolean) - .join(" · "); - } - if (cover && memory.cover?.thumbnailUrl) cover.src = memory.cover.thumbnailUrl; - const tiles = Array.from( - root.querySelectorAll("#memoryPhotos .viewable"), - ); - memory.items?.forEach((item, index) => { - const tile = tiles[index]; - if (!tile) return; - tile.dataset.mediaId = item.id; - const image = tile.querySelector("img"); - if (image && item.thumbnailUrl) image.src = item.thumbnailUrl; - }); -} - -function hydrateCandidates( - root: HTMLElement, - items: readonly MemoryCandidate[], -): void { - const first = items[0]; - if (!first) return; - root.dataset.suggestedCandidateId = first.id; - root - .querySelectorAll("#saveSuggested,[data-save-memory]") - .forEach((button) => { - button.dataset.candidateId = first.id; - }); -} - -function hydratePeople(root: HTMLElement, items: readonly PersonSummary[]): void { - const nodes = Array.from(root.querySelectorAll("[data-person]")); - nodes.forEach((node, index) => { - const item = items[index]; - if (!item) return; - node.dataset.personId = item.id; - if (item.displayName) node.dataset.person = item.displayName; - const label = node.querySelector("strong,span"); - if (label && item.displayName) label.textContent = item.displayName; - }); -} - -function hydratePlaces(root: HTMLElement, items: readonly PlaceSummary[]): void { - const nodes = Array.from( - root.querySelectorAll("[data-place-name]"), - ); - nodes.forEach((node, index) => { - const item = items[index]; - if (!item) return; - node.dataset.placeId = item.id; - node.dataset.placeName = item.name; - const title = node.querySelector("strong"); - if (title) title.textContent = item.name; - }); -} - -function hydrateDevices(root: HTMLElement, items: readonly DeviceSummary[]): void { - const rows = Array.from( - root.querySelectorAll("#settingsContent .device-row"), - ); - rows.forEach((row, index) => { - const device = items[index]; - if (!device) return; - row.dataset.deviceId = device.id; - const title = row.querySelector("strong"); - const paragraph = row.querySelector("p"); - if (title) title.textContent = device.name; - if (paragraph) { - paragraph.textContent = [ - device.lastSyncAt ? `${formatShortDate(device.lastSyncAt)} 동기화` : null, - device.platform, - device.status, - ] - .filter(Boolean) - .join(" · "); - } - const disconnect = row.querySelector("button"); - if (disconnect) { - disconnect.dataset.deviceDisconnect = "true"; - disconnect.dataset.deviceId = device.id; - delete disconnect.dataset.toast; - } - }); -} - -function hydrateStorageSettings( - root: HTMLElement, - settings: StorageSettings, -): void { - const cards = root.querySelectorAll("#settingsContent .settings-card"); - const storage = cards[0]; - if (storage) { - const strong = storage.querySelector("strong"); - const paragraph = storage.querySelector("p"); - if (strong) strong.textContent = formatBytes(settings.quotaBytes); - if (paragraph) { - paragraph.textContent = `${formatBytes(settings.originalBytes)} 사용 · ${formatBytes(settings.freeBytes)} 남음`; - } - } -} - -function hydrateAccount( - root: HTMLElement, - account: Readonly>, -): void { - const card = root.querySelector("#settingsContent .settings-card"); - const paragraph = card?.querySelector("p"); - if (!paragraph) return; - const username = - typeof account["username"] === "string" ? account["username"] : "계정"; - const verified = account["emailVerified"] === true ? "이메일 인증 완료" : ""; - paragraph.textContent = [username, verified].filter(Boolean).join(" · "); -} - -function applyBackupToggleState( - root: HTMLElement, - policy: DeviceBackupPolicy, -): void { - const toggles = root.querySelectorAll( - "#settingsContent [data-toggle]", - ); - const states = [policy.enabled, policy.wifiOnly, policy.includeVideos]; - toggles.forEach((toggle, index) => { - toggle.classList.toggle("on", states[index] ?? false); - }); -} - -function bindCards( - cards: readonly HTMLElement[], - items: readonly T[], - idKey: "albumId" | "memoryId", - title: (item: T) => string, - meta: (item: T) => string, - imageUrl: (item: T) => string | undefined, -): void { - cards.forEach((card, index) => { - const item = items[index] as (T & { id?: string }) | undefined; - if (!item) return; - if (item.id) card.dataset[idKey] = item.id; - const titleNode = card.querySelector(".memory-info strong"); - const metaNode = card.querySelector(".memory-info span"); - const image = card.querySelector("img"); - if (titleNode) titleNode.textContent = title(item); - if (metaNode) metaNode.textContent = meta(item); - const src = imageUrl(item); - if (image && src) image.src = src; - }); -} - -function installUploadPicker( - root: HTMLElement, - gateway: MementoGateway, - run: Run, -): Cleanup { - const fileInput = document.createElement("input"); - fileInput.type = "file"; - fileInput.multiple = true; - fileInput.accept = "image/*,video/*"; - fileInput.hidden = true; - fileInput.dataset.mementoUploadInput = "files"; - - const folderInput = document.createElement("input"); - folderInput.type = "file"; - folderInput.multiple = true; - folderInput.accept = "image/*,video/*"; - folderInput.hidden = true; - folderInput.setAttribute("webkitdirectory", ""); - folderInput.dataset.mementoUploadInput = "folder"; - - root.append(fileInput, folderInput); - - const onFiles = (event: Event) => { - const input = event.currentTarget; - if (!(input instanceof HTMLInputElement) || !input.files) return; - const files = Array.from(input.files); - if (files.length === 0) return; - run(uploadFilesSequentially(root, gateway, files), () => { - showToast(root, `${files.length}개 항목 업로드를 완료했습니다.`); - loadLibrary(root, gateway, run); - }); - input.value = ""; - }; - fileInput.addEventListener("change", onFiles); - folderInput.addEventListener("change", onFiles); - - const dropzone = root.querySelector("#uploadModal .dropzone"); - const onDragOver = (event: DragEvent) => { - event.preventDefault(); - }; - const onDrop = (event: DragEvent) => { - event.preventDefault(); - const files = Array.from(event.dataTransfer?.files ?? []); - if (files.length === 0) return; - run(uploadFilesSequentially(root, gateway, files), () => { - showToast(root, `${files.length}개 항목 업로드를 완료했습니다.`); - loadLibrary(root, gateway, run); - }); - }; - dropzone?.addEventListener("dragover", onDragOver); - dropzone?.addEventListener("drop", onDrop); - - return () => { - fileInput.removeEventListener("change", onFiles); - folderInput.removeEventListener("change", onFiles); - dropzone?.removeEventListener("dragover", onDragOver); - dropzone?.removeEventListener("drop", onDrop); - fileInput.remove(); - folderInput.remove(); - }; -} - -function installConnectivityBoundary(root: HTMLElement): Cleanup { - const update = () => { - const offline = navigator.onLine === false; - root.dataset.mementoConnectivity = offline ? "offline" : "online"; - if (offline) { - showToast(root, "오프라인 · 저장된 화면은 읽기 전용으로 사용할 수 있습니다."); - } else { - showToast(root, "온라인 연결이 복구되었습니다."); - } - }; - window.addEventListener("online", update); - window.addEventListener("offline", update); - return () => { - window.removeEventListener("online", update); - window.removeEventListener("offline", update); - }; -} - -async function uploadFilesSequentially( - root: HTMLElement, - gateway: MementoGateway, - files: readonly File[], -): Promise { - const queue = root.querySelector("#uploadQueue"); - if (queue) queue.style.display = "block"; - - for (const file of files) { - const deviceLocalAssetId = [ - "web", - file.name, - file.size, - file.lastModified, - ].join(":"); - - const preflight = await gateway.preflightUpload({ - deviceId: null, - deviceLocalAssetId, - filename: file.name, - sizeBytes: file.size, - mimeType: file.type || "application/octet-stream", - clientSha256: null, - takenAtHint: new Date(file.lastModified).toISOString(), - }); - - if (preflight.decision === "ALREADY_EXISTS") { - showToast(root, `${file.name} · 이미 저장된 원본입니다.`); - continue; - } - - let uploadSessionId: string; - let offset: number; - let chunkSize: number; - - if (preflight.decision === "RESUME") { - uploadSessionId = preflight.uploadSessionId; - offset = preflight.receivedBytes; - chunkSize = 8 * 1024 * 1024; - } else { - const session = await gateway.createUploadSession({ - deviceId: null, - deviceLocalAssetId, - sourceType: "WEB_MANUAL", - filename: file.name, - expectedSize: file.size, - mimeType: file.type || "application/octet-stream", - clientSha256: null, - }); - uploadSessionId = session.uploadSessionId; - offset = session.offset; - chunkSize = session.chunkSize || preflight.recommendedChunkSize; - } - - try { - while (offset < file.size) { - const chunk = file.slice(offset, Math.min(offset + chunkSize, file.size)); - offset = await gateway.appendUploadChunk(uploadSessionId, offset, chunk); - } - await gateway.commitUpload(uploadSessionId); - } catch (error) { - try { - await gateway.abortUpload(uploadSessionId); - } catch { - // Preserve the original upload failure. - } - throw error; - } - } -} - -function activeShareTarget( - root: HTMLElement, -): - | Readonly<{ type: "album"; id: string }> - | Readonly<{ type: "memory"; id: string }> - | null { - const activePage = root.querySelector(".page.active")?.id; - if (activePage === "page-album" && root.dataset.activeAlbumId) { - return { type: "album", id: root.dataset.activeAlbumId }; - } - if (activePage === "page-memory" && root.dataset.activeMemoryId) { - return { type: "memory", id: root.dataset.activeMemoryId }; - } - return null; -} - -function selectedMediaIds(root: HTMLElement): readonly string[] { - return Array.from( - root.querySelectorAll(".media-tile.selected[data-media-id]"), - ) - .map((item) => item.dataset.mediaId) - .filter((value): value is string => Boolean(value)); -} - -function closePrototypeOverlay(root: HTMLElement): void { - root.querySelector("#scrim")?.classList.remove("show"); - root - .querySelectorAll(".modal.show,.drawer.show") - .forEach((element) => element.classList.remove("show")); -} - -function navigatePrototype(root: HTMLElement, page: string): void { - root - .querySelector(`[data-page="${page}"]`) - ?.click(); -} - -function apiFailureMessage(error: unknown): string { - if ( - error && - typeof error === "object" && - "status" in error && - error.status === 401 - ) { - return "로그인이 필요합니다."; - } - if (error instanceof Error && error.message) { - return `API 연결 실패 · ${error.message}`; - } - return "API 연결 실패 · 서버 상태를 확인하세요."; -} - -function formatShortDate(value: string): string { - const parsed = new Date(value); - if (Number.isNaN(parsed.valueOf())) return value; - return new Intl.DateTimeFormat("ko-KR", { - month: "numeric", - day: "numeric", - }).format(parsed); -} - -function formatBytes(value: number): string { - const gib = value / 1024 ** 3; - if (gib >= 1024) return `${(gib / 1024).toFixed(1)} TB`; - return `${Math.round(gib)} GB`; -} - -function showToast(root: HTMLElement, message: string): void { - const toast = root.querySelector("#toast"); - if (!toast) return; - toast.textContent = message; - toast.classList.add("show"); - window.setTimeout(() => toast.classList.remove("show"), 2400); -} diff --git a/src/features/memento-web/presentation/memento-runtime-bridge.tsx b/src/features/memento-web/presentation/memento-runtime-bridge.tsx deleted file mode 100644 index d7f155c..0000000 --- a/src/features/memento-web/presentation/memento-runtime-bridge.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { useEffect } from "react"; - -import type { MementoGateway } from "../application/memento-gateway.ts"; -import { installMementoPrototypeIntegration } from "./memento-prototype-integration.ts"; - -/** - * Non-visual bridge between the exact Beta prototype DOM and the Memento input - * port. Adapter selection is a bootstrap concern; presentation only sees the - * feature-owned gateway contract. - */ -export function MementoRuntimeBridge({ - gateway, -}: Readonly<{ gateway: MementoGateway }>) { - useEffect(() => { - document.documentElement.dataset.mementoDataMode = gateway.mode; - const cleanup = installMementoPrototypeIntegration(document.body, gateway); - return () => { - cleanup(); - delete document.documentElement.dataset.mementoDataMode; - }; - }, [gateway]); - - return null; -} diff --git a/src/features/memento-web/presentation/memento-ui-context.tsx b/src/features/memento-web/presentation/memento-ui-context.tsx new file mode 100644 index 0000000..19bfe93 --- /dev/null +++ b/src/features/memento-web/presentation/memento-ui-context.tsx @@ -0,0 +1,106 @@ +import type { ShareTarget } from "../application/memento-contracts.ts"; + +import { + createContext, + type ReactNode, + useCallback, + useContext, + useMemo, + useState, +} from "react"; + +export type ActionDialogState = Readonly<{ + title: string; + subtitle?: string; + body: ReactNode; + confirmLabel?: string; + onConfirm?: () => void; +}>; + +type OverlayKind = + | "profile" + | "upload" + | "create-album" + | "share" + | "edit-memory" + | "action" + | null; + +type ViewerState = Readonly<{ src: string; meta: string }> | null; + +type MementoUi = Readonly<{ + overlay: OverlayKind; + viewer: ViewerState; + toast: string | null; + action: ActionDialogState | null; + shareTarget: ShareTarget | null; + openProfile(): void; + openUpload(): void; + openCreateAlbum(): void; + openShare(target: ShareTarget): void; + openEditMemory(): void; + openAction(action: ActionDialogState): void; + closeOverlay(): void; + openViewer(src: string, meta?: string): void; + closeViewer(): void; + notify(message: string): void; +}>; + +const MementoUiContext = createContext(null); + +export function MementoUiProvider({ children }: Readonly<{ children: ReactNode }>) { + const [overlay, setOverlay] = useState(null); + const [viewer, setViewer] = useState(null); + const [toast, setToast] = useState(null); + const [action, setAction] = useState(null); + const [shareTarget, setShareTarget] = useState(null); + + const notify = useCallback((message: string) => { + setToast(message); + globalThis.setTimeout(() => { + setToast((current) => (current === message ? null : current)); + }, 1900); + }, []); + + const value = useMemo( + () => + Object.freeze({ + overlay, + viewer, + toast, + action, + shareTarget, + openProfile: () => setOverlay("profile"), + openUpload: () => setOverlay("upload"), + openCreateAlbum: () => setOverlay("create-album"), + openShare(target) { + setShareTarget(target); + setOverlay("share"); + }, + openEditMemory: () => setOverlay("edit-memory"), + openAction(next) { + setAction(next); + setOverlay("action"); + }, + closeOverlay: () => setOverlay(null), + openViewer(src, meta = "2026.07.13 · 제주 · 서버 원본") { + setViewer(Object.freeze({ src, meta })); + }, + closeViewer: () => setViewer(null), + notify, + }), + [action, notify, overlay, shareTarget, toast, viewer], + ); + + return ( + + {children} + + ); +} + +export function useMementoUi(): MementoUi { + const value = useContext(MementoUiContext); + if (!value) throw new Error("MementoUiProvider is required"); + return value; +} diff --git a/src/features/memento-web/presentation/overlays/memento-overlays.tsx b/src/features/memento-web/presentation/overlays/memento-overlays.tsx new file mode 100644 index 0000000..35946e0 --- /dev/null +++ b/src/features/memento-web/presentation/overlays/memento-overlays.tsx @@ -0,0 +1,232 @@ +import { useState } from "react"; +import { useNavigate } from "react-router-dom"; + +import { + MementoBadge, + MementoButton, + MementoIconButton, +} from "../../../../presentation/design-system/index.ts"; +import { Photo } from "../components/photo.tsx"; +import { + useCreateAlbum, + useCreateShare, +} from "../hooks/use-memento.ts"; +import { useMementoUi } from "../memento-ui-context.tsx"; + +export function MementoOverlays() { + const ui = useMementoUi(); + const navigate = useNavigate(); + const createAlbum = useCreateAlbum(); + const createShare = useCreateShare(); + const [albumName, setAlbumName] = useState("새로운 Album"); + const [cover, setCover] = useState(6); + const [downloadAllowed, setDownloadAllowed] = useState(false); + const [expiry, setExpiry] = useState(true); + const [memoryTitle, setMemoryTitle] = useState("제주, 여름의 끝"); + const [autoUpdate, setAutoUpdate] = useState(true); + const anyOverlay = ui.overlay !== null; + + function close() { + ui.closeOverlay(); + } + + return ( + <> + + + + + + \ No newline at end of file diff --git a/public/login-v2.html b/tests/fixtures/memento-visual-baseline/legacy/login-v2.html similarity index 100% rename from public/login-v2.html rename to tests/fixtures/memento-visual-baseline/legacy/login-v2.html diff --git a/public/register-v2.html b/tests/fixtures/memento-visual-baseline/legacy/register-v2.html similarity index 100% rename from public/register-v2.html rename to tests/fixtures/memento-visual-baseline/legacy/register-v2.html diff --git a/tests/helpers/create-test-application.ts b/tests/helpers/create-test-application.ts index 77f7228..d0086b4 100644 --- a/tests/helpers/create-test-application.ts +++ b/tests/helpers/create-test-application.ts @@ -4,6 +4,9 @@ import { type ApplicationOutputPorts, } from "../../src/application/create-application.ts"; import type { ApplicationFeatureInputs } from "../../src/application/ports/in/application-api.ts"; +import { createMementoFeatureInput } from "../../src/features/memento-web/application/memento-application.ts"; +import { createMockMementoGateway } from "../../src/features/memento-web/adapters/mock-memento-gateway.ts"; +import { MEMENTO_FEATURE_ID } from "../../src/features/memento-web/contracts/memento-feature-contract.ts"; import { createProductFeaturesStub, createRuntimeCapabilitiesStub } from "./runtime-capabilities-stub.ts"; type TestApplicationOverrides = Partial & @@ -14,6 +17,13 @@ type TestApplicationOverrides = Partial & export function createTestApplication( overrides: TestApplicationOverrides = {}, ) { + const featureInputs = Object.freeze({ + [MEMENTO_FEATURE_ID]: createMementoFeatureInput( + createMockMementoGateway(), + ), + ...overrides.featureInputs, + }); + return createApplication( { session: overrides.session ?? createAnonymousSessionAdapter(), @@ -56,6 +66,6 @@ export function createTestApplication( overrides.productFeatures ?? createProductFeaturesStub(), navigation: overrides.navigation ?? { reload: () => {} }, }, - overrides.featureInputs, + featureInputs, ); } diff --git a/tests/integration/security-followup-archive.test.ts b/tests/integration/security-followup-archive.test.ts index a1260ee..b794bb2 100644 --- a/tests/integration/security-followup-archive.test.ts +++ b/tests/integration/security-followup-archive.test.ts @@ -45,6 +45,18 @@ it( force: true, }); await linkFixtureNodeModules(fixtureRoot, sourceRoot); + + // The fixture copies the candidate working tree, including uncommitted + // add/delete changes under review, but the copied .git/index still + // describes HEAD. Stage only inside the disposable fixture so + // repository-file inventory validates the bytes that will actually be + // assessed rather than stale tracked paths from the source checkout. + const staged = spawnSync("git", ["add", "-A"], { + cwd: fixtureRoot, + encoding: "utf8", + }); + expect(staged.status, staged.stderr).toBe(0); + const git = spawnSync("git", ["show", "-s", "--format=%H%n%ct", "HEAD"], { cwd: sourceRoot, encoding: "utf8", diff --git a/tests/storybook/memento-workshop.spec.ts b/tests/storybook/memento-workshop.spec.ts new file mode 100644 index 0000000..c55c648 --- /dev/null +++ b/tests/storybook/memento-workshop.spec.ts @@ -0,0 +1,32 @@ +import { + expect, + test, +} from "../support/browser/strict-browser-test.ts"; + +test("renders Memento product design-system stories", async ({ page }) => { + await page.goto( + "/iframe.html?id=memento-design-system--actions-and-status&viewMode=story", + ); + await expect( + page.getByRole("button", { name: "Primary" }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "공유 중" }), + ).toHaveClass(/active/); + await expect(page.getByText("진행 중")).toBeVisible(); + + await page.goto( + "/iframe.html?id=memento-design-system--memory-and-album-cards&viewMode=story", + ); + await expect(page.getByText("제주, 여름의 끝")).toBeVisible(); + await expect(page.getByText("가족 사진")).toBeVisible(); + await expect(page.getByText("공유 Album")).toBeVisible(); + + await page.goto( + "/iframe.html?id=memento-design-system--media-selection&viewMode=story", + ); + const firstTile = page.locator('.media-tile[data-key="0-0"]'); + await expect(firstTile).toHaveClass(/selected/); + await firstTile.click(); + await expect(firstTile).not.toHaveClass(/selected/); +}); diff --git a/tests/support/browser/strict-browser-test.ts b/tests/support/browser/strict-browser-test.ts index 93e22a8..2bacf8e 100644 --- a/tests/support/browser/strict-browser-test.ts +++ b/tests/support/browser/strict-browser-test.ts @@ -8,7 +8,12 @@ import { function ignoredConsole(message: ConsoleMessage) { return ( message.type() === "warning" && - message.text().includes("NO_COLOR") + ( + message.text().includes("NO_COLOR") || + message.text().includes( + "downloadable font: name: name records are not sorted.", + ) + ) ); } diff --git a/tests/unit/contract-registry-immutability.test.ts b/tests/unit/contract-registry-immutability.test.ts index f62746c..e3b3412 100644 --- a/tests/unit/contract-registry-immutability.test.ts +++ b/tests/unit/contract-registry-immutability.test.ts @@ -88,10 +88,9 @@ describe("LIVE-02 installed REST auth profile registry", () => { const registry = INSTALLED_REST_AUTH_PROFILES; expect(registry.has("ANONYMOUS")).toBe(true); expect(registry.has("NO_SUCH_PROFILE")).toBe(false); - expect([...registry.keys()].sort()).toEqual([ - "ANONYMOUS", - "REFERENCE_EXTERNAL_BEARER", - ]); + expect([...registry.keys()].sort()).toEqual( + Object.keys(REST_AUTH_PROFILES).sort(), + ); expect([...registry.entries()].length).toBe(registry.size); expect([...registry.values()].length).toBe(registry.size); }); diff --git a/tests/unit/memento-environment-gateway.test.ts b/tests/unit/memento-environment-gateway.test.ts index 4c24efc..cddcc63 100644 --- a/tests/unit/memento-environment-gateway.test.ts +++ b/tests/unit/memento-environment-gateway.test.ts @@ -1,32 +1,29 @@ import { describe, expect, it } from "vitest"; -import { createMementoGateway } from "../../src/features/memento-web/adapters/create-memento-gateway.ts"; -import type { MementoEnvironment } from "../../src/features/memento-web/contracts/memento-api.ts"; +import { + resolveMementoDataMode, + type MementoRuntimeCapability, +} from "../../src/features/memento-web/adapters/create-memento-feature-input.ts"; -const API_BASE_URL = "http://localhost:8080/"; - -function config(APP_ENV: MementoEnvironment) { - return { - APP_ENV, - API_BASE_URL, - REQUEST_TIMEOUT_MS: 10_000, - } as const; +function runtime( + appEnvironment: MementoRuntimeCapability["appEnvironment"], +): MementoRuntimeCapability { + return Object.freeze({ + appEnvironment, + apiBaseUrl: "http://localhost:8080/", + requestTimeoutMs: 10_000, + }); } -describe("Memento environment gateway selection", () => { - it("uses the deterministic mock only for local", async () => { - const gateway = createMementoGateway(config("local")); - - expect(gateway.mode).toBe("mock"); - const home = await gateway.getHome(); - expect(home.suggestedMemory?.title).toBe("제주, 여름의 끝"); - expect(home.repository.duplicateCandidateCount).toBe(14); +describe("Memento environment composition", () => { + it("uses deterministic mock data only for local", () => { + expect(resolveMementoDataMode(runtime("local"))).toBe("mock"); }); it.each(["development", "staging", "production"] as const)( - "uses the real BFF/API gateway for %s", + "uses contract-backed API mode for %s", (environment) => { - expect(createMementoGateway(config(environment)).mode).toBe("api"); + expect(resolveMementoDataMode(runtime(environment))).toBe("api"); }, ); }); diff --git a/tests/unit/product-features.test.ts b/tests/unit/product-features.test.ts index 422fd22..757c0f0 100644 --- a/tests/unit/product-features.test.ts +++ b/tests/unit/product-features.test.ts @@ -14,6 +14,7 @@ import { ROUTE_FEATURE_OWNER, ROUTE_REGISTRY, } from "../../src/features/installed-feature-contracts.ts"; +import { MEMENTO_FEATURE_ID } from "../../src/features/memento-web/contracts/memento-feature-contract.ts"; const COMPILED = Object.freeze([ Object.freeze({ featureId: "alpha-feature" }), @@ -204,9 +205,12 @@ describe("route ownership", () => { for (const featureId of INSTALLED_PRODUCT_FEATURE_IDS) { expect(Object.values(ROUTE_FEATURE_OWNER)).toContain(featureId); } - // Platform routes have no owner, so disabling a feature can never withdraw - // the shell's own navigation. - for (const routeId of ["APP_HOME", "NOT_FOUND", "EXAMPLES_PLATFORM"]) { + // Memento intentionally owns the product root route. The remaining + // platform routes stay unowned, so a feature switch cannot withdraw the + // platform diagnostics/examples shell. + expect(ROUTE_FEATURE_OWNER.APP_HOME).toBe(MEMENTO_FEATURE_ID); + expect(Object.keys(ROUTE_REGISTRY)).toContain("APP_HOME"); + for (const routeId of ["NOT_FOUND", "EXAMPLES_PLATFORM"]) { expect(ROUTE_FEATURE_OWNER[routeId], routeId).toBeUndefined(); expect(Object.keys(ROUTE_REGISTRY)).toContain(routeId); } diff --git a/tests/visual/MEMENTO_VISUAL_BASELINE.md b/tests/visual/MEMENTO_VISUAL_BASELINE.md new file mode 100644 index 0000000..0697ff0 --- /dev/null +++ b/tests/visual/MEMENTO_VISUAL_BASELINE.md @@ -0,0 +1,72 @@ +# Memento visual baseline provenance + +## Authority + +The visual authority is the approved Beta prototype captured from Git commit +`85c804b0301091b36fc48a83ae501570340269e7`, preserved under +`tests/fixtures/memento-visual-baseline/legacy/`. + +The normal 26-surface Playwright snapshots are regression evidence for the React +implementation. The separate legacy-parity suite proves that those React +surfaces remain within the approved prototype rendering envelope; snapshot +files are not treated as self-authorizing design truth. + +## Rendering conditions + +- Browser: repository Playwright Chromium +- Desktop viewport: 1600 × 1100 +- Mobile viewport: 390 × 844 +- Auth viewport: 1440 × 1000 +- Color scheme: light +- Locale: en-US +- Media: identical `public/assets` bytes for both renderers +- Map iframe: hidden in both renderers before capture +- Animations: disabled before capture +- Fonts: same host/browser font environment for both renderers + +The comparison requires identical screenshot dimensions. Pixel differences are +measured from two screenshots produced in the same Playwright run. + +## Difference policy + +A visual diff is not fixed by updating a snapshot. + +1. Identify the DOM/CSS source of the diff. +2. Confirm that layout dimensions, product colors, spacing, and typography + values still come from the approved design contract. +3. If the change is intentional, review and approve the design change first. +4. Only after approval may the React regression snapshot be updated. + +The legacy-parity gate uses two independent limits. First, any changed pixel +must remain at or below `0.5%` of the surface. Second, a material pixel—one +whose maximum RGBA channel delta exceeds `13/255` (roughly 5%)—must remain at +or below `0.2%`. This separates harmless font/native-control rasterization from +meaningful layout or color drift. Screenshot dimension mismatch always fails. +A diff above either envelope must be investigated; increasing either limit is +not an acceptable way to make the test green. + +## Accessibility interaction with the visual lock + +The approved legacy palette contains known WCAG AA color-contrast debt. During +this migration the visual authority has higher precedence than an unreviewed +palette change: changing those colors would invalidate the direct legacy ↔ +React parity evidence. + +For routes owned by `memento-web`, the generic Axe E2E suite therefore waives +**only** the `color-contrast` rule. Critical/serious findings from every other +Axe rule remain blocking. This is an explicit migration debt, not an assertion +that the current palette is accessible. + +Removing this waiver requires a separately approved Memento design-system +change. That change must update the visual authority/baselines and accessibility +evidence together; the waiver must not be broadened to other Axe rules. + +## Commands + +- React regression: `corepack pnpm test:visual` +- Approved legacy ↔ React: `corepack pnpm test:visual:memento-legacy` +- Snapshot update after explicit design approval only: + `corepack pnpm test:visual:update` + +The legacy fixture itself is immutable migration evidence. Regenerating it from +the current React implementation is prohibited. diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-login-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-login-chromium-visual-linux.png new file mode 100644 index 0000000..13a7b6a Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-login-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-register-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-register-chromium-visual-linux.png new file mode 100644 index 0000000..17385ac Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-auth-register-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-album-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-album-chromium-visual-linux.png new file mode 100644 index 0000000..32e8f52 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-album-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-albums-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-albums-chromium-visual-linux.png new file mode 100644 index 0000000..633b7b3 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-albums-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-home-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-home-chromium-visual-linux.png new file mode 100644 index 0000000..f87053e Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-home-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-library-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-library-chromium-visual-linux.png new file mode 100644 index 0000000..a4122f6 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-library-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memories-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memories-chromium-visual-linux.png new file mode 100644 index 0000000..12253e2 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memories-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memory-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memory-chromium-visual-linux.png new file mode 100644 index 0000000..3860df4 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-memory-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-people-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-people-chromium-visual-linux.png new file mode 100644 index 0000000..bc1fe61 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-people-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-person-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-person-chromium-visual-linux.png new file mode 100644 index 0000000..58cc9ef Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-person-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-place-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-place-chromium-visual-linux.png new file mode 100644 index 0000000..2e80efc Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-place-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-places-map-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-places-map-chromium-visual-linux.png new file mode 100644 index 0000000..3c5a802 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-places-map-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-search-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-search-chromium-visual-linux.png new file mode 100644 index 0000000..350d8dc Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-search-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-settings-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-settings-chromium-visual-linux.png new file mode 100644 index 0000000..37afaa3 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-desktop-settings-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-home-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-home-chromium-visual-linux.png new file mode 100644 index 0000000..fd00429 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-home-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-library-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-library-chromium-visual-linux.png new file mode 100644 index 0000000..1a21e69 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-library-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-memories-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-memories-chromium-visual-linux.png new file mode 100644 index 0000000..f788a1a Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-memories-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-search-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-search-chromium-visual-linux.png new file mode 100644 index 0000000..18e0c19 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-mobile-search-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-action-modal-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-action-modal-chromium-visual-linux.png new file mode 100644 index 0000000..2c0f14f Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-action-modal-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-create-album-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-create-album-chromium-visual-linux.png new file mode 100644 index 0000000..84f6b1e Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-create-album-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-edit-memory-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-edit-memory-chromium-visual-linux.png new file mode 100644 index 0000000..9692b84 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-edit-memory-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-profile-drawer-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-profile-drawer-chromium-visual-linux.png new file mode 100644 index 0000000..a427f78 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-profile-drawer-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-share-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-share-chromium-visual-linux.png new file mode 100644 index 0000000..a173dc1 Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-share-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-upload-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-upload-chromium-visual-linux.png new file mode 100644 index 0000000..c50f65c Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-upload-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-viewer-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-viewer-chromium-visual-linux.png new file mode 100644 index 0000000..f842c8c Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-overlay-viewer-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-state-library-selection-chromium-visual-linux.png b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-state-library-selection-chromium-visual-linux.png new file mode 100644 index 0000000..2c0ee3d Binary files /dev/null and b/tests/visual/__snapshots__/memento-prototype.visual.spec.ts-snapshots/memento-state-library-selection-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png index c5065a9..e5e56c0 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png index 55ad48e..0c82fa2 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-wide-light-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png index a4b9b7c..8c70854 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/design-system-gallery-dark-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png index 3c7974b..6836b93 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/platform-overview-light-chromium-visual-linux.png differ diff --git a/tests/visual/memento-legacy-parity.visual.spec.ts b/tests/visual/memento-legacy-parity.visual.spec.ts new file mode 100644 index 0000000..36b01f2 --- /dev/null +++ b/tests/visual/memento-legacy-parity.visual.spec.ts @@ -0,0 +1,364 @@ +import { expect, test, type Browser, type Page } from "@playwright/test"; + +const LEGACY = "http://127.0.0.1:4195"; +const MAX_CHANGED_PIXEL_RATIO = 0.005; +const MATERIAL_CHANNEL_DELTA = 13; +const MAX_MATERIAL_PIXEL_RATIO = 0.002; + +type Surface = Readonly<{ + name: string; + reactPath: string; + legacyPage?: string; + width: number; + height: number; + prepareLegacy?: (page: Page) => Promise; + prepareReact?: (page: Page) => Promise; +}>; + +async function settle(page: Page) { + await page.waitForLoadState("networkidle"); + await page.addStyleTag({ + content: ` + iframe { visibility: hidden !important; } + *, *::before, *::after { + animation-duration: 0s !important; + animation-delay: 0s !important; + transition-duration: 0s !important; + transition-delay: 0s !important; + } + `, + }); + await page.waitForFunction(() => + Array.from(document.images).every((image) => image.complete), + ); + await page.evaluate(async () => { + await document.fonts.ready; + }); +} + +async function showLegacyPage(page: Page, name: string) { + await page.evaluate((target) => { + const legacyWindow = window as Window & { + showPage?: (pageName: string) => void; + openPlace?: (placeName: string) => void; + openSettings?: (section: string) => void; + }; + if (target === "place") { + legacyWindow.openPlace?.("제주도"); + return; + } + if (target === "settings") { + legacyWindow.openSettings?.("devices"); + return; + } + legacyWindow.showPage?.(target); + }, name); +} + +async function screenshot(page: Page) { + await settle(page); + return page.screenshot({ + fullPage: true, + animations: "disabled", + caret: "hide", + scale: "css", + }); +} + +async function pixelDiff( + page: Page, + legacy: Buffer, + react: Buffer, +): Promise> { + await page.goto("about:blank"); + return page.evaluate( + async ({ legacyBase64, reactBase64, materialChannelDelta }) => { + async function decode(base64: string) { + const response = await fetch(`data:image/png;base64,${base64}`); + return createImageBitmap(await response.blob()); + } + + const [left, right] = await Promise.all([ + decode(legacyBase64), + decode(reactBase64), + ]); + if (left.width !== right.width || left.height !== right.height) { + throw new Error( + `visual dimension mismatch: legacy=${left.width}x${left.height} react=${right.width}x${right.height}`, + ); + } + + const canvas = document.createElement("canvas"); + canvas.width = left.width; + canvas.height = left.height; + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) throw new Error("2d canvas unavailable"); + + context.drawImage(left, 0, 0); + const a = context.getImageData(0, 0, left.width, left.height).data; + context.clearRect(0, 0, left.width, left.height); + context.drawImage(right, 0, 0); + const b = context.getImageData(0, 0, right.width, right.height).data; + + let changedPixels = 0; + let materialPixels = 0; + let maxChannelDelta = 0; + for (let offset = 0; offset < a.length; offset += 4) { + let changed = false; + let pixelDelta = 0; + for (let channel = 0; channel < 4; channel += 1) { + const delta = Math.abs( + (a[offset + channel] ?? 0) - (b[offset + channel] ?? 0), + ); + if (delta > 0) changed = true; + if (delta > pixelDelta) pixelDelta = delta; + if (delta > maxChannelDelta) maxChannelDelta = delta; + } + if (changed) changedPixels += 1; + if (pixelDelta > materialChannelDelta) materialPixels += 1; + } + + return { + width: left.width, + height: left.height, + changedPixels, + changedPixelRatio: changedPixels / (left.width * left.height), + materialPixels, + materialPixelRatio: materialPixels / (left.width * left.height), + maxChannelDelta, + }; + }, + { + legacyBase64: legacy.toString("base64"), + reactBase64: react.toString("base64"), + materialChannelDelta: MATERIAL_CHANNEL_DELTA, + }, + ); +} + +async function compareSurface( + browser: Browser, + reactPage: Page, + surface: Surface, +) { + await reactPage.setViewportSize({ + width: surface.width, + height: surface.height, + }); + await reactPage.goto(surface.reactPath); + await surface.prepareReact?.(reactPage); + const react = await screenshot(reactPage); + + const legacyContext = await browser.newContext({ + viewport: { width: surface.width, height: surface.height }, + colorScheme: "light", + locale: "en-US", + }); + const legacyPage = await legacyContext.newPage(); + await legacyPage.goto( + surface.legacyPage === "login" + ? `${LEGACY}/login-v2.html` + : surface.legacyPage === "register" + ? `${LEGACY}/register-v2.html` + : LEGACY, + ); + if ( + surface.legacyPage && + surface.legacyPage !== "login" && + surface.legacyPage !== "register" + ) { + await showLegacyPage(legacyPage, surface.legacyPage); + } + await surface.prepareLegacy?.(legacyPage); + const legacy = await screenshot(legacyPage); + await legacyContext.close(); + + const diff = await pixelDiff(reactPage, legacy, react); + console.log(surface.name, JSON.stringify(diff)); + await test.info().attach(`${surface.name}-legacy-parity.json`, { + body: Buffer.from(JSON.stringify(diff, null, 2)), + contentType: "application/json", + }); + + expect(diff.changedPixelRatio, `${surface.name}: any changed pixel`).toBeLessThanOrEqual( + MAX_CHANGED_PIXEL_RATIO, + ); + expect( + diff.materialPixelRatio, + `${surface.name}: material pixel delta > ${MATERIAL_CHANNEL_DELTA}/255`, + ).toBeLessThanOrEqual(MAX_MATERIAL_PIXEL_RATIO); +} + +const desktop: readonly Surface[] = [ + ["home", "/", "home"], + ["library", "/library", "library"], + ["memories", "/memories", "memories"], + ["search", "/search", "search"], + ["place", "/places/place-jeju", "place"], + ["memory", "/memories/memory-jeju", "memory"], + ["albums", "/albums", "albums"], + ["album", "/albums/album-family", "album"], + ["people", "/people", "people"], + ["person", "/people/person-family", "person"], + ["places", "/places", "places-map"], + ["settings", "/settings", "settings"], +].map(([name, reactPath, legacyPage]) => ({ + name: `desktop-${name}`, + reactPath, + legacyPage, + width: 1600, + height: 1100, +})); + +for (const surface of desktop) { + test(`approved legacy parity: ${surface.name}`, async ({ browser, page }) => { + await compareSurface(browser, page, surface); + }); +} + +for (const name of ["home", "library", "memories", "search"] as const) { + test(`approved legacy parity: mobile-${name}`, async ({ browser, page }) => { + await compareSurface(browser, page, { + name: `mobile-${name}`, + reactPath: name === "home" ? "/" : `/${name}`, + legacyPage: name, + width: 390, + height: 844, + }); + }); +} + +const overlays: readonly Surface[] = [ + { + name: "overlay-profile", + reactPath: "/", + legacyPage: "home", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-profile]").first().click(); + }, + prepareReact: async (page) => { + await page.locator("[data-profile]").first().click(); + }, + }, + { + name: "overlay-upload", + reactPath: "/", + legacyPage: "home", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-upload]").first().click(); + }, + prepareReact: async (page) => { + await page.locator("[data-upload]").first().click(); + }, + }, + { + name: "overlay-create-album", + reactPath: "/memories", + legacyPage: "memories", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-create-album]").first().click(); + }, + prepareReact: async (page) => { + await page.locator("[data-create-album]").first().click(); + }, + }, + { + name: "overlay-share", + reactPath: "/memories/memory-jeju", + legacyPage: "memory", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-share]").first().click(); + }, + prepareReact: async (page) => { + await page.locator("[data-share]").first().click(); + }, + }, + { + name: "overlay-edit-memory", + reactPath: "/memories/memory-jeju", + legacyPage: "memory", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-edit-memory]").click(); + }, + prepareReact: async (page) => { + await page.locator("[data-edit-memory]").click(); + }, + }, + { + name: "overlay-action", + reactPath: "/", + legacyPage: "home", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("[data-profile]").first().click(); + await page.locator(".menu-list .danger").click(); + }, + prepareReact: async (page) => { + await page.locator("[data-profile]").first().click(); + await page.locator(".menu-list .danger").click(); + }, + }, + { + name: "state-library-selection", + reactPath: "/library", + legacyPage: "library", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator(".media-tile").first().click(); + }, + prepareReact: async (page) => { + await page.locator(".media-tile").first().click(); + }, + }, + { + name: "overlay-viewer", + reactPath: "/memories/memory-jeju", + legacyPage: "memory", + width: 1600, + height: 1100, + prepareLegacy: async (page) => { + await page.locator("#page-memory .viewable").first().click(); + }, + prepareReact: async (page) => { + await page.locator("#page-memory .viewable").first().click(); + }, + }, +]; + +for (const surface of overlays) { + test(`approved legacy parity: ${surface.name}`, async ({ browser, page }) => { + await compareSurface(browser, page, surface); + }); +} + +for (const name of ["login", "register"] as const) { + test(`approved legacy parity: auth-${name}`, async ({ browser, page }) => { + await compareSurface(browser, page, { + name: `auth-${name}`, + reactPath: `/${name}`, + legacyPage: name, + width: 1440, + height: 1000, + }); + }); +} diff --git a/tests/visual/memento-prototype.visual.spec.ts b/tests/visual/memento-prototype.visual.spec.ts new file mode 100644 index 0000000..5f378be --- /dev/null +++ b/tests/visual/memento-prototype.visual.spec.ts @@ -0,0 +1,118 @@ +import { expect, test } from "@playwright/test"; + +const desktopPages = [ + ["home", "/"], + ["library", "/library"], + ["memories", "/memories"], + ["search", "/search"], + ["place", "/places/place-jeju"], + ["memory", "/memories/memory-jeju"], + ["albums", "/albums"], + ["album", "/albums/album-family"], + ["people", "/people"], + ["person", "/people/person-family"], + ["places-map", "/places"], + ["settings", "/settings"], +] as const; + +for (const [name, url] of desktopPages) { + test(`Memento prototype desktop: ${name}`, async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto(url); + await expect(page.locator(`#page-${name}`)).toHaveClass(/active/); + await expect(page).toHaveScreenshot(`memento-desktop-${name}.png`, { + fullPage: true, + mask: [page.locator("iframe")], + }); + }); +} + +for (const name of ["home", "library", "memories", "search"] as const) { + test(`Memento prototype mobile: ${name}`, async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto(name === "home" ? "/" : `/${name}`); + await expect(page.locator(`#page-${name}`)).toHaveClass(/active/); + await expect(page).toHaveScreenshot(`memento-mobile-${name}.png`, { + fullPage: true, + mask: [page.locator("iframe")], + }); + }); +} + +test("Memento prototype profile drawer", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/"); + await page.locator("[data-profile]").first().click(); + await expect(page.locator("#profileDrawer")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-profile-drawer.png", { fullPage: true }); +}); + +test("Memento prototype upload dialog", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/"); + await page.locator("[data-upload]").first().click(); + await expect(page.locator("#uploadModal")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-upload.png", { fullPage: true }); +}); + +test("Memento prototype create album dialog", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/memories"); + await page.locator("[data-create-album]").first().click(); + await expect(page.locator("#createAlbumModal")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-create-album.png", { fullPage: true }); +}); + +test("Memento prototype share dialog", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/memories/memory-jeju"); + await page.locator("[data-share]").first().click(); + await expect(page.locator("#shareModal")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-share.png", { fullPage: true }); +}); + +test("Memento prototype edit memory dialog", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/memories/memory-jeju"); + await page.locator("[data-edit-memory]").click(); + await expect(page.locator("#editMemoryModal")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-edit-memory.png", { fullPage: true }); +}); + +test("Memento prototype library selection", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/library"); + await page.locator(".media-tile").first().click(); + await expect(page.locator("#selectionBar")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-state-library-selection.png", { fullPage: true }); +}); + +test("Memento prototype media viewer", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/memories/memory-jeju"); + await page.locator("#page-memory .viewable").first().click(); + await expect(page.locator("#viewer")).toHaveClass(/show/); + await expect(page).toHaveScreenshot("memento-overlay-viewer.png", { fullPage: true }); +}); + +for (const name of ["login", "register"] as const) { + test(`Memento prototype auth: ${name}`, async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.goto(`/${name}`); + await expect(page.locator("#main-content")).toHaveClass(/memento-auth-/); + await expect(page).toHaveScreenshot(`memento-auth-${name}.png`, { + fullPage: true, + }); + }); +} + +test("Memento prototype action modal", async ({ page }) => { + await page.setViewportSize({ width: 1600, height: 1100 }); + await page.goto("/"); + await page.locator("[data-profile]").first().click(); + await page.locator(".menu-list .danger").click(); + await expect(page.locator("#actionModal")).toHaveClass(/show/); + await expect(page.locator("#actionModal")).toHaveScreenshot( + "memento-overlay-action-modal.png", + ); +}); diff --git a/tests/visual/platform.visual.spec.ts b/tests/visual/platform.visual.spec.ts index f488dbb..338d299 100644 --- a/tests/visual/platform.visual.spec.ts +++ b/tests/visual/platform.visual.spec.ts @@ -5,7 +5,7 @@ import { test("wide application shell visual contract", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }); - await page.goto("/"); + await page.goto("/examples/states"); await expect(page.getByRole("main")).toBeVisible(); await expect(page).toHaveScreenshot("app-shell-wide-light.png", { fullPage: true, @@ -14,7 +14,7 @@ test("wide application shell visual contract", async ({ page }) => { test("compact drawer and pseudo-locale visual contract", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); - await page.goto("/"); + await page.goto("/examples/states"); await page.locator("#locale-preference").selectOption("en-XA"); await page.locator(".app-shell__menu-button").click(); await expect(page.locator(".ui-drawer")).toHaveJSProperty("open", true); diff --git a/vite.config.ts b/vite.config.ts index c506043..d8590ea 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -53,6 +53,10 @@ function runtimeProfile(environment: NodeJS.ProcessEnv): RuntimeProfile { * pnpm dev:api -> development profile -> real API gateway * * RUNTIME_API_BASE_URL may replace only the endpoint. No secret is accepted. + * + * Vite's dev server does not build service-worker.js, so configureServer + * disables registration for the live dev server only. Profile builds keep the + * checked-in runtime capability setting and still produce the PWA worker. */ function mementoRuntimeProfilePlugin( environment: NodeJS.ProcessEnv, @@ -76,6 +80,17 @@ function mementoRuntimeProfilePlugin( const apiOverride = environment["RUNTIME_API_BASE_URL"]; if (apiOverride) source["API_BASE_URL"] = apiOverride; + const capabilityOverrides = + source["CAPABILITY_OVERRIDES"] && + typeof source["CAPABILITY_OVERRIDES"] === "object" && + !Array.isArray(source["CAPABILITY_OVERRIDES"]) + ? (source["CAPABILITY_OVERRIDES"] as Record) + : {}; + source["CAPABILITY_OVERRIDES"] = { + ...capabilityOverrides, + SERVICE_WORKER: "DISABLED", + }; + response.statusCode = 200; response.setHeader("Content-Type", "application/json; charset=utf-8"); response.setHeader("Cache-Control", "no-store");