diff --git a/config/runtime/development.json b/config/runtime/development.json index 63006b8..55b4a0a 100644 --- a/config/runtime/development.json +++ b/config/runtime/development.json @@ -1,6 +1,6 @@ { "APP_ENV": "development", - "API_BASE_URL": "https://api.dev.example.com/", + "API_BASE_URL": "http://localhost:8080/", "REQUEST_TIMEOUT_MS": 15000, "MAX_RETRY_ATTEMPTS": 2, "TELEMETRY_ENABLED": false, diff --git a/config/runtime/local.json b/config/runtime/local.json index 952aa3c..d204aaf 100644 --- a/config/runtime/local.json +++ b/config/runtime/local.json @@ -10,7 +10,7 @@ "CAPABILITY_OVERRIDES": { "REALTIME": "DEFAULT", "WEB_WORKER": "DEFAULT", - "SERVICE_WORKER": "DEFAULT", + "SERVICE_WORKER": "DISABLED", "OFFLINE_COMMANDS": "DEFAULT" }, "FEATURE_OVERRIDES": { diff --git a/index.html b/index.html index 71e523e..dcc510d 100644 --- a/index.html +++ b/index.html @@ -1,13 +1,214 @@ - - - - - Memento - - -
- - - + + + + +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 c59104d..1b920ec 100644 --- a/package.json +++ b/package.json @@ -131,7 +131,11 @@ "check:types:fixture:http-route-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-route-id.json", "check:types:fixture:feature-contribution-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-contribution-input.json", "check:types:fixture:feature-capability-selection": "tsc -p tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", - "check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json" + "check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json", + "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" }, "dependencies": { "@tanstack/react-query": "5.101.4", diff --git a/public/assets/photo-1.jpg b/public/assets/photo-1.jpg new file mode 100644 index 0000000..427047e Binary files /dev/null and b/public/assets/photo-1.jpg differ diff --git a/public/assets/photo-10.jpg b/public/assets/photo-10.jpg new file mode 100644 index 0000000..a96793d Binary files /dev/null and b/public/assets/photo-10.jpg differ diff --git a/public/assets/photo-11.jpg b/public/assets/photo-11.jpg new file mode 100644 index 0000000..cd291aa Binary files /dev/null and b/public/assets/photo-11.jpg differ diff --git a/public/assets/photo-2.jpg b/public/assets/photo-2.jpg new file mode 100644 index 0000000..8c6ea3d Binary files /dev/null and b/public/assets/photo-2.jpg differ diff --git a/public/assets/photo-3.jpg b/public/assets/photo-3.jpg new file mode 100644 index 0000000..3fb3267 Binary files /dev/null and b/public/assets/photo-3.jpg differ diff --git a/public/assets/photo-4.jpg b/public/assets/photo-4.jpg new file mode 100644 index 0000000..927477b Binary files /dev/null and b/public/assets/photo-4.jpg differ diff --git a/public/assets/photo-5.jpg b/public/assets/photo-5.jpg new file mode 100644 index 0000000..5a01aeb Binary files /dev/null and b/public/assets/photo-5.jpg differ diff --git a/public/assets/photo-6.jpg b/public/assets/photo-6.jpg new file mode 100644 index 0000000..c00f826 Binary files /dev/null and b/public/assets/photo-6.jpg differ diff --git a/public/assets/photo-7.jpg b/public/assets/photo-7.jpg new file mode 100644 index 0000000..4368505 Binary files /dev/null and b/public/assets/photo-7.jpg differ diff --git a/public/assets/photo-8.jpg b/public/assets/photo-8.jpg new file mode 100644 index 0000000..46555d3 Binary files /dev/null and b/public/assets/photo-8.jpg differ diff --git a/public/assets/photo-9.jpg b/public/assets/photo-9.jpg new file mode 100644 index 0000000..00c4f5e Binary files /dev/null and b/public/assets/photo-9.jpg differ diff --git a/public/beta.css b/public/beta.css new file mode 100644 index 0000000..ff57389 --- /dev/null +++ b/public/beta.css @@ -0,0 +1,32 @@ +@import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.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(25,27,23,.08)} +*{box-sizing:border-box}html,body{margin:0;background:var(--bg);color:var(--ink);font-family:'Pretendard Variable',Pretendard,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;letter-spacing:-.012em}button,input{font:inherit}button{cursor:pointer}img{display:block;width:100%;height:100%;object-fit:cover}a{text-decoration:none;color:inherit}.svg-defs{position:absolute;width:0;height:0;overflow:hidden} +.sidebar{position:fixed;inset:0 auto 0 0;width:var(--side);padding:22px 16px 18px;background:rgba(244,244,241,.93);backdrop-filter:blur(18px);border-right:1px solid rgba(0,0,0,.055);z-index:60}.brand{display:flex;align-items:center;gap:10px;padding:2px 8px 28px;font-size:20px;font-weight:780;letter-spacing:-.03em}.brand-mark{width:29px;height:29px;border-radius:10px;background:#171816;position:relative}.brand-mark:after{content:'';position:absolute;inset:7px;border:2px solid #fff;border-radius:50%}.nav{display:grid;gap:5px}.nav button{height:43px;border:0;background:transparent;border-radius:12px;padding:0 12px;display:flex;align-items:center;gap:12px;color:#646760;font-size:13px;text-align:left}.nav button svg,.page-head-actions svg,.field svg,.mobile-tabs svg,.detail-back svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}.nav button.active{background:#e6e7e2;color:#161715;font-weight:700}.sidebar-footer{position:absolute;left:16px;right:16px;bottom:18px}.profile-mini{width:100%;border:0;background:transparent;border-radius:14px;padding:9px;display:flex;align-items:center;gap:10px;text-align:left}.profile-mini:hover{background:#e8e9e4}.profile-copy{flex:1}.profile-copy strong{font-size:13px;display:block}.profile-copy span{display:block;font-size:11px;color:var(--sub);margin-top:2px}.avatar{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#9db0a4,#d7c5a9);flex:none}.dot{width:8px;height:8px;border-radius:50%;background:#5e8b6c;box-shadow:0 0 0 3px #e5efe8} +.main{margin-left:var(--side);padding:30px 38px 96px}.page{display:none;max-width:1360px;margin:0 auto}.page.active{display:block}.page-head{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:26px}.page-head-actions{display:flex;gap:8px;align-items:center}.greeting{font-size:13px;color:var(--sub);margin-bottom:6px}.h1{font-size:34px;line-height:1.08;letter-spacing:-.045em;margin:0;font-weight:760}.h2{font-size:24px;letter-spacing:-.03em;margin:0;font-weight:740}.h3{font-size:18px;letter-spacing:-.02em;margin:0;font-weight:710}.btn,.icon-btn,.chip{height:40px;border:1px solid var(--line);background:#fff;color:var(--ink);border-radius:12px;padding:0 14px;font-size:13px;font-weight:660}.btn{display:inline-flex;align-items:center;gap:7px;justify-content:center}.btn.primary{background:#171816;border-color:#171816;color:#fff}.btn.accent{background:var(--accent);border-color:var(--accent);color:#fff}.btn.ghost{background:transparent;border-color:transparent;color:var(--sub)}.btn.dark-ghost{background:transparent;color:#d6d9d5;border-color:rgba(255,255,255,.18)}.icon-btn{width:40px;padding:0;border-radius:50%;display:grid;place-items:center}.chip{height:34px;border-radius:999px;padding:0 12px;color:var(--sub);font-size:12px}.chip.active{background:var(--accent2);border-color:#c8d8cd;color:#2f4c3d}.badge{display:inline-flex;align-items:center;gap:6px;height:25px;border-radius:999px;padding:0 9px;background:var(--surface2);font-size:11px;font-weight:680;color:var(--sub)}.badge.accent{background:var(--accent2);color:#2f4c3d}.badge.translucent{background:rgba(255,255,255,.18);color:#fff}.field{height:44px;border:1px solid var(--line);background:#fff;border-radius:12px;display:flex;align-items:center;gap:9px;padding:0 13px}.field input{border:0;outline:0;background:transparent;width:100%;font:inherit}.section{margin-top:38px}.section-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.section-note{font-size:12px;color:var(--sub);margin:4px 0 0} +.discovery-card{display:grid;grid-template-columns:1.1fr .9fr;background:#1d211e;border-radius:26px;overflow:hidden;min-height:430px;box-shadow:var(--shadow)}.discovery-media{position:relative;min-height:430px}.collage{position:absolute;inset:0;display:grid;grid-template-columns:1.45fr .8fr;grid-template-rows:1fr 1fr;gap:3px}.collage>div:first-child{grid-row:1/3}.discovery-media:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,transparent 60%,rgba(29,33,30,.25))}.discovery-copy{padding:38px 36px;color:#f8f8f6;display:flex;flex-direction:column;justify-content:center}.kicker{font-size:12px;color:#bdc9c1;font-weight:700;display:flex;align-items:center;gap:8px}.spark{width:28px;height:28px;border-radius:50%;background:#31433a;display:grid;place-items:center}.discovery-copy h2{font-size:38px;line-height:1.08;letter-spacing:-.05em;margin:18px 0 10px}.discovery-copy p{color:#c8cbc6;line-height:1.6;margin:0 0 24px;font-size:14px}.discovery-meta{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:26px}.discovery-meta span{border:1px solid rgba(255,255,255,.15);border-radius:999px;padding:7px 10px;font-size:11px;color:#d9ddd9}.discovery-actions{display:flex;gap:8px} +.memory-strip{display:grid;grid-template-columns:1.35fr 1fr 1fr;gap:10px}.memory-card{height:260px;border-radius:18px;overflow:hidden;position:relative;cursor:pointer}.memory-card:after,.place-card:after{content:'';position:absolute;inset:0;background:linear-gradient(180deg,transparent 42%,rgba(0,0,0,.62))}.memory-copy{position:absolute;left:17px;right:17px;bottom:16px;z-index:2;color:#fff}.memory-copy span{display:block;font-size:12px;opacity:.76}.memory-copy strong{display:block;font-size:18px;margin-top:4px} +.intake-row{display:grid;grid-template-columns:1fr 270px;gap:14px}.today-media{background:#fff;border:1px solid var(--line);border-radius:18px;padding:16px}.today-head{display:flex;align-items:center;justify-content:space-between}.today-head strong{font-size:17px}.today-head>div span{font-size:12px;color:var(--sub);margin-left:7px}.today-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:5px;margin-top:12px}.today-grid div{aspect-ratio:1;border-radius:9px;overflow:hidden}.sync-card{background:#e9ede9;border-radius:18px;padding:18px;display:flex;flex-direction:column;justify-content:space-between}.sync-top{display:flex;align-items:flex-start;justify-content:space-between}.sync-top>div span{display:block;font-size:12px;color:var(--sub)}.sync-top strong{display:block;font-size:28px;letter-spacing:-.04em;margin-top:3px}.sync-card p{font-size:11px;color:var(--sub);margin:8px 0 0}.bar{height:6px;background:rgba(73,99,86,.14);border-radius:999px;overflow:hidden}.bar span{display:block;width:72%;height:100%;background:var(--accent)} +.status-row{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}.status-card{background:#fff;border:1px solid var(--line);border-radius:16px;padding:16px}.status-card .value{font-size:24px;font-weight:740;margin:8px 0 2px}.status-card p{font-size:12px;color:var(--sub);margin:0;line-height:1.45}.text-action{border:0;background:transparent;color:var(--accent);font-size:12px;font-weight:680;padding:12px 0 0} +.tool-row{display:flex;align-items:center;gap:8px;position:sticky;top:10px;z-index:30;margin-bottom:16px}.tool-row .field{width:340px}.view-switch{display:flex;border:1px solid var(--line);background:#fff;border-radius:11px;padding:3px}.view-switch button{width:32px;height:32px;border:0;border-radius:8px;background:transparent;color:var(--sub)}.view-switch button.active{background:var(--surface2);color:var(--ink)}.filter-summary{display:none;background:var(--accent2);color:#2f4c3d;border-radius:12px;padding:11px 13px;margin-bottom:14px;align-items:center;justify-content:space-between;font-size:13px}.filter-summary.show{display:flex}.month-head{display:flex;align-items:center;justify-content:space-between;margin:28px 0 10px}.month-head .left{display:flex;align-items:baseline;gap:8px}.month-head span{font-size:12px;color:var(--sub)}.media-grid{display:grid;grid-template-columns:repeat(6,1fr);grid-auto-rows:92px;gap:3px;grid-auto-flow:dense}.media-tile{position:relative;overflow:hidden;background:#ddd;cursor:pointer;border-radius:3px}.media-tile.wide{grid-column:span 2}.media-tile.tall{grid-row:span 2}.media-tile.large{grid-column:span 2;grid-row:span 2}.media-tile img{transition:transform .25s}.media-tile:hover img{transform:scale(1.018)}.select-mark{position:absolute;left:8px;top:8px;width:22px;height:22px;border-radius:50%;background:rgba(255,255,255,.94);border:1px solid rgba(0,0,0,.14);display:grid;place-items:center;font-size:11px;opacity:0;z-index:2}.media-tile:hover .select-mark,.media-tile.selected .select-mark{opacity:1}.media-tile.selected:after{content:'';position:absolute;inset:0;border:3px solid #fff;box-shadow:inset 0 0 0 3px var(--accent)}.media-tile.selected .select-mark{background:var(--accent);color:#fff}.media-state{position:absolute;right:7px;bottom:7px;display:flex;gap:5px}.media-pill{background:rgba(20,21,19,.62);backdrop-filter:blur(5px);color:#fff;border-radius:999px;padding:4px 7px;font-size:10px}.media-warning{background:#94633d} +.memory-sections{display:grid;gap:32px}.suggested-banner{display:grid;grid-template-columns:1.05fr .95fr;background:#e9ede9;border-radius:22px;overflow:hidden}.suggested-visual{min-height:280px;display:grid;grid-template-columns:2fr 1fr;gap:3px}.suggested-side{display:grid;grid-template-rows:1fr 1fr;gap:3px}.suggested-copy{padding:30px;display:flex;flex-direction:column;justify-content:center}.suggested-copy h2{font-size:29px;letter-spacing:-.04em;margin:12px 0 8px}.suggested-copy p{font-size:14px;color:var(--sub);line-height:1.55;margin:0}.inline-actions{display:flex;gap:8px;margin-top:14px}.memory-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.memory-item{cursor:pointer}.memory-cover{aspect-ratio:4/3;border-radius:18px;overflow:hidden;position:relative}.item-type{position:absolute;left:10px;top:10px}.item-count{position:absolute;right:10px;bottom:10px;background:rgba(0,0,0,.5);color:#fff;border-radius:999px;padding:4px 8px;font-size:10px}.memory-info{padding:11px 2px}.memory-info strong{font-size:16px;display:block}.memory-info span{font-size:12px;color:var(--sub);display:block;margin-top:3px} +.big-search{height:52px;max-width:760px}.search-layout{display:grid;gap:34px}.recent-searches{display:flex;gap:8px;flex-wrap:wrap}.people-row{display:flex;gap:18px;overflow:auto;padding-bottom:3px}.person{min-width:78px;text-align:center}.person-avatar{width:66px;height:66px;border-radius:50%;margin:auto;background:linear-gradient(135deg,#c8d2ca,#d8c5b4);display:grid;place-items:center;font-weight:750;font-size:18px;color:#45554b}.person-avatar.warm{background:linear-gradient(135deg,#d7c6b6,#b9c2c9)}.person-avatar.lilac{background:linear-gradient(135deg,#c8c0d4,#c9d8cc)}.person-avatar.pale{background:linear-gradient(135deg,#d5cfae,#c5b8aa)}.person span{display:block;font-size:12px;margin-top:7px}.place-grid{display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:10px}.place-card{height:210px;border-radius:18px;overflow:hidden;position:relative;cursor:pointer}.place-copy{position:absolute;left:16px;bottom:15px;z-index:2;color:#fff}.place-copy span{display:block;font-size:11px;opacity:.78}.place-copy strong{font-size:18px;display:block;margin-top:2px}.type-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.type-card{background:#fff;border:1px solid var(--line);border-radius:15px;padding:16px;display:flex;align-items:center;justify-content:space-between}.type-card strong{font-size:14px;display:block}.type-card span{display:block;font-size:11px;color:var(--sub);margin-top:3px}.iconbox{width:36px;height:36px;border-radius:10px;background:var(--surface2);display:grid;place-items:center}.year-row{display:grid;grid-template-columns:repeat(5,1fr);gap:8px}.year-row article{background:#fff;border:1px solid var(--line);border-radius:14px;padding:16px}.year-row strong{font-size:24px;display:block}.year-row span{font-size:11px;color:var(--sub);display:block;margin-top:4px} +.detail-page{max-width:1180px}.back-row{margin-bottom:12px}.place-detail-head{background:#e7ebe7;border-radius:24px;overflow:hidden}.osm-map{height:340px}.osm-map iframe,.map-wrap iframe{width:100%;height:100%;border:0}.place-detail-copy{padding:24px}.place-detail-copy h1{font-size:38px;letter-spacing:-.045em;margin:10px 0 5px}.place-detail-copy p{font-size:13px;color:var(--sub);margin:0}.detail-hero{height:67vh;min-height:520px;border-radius:26px;overflow:hidden;position:relative}.detail-hero:after{content:'';position:absolute;inset:0;background:linear-gradient(180deg,rgba(0,0,0,.04),rgba(0,0,0,.65))}.detail-back,.detail-actions{position:absolute;top:18px;z-index:3}.detail-back{left:18px}.detail-actions{right:18px;display:flex;gap:7px}.detail-copy{position:absolute;left:32px;right:32px;bottom:30px;z-index:2;color:#fff}.detail-copy h1{font-size:48px;letter-spacing:-.055em;margin:10px 0 7px}.detail-copy p{font-size:13px;margin:0;opacity:.86}.detail-tabs{display:flex;gap:6px;margin:16px 0 44px;border-bottom:1px solid var(--line)}.detail-tabs button{height:43px;border:0;background:transparent;padding:0 14px;color:var(--sub);font-weight:650;border-bottom:2px solid transparent}.detail-tabs button.active{color:var(--ink);border-bottom-color:var(--ink)}.story{max-width:900px;margin:auto}.moment{margin-bottom:70px}.moment-label{font-size:11px;color:#8a8d87;font-weight:720}.moment h2{font-size:29px;letter-spacing:-.035em;margin:7px 0}.moment-meta{font-size:12px;color:var(--sub);margin-bottom:17px}.story-wide{height:470px;border-radius:18px;overflow:hidden}.story-wide.last{height:430px}.story-pair{display:grid;grid-template-columns:1.15fr .85fr;gap:6px;margin-top:6px}.story-pair>div{height:290px;border-radius:14px;overflow:hidden}.story-mosaic{display:grid;grid-template-columns:1.5fr 1fr;grid-template-rows:190px 190px;gap:6px}.story-mosaic>div{overflow:hidden;border-radius:14px}.story-mosaic>div:first-child{grid-row:1/3}.map-wrap{margin-top:8px;border-radius:18px;overflow:hidden;height:300px;border:1px solid var(--line);background:#e8ece8}.all-photos{display:none}.all-photos.active{display:block}.story-pane.hidden{display:none}.detail-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:3px}.detail-grid>div{aspect-ratio:1;overflow:hidden}.info-card{max-width:720px;margin:auto;background:#fff;border:1px solid var(--line);border-radius:18px;padding:20px}.info-card>p{font-size:13px;color:var(--sub);line-height:1.6}.status-row.compact article{background:var(--surface2);border-radius:14px;padding:14px}.status-row.compact span{display:block;font-size:11px;color:var(--sub)}.status-row.compact strong{font-size:22px;display:block;margin-top:3px} +.selection-bar{position:fixed;left:calc(var(--side) + 50%);transform:translateX(-50%);bottom:20px;z-index:95;background:#171816;color:#fff;border-radius:16px;padding:9px 10px;display:none;gap:7px;align-items:center;box-shadow:0 16px 48px rgba(0,0,0,.22)}.selection-bar.show{display:flex}.selection-bar button{border:0;background:#2e302d;color:#fff;border-radius:10px;padding:9px 11px;font-size:12px}.selection-bar .count{padding:0 10px;font-size:12px;font-weight:680} +.scrim{position:fixed;inset:0;background:rgba(0,0,0,.34);z-index:150;display:none}.scrim.show{display:block}.modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-46%);width:min(650px,calc(100vw - 28px));max-height:85vh;overflow:auto;background:#fff;border-radius:22px;z-index:160;opacity:0;pointer-events:none;transition:.18s;box-shadow:0 24px 70px rgba(0,0,0,.22)}.modal.show{opacity:1;pointer-events:auto;transform:translate(-50%,-50%)}.modal-head,.drawer-head{display:flex;align-items:center;justify-content:space-between;padding:18px 18px 12px}.modal-head>div>strong{display:block}.modal-head>div>span{display:block;font-size:11px;color:var(--sub);margin-top:3px}.modal-body{padding:0 18px 18px}.dropzone{border:1.5px dashed #c9ccc6;background:#fafaf8;border-radius:16px;padding:34px 20px;text-align:center}.dropzone strong{font-size:18px}.dropzone p{font-size:13px;color:var(--sub)}.upload-options{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:10px}.option-card{border:1px solid var(--line);background:#fff;border-radius:14px;padding:15px;text-align:left}.option-card strong{display:block}.option-card span{display:block;font-size:11px;color:var(--sub);margin-top:5px}.queue{display:none;margin-top:16px}.queue-item{display:grid;grid-template-columns:42px 1fr auto;gap:10px;align-items:center;padding:8px 0}.queue-thumb{width:42px;height:42px;border-radius:9px;overflow:hidden}.queue-item strong{font-size:12px;display:block}.queue-item span{font-size:11px;color:var(--sub)}.progress{height:5px;border-radius:99px;background:#e7e8e3;overflow:hidden;margin-top:5px}.progress span{display:block;width:64%;height:100%;background:var(--accent)} +.drawer{position:fixed;right:0;top:0;bottom:0;width:min(400px,92vw);background:#fff;z-index:160;transform:translateX(100%);transition:.2s;box-shadow:-15px 0 45px rgba(0,0,0,.12);visibility:hidden}.drawer.show{transform:none;visibility:visible}.drawer-body{padding:6px 18px 20px}.profile-card{display:flex;align-items:center;gap:11px;padding:10px 0 16px}.avatar.big{width:52px;height:52px}.profile-card strong{display:block}.profile-card span:last-child{display:block;font-size:11px;color:var(--sub);margin-top:3px}.stat-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}.stat-grid article{background:var(--surface2);border-radius:14px;padding:14px}.stat-grid span,.stat-grid small{display:block;font-size:11px;color:var(--sub)}.stat-grid strong{display:block;font-size:22px;margin:3px 0}.menu-list{margin-top:16px;border-top:1px solid var(--line)}.menu-list button,.menu-list a{height:49px;border:0;border-bottom:1px solid var(--line);background:#fff;width:100%;display:flex;align-items:center;justify-content:space-between;font-size:13px;text-align:left}.menu-list span{color:var(--sub);font-size:11px}.menu-list .danger{color:var(--danger)} +.viewer{position:fixed;inset:0;background:#10110f;z-index:300;display:none;place-items:center}.viewer.show{display:grid}.viewer img{width:auto;height:auto;max-width:92vw;max-height:88vh;object-fit:contain}.viewer-close{position:absolute;top:18px;left:18px;width:42px;height:42px;border-radius:50%;border:0;background:rgba(255,255,255,.14);color:#fff;font-size:22px}.viewer-meta{position:absolute;bottom:18px;left:50%;transform:translateX(-50%);padding:7px 11px;border-radius:999px;background:rgba(0,0,0,.35);color:#fff;font-size:12px}.toast{position:fixed;right:22px;bottom:22px;z-index:400;background:#171816;color:#fff;border-radius:11px;padding:11px 14px;font-size:12px;opacity:0;transform:translateY(8px);transition:.18s}.toast.show{opacity:1;transform:none}.mobile-top,.mobile-tabs{display:none} +@media(max-width:1050px){.media-grid{grid-template-columns:repeat(5,1fr)}.memory-grid{grid-template-columns:repeat(2,1fr)}.today-grid{grid-template-columns:repeat(5,1fr)}.today-grid>div:nth-child(n+6){display:none}.place-grid{grid-template-columns:1fr 1fr}.place-grid>*:last-child{display:none}} +@media(max-width:720px){:root{--side:0px}.sidebar{display:none}.mobile-top{display:flex;position:fixed;top:0;left:0;right:0;height:58px;align-items:center;justify-content:space-between;padding:0 14px;background:rgba(244,244,241,.93);backdrop-filter:blur(15px);z-index:70}.mobile-top .brand{padding:0;font-size:18px}.mobile-profile{width:auto;padding:0}.mobile-tabs{display:grid;position:fixed;left:9px;right:9px;bottom:9px;height:62px;grid-template-columns:repeat(4,1fr);padding:5px;background:rgba(23,24,22,.96);border-radius:19px;z-index:110}.mobile-tabs button{border:0;background:transparent;color:#aeb0aa;border-radius:14px;display:grid;place-items:center;font-size:16px}.mobile-tabs button.active{background:#353734;color:#fff}.mobile-tabs svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8}.mobile-tabs small{font-size:9px}.main{margin:0;padding:72px 13px 88px}.page-head{margin-bottom:18px}.h1{font-size:30px}.page-head-actions .btn span{display:none}.discovery-card{grid-template-columns:1fr;min-height:0;border-radius:22px}.discovery-media{min-height:290px}.discovery-copy{padding:24px 21px}.discovery-copy h2{font-size:31px}.memory-strip{grid-template-columns:1.2fr 1fr;gap:8px}.memory-strip>*:last-child{display:none}.memory-card{height:205px}.intake-row{grid-template-columns:1fr}.today-grid{grid-template-columns:repeat(4,1fr);gap:3px}.today-grid>div:nth-child(n+5){display:none}.status-row{grid-template-columns:1fr}.section{margin-top:30px}.tool-row{top:61px;margin-left:-13px;margin-right:-13px;padding:0 13px;overflow:auto}.tool-row .field{min-width:235px}.media-grid{grid-template-columns:repeat(3,1fr);grid-auto-rows:90px}.select-mark{opacity:.72}.suggested-banner{grid-template-columns:1fr}.suggested-visual{min-height:230px}.suggested-copy{padding:22px}.memory-grid{grid-template-columns:1fr 1fr;gap:12px 7px}.memory-cover{aspect-ratio:1;border-radius:14px}.search-layout{gap:28px}.place-grid{grid-template-columns:1fr 1fr;gap:8px}.place-card{height:180px}.type-grid{grid-template-columns:1fr 1fr}.year-row{grid-template-columns:1fr 1fr}.detail-page{margin:-72px -13px -88px;width:auto}.back-row{padding:72px 13px 0}.place-detail-head{border-radius:0}.place-detail-copy{padding:20px}.detail-hero{height:70vh;min-height:520px;border-radius:0}.detail-back,.detail-actions{top:70px}.detail-copy{left:20px;right:20px;bottom:24px}.detail-copy h1{font-size:38px}.detail-tabs{padding:0 13px;margin-top:10px}.story{padding:0 13px}.story-wide{height:52vh}.story-pair>div{height:230px}.story-mosaic{grid-template-rows:165px 165px}.detail-grid{grid-template-columns:repeat(3,1fr)}.selection-bar{left:9px;right:9px;bottom:80px;transform:none;justify-content:space-between}.selection-bar .count{display:none}.modal{left:8px;right:8px;bottom:8px;top:auto;width:auto;transform:translateY(104%);border-radius:20px}.modal.show{transform:none}.upload-options{grid-template-columns:1fr}.viewer-meta{bottom:84px;white-space:nowrap}.toast{left:12px;right:12px;bottom:82px;text-align:center}} + +/* Interaction-complete pages */ +.collection-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:18px}.collection-toolbar .field{width:340px}.album-full-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.album-manual-head{display:grid;grid-template-columns:minmax(300px,.9fr) 1.1fr;gap:26px;align-items:center;background:#fff;border:1px solid var(--line);border-radius:24px;padding:18px}.album-manual-cover{aspect-ratio:4/3;border-radius:18px;overflow:hidden}.album-manual-copy{padding:12px 18px}.album-inline-back{padding-left:0;margin-bottom:18px}.album-manual-copy h1{font-size:40px;letter-spacing:-.045em;margin:10px 0 6px}.album-manual-copy p{color:var(--sub);font-size:13px;margin:0 0 22px}.album-tabs{margin-bottom:28px}.album-pane{display:none}.album-pane.active{display:block}.album-grid-toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.album-grid-toolbar>div:first-child strong{font-size:14px}.album-grid-toolbar>div:first-child span{font-size:11px;color:var(--sub);margin-left:8px}.album-photo-grid.select-mode .viewable:after{content:'';position:absolute;left:8px;top:8px;width:22px;height:22px;border-radius:50%;background:#fff;border:1px solid rgba(0,0,0,.15)}.album-photo-grid .viewable{position:relative;cursor:pointer} +.people-full-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:18px}.people-full-grid article{text-align:center;cursor:pointer}.person-photo{aspect-ratio:1;border-radius:50%;display:grid;place-items:center;font-size:30px;font-weight:760;color:#45554b;margin-bottom:9px;background:linear-gradient(135deg,#cbd5ce,#ddd0bd)}.tone-a{background:linear-gradient(135deg,#cbd5ce,#ddd0bd)}.tone-b{background:linear-gradient(135deg,#dcc8b7,#c0c9ce)}.tone-c{background:linear-gradient(135deg,#c9c0d8,#ccdbcf)}.tone-d{background:linear-gradient(135deg,#d8cdb0,#c9bcae)}.tone-e{background:linear-gradient(135deg,#bad0cb,#d6c7bd)}.tone-f{background:linear-gradient(135deg,#c9cfd8,#d9c4cf)}.people-full-grid strong{display:block;font-size:14px}.people-full-grid span{display:block;font-size:11px;color:var(--sub);margin-top:3px}.person-detail-head{display:flex;align-items:center;gap:22px;background:#fff;border:1px solid var(--line);border-radius:22px;padding:22px}.big-person{width:116px;height:116px;flex:none;margin:0;font-size:38px}.person-detail-head h1{font-size:34px;letter-spacing:-.04em;margin:8px 0 4px}.person-detail-head p{font-size:12px;color:var(--sub);margin:0 0 13px} +.places-layout{display:grid;grid-template-columns:1fr 320px;gap:14px}.places-big-map{height:620px;border-radius:22px;overflow:hidden;border:1px solid var(--line);background:#e7ebe7}.places-big-map iframe{width:100%;height:100%;border:0}.place-list{background:#fff;border:1px solid var(--line);border-radius:18px;overflow:hidden;height:max-content}.place-list button{width:100%;border:0;border-bottom:1px solid var(--line);background:#fff;padding:16px;display:flex;align-items:center;justify-content:space-between;text-align:left}.place-list button:last-child{border-bottom:0}.place-list strong{display:block;font-size:14px}.place-list small{display:block;font-size:11px;color:var(--sub);margin-top:3px} +.settings-shell{display:grid;grid-template-columns:220px 1fr;gap:18px}.settings-nav{display:grid;gap:5px;height:max-content}.settings-nav button{height:42px;border:0;background:transparent;border-radius:11px;text-align:left;padding:0 12px;color:var(--sub)}.settings-nav button.active{background:#e6e7e2;color:var(--ink);font-weight:680}.settings-content{background:#fff;border:1px solid var(--line);border-radius:20px;padding:20px;min-height:430px}.settings-card{border:1px solid var(--line);border-radius:15px;padding:15px;margin-bottom:10px}.settings-card:last-child{margin-bottom:0}.settings-card-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.settings-card strong{font-size:14px}.settings-card p{font-size:12px;color:var(--sub);margin:5px 0 0;line-height:1.5}.device-row{display:grid;grid-template-columns:44px 1fr auto;gap:12px;align-items:center}.device-icon{width:44px;height:44px;border-radius:12px;background:var(--surface2);display:grid;place-items:center;font-weight:700}.toggle{width:42px;height:24px;border-radius:999px;background:#c9cbc6;position:relative;border:0;padding:0}.toggle:after{content:'';position:absolute;width:18px;height:18px;border-radius:50%;background:#fff;left:3px;top:3px;transition:.18s}.toggle.on{background:var(--accent)}.toggle.on:after{left:21px}.storage-meter{height:8px;border-radius:99px;background:#e6e7e2;overflow:hidden;margin-top:12px}.storage-meter span{display:block;height:100%;width:42%;background:var(--accent)} +.form-label{display:grid;gap:7px;font-size:12px;font-weight:680;margin-bottom:15px}.text-input{height:44px;border:1px solid var(--line);border-radius:12px;padding:0 12px;font:inherit;outline:0}.text-input:focus{border-color:#aabaae;box-shadow:0 0 0 3px #e5eee8}.cover-picker{display:grid;grid-template-columns:repeat(4,1fr);gap:7px}.cover-picker button{border:2px solid transparent;padding:0;border-radius:12px;overflow:hidden;aspect-ratio:1;background:#ddd}.cover-picker button.active{border-color:var(--accent)}.check-row{display:flex;align-items:center;justify-content:space-between;gap:16px;border-top:1px solid var(--line);padding:14px 0}.check-row strong{display:block;font-size:13px}.check-row small{display:block;font-size:11px;color:var(--sub);margin-top:3px;font-weight:400}.check-row input{width:18px;height:18px;accent-color:var(--accent)}.modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:18px}.share-link{display:flex;gap:8px;align-items:center;background:var(--surface2);border-radius:12px;padding:10px}.share-link span{flex:1;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.edit-options{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px}.settings-list>div{display:flex;align-items:center;justify-content:space-between;padding:13px 0;border-bottom:1px solid var(--line);font-size:13px}.settings-list>div:last-child{border-bottom:0}.settings-list span{color:var(--sub)} +.memory-card,.person,.type-card,.year-row article,.place-card,.memory-item{transition:transform .18s,box-shadow .18s}.memory-card:hover,.place-card:hover,.memory-item:hover{transform:translateY(-2px)}.person:hover,.type-card:hover,.year-row article:hover{transform:translateY(-1px)}.type-card,.year-row article{cursor:pointer} +@media(max-width:1050px){.album-full-grid{grid-template-columns:repeat(2,1fr)}.people-full-grid{grid-template-columns:repeat(4,1fr)}.places-layout{grid-template-columns:1fr}.place-list{display:grid;grid-template-columns:1fr 1fr}.place-list button:nth-child(odd){border-right:1px solid var(--line)}.settings-shell{grid-template-columns:180px 1fr}} +@media(max-width:720px){.collection-toolbar{align-items:stretch;flex-direction:column}.collection-toolbar .field{width:100%}.album-full-grid{grid-template-columns:1fr 1fr;gap:12px 7px}.album-manual-head{grid-template-columns:1fr;border-radius:0;border-left:0;border-right:0;padding:13px}.album-manual-copy{padding:4px 5px 14px}.album-manual-copy h1{font-size:32px}.people-full-grid{grid-template-columns:repeat(3,1fr);gap:14px}.person-detail-head{border-radius:0;border-left:0;border-right:0}.big-person{width:92px;height:92px}.places-layout{grid-template-columns:1fr}.places-big-map{height:58vh;border-radius:0;margin-left:-13px;margin-right:-13px}.place-list{grid-template-columns:1fr}.place-list button:nth-child(odd){border-right:0}.settings-shell{grid-template-columns:1fr}.settings-nav{display:flex;overflow:auto}.settings-nav button{white-space:nowrap}.cover-picker{grid-template-columns:repeat(4,1fr)}.edit-options{grid-template-columns:1fr}} + +.dense-library .media-grid{grid-template-columns:repeat(9,1fr);grid-auto-rows:78px}.dense-library .media-tile,.dense-library .media-tile.wide,.dense-library .media-tile.tall,.dense-library .media-tile.large{grid-column:span 1;grid-row:span 1}.album-photo-grid.select-mode .viewable.selected:after{content:'✓';position:absolute;inset:0;display:grid;place-items:center;background:rgba(73,99,86,.45);color:#fff;font-size:22px;font-weight:800}.album-photo-grid.select-mode .viewable{cursor:pointer} +@media(max-width:720px){.dense-library .media-grid{grid-template-columns:repeat(4,1fr);grid-auto-rows:82px}} diff --git a/public/beta.js b/public/beta.js new file mode 100644 index 0000000..5fe0e23 --- /dev/null +++ b/public/beta.js @@ -0,0 +1,353 @@ +const P=Array.from({length:11},(_,i)=>'./assets/photo-'+(i+1)+'.jpg'); + +const groups=[ + ['9월 15일','오늘 · Galaxy에서 42개 동기화됨',0], + ['9월 13일','서울 · 24개 항목',4], + ['8월 29일','강릉 · 18개 항목',7] +]; +const layout=['large','wide','tall','','wide','','tall','','','wide','','']; +const memories=[ + ['강릉에서 보낸 주말','1년 전 오늘 · 67개',P[1],67], + ['가평 드라이브','2025.10.03 · 41개',P[2],41], + ['서울의 겨울','2025.12 — 2026.02 · 123개',P[4],123], + ['처음 떠난 부산','2023.08.18 — 08.21 · 108개',P[7],108], + ['평범했던 봄','2025.03 — 05 · 96개',P[9],96], + ['산으로 간 날','2024.11.02 · 34개',P[10],34] +]; +const albums=[ + ['가족 사진','124개 · 최근 수정 9월 14일',P[5],124,false], + ['프로필 후보','48개 · 최근 수정 9월 10일',P[8],48,false], + ['2026 제주 베스트','36개 · 공유 중',P[0],36,true], + ['강아지','82개 · 최근 수정 8월 21일',P[10],82,false], + ['인테리어 참고','64개 · 최근 수정 8월 08일',P[4],64,false], + ['친구들과','91개 · 공유 중',P[2],91,true] +]; + +function memoryCard(a,type){ + return '
'+type+''+a[3]+'
'+a[0]+''+a[1]+'
'; +} +function albumCard(a){ + return '
'+(a[4]?'공유 Album':'Album')+''+a[3]+'
'+a[0]+''+a[1]+'
'; +} + +function buildInitialUI(){ + const today=document.getElementById('todayGrid'); + P.slice(0,7).forEach(u=>today.insertAdjacentHTML('beforeend','
')); + + const lib=document.getElementById('libraryContent'); + groups.forEach((g,gi)=>{ + let html='

'+g[0]+'

'+g[1]+'
'; + for(let i=0;i<12;i++){ + const cls=layout[(i+gi)%layout.length]; + const state=i===3?'▶ 0:18':i===6?'중복 후보':i===8?'✓ 서버':''; + html+='
✓'+state+'
'; + } + html+='
'; + lib.insertAdjacentHTML('beforeend',html); + }); + + memories.slice(0,4).forEach((a,i)=>document.getElementById('savedMemories').insertAdjacentHTML('beforeend',memoryCard(a,i===0?'Memory':'자동 Memory'))); + memories.slice(4).forEach(a=>document.getElementById('manualAlbums').insertAdjacentHTML('beforeend',memoryCard(a,'Album'))); + albums.forEach(a=>document.getElementById('albumsPageGrid').insertAdjacentHTML('beforeend',albumCard(a))); + + ['placePhotos','memoryPhotos','personPhotos','albumPhotos'].forEach((id,offset)=>{ + const el=document.getElementById(id); + if(!el)return; + for(let i=0;i<15;i++)el.insertAdjacentHTML('beforeend','
'); + }); +} +buildInitialUI(); + +let lastPage='home'; +function showPage(name){ + if(!['memory','place','album','person'].includes(name))lastPage=name; + document.querySelectorAll('.page').forEach(p=>p.classList.toggle('active',p.id==='page-'+name)); + document.querySelectorAll('[data-page]').forEach(b=>b.classList.toggle('active',b.dataset.page===name)); + window.scrollTo(0,0); +} +function updateMemoryDetail(card){ + if(!card)return; + const title=card.querySelector('.memory-info strong,.memory-copy strong,h2')?.textContent?.trim(); + const img=card.querySelector('img')?.src; + const meta=card.querySelector('.memory-info span,.memory-copy span')?.textContent?.trim(); + if(title)document.getElementById('memoryDetailTitle').textContent=title; + if(img)document.getElementById('memoryDetailCover').src=img; + if(meta)document.getElementById('memoryDetailMeta').textContent=meta+' · 자동 구성 Memory'; +} +function updateAlbumDetail(card){ + if(!card)return; + const title=card.querySelector('.memory-info strong')?.textContent?.trim()||'가족 사진'; + const img=card.querySelector('img')?.src; + const meta=card.querySelector('.memory-info span')?.textContent?.trim()||'124개'; + document.getElementById('albumDetailTitle').textContent=title; + document.getElementById('albumDetailMeta').textContent=meta; + if(img)document.getElementById('albumDetailCover').src=img; +} +document.addEventListener('click',e=>{ + const nav=e.target.closest('[data-page]'); + if(nav){showPage(nav.dataset.page);return;} + const memory=e.target.closest('[data-open-memory],.memory-card'); + if(memory){updateMemoryDetail(memory);showPage('memory');return;} + const album=e.target.closest('[data-open-album]'); + if(album){updateAlbumDetail(album);showPage('album');return;} +}); +document.querySelectorAll('[data-back]').forEach(b=>b.onclick=()=>showPage(lastPage)); + +/* overlays */ +const scrim=document.getElementById('scrim'); +const modals=[...document.querySelectorAll('.modal')]; +const drawer=document.getElementById('profileDrawer'); +function closeOverlay(){ + scrim.classList.remove('show'); + modals.forEach(m=>m.classList.remove('show')); + drawer.classList.remove('show'); +} +function openOverlay(el){ + closeOverlay(); + scrim.classList.add('show'); + el.classList.add('show'); +} +function openUpload(){openOverlay(document.getElementById('uploadModal'))} +function openProfile(){openOverlay(drawer)} +document.querySelectorAll('[data-upload]').forEach(b=>b.onclick=openUpload); +document.querySelectorAll('[data-profile]').forEach(b=>b.onclick=openProfile); +document.querySelectorAll('[data-close]').forEach(b=>b.onclick=closeOverlay); +scrim.onclick=closeOverlay; + +/* upload */ +document.getElementById('fakeChoose').onclick=()=>{ + document.getElementById('uploadQueue').style.display='block'; + toast('선택한 파일 2개를 Queue에 추가했습니다.'); +}; +document.querySelector('[data-folder-upload]').onclick=()=>{ + document.getElementById('uploadQueue').style.display='block'; + toast('폴더에서 128개 항목을 찾았습니다.'); +}; +document.querySelector('[data-sync-settings]').onclick=()=>{ + closeOverlay(); + openSettings('backup-settings'); +}; + +/* library */ +const summary=document.getElementById('filterSummary'); +const filterText=document.getElementById('filterText'); +let currentFilter=''; +function setFilter(f,label){ + currentFilter=f; + document.querySelectorAll('[data-filter]').forEach(b=>b.classList.toggle('active',b.dataset.filter===f)); + const m={ + date:(label||'2026년 9월')+' · 날짜 필터 적용 중', + type:(label||'사진')+' · 미디어 유형 필터 적용 중', + unorganized:'정리 안 됨 · 어떤 Memory나 Album에도 포함되지 않은 128장', + duplicate:'중복 후보 · 시각적으로 유사한 사진 14장' + }; + filterText.textContent=m[f]||''; + summary.classList.toggle('show',!!f); + document.querySelectorAll('.media-tile').forEach((tile,i)=>{ + const hide=f==='duplicate' ? i%6!==0 : f==='unorganized' ? i%4===0 : false; + tile.style.display=hide?'none':''; + }); +} +document.querySelectorAll('[data-filter]').forEach(b=>b.onclick=()=>setFilter(b.dataset.filter)); +document.getElementById('clearFilter').onclick=()=>{setFilter('');document.querySelectorAll('.media-tile').forEach(t=>t.style.display='')}; +document.querySelector('[data-unorganized]').onclick=()=>{showPage('library');setFilter('unorganized')}; +document.querySelector('[data-duplicate]').onclick=()=>{showPage('library');setFilter('duplicate')}; +document.querySelectorAll('[data-view]').forEach(b=>b.onclick=()=>{ + document.querySelectorAll('[data-view]').forEach(x=>x.classList.toggle('active',x===b)); + document.getElementById('libraryContent').classList.toggle('dense-library',b.dataset.view==='dense'); +}); +const librarySearch=document.querySelector('#page-library .field input'); +librarySearch.addEventListener('keydown',e=>{if(e.key==='Enter'&&librarySearch.value.trim()){filterText.textContent='"'+librarySearch.value.trim()+'" 검색 결과 · 24개 항목';summary.classList.add('show')}}); + +let selected=new Set(); +const selBar=document.getElementById('selectionBar'),selCount=document.getElementById('selectionCount'); +function updateSelection(){selBar.classList.toggle('show',selected.size>0);selCount.textContent=selected.size+'개 선택'} +document.querySelectorAll('.media-tile').forEach(t=>t.onclick=()=>{ + const k=t.dataset.key; + if(selected.has(k)){selected.delete(k);t.classList.remove('selected')}else{selected.add(k);t.classList.add('selected')} + updateSelection(); +}); +document.querySelectorAll('[data-select-group]').forEach(b=>b.onclick=()=>{ + const gi=b.dataset.selectGroup; + const tiles=[...document.querySelectorAll('.media-tile[data-group="'+gi+'"]')].filter(t=>t.style.display!=='none'); + const all=tiles.every(t=>selected.has(t.dataset.key)); + tiles.forEach(t=>{if(all){selected.delete(t.dataset.key);t.classList.remove('selected')}else{selected.add(t.dataset.key);t.classList.add('selected')}}); + b.textContent=all?'전체 선택':'선택 해제'; + updateSelection(); +}); +document.getElementById('clearSelection').onclick=()=>{ + selected.clear();document.querySelectorAll('.media-tile.selected').forEach(t=>t.classList.remove('selected'));updateSelection(); +}; +document.querySelectorAll('.selection-bar button:not(#clearSelection)').forEach(b=>b.onclick=()=>toast(b.textContent+' · '+selected.size+'개 항목 처리 준비')); + +/* memories + albums */ +document.getElementById('saveSuggested').onclick=e=>saveMemoryButton(e.currentTarget); +document.querySelectorAll('[data-save-memory]').forEach(b=>b.onclick=e=>saveMemoryButton(e.currentTarget)); +function saveMemoryButton(btn){btn.textContent='보관됨 ✓';btn.disabled=true;toast('Memory에 보관했습니다.')} +document.querySelector('[data-sort-memories]').onclick=e=>{ + const b=e.currentTarget; + b.dataset.sort=b.dataset.sort==='date'?'recent':'date'; + b.textContent=b.dataset.sort==='date'?'정렬: 촬영일 순':'정렬: 최근 본 순'; + toast(b.textContent+'으로 변경했습니다.'); +}; +document.querySelectorAll('[data-create-album]').forEach(b=>b.onclick=()=>openOverlay(document.getElementById('createAlbumModal'))); +document.querySelectorAll('.cover-picker button').forEach(b=>b.onclick=()=>{document.querySelectorAll('.cover-picker button').forEach(x=>x.classList.toggle('active',x===b))}); +document.getElementById('confirmCreateAlbum').onclick=()=>{ + const name=document.getElementById('newAlbumName').value.trim()||'새로운 Album'; + const a=[name,'0개 · 방금 생성',P[5],0,false]; + document.getElementById('albumsPageGrid').insertAdjacentHTML('afterbegin',albumCard(a)); + document.getElementById('manualAlbums').insertAdjacentHTML('afterbegin',memoryCard(a,'Album')); + closeOverlay();showPage('albums');toast(name+' Album을 만들었습니다.'); +}; +document.querySelectorAll('[data-album-filter]').forEach(b=>b.onclick=()=>{ + document.querySelectorAll('[data-album-filter]').forEach(x=>x.classList.toggle('active',x===b)); + document.querySelectorAll('#albumsPageGrid .album-list-item').forEach(card=>card.style.display=b.dataset.albumFilter==='shared'&&card.dataset.shared!=='true'?'none':''); +}); +document.querySelector('[data-album-sort]').onclick=e=>{ + const grid=document.getElementById('albumsPageGrid'); + [...grid.children].reverse().forEach(c=>grid.appendChild(c)); + e.currentTarget.textContent=e.currentTarget.textContent==='최근 수정순'?'이름순':'최근 수정순'; +}; +document.getElementById('albumSearch').addEventListener('input',e=>{ + const q=e.target.value.trim().toLowerCase(); + document.querySelectorAll('#albumsPageGrid .album-list-item').forEach(card=>card.style.display=card.textContent.toLowerCase().includes(q)?'':'none'); +}); + +/* album detail */ +document.querySelectorAll('[data-album-tab]').forEach(b=>b.onclick=()=>{ + document.querySelectorAll('[data-album-tab]').forEach(x=>x.classList.toggle('active',x===b)); + document.querySelectorAll('.album-pane').forEach(p=>p.classList.remove('active')); + document.getElementById(b.dataset.albumTab==='grid'?'albumGridPane':b.dataset.albumTab==='story'?'albumStoryPane':'albumInfoPane').classList.add('active'); +}); +document.querySelector('[data-album-order]').onclick=e=>{ + e.currentTarget.textContent=e.currentTarget.textContent==='직접 설정'?'촬영일 순':'직접 설정'; + toast('Album 정렬 방식을 '+e.currentTarget.textContent+'으로 변경했습니다.'); +}; +document.querySelector('[data-album-select]').onclick=e=>{ + const grid=document.getElementById('albumPhotos'); + grid.classList.toggle('select-mode'); + if(!grid.classList.contains('select-mode')) grid.querySelectorAll('.selected').forEach(x=>x.classList.remove('selected')); + e.currentTarget.textContent=grid.classList.contains('select-mode')?'선택 종료':'선택'; +}; +document.getElementById('albumPhotos').addEventListener('click',e=>{ + const item=e.target.closest('.viewable'); + if(item && document.getElementById('albumPhotos').classList.contains('select-mode')){ + e.stopPropagation(); item.classList.toggle('selected'); + } +},true); +document.querySelector('[data-add-album-photos]').onclick=openUpload; +document.querySelector('[data-edit-album]').onclick=()=>openAction('Album 편집','이름과 커버를 변경합니다.','','저장',()=>toast('Album 정보를 저장했습니다.')); +document.querySelector('[data-album-more]').onclick=()=>openAction('Album 관리','이 Album에 적용할 작업을 선택합니다.','
커버 사진 변경›
Album 복제›
사진만 제거›
Album 삭제›
','완료',()=>toast('Album 관리 설정을 반영했습니다.')); + +/* search */ +const bigSearch=document.querySelector('.big-search input'); +document.querySelectorAll('[data-search-term]').forEach(b=>b.onclick=()=>{ + bigSearch.value=b.dataset.searchTerm; + if(b.dataset.searchTerm==='제주')openPlace('제주도');else if(b.dataset.searchTerm==='동영상'){showPage('library');setFilter('type','동영상')}else{showPage('library');setFilter('date',b.dataset.searchTerm)} +}); +bigSearch.addEventListener('keydown',e=>{if(e.key==='Enter'&&bigSearch.value.trim()){showPage('library');filterText.textContent='"'+bigSearch.value.trim()+'" 검색 결과';summary.classList.add('show')}}); + +const people={나:['나','842장의 사진 · 18개의 Memory'],가족:['가','381장의 사진 · 12개의 Memory'],친구:['친','264장의 사진 · 8개의 Memory']}; +document.querySelectorAll('[data-person]').forEach(el=>el.onclick=()=>openPerson(el.dataset.person)); +function openPerson(name){ + const d=people[name]||[name[0]||'?','사진 모음']; + document.getElementById('personTitle').textContent=name; + document.getElementById('personInitial').textContent=d[0]; + document.getElementById('personMeta').textContent=d[1]; + showPage('person'); +} +document.querySelectorAll('[data-name-person]').forEach(b=>b.onclick=()=>openAction('사람 이름 지정','이 얼굴 그룹에 이름을 붙입니다.','','저장',()=>toast('사람 이름을 저장했습니다.'))); +document.querySelector('[data-rename-person]').onclick=()=>openAction('이름 변경','이 사람의 표시 이름을 변경합니다.','','저장',()=>toast('이름을 변경했습니다.')); +document.querySelector('[data-person-sort]').onclick=e=>{e.currentTarget.textContent=e.currentTarget.textContent==='최신순'?'오래된 순':'최신순'}; + +const placeData={ + 제주도:{count:'168',bbox:'126.13%2C33.15%2C126.95%2C33.58'}, + 서울:{count:'624',bbox:'126.76%2C37.42%2C127.18%2C37.70'}, + 강릉:{count:'91',bbox:'128.78%2C37.65%2C129.12%2C37.86'}, + 부산:{count:'108',bbox:'128.85%2C35.02%2C129.30%2C35.30'} +}; +function openPlace(name){ + const d=placeData[name]||placeData['제주도']; + document.getElementById('placeTitle').textContent=name; + document.getElementById('placeDesc').textContent='GPS 메타데이터가 '+name+'로 분류된 '+d.count+'장의 사진과 영상 · 사진이 추가되면 자동으로 갱신됩니다.'; + document.getElementById('placeAllTitle').textContent=name+'에서 찍은 모든 사진'; + const pr=document.getElementById('placeRecordTitle'); if(pr) pr.textContent=name==='제주도'?'제주, 여름의 끝':name+'에서의 기록'; + document.getElementById('placeMap').src='https://www.openstreetmap.org/export/embed.html?bbox='+d.bbox+'&layer=mapnik'; + showPage('place'); +} +document.querySelectorAll('[data-place-name]').forEach(el=>el.onclick=()=>openPlace(el.dataset.placeName)); +document.querySelectorAll('[data-media-type]').forEach(el=>el.onclick=()=>{showPage('library');setFilter('type',el.dataset.mediaType)}); +document.querySelectorAll('[data-year]').forEach(el=>el.onclick=()=>{showPage('library');setFilter('date',el.dataset.year)}); +document.querySelector('[data-place-sort]').onclick=e=>{e.currentTarget.textContent=e.currentTarget.textContent==='최신순'?'오래된 순':'최신순'}; + +/* viewer */ +const viewer=document.getElementById('viewer'),viewerImage=document.getElementById('viewerImage'); +document.addEventListener('click',e=>{ + const v=e.target.closest('.viewable'); + if(v && !v.closest('.album-photo-grid.select-mode')){ + viewerImage.src=v.querySelector('img').src;viewer.classList.add('show'); + } +}); +document.getElementById('viewerClose').onclick=()=>viewer.classList.remove('show'); +viewer.onclick=e=>{if(e.target===viewer)viewer.classList.remove('show')}; + +/* memory detail */ +document.querySelectorAll('[data-detail-tab]').forEach(b=>b.onclick=()=>{ + document.querySelectorAll('[data-detail-tab]').forEach(x=>x.classList.toggle('active',x===b)); + document.getElementById('storyPane').classList.toggle('hidden',b.dataset.detailTab!=='story'); + document.getElementById('allPhotos').classList.toggle('active',b.dataset.detailTab==='photos'); + document.getElementById('infoPane').classList.toggle('active',b.dataset.detailTab==='info'); +}); +document.querySelectorAll('[data-share]').forEach(b=>b.onclick=()=>openOverlay(document.getElementById('shareModal'))); +document.querySelector('[data-edit-memory]').onclick=()=>openOverlay(document.getElementById('editMemoryModal')); +document.getElementById('copyShare').onclick=async()=>{try{await navigator.clipboard.writeText('https://gpt.hyeonworks.com/s/mem-7F2A')}catch{}toast('공유 링크를 복사했습니다.')}; +document.getElementById('applyShare').onclick=()=>{closeOverlay();toast('공유 설정을 저장했습니다.')}; +document.getElementById('saveMemoryEdit').onclick=()=>{closeOverlay();toast('Memory 편집 내용을 저장했습니다.')}; + +/* settings/profile */ +const settingsContent=document.getElementById('settingsContent'); +const settingsTitle=document.getElementById('settingsTitle'); +const settingsTemplates={ + devices:['동기화된 기기','
📱
Galaxy S24

2분 전 동기화 · Android · 사진 2,118개

현재 기기
💻
Galaxy Book

어제 23:18 · Web · 최근 업로드 312개

'], + 'backup-settings':['모바일 백업','
자동 백업

새 사진과 영상을 서버에 자동 업로드합니다.

Wi‑Fi에서만 백업

모바일 데이터 사용을 막습니다.

동영상 자동 백업

원본 동영상도 백업 대상에 포함합니다.

'], + storage:['저장소 및 백업','
1 TB 저장소

428 GB 사용 · 572 GB 남음

DB 백업

오늘 03:00 · 성공 · 184 MB

정상
원본 무결성 검사

마지막 검사 9월 14일 · 문제 없음

'], + account:['계정 설정','
Keycloak 계정

donghyeon · 이메일 인증 완료

세션

현재 로그인된 브라우저 2개

'] +}; +function openSettings(kind){ + closeOverlay(); + const [title,html]=settingsTemplates[kind]||settingsTemplates.devices; + settingsTitle.textContent=title; + settingsContent.innerHTML=html; + document.querySelectorAll('[data-settings]').forEach(b=>b.classList.toggle('active',b.dataset.settings===kind)); + showPage('settings'); + bindDynamicActions(); +} +document.querySelectorAll('[data-profile-page]').forEach(b=>b.onclick=()=>openSettings(b.dataset.profilePage)); +document.querySelectorAll('[data-settings]').forEach(b=>b.onclick=()=>openSettings(b.dataset.settings)); +document.querySelector('[data-logout]').onclick=()=>openAction('로그아웃','현재 Memento 세션에서 로그아웃합니다.','

Keycloak 세션 정책에 따라 SSO 세션도 함께 종료할 수 있습니다.

','로그아웃',()=>{location.href='./login-v2.html'}); + +/* generic action modal */ +let actionCallback=null; +function openAction(title,subtitle,body,confirmLabel,callback){ + document.getElementById('actionTitle').textContent=title; + document.getElementById('actionSubtitle').textContent=subtitle||''; + document.getElementById('actionBody').innerHTML=body||''; + document.getElementById('actionConfirm').textContent=confirmLabel||'확인'; + actionCallback=callback||null; + openOverlay(document.getElementById('actionModal')); +} +document.getElementById('actionConfirm').onclick=()=>{const cb=actionCallback;closeOverlay();if(cb)cb()}; +function bindDynamicActions(){ + document.querySelectorAll('#settingsContent [data-toast]').forEach(b=>b.onclick=()=>toast(b.dataset.toast)); + document.querySelectorAll('#settingsContent [data-toggle]').forEach(b=>b.onclick=()=>b.classList.toggle('on')); +} +document.querySelectorAll('[data-toast]').forEach(b=>b.onclick=()=>toast(b.dataset.toast)); + +function toast(msg){ + const t=document.getElementById('toast');t.textContent=msg;t.classList.add('show'); + clearTimeout(window.__tt);window.__tt=setTimeout(()=>t.classList.remove('show'),1900); +} + +const requestedPage=new URLSearchParams(location.search).get('page'); +if(requestedPage==='settings')openSettings('devices'); +else if(requestedPage&&document.getElementById('page-'+requestedPage))showPage(requestedPage); diff --git a/public/config.json b/public/config.json index e8466b6..2f99af5 100644 --- a/public/config.json +++ b/public/config.json @@ -12,7 +12,7 @@ "CAPABILITY_OVERRIDES": { "REALTIME": "DEFAULT", "WEB_WORKER": "DEFAULT", - "SERVICE_WORKER": "DEFAULT", + "SERVICE_WORKER": "DISABLED", "OFFLINE_COMMANDS": "DEFAULT" }, "FEATURE_OVERRIDES": { diff --git a/public/icons/memento-192.png b/public/icons/memento-192.png new file mode 100644 index 0000000..771f319 Binary files /dev/null and b/public/icons/memento-192.png differ diff --git a/public/icons/memento-512.png b/public/icons/memento-512.png new file mode 100644 index 0000000..032a525 Binary files /dev/null and b/public/icons/memento-512.png differ diff --git a/public/login-v2.html b/public/login-v2.html new file mode 100644 index 0000000..21a4531 --- /dev/null +++ b/public/login-v2.html @@ -0,0 +1 @@ +Memento 로그인
Private Living Archive

사진을 저장하는 데서 끝내지 않습니다.

내 서버에 원본을 보관하고, 새로 들어온 사진을 시간과 장소의 흐름으로 정리해 다시 보고 싶은 Memory로 만듭니다.

Memento
개인 저장소 연결 준비됨

사진 보관함에 로그인

계정과 인증은 Keycloak이 담당합니다. Memento는 비밀번호를 직접 저장하지 않습니다.

또는
실제 구현에서는 이 화면에서 Keycloak Authorization Code Flow로 이동합니다. 회원가입은 Self Registration / Invite / 관리자 승인 정책 중 하나로 제한할 수 있습니다.
← 프로토타입으로 돌아가기
\ No newline at end of file diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..ffc6d93 --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,24 @@ +{ + "name": "Memento", + "short_name": "Memento", + "description": "개인 사진과 영상을 기억 단위로 정리하는 Memento", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#f4f4f1", + "theme_color": "#171816", + "icons": [ + { + "src": "/icons/memento-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any maskable" + }, + { + "src": "/icons/memento-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any maskable" + } + ] +} diff --git a/public/register-v2.html b/public/register-v2.html new file mode 100644 index 0000000..bd88b66 --- /dev/null +++ b/public/register-v2.html @@ -0,0 +1 @@ +Memento 회원가입

내 사진을 맡길
개인 보관함을 만듭니다.

실제 서비스에서는 회원가입 정보가 Keycloak에 저장되고, Memento는 인증 결과만 사용합니다.

Memento

새 계정 만들기

현재는 Keycloak Self Registration을 가정한 UI Mock입니다.

가입 요청을 만들었습니다. 실제 구현에서는 Keycloak 등록 완료 후 로그인 흐름으로 이동합니다.

초기 개인용 배포에서는 공개 가입을 끄고 Invite 또는 관리자 승인 방식으로 제한할 수 있습니다.

← 로그인으로 돌아가기
\ No newline at end of file diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index 7586c95..a2dc976 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -19,8 +19,9 @@ import { * §17.2.2 step 4. Scans the completed app `dist` and emits the exact hashed * asset list the Service Worker will verify at install time. * - * `service-worker.js` itself and `index.html` are excluded (§17.2.2), as are - * the runtime config and release manifest, which are network-only (§18.4). + * `service-worker.js`, runtime config and release manifest are excluded. + * Memento explicitly includes its approved static index shell below so a + * verified read-only shell can be served when navigation is offline. */ const OUTPUT = ".generated/frontend-runtime/service-worker-assets.ts"; @@ -30,14 +31,26 @@ const OUTPUT = ".generated/frontend-runtime/service-worker-assets.ts"; const CACHEABLE_EXTENSIONS = CACHEABLE_ASSET_CONTENT_TYPES; const EXCLUDED_FILES: ReadonlySet = new Set([ - "index.html", SERVICE_WORKER_SCRIPT_PATH, "config.json", "release-manifest.json", "runtime-config.schema.json", ]); -/** Vite emits content-hashed names; only those may be treated as immutable. */ +/** + * 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. + */ +const MEMENTO_SHELL_FILES: ReadonlySet = new Set([ + "index.html", + "beta.css", + "beta.js", + ...Array.from({ length: 11 }, (_, index) => `assets/photo-${index + 1}.jpg`), +]); + +/** Vite emits content-hashed names; product shell files are the explicit exception. */ const HASHED_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/; export async function collectStaticAssets( @@ -52,7 +65,8 @@ export async function collectStaticAssets( const base = path.basename(relative); if (EXCLUDED_FILES.has(base) || relative.startsWith(".vite/")) continue; const contentType = CACHEABLE_EXTENSIONS[path.extname(base).toLowerCase()]; - if (!contentType || !HASHED_NAME.test(base)) continue; + const isProductShell = MEMENTO_SHELL_FILES.has(relative.split(path.sep).join("/")); + if (!contentType || (!HASHED_NAME.test(base) && !isProductShell)) continue; const absolute = path.join(distDirectory, relative); const bytes = await readFile(absolute); diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index bae8ebf..ff3d339 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -117,6 +117,14 @@ export function createServiceWorkerRuntime( : [], ), ); + const navigationShellUrl = + [...manifestUrls].find((url) => { + try { + return new URL(url).pathname.endsWith("/index.html"); + } catch { + return false; + } + }) ?? null; const consumedNonces = new Set(); type PendingActivation = Readonly<{ requesterBuildId: string; @@ -207,6 +215,36 @@ export function createServiceWorkerRuntime( async function onFetch( request: Readonly<{ method: string; url: string; mode?: string }>, ): Promise { + /** + * Memento PWA is online-first. A navigation always attempts the network, + * but if the browser is actually offline the exact, digest-verified + * index.html from the current release cache becomes the read-only shell. + * API calls never enter this branch and remain network-only/passthrough. + */ + if ( + request.method === "GET" && + request.mode === "navigate" && + staticEnabled && + config.manifest && + navigationShellUrl + ) { + try { + return await scope.fetcher(request.url); + } catch { + const currentCacheName = staticCacheName(config.manifest.setDigest); + try { + const currentCache = await scope.caches.open(currentCacheName); + const cached = await currentCache.match(navigationShellUrl); + if (cached?.status === 200 && cached.type !== "opaque") { + return cached; + } + } catch { + // The entry point will perform the normal network fallback. + } + return null; + } + } + const classification = classifyFetch({ method: request.method, requestUrl: request.url, diff --git a/src/bootstrap/create-runtime-composition.ts b/src/bootstrap/create-runtime-composition.ts index 8d1b712..d3c3375 100644 --- a/src/bootstrap/create-runtime-composition.ts +++ b/src/bootstrap/create-runtime-composition.ts @@ -1,5 +1,6 @@ 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"; @@ -53,10 +54,13 @@ 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 d741772..f24c2eb 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,6 +15,14 @@ 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-application.tsx b/src/bootstrap/runtime-application.tsx index 475eeed..5eb1d9c 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 { AppRouter } from "../presentation/routes/app-router.tsx"; +import { MementoRuntimeBridge } from "../features/memento-web/presentation/memento-runtime-bridge.tsx"; import type { RuntimeComposition } from "./create-runtime-composition.ts"; /** @@ -44,10 +44,7 @@ export function RuntimeApplication({ > - + diff --git a/src/contracts/service-worker-static-manifest.ts b/src/contracts/service-worker-static-manifest.ts index 86c2f05..d6acdd6 100644 --- a/src/contracts/service-worker-static-manifest.ts +++ b/src/contracts/service-worker-static-manifest.ts @@ -45,6 +45,8 @@ export const CACHEABLE_ASSET_CONTENT_TYPES: Readonly< Record > = Object.freeze({ ".css": "text/css", + ".html": "text/html", + ".jpg": "image/jpeg", ".js": "text/javascript", ".mjs": "text/javascript", ".png": "image/png", diff --git a/src/features/installed-runtime-capabilities.ts b/src/features/installed-runtime-capabilities.ts index 822fa31..95b1f05 100644 --- a/src/features/installed-runtime-capabilities.ts +++ b/src/features/installed-runtime-capabilities.ts @@ -26,8 +26,9 @@ import { * endpoint, event descriptor and recovery mode (§13.6). * - webWorkers: `NOT_SELECTED`. No profiled CPU-bound task with an owner * exists, so no production worker entry is created (§16.2). - * - serviceWorker: `null`. Switching to `ACTIVE` also enables the two-pass - * build in `scripts/build-frontend.ts`. + * - serviceWorker: `ACTIVE` for the Memento installable PWA shell. The + * product selects static app-shell caching only; offline command replay stays + * unselected by design. * - offlineCommands: `NOT_SELECTED`. No external package declares a `KEYED` * operation with a recovery descriptor (§19.3). */ @@ -36,7 +37,11 @@ const REALTIME: readonly InstalledRealtimeContribution[] = Object.freeze([]); const WEB_WORKERS: readonly InstalledWebWorkerContribution[] = Object.freeze([]); -const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null; +const SERVICE_WORKER: InstalledServiceWorkerSelection = Object.freeze({ + mode: "ACTIVE", + scriptPath: "service-worker.js", + handlers: Object.freeze(["PWA_STATIC_ASSETS"] as const), +}); const OFFLINE_COMMANDS: InstalledOfflineCommandContribution | null = null; diff --git a/src/features/memento-web/adapters/create-memento-gateway.ts b/src/features/memento-web/adapters/create-memento-gateway.ts new file mode 100644 index 0000000..ea7c74f --- /dev/null +++ b/src/features/memento-web/adapters/create-memento-gateway.ts @@ -0,0 +1,27 @@ +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 new file mode 100644 index 0000000..c69ecdf --- /dev/null +++ b/src/features/memento-web/adapters/http-memento-gateway.ts @@ -0,0 +1,469 @@ +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/mock-memento-gateway.ts b/src/features/memento-web/adapters/mock-memento-gateway.ts new file mode 100644 index 0000000..b26366d --- /dev/null +++ b/src/features/memento-web/adapters/mock-memento-gateway.ts @@ -0,0 +1,405 @@ +import type { MementoGateway } from "../application/memento-gateway.ts"; +import type { + AlbumSummary, + HomeResponse, + LibraryItem, + MemoryCandidate, + MemorySummary, + PersonSummary, + PlaceSummary, +} from "../contracts/memento-api.ts"; + +const PHOTOS = Object.freeze( + Array.from({ length: 11 }, (_, index) => `/assets/photo-${index + 1}.jpg`), +); + +const ALBUMS: readonly AlbumSummary[] = Object.freeze([ + album("album-family", "가족 사진", 124, false, PHOTOS[5]), + album("album-profile", "프로필 후보", 48, false, PHOTOS[8]), + album("album-jeju", "2026 제주 베스트", 36, true, PHOTOS[0]), + album("album-dog", "강아지", 82, false, PHOTOS[10]), + album("album-interior", "인테리어 참고", 64, false, PHOTOS[4]), + album("album-friends", "친구들과", 91, true, PHOTOS[2]), +]); + +const MEMORIES: readonly MemorySummary[] = Object.freeze([ + memory("memory-gangneung", "강릉에서 보낸 주말", 67, PHOTOS[1]), + memory("memory-gapyeong", "가평 드라이브", 41, PHOTOS[2]), + memory("memory-seoul", "서울의 겨울", 123, PHOTOS[4]), + memory("memory-busan", "처음 떠난 부산", 108, PHOTOS[7]), +]); + +const CANDIDATES: readonly MemoryCandidate[] = Object.freeze([ + { + id: "candidate-jeju-summer", + title: "제주, 여름의 끝", + mediaCount: 84, + momentCount: 3, + placeCount: 4, + coverMedia: Object.freeze([{ thumbnailUrl: PHOTOS[0] }]), + score: 0.91, + }, +]); + +const PEOPLE: readonly PersonSummary[] = Object.freeze([ + { id: "person-me", displayName: "나", mediaCount: 842, memoryCount: 18 }, + { id: "person-family", displayName: "가족", mediaCount: 381, memoryCount: 12 }, + { id: "person-friends", displayName: "친구", mediaCount: 264, memoryCount: 8 }, +]); + +const PLACES: readonly PlaceSummary[] = Object.freeze([ + place("place-jeju", "제주도", 168, 4, 33.38, 126.55), + place("place-seoul", "서울", 624, 38, 37.56, 126.98), + place("place-gangneung", "강릉", 91, 3, 37.75, 128.90), + place("place-busan", "부산", 108, 2, 35.18, 129.08), +]); + +const LIBRARY: readonly LibraryItem[] = Object.freeze( + Array.from({ length: 36 }, (_, index) => ({ + id: `media-${index + 1}`, + mediaType: index % 8 === 3 ? "VIDEO" : "PHOTO", + thumbnailUrl: PHOTOS[index % PHOTOS.length] ?? PHOTOS[0]!, + takenAt: new Date(Date.UTC(2026, 8, 15 - Math.floor(index / 12), 9, index)).toISOString(), + durationMs: index % 8 === 3 ? 18_000 : null, + width: 4000, + height: 3000, + favorite: false, + processingState: "READY", + duplicateState: index % 12 === 6 ? "CANDIDATE" : "NONE", + badges: Object.freeze(["SERVER_BACKED_UP"]), + })), +); + +const HOME: HomeResponse = Object.freeze({ + suggestedMemory: Object.freeze({ + candidateId: CANDIDATES[0]!.id, + title: CANDIDATES[0]!.title, + mediaCount: CANDIDATES[0]!.mediaCount, + placeCount: CANDIDATES[0]!.placeCount, + momentCount: CANDIDATES[0]!.momentCount, + coverMedia: CANDIDATES[0]!.coverMedia, + }), + rediscoveries: Object.freeze([]), + todayImport: Object.freeze({ + uploadedCount: 42, + duplicateSkippedCount: 3, + items: Object.freeze([]), + }), + backup: Object.freeze({ + deviceId: "device-galaxy-s24", + deviceName: "Galaxy S24", + progress: 0.72, + state: "SYNCING", + }), + repository: Object.freeze({ + unorganizedCount: 128, + duplicateCandidateCount: 14, + originalBytes: 459_561_500_672, + quotaBytes: 1_099_511_627_776, + }), +}); + +export function createMockMementoGateway(): MementoGateway { + let albums = [...ALBUMS]; + + const gateway: MementoGateway = { + mode: "mock", + getCapabilities: async () => ({ + apiVersion: "local-mock", + features: Object.freeze({ + people: true, + places: true, + duplicates: true, + resumableUpload: true, + }), + }), + getHome: async () => HOME, + getLibrary: async (query = {}) => { + let items = [...LIBRARY]; + if (query.mediaType) { + items = items.filter((item) => item.mediaType === query.mediaType); + } + if (query.search) { + const offset = Math.min(items.length, 24); + items = items.slice(0, offset); + } + if (query.state === "DUPLICATE_CANDIDATE") { + items = items.filter((item) => item.duplicateState === "CANDIDATE"); + } + return { items: Object.freeze(items), nextCursor: null }; + }, + getMedia: async (mediaId) => ({ + ...(LIBRARY.find((item) => item.id === mediaId) ?? LIBRARY[0]!), + filename: `${mediaId}.jpg`, + originalUrl: PHOTOS[0], + previewUrl: PHOTOS[0], + metadata: Object.freeze({ source: "local-mock" }), + version: 1, + }), + setMediaFavorite: async (mediaId, favorite) => ({ + ...(LIBRARY.find((item) => item.id === mediaId) ?? LIBRARY[0]!), + favorite, + version: 1, + }), + trashMedia: async () => undefined, + restoreMedia: async () => undefined, + updateMediaMetadata: async (mediaId, input) => ({ + ...(LIBRARY.find((item) => item.id === mediaId) ?? LIBRARY[0]!), + metadata: Object.freeze({ ...input }), + version: (input.expectedVersion ?? 0) + 1, + }), + getAlbums: async (query = {}) => ({ + items: Object.freeze( + albums.filter((item) => { + if (query.shared === true && !item.shared) return false; + if ( + query.search && + !item.title.toLocaleLowerCase().includes(query.search.toLocaleLowerCase()) + ) { + return false; + } + return true; + }), + ), + nextCursor: null, + }), + getAlbum: async (albumId) => { + const item = albums.find((albumItem) => albumItem.id === albumId) ?? albums[0]!; + return { + ...item, + description: "로컬 Mock Album", + sortMode: "MANUAL", + items: LIBRARY.slice(0, Math.min(item.mediaCount, 12)), + story: Object.freeze([]), + }; + }, + createAlbum: async (input) => { + const created: AlbumSummary = Object.freeze({ + id: `album-local-${albums.length + 1}`, + title: input.title, + mediaCount: input.mediaIds?.length ?? 0, + shared: false, + cover: Object.freeze({ thumbnailUrl: PHOTOS[5] }), + version: 1, + }); + albums = [created, ...albums]; + return { id: created.id, title: created.title, version: 1 }; + }, + updateAlbum: async (albumId, input) => { + const current = albums.find((item) => item.id === albumId) ?? albums[0]!; + const updated = { + ...current, + title: input.title ?? current.title, + version: (input.expectedVersion ?? current.version ?? 0) + 1, + }; + albums = albums.map((item) => (item.id === albumId ? updated : item)); + return { + ...updated, + description: input.description ?? "로컬 Mock Album", + sortMode: input.sortMode ?? "MANUAL", + items: LIBRARY.slice(0, 12), + story: Object.freeze([]), + }; + }, + deleteAlbum: async (albumId) => { + albums = albums.filter((item) => item.id !== albumId); + }, + addAlbumItems: async () => undefined, + removeAlbumItem: async () => undefined, + reorderAlbumItems: async () => undefined, + getAlbumStory: async () => Object.freeze([]), + getMemories: async () => ({ items: MEMORIES, nextCursor: null }), + getMemory: async (memoryId) => { + const item = MEMORIES.find((memoryItem) => memoryItem.id === memoryId) ?? MEMORIES[0]!; + return { + ...item, + description: "로컬 Mock Memory", + placeNames: Object.freeze(["제주도"]), + items: LIBRARY.slice(0, 12), + moments: Object.freeze([]), + story: Object.freeze([]), + autoUpdate: true, + version: 1, + }; + }, + updateMemory: async (memoryId, input) => { + const item = MEMORIES.find((memoryItem) => memoryItem.id === memoryId) ?? MEMORIES[0]!; + return { + ...item, + title: input.title ?? item.title, + autoUpdate: input.autoUpdate ?? true, + version: (input.expectedVersion ?? 0) + 1, + }; + }, + getMemoryCandidates: async () => ({ items: CANDIDATES, nextCursor: null }), + saveMemoryCandidate: async (candidateId) => ({ + memoryId: `memory-from-${candidateId}`, + version: 1, + }), + dismissMemoryCandidate: async () => undefined, + regenerateMemory: async () => undefined, + getMemoryStory: async () => Object.freeze([]), + getDuplicateGroups: async () => ({ + items: Object.freeze([ + Object.freeze({ + id: "duplicate-group-1", + state: "OPEN", + recommendedKeepMediaId: LIBRARY[0]!.id, + items: Object.freeze([LIBRARY[0]!, LIBRARY[6]!]), + }), + ]), + nextCursor: null, + }), + resolveDuplicateGroup: async () => undefined, + search: async () => ({ + people: PEOPLE, + places: PLACES, + albums, + memories: MEMORIES, + media: LIBRARY.slice(0, 12), + }), + getPeople: async () => ({ items: PEOPLE, nextCursor: null }), + getPlaces: async () => ({ items: PLACES, nextCursor: null }), + getDevices: async () => ({ + items: Object.freeze([ + Object.freeze({ + id: "device-galaxy-s24", + name: "Galaxy S24", + platform: "ANDROID", + status: "ACTIVE", + lastSyncAt: new Date().toISOString(), + backup: Object.freeze({ enabled: true, wifiOnly: true }), + }), + Object.freeze({ + id: "device-galaxy-book", + name: "Galaxy Book", + platform: "WEB", + status: "ACTIVE", + lastSyncAt: new Date(Date.now() - 86_400_000).toISOString(), + backup: Object.freeze({ enabled: false, wifiOnly: true }), + }), + ]), + nextCursor: null, + }), + getDeviceBackupPolicy: async () => ({ + enabled: true, + wifiOnly: true, + includeVideos: true, + version: 1, + }), + updateDeviceBackupPolicy: async (_deviceId, policy) => ({ + ...policy, + version: (policy.version ?? 0) + 1, + }), + disconnectDevice: async () => undefined, + getBackupSummary: async () => ({ + state: "SYNCING", + pendingCount: 12, + uploadedCount: 2_118, + duplicateSkippedCount: 42, + failedCount: 0, + lastCompletedAt: new Date().toISOString(), + }), + getStorageSettings: async () => ({ + quotaBytes: 1_099_511_627_776, + originalBytes: 459_561_500_672, + derivedBytes: 32_122_122_240, + trashBytes: 9_432_217_600, + freeBytes: 607_712_894_976, + health: "HEALTHY", + lastIntegrityScanAt: "2026-09-14T03:00:00Z", + }), + getAccount: async () => ({ username: "donghyeon", emailVerified: true }), + updateAccount: async (input) => ({ + username: "donghyeon", + emailVerified: true, + ...input, + }), + runStorageIntegrityScan: async () => undefined, + createShare: async (target, input) => ({ + shareId: `share-${target.type}-${target.id}`, + url: "https://memento.example.com/s/mock", + expiresAt: input.expiresAt ?? null, + allowDownload: input.allowDownload, + version: 1, + }), + revokeShare: async () => undefined, + getPublicShare: async (token) => ({ + shareId: `share-${token}`, + title: "제주, 여름의 끝", + targetType: "MEMORY", + allowDownload: false, + expiresAt: null, + coverUrl: PHOTOS[0], + items: LIBRARY.slice(0, 12), + }), + preflightUpload: async () => ({ + decision: "UPLOAD_REQUIRED" as const, + recommendedChunkSize: 8 * 1024 * 1024, + }), + createUploadSession: async (input) => ({ + uploadSessionId: `upload-${input.deviceLocalAssetId}`, + state: "CREATED", + offset: 0, + chunkSize: 8 * 1024 * 1024, + }), + appendUploadChunk: async (_sessionId, offset, chunk) => offset + chunk.size, + commitUpload: async (uploadSessionId) => ({ + result: "CREATED" as const, + mediaAssetId: `media-${uploadSessionId}`, + processingState: "PROCESSING", + }), + abortUpload: async () => undefined, + }; + + return Object.freeze(gateway); +} + +function album( + id: string, + title: string, + mediaCount: number, + shared: boolean, + thumbnailUrl: string | undefined, +): AlbumSummary { + return Object.freeze({ + id, + title, + mediaCount, + shared, + cover: Object.freeze({ thumbnailUrl }), + updatedAt: "2026-09-14T12:00:00Z", + version: 1, + }); +} + +function memory( + id: string, + title: string, + mediaCount: number, + thumbnailUrl: string | undefined, +): MemorySummary { + return Object.freeze({ + id, + title, + mediaCount, + cover: Object.freeze({ thumbnailUrl }), + }); +} + +function place( + id: string, + name: string, + mediaCount: number, + visitCount: number, + latitude: number, + longitude: number, +): PlaceSummary { + return Object.freeze({ + id, + name, + mediaCount, + visitCount, + center: Object.freeze({ latitude, longitude }), + }); +} diff --git a/src/features/memento-web/application/memento-gateway.ts b/src/features/memento-web/application/memento-gateway.ts new file mode 100644 index 0000000..535350c --- /dev/null +++ b/src/features/memento-web/application/memento-gateway.ts @@ -0,0 +1,184 @@ +import type { + AccountSettings, + AlbumDetail, + AlbumSummary, + BackupSummary, + CursorPage, + DeviceBackupPolicy, + DeviceSummary, + DuplicateGroup, + DuplicateResolutionInput, + HomeResponse, + LibraryItem, + MediaDetail, + MemoryCandidate, + MemoryDetail, + MemorySummary, + MementoCapabilities, + MementoDataMode, + PersonSummary, + PlaceSummary, + PublicShare, + SearchResponse, + ShareCreateResult, + StorageSettings, + UploadCommitResult, + UploadPreflightInput, + UploadPreflightResponse, + 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 }>; + +export interface MementoGateway { + readonly mode: MementoDataMode; + + getCapabilities(): Promise; + getHome(): Promise; + + getLibrary(query?: LibraryQuery): Promise>; + getMedia(mediaId: string): Promise; + setMediaFavorite(mediaId: string, favorite: boolean): Promise; + trashMedia(mediaId: string): Promise; + restoreMedia(mediaId: string): Promise; + updateMediaMetadata( + mediaId: string, + input: UpdateMediaMetadataInput, + ): Promise; + + getAlbums(query?: AlbumQuery): Promise>; + getAlbum(albumId: string): Promise; + createAlbum( + input: CreateAlbumInput, + ): Promise>; + updateAlbum(albumId: string, input: UpdateAlbumInput): Promise; + deleteAlbum(albumId: string, expectedVersion?: number): Promise; + addAlbumItems(albumId: string, mediaIds: readonly string[]): Promise; + removeAlbumItem(albumId: string, mediaId: string): Promise; + reorderAlbumItems(albumId: string, mediaIds: readonly string[]): Promise; + getAlbumStory(albumId: string): Promise; + + getMemories(query?: MemoryQuery): Promise>; + getMemory(memoryId: string): Promise; + updateMemory(memoryId: string, input: UpdateMemoryInput): Promise; + getMemoryCandidates(): Promise>; + saveMemoryCandidate( + candidateId: string, + ): Promise>; + dismissMemoryCandidate(candidateId: string): Promise; + regenerateMemory(memoryId: string): Promise; + getMemoryStory(memoryId: string): Promise; + + getDuplicateGroups(): Promise>; + resolveDuplicateGroup( + groupId: string, + input: DuplicateResolutionInput, + ): Promise; + + search(query: string): Promise; + getPeople(): Promise>; + getPlaces(): Promise>; + + getDevices(): Promise>; + getDeviceBackupPolicy(deviceId: string): Promise; + updateDeviceBackupPolicy( + deviceId: string, + policy: DeviceBackupPolicy, + ): Promise; + disconnectDevice(deviceId: string): Promise; + getBackupSummary(deviceId: string): Promise; + + getStorageSettings(): Promise; + getAccount(): Promise; + updateAccount(input: Readonly>): Promise; + runStorageIntegrityScan(): Promise; + + createShare( + target: ShareTarget, + input: CreateShareInput, + ): Promise; + revokeShare(shareId: string): Promise; + getPublicShare(token: string): Promise; + + preflightUpload(input: UploadPreflightInput): Promise; + createUploadSession(input: Readonly<{ + deviceId?: string | null; + deviceLocalAssetId: string; + sourceType: "WEB_MANUAL"; + filename: string; + expectedSize: number; + mimeType: string; + clientSha256?: string | null; + }>): Promise; + appendUploadChunk( + uploadSessionId: string, + offset: number, + chunk: Blob, + ): Promise; + commitUpload(uploadSessionId: string): Promise; + abortUpload(uploadSessionId: string): Promise; +} diff --git a/src/features/memento-web/contracts/memento-api.ts b/src/features/memento-web/contracts/memento-api.ts new file mode 100644 index 0000000..d634810 --- /dev/null +++ b/src/features/memento-web/contracts/memento-api.ts @@ -0,0 +1,284 @@ +export type MementoEnvironment = + | "local" + | "development" + | "staging" + | "production"; + +export type MementoDataMode = "mock" | "api"; + +export type MementoRuntimeConfig = Readonly<{ + APP_ENV: MementoEnvironment; + API_BASE_URL: string; + REQUEST_TIMEOUT_MS: number; +}>; + +export type CursorPage = Readonly<{ + items: readonly T[]; + nextCursor?: string | null; +}>; + +export type HomeResponse = Readonly<{ + suggestedMemory: Readonly<{ + candidateId: string; + title: string; + mediaCount: number; + placeCount: number; + momentCount: number; + coverMedia: readonly unknown[]; + }> | null; + rediscoveries: readonly unknown[]; + todayImport: Readonly<{ + uploadedCount: number; + duplicateSkippedCount: number; + items: readonly unknown[]; + }>; + backup: Readonly<{ + deviceId: string; + deviceName: string; + progress: number; + state: string; + }> | null; + repository: Readonly<{ + unorganizedCount: number; + duplicateCandidateCount: number; + originalBytes: number; + quotaBytes: number; + }>; +}>; + +export type LibraryItem = Readonly<{ + id: string; + mediaType: "PHOTO" | "VIDEO" | string; + thumbnailUrl: string; + takenAt: string; + durationMs?: number | null; + width?: number | null; + height?: number | null; + favorite: boolean; + processingState: string; + duplicateState: string; + badges: readonly string[]; +}>; + +export type AlbumSummary = Readonly<{ + id: string; + title: string; + cover?: Readonly<{ + mediaId?: string; + thumbnailUrl?: string; + }> | null; + mediaCount: number; + shared: boolean; + updatedAt?: string; + version?: number; +}>; + +export type MemorySummary = Readonly<{ + id: string; + title: string; + cover?: Readonly<{ + mediaId?: string; + thumbnailUrl?: string; + }> | null; + mediaCount?: number; + startAt?: string; + endAt?: string; + updatedAt?: string; +}>; + +export type MemoryCandidate = Readonly<{ + id: string; + title: string; + startAt?: string; + endAt?: string; + mediaCount: number; + momentCount: number; + placeCount: number; + coverMedia: readonly unknown[]; + score?: number; +}>; + +export type PersonSummary = Readonly<{ + id: string; + displayName: string | null; + representativeFaceUrl?: string | null; + mediaCount: number; + memoryCount: number; +}>; + +export type PlaceSummary = Readonly<{ + id: string; + name: string; + mediaCount: number; + visitCount: number; + center?: Readonly<{ + latitude: number; + longitude: number; + }>; +}>; + +export type DeviceSummary = Readonly<{ + id: string; + name: string; + platform: string; + status: string; + lastSeenAt?: string | null; + lastSyncAt?: string | null; + backup?: Readonly<{ + enabled: boolean; + wifiOnly: boolean; + }>; +}>; + +export type StorageSettings = Readonly<{ + quotaBytes: number; + originalBytes: number; + derivedBytes: number; + trashBytes: number; + freeBytes: number; + health: string; + lastIntegrityScanAt?: string | null; +}>; + +export type AccountSettings = Readonly>; + +export type SearchResponse = Readonly<{ + people: readonly PersonSummary[]; + places: readonly PlaceSummary[]; + albums: readonly AlbumSummary[]; + memories: readonly MemorySummary[]; + media: readonly LibraryItem[]; +}>; + +export type UploadPreflightInput = Readonly<{ + deviceId?: string | null; + deviceLocalAssetId: string; + filename: string; + sizeBytes: number; + mimeType: string; + clientSha256?: string | null; + takenAtHint?: string | null; +}>; + +export type UploadPreflightResponse = + | Readonly<{ + decision: "UPLOAD_REQUIRED"; + recommendedChunkSize: number; + }> + | Readonly<{ + decision: "ALREADY_EXISTS"; + mediaAssetId: string; + reason: string; + }> + | Readonly<{ + decision: "RESUME"; + uploadSessionId: string; + receivedBytes: number; + }>; + +export type UploadSession = Readonly<{ + uploadSessionId: string; + state: string; + offset: number; + chunkSize: number; + expiresAt?: string; +}>; + +export type UploadCommitResult = + | Readonly<{ + result: "CREATED"; + mediaAssetId: string; + processingState: string; + }> + | Readonly<{ + result: "DUPLICATE_SKIPPED"; + duplicateType: string; + existingMediaAssetId: string; + }>; + +export type ShareCreateResult = Readonly<{ + shareId: string; + url: string; + expiresAt?: string | null; + allowDownload: boolean; + version?: number; +}>; + +export type ApiErrorPayload = Readonly<{ + code?: string; + message?: string; + traceId?: string; + details?: unknown; +}>; + + +export type MediaDetail = LibraryItem & + Readonly<{ + filename?: string; + originalUrl?: string; + previewUrl?: string; + metadata?: Readonly>; + version?: number; + }>; + +export type AlbumDetail = AlbumSummary & + Readonly<{ + description?: string | null; + sortMode?: string; + items?: readonly LibraryItem[]; + story?: readonly unknown[]; + }>; + +export type MemoryDetail = MemorySummary & + Readonly<{ + description?: string | null; + placeNames?: readonly string[]; + items?: readonly LibraryItem[]; + moments?: readonly unknown[]; + story?: readonly unknown[]; + autoUpdate?: boolean; + version?: number; + }>; + +export type DuplicateGroup = Readonly<{ + id: string; + state: string; + recommendedKeepMediaId?: string | null; + items: readonly LibraryItem[]; +}>; + +export type DuplicateResolutionInput = Readonly<{ + keepMediaId: string; + trashMediaIds: readonly string[]; +}>; + +export type DeviceBackupPolicy = Readonly<{ + enabled: boolean; + wifiOnly: boolean; + includeVideos: boolean; + version?: number; +}>; + +export type BackupSummary = Readonly<{ + state: string; + pendingCount: number; + uploadedCount: number; + duplicateSkippedCount: number; + failedCount: number; + lastCompletedAt?: string | null; +}>; + +export type PublicShare = Readonly<{ + shareId: string; + title: string; + targetType: "ALBUM" | "MEMORY" | string; + allowDownload: boolean; + expiresAt?: string | null; + coverUrl?: string | null; + items: readonly LibraryItem[]; +}>; + +export type MementoCapabilities = Readonly<{ + apiVersion?: string; + features?: Readonly>; +}>; diff --git a/src/features/memento-web/presentation/memento-prototype-integration.ts b/src/features/memento-web/presentation/memento-prototype-integration.ts new file mode 100644 index 0000000..f592fb7 --- /dev/null +++ b/src/features/memento-web/presentation/memento-prototype-integration.ts @@ -0,0 +1,1124 @@ +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 new file mode 100644 index 0000000..d7f155c --- /dev/null +++ b/src/features/memento-web/presentation/memento-runtime-bridge.tsx @@ -0,0 +1,24 @@ +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/tests/unit/memento-environment-gateway.test.ts b/tests/unit/memento-environment-gateway.test.ts new file mode 100644 index 0000000..4c24efc --- /dev/null +++ b/tests/unit/memento-environment-gateway.test.ts @@ -0,0 +1,32 @@ +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"; + +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; +} + +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); + }); + + it.each(["development", "staging", "production"] as const)( + "uses the real BFF/API gateway for %s", + (environment) => { + expect(createMementoGateway(config(environment)).mode).toBe("api"); + }, + ); +}); diff --git a/vite.config.ts b/vite.config.ts index 7fc05d4..c506043 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,17 +1,27 @@ -import { defineConfig } from "vite"; -import react from "@vitejs/plugin-react"; +import { readFile } from "node:fs/promises"; + import tailwindcss from "@tailwindcss/vite"; +import react from "@vitejs/plugin-react"; +import { defineConfig, type Plugin } from "vite"; import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts"; +const RUNTIME_PROFILES = Object.freeze([ + "local", + "development", + "staging", + "production", +] as const); + +type RuntimeProfile = (typeof RUNTIME_PROFILES)[number]; + /** * §6.1. One sub-path, declared once. * - * `VITE_ROUTER_BASE_PATH` already drives the router and the Service Worker - * scope. Vite's asset `base` was left at its default, so a build served from - * `/app/` emitted root-absolute asset URLs and loaded nothing: the three - * consumers of the same setting disagreed. They are read from one value here so - * a sub-path deployment is coherent or fails at build time. + * VITE_ROUTER_BASE_PATH drives Vite assets and the optional Service Worker. + * Memento's current beta shell does not need React Router, but retaining one + * deployment base contract keeps the derived application compatible with the + * frontend foundation. */ function routerBasePath(environment: NodeJS.ProcessEnv): string { const declared = environment["VITE_ROUTER_BASE_PATH"]; @@ -24,9 +34,68 @@ function routerBasePath(environment: NodeJS.ProcessEnv): string { return declared; } +function runtimeProfile(environment: NodeJS.ProcessEnv): RuntimeProfile { + const declared = environment["APP_PROFILE"] ?? "local"; + if ((RUNTIME_PROFILES as readonly string[]).includes(declared)) { + return declared as RuntimeProfile; + } + throw new Error( + `APP_PROFILE must be one of ${RUNTIME_PROFILES.join(", ")}; received ${declared}`, + ); +} + +/** + * Vite dev normally copies public/config.json, which would make every local + * dev server run the local profile. This middleware serves config/runtime + * directly so the runtime profile also works without a production build: + * + * pnpm dev -> local profile -> mock gateway + * pnpm dev:api -> development profile -> real API gateway + * + * RUNTIME_API_BASE_URL may replace only the endpoint. No secret is accepted. + */ +function mementoRuntimeProfilePlugin( + environment: NodeJS.ProcessEnv, +): Plugin { + const profile = runtimeProfile(environment); + + return { + name: "memento-runtime-profile", + configureServer(server) { + server.middlewares.use(async (request, response, next) => { + const pathname = request.url?.split("?", 1)[0]; + if (pathname !== "/config.json" || request.method !== "GET") { + next(); + return; + } + + try { + const source = JSON.parse( + await readFile(`config/runtime/${profile}.json`, "utf8"), + ) as Record; + const apiOverride = environment["RUNTIME_API_BASE_URL"]; + if (apiOverride) source["API_BASE_URL"] = apiOverride; + + response.statusCode = 200; + response.setHeader("Content-Type", "application/json; charset=utf-8"); + response.setHeader("Cache-Control", "no-store"); + response.end(`${JSON.stringify(source, null, 2)}\n`); + } catch (error) { + next(error as Error); + } + }); + }, + }; +} + export default defineConfig({ base: routerBasePath(process.env), - plugins: [react(), tailwindcss(), viteModuleInventoryPlugin()], + plugins: [ + mementoRuntimeProfilePlugin(process.env), + react(), + tailwindcss(), + viteModuleInventoryPlugin(), + ], build: { manifest: true, sourcemap: false, diff --git a/vite.service-worker.config.ts b/vite.service-worker.config.ts index 31b0455..04f12c1 100644 --- a/vite.service-worker.config.ts +++ b/vite.service-worker.config.ts @@ -1,4 +1,6 @@ import { readFile } from "node:fs/promises"; +import { resolve as resolvePath } from "node:path"; +import { pathToFileURL } from "node:url"; import { defineConfig } from "vite"; import { @@ -20,17 +22,24 @@ import { resolveServiceWorkerBuildInput } from "./scripts/lib/service-worker-bui const selection = INSTALLED_RUNTIME_CAPABILITIES.serviceWorker; -async function readGenerated(path: string, exportName: string): Promise { +async function readGenerated( + relativePath: string, + exportName: string, +): Promise { + const moduleUrl = pathToFileURL( + resolvePath(process.cwd(), relativePath), + ).href; try { - const module = (await import(path)) as Record; + const module = (await import(moduleUrl)) as Record; if (!(exportName in module)) { throw new TypeError(`Generated module does not export ${exportName}.`); } return module[exportName] as T; } catch (error) { - throw new TypeError(`Required generated module is unavailable: ${path}`, { - cause: error, - }); + throw new TypeError( + `Required generated module is unavailable: ${relativePath}`, + { cause: error }, + ); } } @@ -43,7 +52,7 @@ const contractSet = await readGenerated<{ setDigest?: string }>( "BUILD_CONTRACT_SET", ); const runtimeConfig = JSON.parse( - await readFile("public/config.json", "utf8"), + await readFile("dist/config.json", "utf8"), ) as Record; const buildId = process.env.VITE_BUILD_ID ?? "local-build"; @@ -58,6 +67,9 @@ const buildInput = resolveServiceWorkerBuildInput({ }); export default defineConfig({ + // The app build already copied public/. Re-copying it in this second pass + // would overwrite the profile-specific dist/config.json with public/config.json. + publicDir: false, build: { // §17.2.2: exactly one input, exactly one output, no additional chunk. emptyOutDir: false,