refactor: FSD 구조 강화 및 파일 500줄 제한에 따른 대규모 리팩토링

- SpaceWorkspaceWidget 로직을 전용 훅 및 유틸리티로 분리 (900줄 -> 300줄)
- useSpaceWorkspaceSelection 훅을 기능별(영속성, 진단 등) 소형 훅으로 분리
- SpaceToolsDockWidget의 상태 및 핸들러 로직 추출
- 거대 i18n 번역 파일(ko.ts)을 도메인별 메시지 파일로 구조화
- AdminConsoleWidget 누락분 추가 및 미디어 엔티티 타입 오류 수정
This commit is contained in:
2026-03-11 15:08:36 +09:00
parent 7867bd39ca
commit 35f1dfb92d
36 changed files with 3238 additions and 2611 deletions

View File

@@ -1,7 +1,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { TOKEN_COOKIE_KEY } from "@/features/auth/model/constants"; import { TOKEN_COOKIE_KEY } from "@/shared/config/authTokens";
interface AppLayoutProps { interface AppLayoutProps {
children: ReactNode; children: ReactNode;

View File

@@ -1,712 +1,7 @@
'use client'; 'use client';
import { FormEvent, useEffect, useState } from 'react'; import { AdminConsoleWidget } from '@/widgets/admin-console';
import { adminApi, type SceneMediaAssetUploadResponse, type SoundMediaAssetUploadResponse } from '@/features/admin/api/adminApi';
import type { AuthResponse } from '@/features/auth/types';
import { copy } from '@/shared/i18n';
import { Button } from '@/shared/ui';
const ADMIN_STORAGE_KEY = 'vr_admin_session';
type AdminView = 'scene' | 'sound';
type UploadResult =
| { type: 'scene'; payload: SceneMediaAssetUploadResponse }
| { type: 'sound'; payload: SoundMediaAssetUploadResponse };
type NavItem = {
id: AdminView;
title: string;
subtitle: string;
section: string;
};
const navItems: NavItem[] = [...copy.admin.navItems];
const readStoredSession = (): AuthResponse | null => {
if (typeof window === 'undefined') {
return null;
}
const rawValue = window.localStorage.getItem(ADMIN_STORAGE_KEY);
if (!rawValue) {
return null;
}
try {
return JSON.parse(rawValue) as AuthResponse;
} catch {
window.localStorage.removeItem(ADMIN_STORAGE_KEY);
return null;
}
};
const storeSession = (session: AuthResponse | null) => {
if (typeof window === 'undefined') {
return;
}
if (!session) {
window.localStorage.removeItem(ADMIN_STORAGE_KEY);
return;
}
window.localStorage.setItem(ADMIN_STORAGE_KEY, JSON.stringify(session));
};
const fieldClassName =
'h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-100';
const fileClassName =
'block w-full rounded-xl border border-dashed border-slate-200 bg-slate-50 px-3 py-3 text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-slate-900 file:px-3 file:py-2 file:text-sm file:font-medium file:text-white hover:file:bg-slate-800';
const textareaClassName =
'min-h-32 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-100';
const getViewMeta = (view: AdminView) => {
return copy.admin.views[view];
};
const formatResultSummary = (uploadResult: UploadResult | null) => {
if (!uploadResult) {
return copy.admin.inspector.noUploadSummary;
}
if (uploadResult.type === 'scene') {
return copy.admin.messages.sceneSummary(uploadResult.payload.sceneId, uploadResult.payload.assetVersion);
}
return copy.admin.messages.soundSummary(uploadResult.payload.presetId, uploadResult.payload.assetVersion);
};
export default function AdminPage() { export default function AdminPage() {
const [session, setSession] = useState<AuthResponse | null>(null); return <AdminConsoleWidget />;
const [activeView, setActiveView] = useState<AdminView>('scene');
const [isDurationOverrideEnabled, setIsDurationOverrideEnabled] = useState(false);
const [loginId, setLoginId] = useState<string>(copy.admin.defaultLoginId);
const [password, setPassword] = useState<string>(copy.admin.defaultPassword);
const [loginError, setLoginError] = useState<string | null>(null);
const [loginPending, setLoginPending] = useState(false);
const [scenePending, setScenePending] = useState(false);
const [soundPending, setSoundPending] = useState(false);
const [sceneMessage, setSceneMessage] = useState<string | null>(null);
const [soundMessage, setSoundMessage] = useState<string | null>(null);
const [uploadResult, setUploadResult] = useState<UploadResult | null>(null);
useEffect(() => {
setSession(readStoredSession());
}, []);
const handleLogin = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoginPending(true);
setLoginError(null);
try {
const response = await adminApi.login({
loginId: loginId.trim(),
password,
});
if (response.user?.grade !== 'ADMIN') {
throw new Error(copy.admin.messages.nonAdmin);
}
setSession(response);
storeSession(response);
} catch (error) {
setLoginError(error instanceof Error ? error.message : copy.admin.messages.loginFailed);
} finally {
setLoginPending(false);
}
};
const handleLogout = () => {
setSession(null);
setActiveView('scene');
setIsDurationOverrideEnabled(false);
setSceneMessage(null);
setSoundMessage(null);
setUploadResult(null);
storeSession(null);
};
const handleSceneUpload = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!session?.accessToken) {
setSceneMessage(copy.admin.messages.loginRequired);
return;
}
setScenePending(true);
setSceneMessage(null);
try {
const form = event.currentTarget;
const source = new FormData(form);
const sceneId = String(source.get('sceneId') ?? '').trim();
if (!sceneId) {
throw new Error(copy.admin.messages.sceneIdRequired);
}
const formData = new FormData();
const sourceImageFile = source.get('sourceImageFile');
if (sourceImageFile instanceof File && sourceImageFile.size > 0) {
formData.append('sourceImageFile', sourceImageFile);
}
const blurDataUrl = String(source.get('blurDataUrl') ?? '').trim();
if (blurDataUrl) {
formData.append('blurDataUrl', blurDataUrl);
}
const response = await adminApi.uploadScene(sceneId, formData, session.accessToken);
setUploadResult({ type: 'scene', payload: response });
setSceneMessage(copy.admin.messages.sceneUploadDone(sceneId));
form.reset();
} catch (error) {
setSceneMessage(error instanceof Error ? error.message : copy.admin.messages.sceneUploadFailed);
} finally {
setScenePending(false);
}
};
const handleSoundUpload = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!session?.accessToken) {
setSoundMessage(copy.admin.messages.loginRequired);
return;
}
setSoundPending(true);
setSoundMessage(null);
try {
const form = event.currentTarget;
const source = new FormData(form);
const presetId = String(source.get('presetId') ?? '').trim();
if (!presetId) {
throw new Error(copy.admin.messages.presetIdRequired);
}
const formData = new FormData();
for (const fieldName of ['loopFile', 'previewFile', 'fallbackLoopFile']) {
const file = source.get(fieldName);
if (file instanceof File && file.size > 0) {
formData.append(fieldName, file);
}
}
const defaultVolume = String(source.get('defaultVolume') ?? '').trim();
if (defaultVolume) {
formData.append('defaultVolume', defaultVolume);
}
if (isDurationOverrideEnabled) {
const durationSec = String(source.get('durationSec') ?? '').trim();
if (durationSec) {
formData.append('durationSec', durationSec);
}
}
const response = await adminApi.uploadSound(presetId, formData, session.accessToken);
setUploadResult({ type: 'sound', payload: response });
setSoundMessage(copy.admin.messages.soundUploadDone(presetId));
form.reset();
setIsDurationOverrideEnabled(false);
} catch (error) {
setSoundMessage(error instanceof Error ? error.message : copy.admin.messages.soundUploadFailed);
} finally {
setSoundPending(false);
}
};
const activeMeta = getViewMeta(activeView);
const currentMessage = activeView === 'scene' ? sceneMessage : soundMessage;
const lastExtractedDurationSec =
uploadResult?.type === 'sound' ? uploadResult.payload.durationSec ?? null : null;
if (!session) {
return (
<main className="min-h-screen bg-[#f3f4f8] text-slate-900">
<div className="grid min-h-screen lg:grid-cols-[280px_minmax(0,1fr)]">
<aside className="flex flex-col justify-between bg-[#171821] px-8 py-8 text-white">
<div>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-fuchsia-500 to-sky-500 text-lg font-bold">
V
</div>
<div>
<p className="text-xl font-semibold tracking-tight">{copy.appName}</p>
<p className="text-xs uppercase tracking-[0.28em] text-slate-400">{copy.admin.consoleLabel}</p>
</div>
</div>
<div className="mt-12 space-y-8">
<div>
<p className="mb-4 text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">
{copy.admin.mediaOperations}
</p>
<div className="space-y-2">
{navItems.map((item, index) => (
<div
key={item.id}
className={`flex items-center gap-3 rounded-xl px-4 py-3 ${
index === 0 ? 'bg-white/10 text-white' : 'text-slate-400'
}`}
>
<span className="h-2 w-2 rounded-full bg-sky-400" />
<div>
<p className="text-sm font-medium">{item.title}</p>
<p className="text-xs text-slate-500">{item.subtitle}</p>
</div>
</div>
))}
</div>
</div>
<div className="rounded-2xl border border-white/8 bg-white/5 p-5">
<p className="text-xs uppercase tracking-[0.24em] text-slate-500">{copy.admin.access}</p>
<p className="mt-3 text-2xl font-semibold">{copy.admin.accessTitle}</p>
<p className="mt-2 text-sm leading-6 text-slate-400">
{copy.admin.accessDescription}
</p>
</div>
</div>
</div>
<p className="text-xs uppercase tracking-[0.24em] text-slate-500">
{copy.admin.localCredentialsHint}
</p>
</aside>
<section className="flex items-center justify-center px-6 py-10">
<div className="w-full max-w-md rounded-[28px] border border-slate-200 bg-white px-8 py-8 shadow-[0_30px_80px_rgba(15,23,42,0.08)]">
<div className="mb-8">
<p className="text-xs font-semibold uppercase tracking-[0.28em] text-sky-600">{copy.admin.signInEyebrow}</p>
<h1 className="mt-3 text-3xl font-semibold tracking-tight text-slate-950">
{copy.admin.loginTitle}
</h1>
<p className="mt-3 text-sm leading-6 text-slate-500">
{copy.admin.loginDescription}
</p>
</div>
<form className="space-y-4" onSubmit={handleLogin}>
<div>
<label htmlFor="admin-login-id" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.loginIdLabel}
</label>
<input
id="admin-login-id"
className={fieldClassName}
value={loginId}
onChange={(event) => setLoginId(event.target.value)}
autoComplete="username"
placeholder={copy.admin.defaultLoginId}
/>
</div>
<div>
<label htmlFor="admin-login-password" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.loginPasswordLabel}
</label>
<input
id="admin-login-password"
type="password"
className={fieldClassName}
value={password}
onChange={(event) => setPassword(event.target.value)}
autoComplete="current-password"
placeholder={copy.admin.defaultPassword}
/>
</div>
{loginError ? (
<div className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{loginError}
</div>
) : null}
<Button type="submit" size="full" className="h-12 rounded-xl" disabled={loginPending}>
{loginPending ? copy.admin.loggingIn : copy.admin.openDashboard}
</Button>
</form>
</div>
</section>
</div>
</main>
);
}
return (
<main className="min-h-screen bg-[#f3f4f8] text-slate-900">
<div className="grid min-h-screen lg:grid-cols-[280px_minmax(0,1fr)]">
<aside className="flex flex-col bg-[#171821] px-5 py-6 text-white">
<div className="flex items-center gap-3 px-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-fuchsia-500 to-sky-500 text-lg font-bold">
V
</div>
<div>
<p className="text-2xl font-semibold tracking-tight">{copy.appName}</p>
<p className="text-xs uppercase tracking-[0.28em] text-slate-400">{copy.admin.mediaAdminLabel}</p>
</div>
</div>
<nav className="mt-10 flex-1">
<div className="px-3">
<p className="mb-4 text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">
{copy.admin.navItems[0].section}
</p>
</div>
<div className="space-y-1">
{navItems.map((item) => {
const isActive = item.id === activeView;
return (
<button
key={item.id}
type="button"
onClick={() => setActiveView(item.id)}
className={`flex w-full items-center gap-3 rounded-xl px-4 py-3 text-left transition ${
isActive
? 'bg-white/10 text-white'
: 'text-slate-400 hover:bg-white/6 hover:text-white'
}`}
>
<span className={`h-8 w-1 rounded-full ${isActive ? 'bg-sky-400' : 'bg-transparent'}`} />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{item.title}</p>
<p className="truncate text-xs text-slate-500">{item.subtitle}</p>
</div>
</button>
);
})}
</div>
<div className="mt-10 px-3">
<p className="mb-4 text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">
{copy.admin.sessionSection}
</p>
<div className="space-y-3 text-sm text-slate-300">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-slate-500">{copy.admin.sessionAdminLabel}</p>
<p className="mt-1 font-medium text-white">{session.user?.name ?? copy.common.admin}</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.2em] text-slate-500">{copy.admin.sessionRoleLabel}</p>
<p className="mt-1 font-medium text-emerald-300">{session.user?.grade ?? 'ADMIN'}{copy.admin.roleAccessSuffix}</p>
</div>
</div>
</div>
</nav>
<div className="border-t border-white/8 px-3 pt-5">
<Button
type="button"
variant="ghost"
size="full"
className="h-11 justify-start rounded-xl bg-white/6 px-4 text-white hover:bg-white/10"
onClick={handleLogout}
>
{copy.admin.logout}
</Button>
</div>
</aside>
<div className="flex min-w-0 flex-col">
<header className="border-b border-slate-200 bg-white">
<div className="flex flex-wrap items-center justify-between gap-4 px-6 py-4">
<div className="flex min-w-[280px] flex-1 items-center gap-3">
<button
type="button"
className="flex h-11 w-11 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500"
>
</button>
<div className="relative w-full max-w-md">
<input
value={activeView === 'scene' ? copy.admin.searchValues.scene : copy.admin.searchValues.sound}
readOnly
className="h-11 w-full rounded-xl border border-slate-200 bg-slate-50 pl-11 pr-4 text-sm text-slate-500 outline-none"
/>
<span className="pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
</span>
</div>
</div>
<div className="flex items-center gap-3">
<div className="hidden items-center gap-2 rounded-full bg-slate-100 px-3 py-2 text-xs font-medium text-slate-500 md:flex">
<span className="h-2 w-2 rounded-full bg-emerald-400" />
{copy.admin.manifestReady}
</div>
<div className="flex h-11 items-center gap-3 rounded-full border border-slate-200 bg-white px-4">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-900 text-xs font-semibold text-white">
A
</div>
<div className="hidden sm:block">
<p className="text-sm font-semibold text-slate-900">{session.user?.name ?? copy.common.admin}</p>
<p className="text-xs text-slate-500">{session.user?.email}</p>
</div>
</div>
</div>
</div>
</header>
<section className="flex-1 overflow-auto px-6 py-6">
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
<div className="min-w-0 space-y-6">
<div className="grid gap-4 md:grid-cols-[minmax(0,1.5fr)_repeat(2,minmax(0,1fr))]">
<div className="rounded-2xl border border-slate-200 bg-white px-5 py-5">
<p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-400">
{activeMeta.eyebrow}
</p>
<h1 className="mt-3 text-3xl font-semibold tracking-tight text-slate-950">
{activeMeta.title}
</h1>
<p className="mt-3 text-sm leading-6 text-slate-500">
{activeMeta.description}
</p>
</div>
<div className="rounded-2xl border border-slate-200 bg-white px-5 py-5">
<p className="text-sm font-medium text-slate-500">{activeMeta.statTitle}</p>
<p className="mt-6 text-3xl font-semibold tracking-tight text-slate-950">{activeMeta.statValue}</p>
<p className="mt-2 text-sm text-slate-500">{activeMeta.statHint}</p>
</div>
<div className="rounded-2xl border border-slate-200 bg-white px-5 py-5">
<p className="text-sm font-medium text-slate-500">{copy.admin.inspector.currentRoleTitle}</p>
<p className="mt-6 text-3xl font-semibold tracking-tight text-slate-950">
{session.user?.grade ?? 'ADMIN'}
</p>
<p className="mt-2 text-sm text-slate-500">{copy.admin.inspector.bearerTokenSession}</p>
</div>
</div>
{activeView === 'scene' ? (
<form onSubmit={handleSceneUpload} className="rounded-2xl border border-slate-200 bg-white">
<div className="border-b border-slate-200 px-6 py-5">
<p className="text-lg font-semibold text-slate-950">{copy.admin.views.scene.workspaceTitle}</p>
<p className="mt-1 text-sm text-slate-500">
{copy.admin.views.scene.workspaceDescription}
</p>
</div>
<div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_360px]">
<div className="px-6 py-6">
<div className="max-w-xl">
<div>
<label htmlFor="scene-id" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.views.scene.sceneIdLabel}
</label>
<input id="scene-id" name="sceneId" className={fieldClassName} placeholder={copy.admin.views.scene.sceneIdPlaceholder} />
<p className="mt-2 text-xs text-slate-500">{copy.admin.views.scene.sceneIdHint}</p>
</div>
</div>
<div className="mt-6 rounded-2xl border border-slate-200 bg-slate-50 px-5 py-5">
<div className="max-w-2xl">
<label className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.views.scene.sourceImageLabel}
</label>
<input
name="sourceImageFile"
type="file"
accept="image/jpeg,image/png"
className={fileClassName}
/>
<p className="mt-2 text-xs text-slate-500">{copy.admin.views.scene.sourceImageHint}</p>
<p className="mt-1 text-xs text-slate-400">{copy.admin.views.scene.sourceImageDerivedHint}</p>
</div>
</div>
<div className="mt-6 max-w-2xl">
<label className="mb-2 block text-sm font-medium text-slate-700">{copy.admin.views.scene.blurDataUrlLabel}</label>
<textarea
name="blurDataUrl"
rows={6}
className={textareaClassName}
placeholder={copy.admin.views.scene.blurDataUrlPlaceholder}
/>
<p className="mt-2 text-xs text-slate-500">{copy.admin.views.scene.blurDataUrlHint}</p>
</div>
</div>
<div className="border-t border-slate-200 bg-slate-50 px-6 py-6 xl:border-l xl:border-t-0">
<p className="text-sm font-semibold text-slate-900">{copy.admin.views.scene.notesTitle}</p>
<ul className="mt-4 space-y-3 text-sm leading-6 text-slate-500">
{copy.admin.views.scene.notes.map((note) => (
<li key={note}>{note}</li>
))}
</ul>
{currentMessage ? (
<div className="mt-5 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">
{currentMessage}
</div>
) : null}
<Button
type="submit"
className="mt-6 h-12 w-full rounded-xl bg-slate-900 hover:bg-slate-800"
disabled={scenePending}
>
{scenePending ? copy.admin.views.scene.pending : copy.admin.views.scene.submit}
</Button>
</div>
</div>
</form>
) : (
<form onSubmit={handleSoundUpload} className="rounded-2xl border border-slate-200 bg-white">
<div className="border-b border-slate-200 px-6 py-5">
<p className="text-lg font-semibold text-slate-950">{copy.admin.views.sound.workspaceTitle}</p>
<p className="mt-1 text-sm text-slate-500">
{copy.admin.views.sound.workspaceDescription}
</p>
</div>
<div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_360px]">
<div className="px-6 py-6">
<div className="grid gap-5 md:grid-cols-3">
<div className="md:col-span-2">
<label htmlFor="preset-id" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.views.sound.presetIdLabel}
</label>
<input id="preset-id" name="presetId" className={fieldClassName} placeholder={copy.admin.views.sound.presetIdPlaceholder} />
</div>
<div>
<label className="mb-2 block text-sm font-medium text-slate-700">{copy.admin.views.sound.defaultVolumeLabel}</label>
<input name="defaultVolume" type="number" min={0} max={100} className={fieldClassName} placeholder={copy.admin.views.sound.defaultVolumePlaceholder} />
</div>
</div>
<div className="mt-5 grid gap-5 md:grid-cols-2">
<div>
<label className="mb-2 block text-sm font-medium text-slate-700">{copy.admin.views.sound.loopFileLabel}</label>
<input name="loopFile" type="file" accept="audio/*" className={fileClassName} />
</div>
<div>
<label className="mb-2 block text-sm font-medium text-slate-700">{copy.admin.views.sound.previewFileLabel}</label>
<input name="previewFile" type="file" accept="audio/*" className={fileClassName} />
</div>
</div>
<div className="mt-5">
<label className="mb-2 block text-sm font-medium text-slate-700">{copy.admin.views.sound.fallbackLoopFileLabel}</label>
<input name="fallbackLoopFile" type="file" accept="audio/*" className={fileClassName} />
</div>
<div className="mt-5 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4">
<div className="flex items-start justify-between gap-3">
<div>
<p className="text-sm font-medium text-slate-900">
{copy.admin.views.sound.durationOverrideToggle}
</p>
<p className="mt-1 text-xs leading-5 text-slate-500">
{copy.admin.views.sound.durationOverrideHint}
</p>
</div>
<button
type="button"
onClick={() => setIsDurationOverrideEnabled((current) => !current)}
className={`inline-flex h-7 w-12 items-center rounded-full px-1 transition ${
isDurationOverrideEnabled ? 'bg-slate-900' : 'bg-slate-300'
}`}
aria-pressed={isDurationOverrideEnabled}
>
<span
className={`h-5 w-5 rounded-full bg-white transition ${
isDurationOverrideEnabled ? 'translate-x-5' : 'translate-x-0'
}`}
/>
</button>
</div>
{isDurationOverrideEnabled ? (
<div className="mt-4">
<label className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.views.sound.durationLabel}
</label>
<input
name="durationSec"
type="number"
min={0}
className={fieldClassName}
placeholder={copy.admin.views.sound.durationPlaceholder}
/>
</div>
) : null}
</div>
</div>
<div className="border-t border-slate-200 bg-slate-50 px-6 py-6 xl:border-l xl:border-t-0">
<p className="text-sm font-semibold text-slate-900">{copy.admin.views.sound.notesTitle}</p>
<div className="mt-4 rounded-xl border border-slate-200 bg-white px-4 py-3">
<p className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">
{copy.admin.views.sound.extractedDurationLabel}
</p>
<p className="mt-2 text-sm font-medium text-slate-900">
{lastExtractedDurationSec == null
? copy.admin.views.sound.extractedDurationEmpty
: copy.admin.views.sound.extractedDurationValue(lastExtractedDurationSec)}
</p>
</div>
<ul className="mt-4 space-y-3 text-sm leading-6 text-slate-500">
{copy.admin.views.sound.notes.map((note) => (
<li key={note}>{note}</li>
))}
</ul>
{currentMessage ? (
<div className="mt-5 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">
{currentMessage}
</div>
) : null}
<Button
type="submit"
className="mt-6 h-12 w-full rounded-xl bg-slate-900 hover:bg-slate-800"
disabled={soundPending}
>
{soundPending ? copy.admin.views.sound.pending : copy.admin.views.sound.submit}
</Button>
</div>
</div>
</form>
)}
</div>
<aside className="space-y-6">
<div className="rounded-2xl border border-slate-200 bg-white">
<div className="border-b border-slate-200 px-5 py-4">
<p className="text-sm font-semibold text-slate-950">{copy.admin.inspector.recentResponse}</p>
</div>
<div className="px-5 py-4">
<p className="text-sm leading-6 text-slate-500">
{formatResultSummary(uploadResult)}
</p>
<pre className="mt-4 max-h-[340px] overflow-auto rounded-xl bg-[#171821] px-4 py-4 text-[11px] leading-6 text-slate-100">
{uploadResult ? JSON.stringify(uploadResult, null, 2) : copy.admin.inspector.noUploadPayload}
</pre>
</div>
</div>
<div className="rounded-2xl border border-slate-200 bg-white">
<div className="border-b border-slate-200 px-5 py-4">
<p className="text-sm font-semibold text-slate-950">{copy.admin.inspector.sessionToken}</p>
</div>
<div className="px-5 py-4">
<p className="break-all text-xs leading-6 text-slate-500">
{session.accessToken}
</p>
</div>
</div>
</aside>
</div>
</section>
</div>
</div>
</main>
);
} }

View File

@@ -0,0 +1 @@
export * from './model/types';

View File

@@ -0,0 +1,22 @@
export interface SocialLoginRequest {
provider: 'google' | 'apple' | 'facebook';
token: string;
}
export interface PasswordLoginRequest {
email: string;
password: string;
}
export interface UserMeResponse {
id: number;
name: string;
email: string;
grade: string;
}
export interface AuthResponse {
accessToken: string;
refreshToken: string;
user?: UserMeResponse;
}

View File

@@ -33,7 +33,7 @@ export const inboxApi = {
updateThoughtComplete: async ( updateThoughtComplete: async (
thoughtId: string, thoughtId: string,
payload: UpdateInboxThoughtRequest payload: UpdateInboxThoughtRequest,
): Promise<InboxThoughtResponse> => { ): Promise<InboxThoughtResponse> => {
return apiClient<InboxThoughtResponse>(`api/v1/inbox/thoughts/${thoughtId}/complete`, { return apiClient<InboxThoughtResponse>(`api/v1/inbox/thoughts/${thoughtId}/complete`, {
method: 'PUT', method: 'PUT',

View File

@@ -2,8 +2,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { copy } from '@/shared/i18n'; import { copy } from '@/shared/i18n';
import { inboxApi } from '../api/inboxApi';
import type { RecentThought } from './types'; import type { RecentThought } from './types';
import { inboxApi } from '@/features/inbox/api/inboxApi';
const MAX_THOUGHT_INBOX_ITEMS = 40; const MAX_THOUGHT_INBOX_ITEMS = 40;

View File

@@ -3,7 +3,7 @@
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { TOKEN_COOKIE_KEY } from "@/features/auth/model/constants"; import { TOKEN_COOKIE_KEY } from "@/shared/config/authTokens";
import { Button, type ButtonSize, type ButtonVariant } from "@/shared/ui/Button"; import { Button, type ButtonSize, type ButtonVariant } from "@/shared/ui/Button";
import { useAuthStore } from "@/store/useAuthStore"; import { useAuthStore } from "@/store/useAuthStore";

View File

@@ -0,0 +1,2 @@
export const TOKEN_COOKIE_KEY = 'vr_access_token';
export const REFRESH_TOKEN_COOKIE_KEY = 'vr_refresh_token';

View File

@@ -1,726 +1,11 @@
import { core } from './messages/core';
import { space } from './messages/space';
import { admin } from './messages/admin';
import { app } from './messages/app';
export const ko = { export const ko = {
appName: 'VibeRoom', ...core,
metadata: { ...app,
title: 'VibeRoom - 당신만의 편안한 몰입 공간', admin,
description: space,
'프리랜서와 온전한 집중이 필요한 분들을 위한 따뜻하고 구조화된 온라인 코워킹 스페이스. 작업 타이머, 세션 관리, 그리고 느슨한 연대를 통해 당신의 리듬을 찾아보세요.',
},
common: {
close: '닫기',
cancel: '취소',
save: '저장',
delete: '삭제',
complete: '완료',
select: '선택',
hub: '허브로',
loading: '불러오는 중이에요.',
default: '기본',
defaultBackground: '기본 배경',
admin: '관리자',
requestFailed: (status: number) => `요청 실패: ${status}`,
apiRequestFailed: (status: number) => `API 요청 실패: ${status}`,
},
landing: {
nav: {
features: '기능 소개',
pricing: '요금제',
login: '로그인',
startFree: '무료로 시작하기',
},
hero: {
titleLead: '함께하는 조용한 몰입,',
titleAccent: 'VibeRoom',
description:
'집중하기 어려운 순간, 당신을 다그치지 않는 편안한 공간으로 들어오세요. 구조화된 코워킹 세션과 느슨한 연대가 당신의 페이스를 되찾아 줍니다.',
primaryCta: '나만의 공간 만들기',
secondaryCta: '더 알아보기',
timerPreview: '45:00 남음',
},
features: {
title: '당신을 위한 다정한 몰입 장치',
description: '단순한 타이머가 아닙니다. 무리하지 않고 오래 지속할 수 있는 환경을 제공합니다.',
items: [
{
icon: '⏳',
title: '구조화된 세션 타이머',
description:
'부담 없이 시작할 수 있는 짧은 몰입과 확실한 휴식. 당신만의 작업 리듬을 부드럽게 설정하고 관리하세요.',
},
{
icon: '🌱',
title: '다정한 연대와 코워킹',
description:
'화면 너머 누군가와 함께하는 바디 더블링 효과. 감시가 아닌, 조용하지만 강력한 동기를 서로 나누어보세요.',
},
{
icon: '🛋️',
title: '나만의 심미적 공간',
description:
'비 오는 다락방, 햇살 드는 카페. 백색소음과 함께 내가 가장 편안함을 느끼는 가상 공간을 꾸미고 머무르세요.',
},
],
},
pricing: {
title: '나에게 맞는 공간 선택하기',
description: '개인의 가벼운 집중부터 프리랜서의 완벽한 워크스페이스까지.',
plans: {
starter: {
name: 'Starter',
subtitle: '가벼운 집중이 필요한 분',
price: '무료',
cta: '무료로 시작하기',
features: ['기본 가상 공간 테마', '1:1 파트너 매칭 (주 3회)', '오픈 코워킹 룸 입장'],
},
pro: {
badge: '추천',
name: 'Pro',
subtitle: '방해 없는 완벽한 몰입 환경',
price: '₩6,900',
priceSuffix: '/월',
cta: 'Pro 시작하기',
features: [
'프리미엄 테마 무제한',
'1:1 매칭 무제한',
'고급 집중 통계 및 리포트',
'공간 커스텀 아이템 제공',
],
},
teams: {
name: 'Teams',
subtitle: '리모트 워크 기업 및 팀',
price: '₩12,000',
priceSuffix: '/인·월',
cta: '도입 문의하기',
features: ['Pro 플랜의 모든 기능', '프라이빗 팀 스페이스', '팀 전체 생산성 대시보드'],
},
},
},
footer: {
description:
'프리랜서와 온전한 집중이 필요한 분들을 위한 따뜻하고 구조화된 온라인 코워킹 스페이스입니다.',
productTitle: '제품',
companyTitle: '회사',
links: {
features: '기능 소개',
pricing: '요금제',
webLogin: '웹앱 로그인',
about: '소개',
privacy: '개인정보처리방침',
terms: '이용약관',
},
copyright: '© 2026 VibeRoom. All rights reserved.',
},
},
login: {
title: '다시 오셨군요!',
descriptionFirstLine: '비밀번호를 외울 필요 없이,',
descriptionSecondLine: '사용 중인 계정으로 3초 만에 시작하세요.',
agreementPrefix: '로그인함으로써 VibeRoom의',
agreementAnd: '및',
terms: '이용약관',
privacy: '개인정보처리방침',
agreementSuffix: '에 동의하게 됩니다.',
},
auth: {
social: {
connecting: '연결 중...',
continueWithGoogle: 'Google로 계속하기',
continueWithApple: 'Apple로 계속하기',
continueWithFacebook: 'Facebook으로 계속하기',
},
errors: {
loginFailed: '로그인에 실패했습니다. 다시 시도해 주세요.',
googleFailed: '구글 로그인에 실패했습니다. 팝업 차단 여부를 확인해 주세요.',
appleFailed: '애플 로그인 중 오류가 발생했습니다.',
appleInitFailed: '애플 로그인 초기화 실패',
facebookFailed: '페이스북 로그인에 실패했습니다.',
},
},
admin: {
defaultLoginId: 'qwer1234',
defaultPassword: 'qwer1234!',
consoleLabel: 'Admin Console',
mediaAdminLabel: 'Media Admin',
localCredentialsHint: 'Local admin credentials',
signInEyebrow: 'Sign In',
loginTitle: '관리자 로그인',
loginDescription: '관리자 권한이 확인되면 좌측 사이드바 기반 대시보드가 열립니다.',
loginIdLabel: '아이디',
loginPasswordLabel: '비밀번호',
openDashboard: '대시보드 열기',
loggingIn: '로그인 중...',
logout: '로그아웃',
mediaOperations: 'Media Operations',
access: 'Access',
accessTitle: 'Admin Only',
accessDescription: '로그인 후 업로드 토큰으로 scene 이미지와 sound 오디오를 바로 R2에 반영합니다.',
manifestReady: 'Manifest Ready',
sessionSection: 'Session',
sessionAdminLabel: 'Admin',
sessionRoleLabel: 'Role',
roleAccessSuffix: ' Access',
searchValues: {
scene: 'scene assets',
sound: 'sound assets',
},
navItems: [
{
id: 'scene',
title: '이미지 등록',
subtitle: 'Scene background assets',
section: 'MEDIA',
},
{
id: 'sound',
title: '오디오 등록',
subtitle: 'Loop and preview assets',
section: 'MEDIA',
},
],
views: {
scene: {
eyebrow: 'Image Registration',
title: 'Scene 이미지 등록',
description:
'Space에 들어온 사용자가 선택하는 배경 이미지 세트를 등록합니다. 원본 1장을 올리면 서버가 card, stage, mobileStage, hdStage를 자동 생성합니다.',
statTitle: 'Image Pipeline',
statValue: 'Scene Assets',
statHint: 'R2 / Manifest Sync',
workspaceTitle: '이미지 등록 워크스페이스',
workspaceDescription: '왼쪽 메뉴는 유지되고, 이 중앙 영역에서 원본 이미지 1장으로 전체 scene 파생본을 생성합니다.',
sceneIdLabel: 'Scene ID',
sceneIdPlaceholder: 'rain-window',
sceneIdHint: 'scene catalog에 등록된 id와 동일한 값을 사용하세요.',
sourceImageLabel: 'Source Image',
sourceImageHint: '최소 3200x1800 · 권장 3840x2160',
sourceImageDerivedHint: '업로드하면 card, stage, mobileStage, hdStage 파생본이 자동 생성됩니다.',
blurDataUrlLabel: 'Blur Placeholder Data URL',
blurDataUrlPlaceholder: 'data:image/jpeg;base64,... 저해상도 프리뷰 문자열',
blurDataUrlHint: '선택 입력입니다. 이미지가 완전히 로드되기 전 잠깐 보여줄 저해상도 프리뷰가 필요할 때만 넣으세요.',
notesTitle: '업로드 메모',
notes: [
'최초 생성 시 `sourceImageFile`은 필수입니다.',
'원본 1장을 업로드하면 서버가 4개 파생본(card, stage, mobileStage, hdStage)을 자동 생성합니다.',
'가로형 기준 최소 3200x1800, 권장 3840x2160 원본을 사용하세요.',
'`blurDataUrl`은 이미지가 완전히 로드되기 전 잠깐 보여줄 저해상도 base64 프리뷰입니다.',
'업로드 즉시 R2 경로와 manifest 응답 값이 갱신됩니다.',
],
submit: '이미지 등록',
pending: '이미지 업로드 중...',
},
sound: {
eyebrow: 'Audio Registration',
title: 'Sound 오디오 등록',
description:
'Loop, preview, fallback 오디오를 등록합니다. loopFile은 최초 생성 시 필수이며 duration은 기본적으로 loopFile에서 자동 추출됩니다.',
statTitle: 'Audio Pipeline',
statValue: 'Sound Assets',
statHint: 'Loop / Preview / Fallback',
workspaceTitle: '오디오 등록 워크스페이스',
workspaceDescription: '좌측 네비게이션은 고정되고, 이 중앙 영역에서 loop 메타데이터와 파생 오디오를 함께 관리합니다.',
presetIdLabel: 'Preset ID',
presetIdPlaceholder: 'rain-focus',
durationLabel: 'Duration Override Sec',
durationPlaceholder: '비워두면 loopFile에서 자동 추출',
durationOverrideToggle: '수동 duration 보정',
durationOverrideHint: '기본값은 loopFile에서 자동 추출됩니다. 값을 넣으면 자동 추출 대신 이 값으로 저장합니다.',
extractedDurationLabel: '최근 추출 길이',
extractedDurationEmpty: '아직 자동 추출 결과가 없습니다.',
extractedDurationValue: (seconds: number) => `${seconds} sec`,
defaultVolumeLabel: 'Default Volume',
defaultVolumePlaceholder: '60',
loopFileLabel: 'Loop File',
previewFileLabel: 'Preview File',
fallbackLoopFileLabel: 'Fallback Loop File',
notesTitle: '업로드 메모',
notes: [
'최초 생성 시 `loopFile`은 필수입니다.',
'`preview`, `fallback`은 선택값이며 기존 메타데이터를 유지할 수 있습니다.',
'`durationSec`은 기본적으로 자동 추출되고, 필요할 때만 수동 override를 켤 수 있습니다.',
'`defaultVolume`와 최종 `durationSec`는 manifest 응답에 함께 반영됩니다.',
],
submit: '오디오 등록',
pending: '오디오 업로드 중...',
},
},
inspector: {
recentResponse: '최근 응답',
noUploadSummary: '아직 업로드 작업이 없습니다.',
noUploadPayload: '업로드 응답이 아직 없습니다.',
sessionToken: '세션 토큰',
currentRoleTitle: 'Current Role',
bearerTokenSession: 'Bearer token enabled session',
},
messages: {
nonAdmin: 'ADMIN 권한이 없는 계정입니다.',
loginFailed: '로그인에 실패했습니다.',
loginRequired: '먼저 관리자 로그인을 해주세요.',
sceneIdRequired: 'sceneId를 입력해주세요.',
presetIdRequired: 'presetId를 입력해주세요.',
sceneUploadFailed: 'scene 업로드에 실패했습니다.',
soundUploadFailed: 'sound 업로드에 실패했습니다.',
sceneUploadDone: (sceneId: string) => `scene "${sceneId}" 업로드가 완료되었습니다.`,
soundUploadDone: (presetId: string) => `sound "${presetId}" 업로드가 완료되었습니다.`,
sceneSummary: (sceneId: string, version: string) =>
`${sceneId} 이미지 세트가 최신 버전 ${version}로 반영되었습니다.`,
soundSummary: (presetId: string, version: string) =>
`${presetId} 오디오 세트가 최신 버전 ${version}로 반영되었습니다.`,
},
},
settings: {
title: 'Settings',
focusPreferencesApi: 'Focus Preferences API',
loading: '저장된 설정을 불러오는 중이에요.',
saving: '변경 사항을 저장하는 중이에요.',
synced: '변경 즉시 서버에 저장합니다.',
reduceMotionTitle: 'Reduce Motion',
reduceMotionDescription: '전환 애니메이션을 최소화합니다. (UI 토글 목업)',
notificationIntensityTitle: '알림 강도',
notificationIntensityDescription: '집중 시작/종료 신호의 존재감을 선택합니다.',
defaultPresetTitle: '기본 프리셋',
defaultPresetDescription: '입장 시 자동 선택될 추천 세트를 고릅니다.',
notificationIntensityOptions: ['조용함', '기본', '강함'],
defaultPresetOptions: [
{ id: 'balanced', label: 'Balanced 25/5 + Rain Focus' },
{ id: 'deep-work', label: 'Deep Work 50/10 + Deep White' },
{ id: 'gentle', label: 'Gentle 25/5 + Silent' },
],
},
stats: {
title: 'Stats',
apiLabel: 'API',
mockLabel: 'Mock',
sourceApi: 'API 통계 사용 중',
sourceMock: 'API 실패로 mock 통계 표시 중',
loading: '통계를 불러오는 중이에요.',
loadFailed: '통계를 불러오지 못했어요.',
synced: '화면 진입 시 최신 요약을 동기화합니다.',
refresh: '새로고침',
today: '오늘',
last7Days: '최근 7일',
chartTitle: '집중 흐름 그래프',
chartWithTrend: 'trend 응답으로 간단한 막대 그래프를 렌더링합니다.',
chartWithoutTrend: 'trend 응답이 비어 있어 플레이스홀더 상태입니다.',
todayFocus: '오늘 집중 시간',
completedCycles: '완료한 사이클',
sessionEntries: '입장 횟수',
last7DaysFocus: '최근 7일 집중 시간',
bestDay: '최고 몰입일',
streak: '연속 달성',
syncedApi: '동기화됨',
temporary: '임시값',
actualAggregate: '실집계',
mockAggregate: '목업',
streakActive: '유지 중',
streakStart: '시작 전',
countUnit: '회',
dayUnit: '일',
minuteUnit: '분',
barTitle: (date: string, minutes: number) => `${date} · ${minutes}`,
},
plan: {
proFeatureCards: [
{
id: 'scene-packs',
name: 'Scene Packs',
description: '프리미엄 공간 묶음과 장면 변주',
},
{
id: 'sound-packs',
name: 'Sound Packs',
description: '확장 사운드 프리셋 묶음',
},
{
id: 'profiles',
name: 'Profiles',
description: '내 기본 세팅 저장/불러오기',
},
],
},
session: {
todayOneLiner: '오늘의 한 줄: 완벽보다 시작, 한 조각이면 충분해요.',
goalChips: [
{ id: 'mail-3', label: '메일 3개' },
{ id: 'doc-1p', label: '문서 1p' },
{ id: 'code-1-function', label: '코딩 1함수' },
{ id: 'tidy-10m', label: '정리 10분' },
{ id: 'reading-15m', label: '독서 15분' },
{ id: 'resume-1paragraph', label: '이력서 1문단' },
],
checkInPhrases: [
{ id: 'arrived', text: '지금 들어왔어요' },
{ id: 'sprint-25', text: '25분만 달릴게요' },
{ id: 'on-break', text: '휴식 중' },
{ id: 'back-focus', text: '다시 집중!' },
{ id: 'slow-day', text: '오늘은 천천히' },
],
reactionOptions: [
{ id: 'thumbs-up', emoji: '👍', label: '응원해요' },
{ id: 'fire', emoji: '🔥', label: '집중 모드' },
{ id: 'clap', emoji: '👏', label: '잘하고 있어요' },
{ id: 'heart-hands', emoji: '🫶', label: '연결되어 있어요' },
],
soundPresets: [
{ id: 'deep-white', label: 'Deep White' },
{ id: 'rain-focus', label: 'Rain Focus' },
{ id: 'forest-birds', label: 'Forest Birds' },
{ id: 'cafe-work', label: 'Cafe Work' },
{ id: 'ocean-calm', label: 'Ocean Calm' },
{ id: 'fireplace', label: 'Fireplace' },
{ id: 'silent', label: 'Silent' },
],
timerPresets: [
{ id: '25-5', label: '25/5', focusMinutes: 25, breakMinutes: 5 },
{ id: '50-10', label: '50/10', focusMinutes: 50, breakMinutes: 10 },
{ id: '90-20', label: '90/20', focusMinutes: 90, breakMinutes: 20 },
{ id: 'custom', label: '커스텀' },
],
distractionDumpPlaceholder: ['디자인 QA 요청 확인', '세금계산서 발행 메모', '오후 미팅 질문 1개 정리'],
todayStats: [
{ id: 'today-focus', label: '오늘 집중 시간', value: '2h 40m', delta: '+35m' },
{ id: 'today-cycles', label: '완료한 사이클', value: '5회', delta: '+1' },
{ id: 'today-entry', label: '입장 횟수', value: '3회', delta: '유지' },
],
weeklyStats: [
{ id: 'week-focus', label: '최근 7일 집중 시간', value: '14h 20m', delta: '+2h 10m' },
{ id: 'week-best-day', label: '최고 몰입일', value: '수요일', delta: '3h 30m' },
{ id: 'week-consistency', label: '연속 달성', value: '4일', delta: '+1일' },
],
recentThoughts: [
{
id: 'thought-1',
text: '내일 미팅 전에 제안서 첫 문단만 다시 다듬기',
sceneName: '도서관',
capturedAt: '방금 전',
},
{
id: 'thought-2',
text: '기획 문서의 핵심 흐름을 한 문장으로 정리해두기',
sceneName: '비 오는 창가',
capturedAt: '24분 전',
},
{
id: 'thought-3',
text: '오후에 확인할 이슈 번호만 메모하고 지금 작업 복귀',
sceneName: '숲',
capturedAt: '1시간 전',
},
{
id: 'thought-4',
text: '리뷰 코멘트는 오늘 17시 이후에 한 번에 처리',
sceneName: '벽난로',
capturedAt: '어제',
},
],
justNow: '방금 전',
},
scenes: [
{
id: 'rain-window',
name: '비 오는 창가',
description: '빗소리 위로 스탠드 조명이 부드럽게 번집니다.',
tags: ['저자극', '감성'],
recommendedSound: 'Rain Focus',
recommendedTime: '밤',
vibeLabel: '잔잔함',
},
{
id: 'dawn-cafe',
name: '새벽 카페',
description: '첫 커피 향처럼 잔잔하고 따뜻한 좌석.',
tags: ['감성', '딥워크'],
recommendedSound: 'Cafe Murmur',
recommendedTime: '새벽',
vibeLabel: '포근함',
},
{
id: 'quiet-library',
name: '도서관',
description: '넘기는 종이 소리만 들리는 정돈된 책상.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Deep White',
recommendedTime: '오후',
vibeLabel: '몰입',
},
{
id: 'wave-sound',
name: '파도 소리',
description: '잔잔한 해변 위로 호흡을 고르는 공간.',
tags: ['움직임 적음', '감성'],
recommendedSound: 'Ocean Breath',
recommendedTime: '밤',
vibeLabel: '차분함',
},
{
id: 'forest',
name: '숲',
description: '바람이 나뭇잎을 스치는 소리로 마음을 낮춥니다.',
tags: ['저자극', '움직임 적음'],
recommendedSound: 'Forest Birds',
recommendedTime: '오전',
vibeLabel: '맑음',
},
{
id: 'fireplace',
name: '벽난로',
description: '작은 불꽃이 주는 리듬으로 집중을 붙잡습니다.',
tags: ['감성', '저자극'],
recommendedSound: 'Fireplace',
recommendedTime: '밤',
vibeLabel: '온기',
},
{
id: 'city-night',
name: '도시 야경',
description: '유리창 너머 야경이 멀리 흐르는 고요한 밤.',
tags: ['딥워크', '감성'],
recommendedSound: 'Night Lo-fi',
recommendedTime: '심야',
vibeLabel: '고요함',
},
{
id: 'snow-mountain',
name: '설산',
description: '차분한 공기와 선명한 수평선이 머리를 맑게 합니다.',
tags: ['움직임 적음', '딥워크'],
recommendedSound: 'Cold Wind',
recommendedTime: '새벽',
vibeLabel: '선명함',
},
{
id: 'sun-window',
name: '창가',
description: '햇살이 들어오는 간결한 책상, 부담 없는 시작.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Soft Daylight',
recommendedTime: '오후',
vibeLabel: '가벼움',
},
{
id: 'outer-space',
name: '우주',
description: '별빛만 남긴 어둠 속에서 깊게 잠수합니다.',
tags: ['딥워크', '감성'],
recommendedSound: 'Deep Drone',
recommendedTime: '심야',
vibeLabel: '깊음',
},
],
modal: {
closeAriaLabel: '모달 닫기',
closeButton: '닫기',
},
media: {
manifestLoadFailed: '미디어 manifest를 불러오지 못했어요.',
},
preferences: {
defaultNotificationIntensity: '기본',
loadFailed: '설정을 불러오지 못했어요.',
saveFailed: '설정을 저장하지 못했어요.',
saved: '저장됨',
saveFailedLabel: '저장 실패',
},
focusSession: {
syncFailed: '세션 엔진과 동기화하지 못했어요.',
startFailed: '세션을 시작하지 못했어요.',
pauseFailed: '세션을 일시정지하지 못했어요.',
resumeFailed: '세션을 다시 시작하지 못했어요.',
restartPhaseFailed: '현재 페이즈를 다시 시작하지 못했어요.',
completeFailed: '세션을 완료 처리하지 못했어요.',
abandonFailed: '세션을 종료하지 못했어요.',
},
space: {
sessionGoal: {
label: '이번 25분, 딱 한 가지',
required: '(필수)',
placeholder: '예: 계약서 1페이지 정리',
hint: '크게 말고, 바로 다음 한 조각.',
},
setup: {
panelAriaLabel: '집중 시작 패널',
eyebrow: 'Ritual',
title: '이번 한 조각을 정하고 시작해요.',
description: '목표를 정한 뒤 HUD의 시작 버튼으로 실제 세션을 시작해요.',
resumeTitle: '지난 한 조각 이어서',
startFresh: '새로 시작',
resumePrepare: '이어서 준비',
sceneLabel: '배경',
timerLabel: '타이머',
soundLabel: '사운드',
readyHint: '목표를 적으면 시작할 수 있어요.',
openFocusScreen: '집중 화면 열기',
},
timerHud: {
actions: [
{ id: 'start', label: '시작', icon: '▶' },
{ id: 'pause', label: '일시정지', icon: '⏸' },
{ id: 'reset', label: '리셋', icon: '↺' },
],
readyMode: 'Ready',
focusMode: 'Focus',
breakMode: 'Break',
goalFallback: '이번 한 조각을 설정해 주세요.',
goalPrefix: '이번 한 조각 · ',
completeButton: '완료',
},
focusHud: {
goalFallback: '집중을 시작해요.',
goalToast: (goal: string) => `이번 한 조각 · ${goal}`,
restReminder: '5분이 지났어요. 다음 한 조각으로 돌아와요.',
},
goalComplete: {
suggestions: ['리뷰 코멘트 2개 처리', '문서 1문단 다듬기', '이슈 1개 정리', '메일 2개 회신'],
placeholderFallback: '다음 한 조각을 적어보세요',
placeholderExample: (goal: string) => `예: ${goal}`,
title: '좋아요. 다음 한 조각은?',
description: '너무 크게 잡지 말고, 바로 다음 한 조각만.',
closeAriaLabel: '닫기',
restButton: '잠깐 쉬기',
confirmButton: '바로 다음 조각 시작',
},
controlCenter: {
sectionTitles: {
background: 'Background',
time: 'Time',
sound: 'Sound',
packs: 'Packs',
},
packsDescription: '확장/개인화',
recommendation: (soundLabel: string, timerLabel: string) => `추천: ${soundLabel} · ${timerLabel}`,
recommendationHint: '추천 조합은 참고 정보로만 제공돼요.',
autoHideTitle: '컨트롤 자동 숨김',
autoHideDescription: '입력이 없으면 잠시 후 패널을 닫아요.',
autoHideAriaLabel: '컨트롤 자동 숨김',
sideSheetSubtitle: '배경 · 타이머 · 사운드를 그 자리에서 바꿔요.',
quickControlsTitle: 'Quick Controls',
},
toolsDock: {
notesButton: 'Notes',
popoverCloseAria: '팝오버 닫기',
planPro: 'PRO',
planNormal: 'Normal',
inboxSaved: '인박스에 저장됨',
undo: '실행취소',
inboxSaveUndone: '저장 취소됨',
deleted: '삭제됨',
deleteUndone: '삭제를 취소했어요.',
emptyToClear: '비울 항목이 없어요.',
clearedAll: '모두 비워짐',
restored: '복원했어요.',
normalPlanInfo: 'NORMAL 플랜 사용 중 · 잠금 항목에서만 업그레이드할 수 있어요.',
proFeatureLocked: (source: string) => `${source}은(는) PRO 기능이에요.`,
proFeaturePending: (label: string) => `${label} 준비 중(더미)`,
purchaseMock: '결제(더미)',
manageSubscriptionMock: '구독 관리(더미)',
restorePurchaseMock: '구매 복원(더미)',
featureLabels: {
scenePacks: 'Scene Packs',
soundPacks: 'Sound Packs',
profiles: 'Profiles',
},
utilityPanelTitle: {
'control-center': 'Quick Controls',
inbox: '인박스',
paywall: 'PRO',
'manage-plan': '플랜 관리',
},
},
quickNotes: {
title: '떠오른 생각을 잠깐 주차해요',
placeholder: '떠오른 생각을 잠깐 주차…',
submit: '저장',
hint: '나중에 인박스에서 정리해요.',
},
quickSound: {
currentSound: '현재 사운드',
muteAriaLabel: '음소거',
unmuteAriaLabel: '음소거 해제',
volumeAriaLabel: '사운드 볼륨',
quickSwitch: '빠른 전환',
},
soundPresetControls: {
preset: 'Preset',
mixerOpen: 'Mixer 펼치기',
mixerClose: 'Mixer 접기',
mock: '더미',
masterVolume: '마스터 볼륨',
mute: '뮤트',
muteToggleAriaLabel: '마스터 뮤트 토글',
trackLabels: {
white: 'White',
rain: 'Rain',
cafe: 'Cafe',
wave: 'Wave',
fan: 'Fan',
},
},
inbox: {
empty: '지금은 비어 있어요. 집중 중 떠오른 생각을 여기로 주차할 수 있어요.',
complete: '완료',
completed: '완료됨',
delete: '삭제',
readOnly: '나중에 모아보는 읽기 전용 인박스',
clearAll: '모두 비우기',
clearConfirmTitle: '정말 인박스를 비울까요?',
clearConfirmDescription: '실수라면 토스트에서 실행취소할 수 있어요.',
clearButton: '비우기',
openInboxAriaLabel: '인박스 열기',
openInboxTitle: '인박스',
},
rightRail: {
openQuickControlsAriaLabel: 'Quick Controls 열기',
openQuickControlsTitle: 'Quick Controls',
},
paywall: {
points: ['프리미엄 Scene Packs', '확장 Sound Packs', '프로필 저장 / 불러오기'],
title: 'PRO에서 더 많은 공간과 사운드를 열어둘 수 있어요.',
description: '잠금 항목을 누른 순간에만 열리는 더미 결제 시트입니다.',
later: '나중에',
startPro: 'PRO 시작하기',
manageTitle: 'PRO 관리',
manageDescription: '결제/복원은 더미 동작이며 실제 연동은 하지 않아요.',
openSubscription: '구독 관리 열기',
restorePurchase: '구매 복원',
},
statsPanel: {
description: '오늘 흐름과 최근 7일 리듬을 가볍게 확인하세요.',
graphPlaceholder: '그래프 플레이스홀더',
},
settingsPanel: {
reduceMotion: 'Reduce Motion',
reduceMotionDescription: '화면 전환을 조금 더 차분하게 표시합니다.',
background: '배경',
backgroundDescription: '몰입 중에도 배경 scene을 바꿀 수 있어요.',
timerPreset: '타이머 프리셋',
timerPresetDescription: '기본 프리셋만 빠르게 고를 수 있어요.',
defaultPreset: '기본 프리셋',
},
workspace: {
readyToStart: '준비 완료 · 시작 버튼을 눌러 집중을 시작해요.',
startFailed: '세션을 시작하지 못했어요. 잠시 후 다시 시도해 주세요.',
resumeFailed: '세션을 다시 시작하지 못했어요.',
abandonFailed: '세션 종료를 완료하지 못했어요.',
pauseFailed: '세션을 일시정지하지 못했어요.',
restartFailed: '현재 페이즈를 다시 시작하지 못했어요.',
restarted: '현재 페이즈를 처음부터 다시 시작했어요.',
goalCompleteSyncFailed: '현재 세션 완료를 서버에 반영하지 못했어요.',
nextGoalReady: '다음 한 조각 준비 완료 · 시작 버튼을 눌러 이어가요.',
selectionPreferenceSaveFailed: '배경/사운드 기본 설정을 저장하지 못했어요.',
selectionSessionSyncFailed: '현재 세션의 배경/사운드 선택을 동기화하지 못했어요.',
},
exitHold: {
holdToExitAriaLabel: '길게 눌러 나가기',
exit: '나가기',
},
},
soundPlayback: {
loadFailed: '사운드 파일을 불러오지 못했어요.',
browserDeferred: '브라우저가 사운드 재생을 보류했어요.',
},
restart30s: {
button: '숨 고르기 30초',
mode: 'BREATHE',
toast: '잠깐 숨 고르고, 다시 천천히 시작해요.',
complete: '준비됐어요. 집중으로 돌아가요.',
},
} as const; } as const;

View File

@@ -0,0 +1,131 @@
export const admin = {
defaultLoginId: 'qwer1234',
defaultPassword: 'qwer1234!',
consoleLabel: 'Admin Console',
mediaAdminLabel: 'Media Admin',
localCredentialsHint: 'Local admin credentials',
signInEyebrow: 'Sign In',
loginTitle: '관리자 로그인',
loginDescription: '관리자 권한이 확인되면 좌측 사이드바 기반 대시보드가 열립니다.',
loginIdLabel: '아이디',
loginPasswordLabel: '비밀번호',
openDashboard: '대시보드 열기',
loggingIn: '로그인 중...',
logout: '로그아웃',
mediaOperations: 'Media Operations',
access: 'Access',
accessTitle: 'Admin Only',
accessDescription: '로그인 후 업로드 토큰으로 scene 이미지와 sound 오디오를 바로 R2에 반영합니다.',
manifestReady: 'Manifest Ready',
sessionSection: 'Session',
sessionAdminLabel: 'Admin',
sessionRoleLabel: 'Role',
roleAccessSuffix: ' Access',
searchValues: {
scene: 'scene assets',
sound: 'sound assets',
},
navItems: [
{
id: 'scene',
title: '이미지 등록',
subtitle: 'Scene background assets',
section: 'MEDIA',
},
{
id: 'sound',
title: '오디오 등록',
subtitle: 'Loop and preview assets',
section: 'MEDIA',
},
],
views: {
scene: {
eyebrow: 'Image Registration',
title: 'Scene 이미지 등록',
description:
'Space에 들어온 사용자가 선택하는 배경 이미지 세트를 등록합니다. 원본 1장을 올리면 서버가 card, stage, mobileStage, hdStage를 자동 생성합니다.',
statTitle: 'Image Pipeline',
statValue: 'Scene Assets',
statHint: 'R2 / Manifest Sync',
workspaceTitle: '이미지 등록 워크스페이스',
workspaceDescription: '왼쪽 메뉴는 유지되고, 이 중앙 영역에서 원본 이미지 1장으로 전체 scene 파생본을 생성합니다.',
sceneIdLabel: 'Scene ID',
sceneIdPlaceholder: 'rain-window',
sceneIdHint: 'scene catalog에 등록된 id와 동일한 값을 사용하세요.',
sourceImageLabel: 'Source Image',
sourceImageHint: '최소 3200x1800 · 권장 3840x2160',
sourceImageDerivedHint: '업로드하면 card, stage, mobileStage, hdStage 파생본이 자동 생성됩니다.',
blurDataUrlLabel: 'Blur Placeholder Data URL',
blurDataUrlPlaceholder: 'data:image/jpeg;base64,... 저해상도 프리뷰 문자열',
blurDataUrlHint: '선택 입력입니다. 이미지가 완전히 로드되기 전 잠깐 보여줄 저해상도 프리뷰가 필요할 때만 넣으세요.',
notesTitle: '업로드 메모',
notes: [
'최초 생성 시 `sourceImageFile`은 필수입니다.',
'원본 1장을 업로드하면 서버가 4개 파생본(card, stage, mobileStage, hdStage)을 자동 생성합니다.',
'가로형 기준 최소 3200x1800, 권장 3840x2160 원본을 사용하세요.',
'`blurDataUrl`은 이미지가 완전히 로드되기 전 잠깐 보여줄 저해상도 base64 프리뷰입니다.',
'업로드 즉시 R2 경로와 manifest 응답 값이 갱신됩니다.',
],
submit: '이미지 등록',
pending: '이미지 업로드 중...',
},
sound: {
eyebrow: 'Audio Registration',
title: 'Sound 오디오 등록',
description:
'Loop, preview, fallback 오디오를 등록합니다. loopFile은 최초 생성 시 필수이며 duration은 기본적으로 loopFile에서 자동 추출됩니다.',
statTitle: 'Audio Pipeline',
statValue: 'Sound Assets',
statHint: 'Loop / Preview / Fallback',
workspaceTitle: '오디오 등록 워크스페이스',
workspaceDescription: '좌측 네비게이션은 고정되고, 이 중앙 영역에서 loop 메타데이터와 파생 오디오를 함께 관리합니다.',
presetIdLabel: 'Preset ID',
presetIdPlaceholder: 'rain-focus',
durationLabel: 'Duration Override Sec',
durationPlaceholder: '비워두면 loopFile에서 자동 추출',
durationOverrideToggle: '수동 duration 보정',
durationOverrideHint: '기본값은 loopFile에서 자동 추출됩니다. 값을 넣으면 자동 추출 대신 이 값으로 저장합니다.',
extractedDurationLabel: '최근 추출 길이',
extractedDurationEmpty: '아직 자동 추출 결과가 없습니다.',
extractedDurationValue: (seconds: number) => `${seconds} sec`,
defaultVolumeLabel: 'Default Volume',
defaultVolumePlaceholder: '60',
loopFileLabel: 'Loop File',
previewFileLabel: 'Preview File',
fallbackLoopFileLabel: 'Fallback Loop File',
notesTitle: '업로드 메모',
notes: [
'최초 생성 시 `loopFile`은 필수입니다.',
'`preview`, `fallback`은 선택값이며 기존 메타데이터를 유지할 수 있습니다.',
'`durationSec`은 기본적으로 자동 추출되고, 필요할 때만 수동 override를 켤 수 있습니다.',
'`defaultVolume`와 최종 `durationSec`는 manifest 응답에 함께 반영됩니다.',
],
submit: '오디오 등록',
pending: '오디오 업로드 중...',
},
},
inspector: {
recentResponse: '최근 응답',
noUploadSummary: '아직 업로드 작업이 없습니다.',
noUploadPayload: '업로드 응답이 아직 없습니다.',
sessionToken: '세션 토큰',
currentRoleTitle: 'Current Role',
bearerTokenSession: 'Bearer token enabled session',
},
messages: {
nonAdmin: 'ADMIN 권한이 없는 계정입니다.',
loginFailed: '로그인에 실패했습니다.',
loginRequired: '먼저 관리자 로그인을 해주세요.',
sceneIdRequired: 'sceneId를 입력해주세요.',
presetIdRequired: 'presetId를 입력해주세요.',
sceneUploadFailed: 'scene 업로드에 실패했습니다.',
soundUploadFailed: 'sound 업로드에 실패했습니다.',
sceneUploadDone: (sceneId: string) => `scene "${sceneId}" 업로드가 완료되었습니다.`,
soundUploadDone: (presetId: string) => `sound "${presetId}" 업로드가 완료되었습니다.`,
sceneSummary: (sceneId: string, version: string) =>
`${sceneId} 이미지 세트가 최신 버전 ${version}로 반영되었습니다.`,
soundSummary: (presetId: string, version: string) =>
`${presetId} 오디오 세트가 최신 버전 ${version}로 반영되었습니다.`,
},
} as const;

View File

@@ -0,0 +1,241 @@
export const app = {
settings: {
title: 'Settings',
focusPreferencesApi: 'Focus Preferences API',
loading: '저장된 설정을 불러오는 중이에요.',
saving: '변경 사항을 저장하는 중이에요.',
synced: '변경 즉시 서버에 저장합니다.',
reduceMotionTitle: 'Reduce Motion',
reduceMotionDescription: '전환 애니메이션을 최소화합니다. (UI 토글 목업)',
notificationIntensityTitle: '알림 강도',
notificationIntensityDescription: '집중 시작/종료 신호의 존재감을 선택합니다.',
defaultPresetTitle: '기본 프리셋',
defaultPresetDescription: '입장 시 자동 선택될 추천 세트를 고릅니다.',
notificationIntensityOptions: ['조용함', '기본', '강함'],
defaultPresetOptions: [
{ id: 'balanced', label: 'Balanced 25/5 + Rain Focus' },
{ id: 'deep-work', label: 'Deep Work 50/10 + Deep White' },
{ id: 'gentle', label: 'Gentle 25/5 + Silent' },
],
},
stats: {
title: 'Stats',
apiLabel: 'API',
mockLabel: 'Mock',
sourceApi: 'API 통계 사용 중',
sourceMock: 'API 실패로 mock 통계 표시 중',
loading: '통계를 불러오는 중이에요.',
loadFailed: '통계를 불러오지 못했어요.',
synced: '화면 진입 시 최신 요약을 동기화합니다.',
refresh: '새로고침',
today: '오늘',
last7Days: '최근 7일',
chartTitle: '집중 흐름 그래프',
chartWithTrend: 'trend 응답으로 간단한 막대 그래프를 렌더링합니다.',
chartWithoutTrend: 'trend 응답이 비어 있어 플레이스홀더 상태입니다.',
todayFocus: '오늘 집중 시간',
completedCycles: '완료한 사이클',
sessionEntries: '입장 횟수',
last7DaysFocus: '최근 7일 집중 시간',
bestDay: '최고 몰입일',
streak: '연속 달성',
syncedApi: '동기화됨',
temporary: '임시값',
actualAggregate: '실집계',
mockAggregate: '목업',
streakActive: '유지 중',
streakStart: '시작 전',
countUnit: '회',
dayUnit: '일',
minuteUnit: '분',
barTitle: (date: string, minutes: number) => `${date} · ${minutes}`,
},
plan: {
proFeatureCards: [
{
id: 'scene-packs',
name: 'Scene Packs',
description: '프리미엄 공간 묶음과 장면 변주',
},
{
id: 'sound-packs',
name: 'Sound Packs',
description: '확장 사운드 프리셋 묶음',
},
{
id: 'profiles',
name: 'Profiles',
description: '내 기본 세팅 저장/불러오기',
},
],
},
session: {
todayOneLiner: '오늘의 한 줄: 완벽보다 시작, 한 조각이면 충분해요.',
goalChips: [
{ id: 'mail-3', label: '메일 3개' },
{ id: 'doc-1p', label: '문서 1p' },
{ id: 'code-1-function', label: '코딩 1함수' },
{ id: 'tidy-10m', label: '정리 10분' },
{ id: 'reading-15m', label: '독서 15분' },
{ id: 'resume-1paragraph', label: '이력서 1문단' },
],
checkInPhrases: [
{ id: 'arrived', text: '지금 들어왔어요' },
{ id: 'sprint-25', text: '25분만 달릴게요' },
{ id: 'on-break', text: '휴식 중' },
{ id: 'back-focus', text: '다시 집중!' },
{ id: 'slow-day', text: '오늘은 천천히' },
],
reactionOptions: [
{ id: 'thumbs-up', emoji: '👍', label: '응원해요' },
{ id: 'fire', emoji: '🔥', label: '집중 모드' },
{ id: 'clap', emoji: '👏', label: '잘하고 있어요' },
{ id: 'heart-hands', emoji: '🫶', label: '연결되어 있어요' },
],
soundPresets: [
{ id: 'deep-white', label: 'Deep White' },
{ id: 'rain-focus', label: 'Rain Focus' },
{ id: 'forest-birds', label: 'Forest Birds' },
{ id: 'cafe-work', label: 'Cafe Work' },
{ id: 'ocean-calm', label: 'Ocean Calm' },
{ id: 'fireplace', label: 'Fireplace' },
{ id: 'silent', label: 'Silent' },
],
timerPresets: [
{ id: '25-5', label: '25/5', focusMinutes: 25, breakMinutes: 5 },
{ id: '50-10', label: '50/10', focusMinutes: 50, breakMinutes: 10 },
{ id: '90-20', label: '90/20', focusMinutes: 90, breakMinutes: 20 },
{ id: 'custom', label: '커스텀' },
],
distractionDumpPlaceholder: ['디자인 QA 요청 확인', '세금계산서 발행 메모', '오후 미팅 질문 1개 정리'],
todayStats: [
{ id: 'today-focus', label: '오늘 집중 시간', value: '2h 40m', delta: '+35m' },
{ id: 'today-cycles', label: '완료한 사이클', value: '5회', delta: '+1' },
{ id: 'today-entry', label: '입장 횟수', value: '3회', delta: '유지' },
],
weeklyStats: [
{ id: 'week-focus', label: '최근 7일 집중 시간', value: '14h 20m', delta: '+2h 10m' },
{ id: 'week-best-day', label: '최고 몰입일', value: '수요일', delta: '3h 30m' },
{ id: 'week-consistency', label: '연속 달성', value: '4일', delta: '+1일' },
],
recentThoughts: [
{
id: 'thought-1',
text: '내일 미팅 전에 제안서 첫 문단만 다시 다듬기',
sceneName: '도서관',
capturedAt: '방금 전',
},
{
id: 'thought-2',
text: '기획 문서의 핵심 흐름을 한 문장으로 정리해두기',
sceneName: '비 오는 창가',
capturedAt: '24분 전',
},
{
id: 'thought-3',
text: '오후에 확인할 이슈 번호만 메모하고 지금 작업 복귀',
sceneName: '숲',
capturedAt: '1시간 전',
},
{
id: 'thought-4',
text: '리뷰 코멘트는 오늘 17시 이후에 한 번에 처리',
sceneName: '벽난로',
capturedAt: '어제',
},
],
justNow: '방금 전',
},
scenes: [
{
id: 'rain-window',
name: '비 오는 창가',
description: '빗소리 위로 스탠드 조명이 부드럽게 번집니다.',
tags: ['저자극', '감성'],
recommendedSound: 'Rain Focus',
recommendedTime: '밤',
vibeLabel: '잔잔함',
},
{
id: 'dawn-cafe',
name: '새벽 카페',
description: '첫 커피 향처럼 잔잔하고 따뜻한 좌석.',
tags: ['감성', '딥워크'],
recommendedSound: 'Cafe Murmur',
recommendedTime: '새벽',
vibeLabel: '포근함',
},
{
id: 'quiet-library',
name: '도서관',
description: '넘기는 종이 소리만 들리는 정돈된 책상.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Deep White',
recommendedTime: '오후',
vibeLabel: '몰입',
},
{
id: 'wave-sound',
name: '파도 소리',
description: '잔잔한 해변 위로 호흡을 고르는 공간.',
tags: ['움직임 적음', '감성'],
recommendedSound: 'Ocean Breath',
recommendedTime: '밤',
vibeLabel: '차분함',
},
{
id: 'forest',
name: '숲',
description: '바람이 나뭇잎을 스치는 소리로 마음을 낮춥니다.',
tags: ['저자극', '움직임 적음'],
recommendedSound: 'Forest Birds',
recommendedTime: '오전',
vibeLabel: '맑음',
},
{
id: 'fireplace',
name: '벽난로',
description: '작은 불꽃이 주는 리듬으로 집중을 붙잡습니다.',
tags: ['감성', '저자극'],
recommendedSound: 'Fireplace',
recommendedTime: '밤',
vibeLabel: '온기',
},
{
id: 'city-night',
name: '도시 야경',
description: '유리창 너머 야경이 멀리 흐르는 고요한 밤.',
tags: ['딥워크', '감성'],
recommendedSound: 'Night Lo-fi',
recommendedTime: '심야',
vibeLabel: '고요함',
},
{
id: 'snow-mountain',
name: '설산',
description: '차분한 공기와 선명한 수평선이 머리를 맑게 합니다.',
tags: ['움직임 적음', '딥워크'],
recommendedSound: 'Cold Wind',
recommendedTime: '새벽',
vibeLabel: '선명함',
},
{
id: 'sun-window',
name: '창가',
description: '햇살이 들어오는 간결한 책상, 부담 없는 시작.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Soft Daylight',
recommendedTime: '오후',
vibeLabel: '가벼움',
},
{
id: 'outer-space',
name: '우주',
description: '별빛만 남긴 어둠 속에서 깊게 잠수합니다.',
tags: ['딥워크', '감성'],
recommendedSound: 'Deep Drone',
recommendedTime: '심야',
vibeLabel: '깊음',
},
],
} as const;

View File

@@ -0,0 +1,172 @@
export const core = {
appName: 'VibeRoom',
metadata: {
title: 'VibeRoom - 당신만의 편안한 몰입 공간',
description:
'프리랜서와 온전한 집중이 필요한 분들을 위한 따뜻하고 구조화된 온라인 코워킹 스페이스. 작업 타이머, 세션 관리, 그리고 느슨한 연대를 통해 당신의 리듬을 찾아보세요.',
},
common: {
close: '닫기',
cancel: '취소',
save: '저장',
delete: '삭제',
complete: '완료',
select: '선택',
hub: '허브로',
loading: '불러오는 중이에요.',
default: '기본',
defaultBackground: '기본 배경',
admin: '관리자',
requestFailed: (status: number) => `요청 실패: ${status}`,
apiRequestFailed: (status: number) => `API 요청 실패: ${status}`,
},
landing: {
nav: {
features: '기능 소개',
pricing: '요금제',
login: '로그인',
startFree: '무료로 시작하기',
},
hero: {
titleLead: '함께하는 조용한 몰입,',
titleAccent: 'VibeRoom',
description:
'집중하기 어려운 순간, 당신을 다그치지 않는 편안한 공간으로 들어오세요. 구조화된 코워킹 세션과 느슨한 연대가 당신의 페이스를 되찾아 줍니다.',
primaryCta: '나만의 공간 만들기',
secondaryCta: '더 알아보기',
timerPreview: '45:00 남음',
},
features: {
title: '당신을 위한 다정한 몰입 장치',
description: '단순한 타이머가 아닙니다. 무리하지 않고 오래 지속할 수 있는 환경을 제공합니다.',
items: [
{
icon: '⏳',
title: '구조화된 세션 타이머',
description:
'부담 없이 시작할 수 있는 짧은 몰입과 확실한 휴식. 당신만의 작업 리듬을 부드럽게 설정하고 관리하세요.',
},
{
icon: '🌱',
title: '다정한 연대와 코워킹',
description:
'화면 너머 누군가와 함께하는 바디 더블링 효과. 감시가 아닌, 조용하지만 강력한 동기를 서로 나누어보세요.',
},
{
icon: '🛋️',
title: '나만의 심미적 공간',
description:
'비 오는 다락방, 햇살 드는 카페. 백색소음과 함께 내가 가장 편안함을 느끼는 가상 공간을 꾸미고 머무르세요.',
},
],
},
pricing: {
title: '나에게 맞는 공간 선택하기',
description: '개인의 가벼운 집중부터 프리랜서의 완벽한 워크스페이스까지.',
plans: {
starter: {
name: 'Starter',
subtitle: '가벼운 집중이 필요한 분',
price: '무료',
cta: '무료로 시작하기',
features: ['기본 가상 공간 테마', '1:1 파트너 매칭 (주 3회)', '오픈 코워킹 룸 입장'],
},
pro: {
badge: '추천',
name: 'Pro',
subtitle: '방해 없는 완벽한 몰입 환경',
price: '₩6,900',
priceSuffix: '/월',
cta: 'Pro 시작하기',
features: [
'프리미엄 테마 무제한',
'1:1 매칭 무제한',
'고급 집중 통계 및 리포트',
'공간 커스텀 아이템 제공',
],
},
teams: {
name: 'Teams',
subtitle: '리모트 워크 기업 및 팀',
price: '₩12,000',
priceSuffix: '/인·월',
cta: '도입 문의하기',
features: ['Pro 플랜의 모든 기능', '프라이빗 팀 스페이스', '팀 전체 생산성 대시보드'],
},
},
},
footer: {
description:
'프리랜서와 온전한 집중이 필요한 분들을 위한 따뜻하고 구조화된 온라인 코워킹 스페이스입니다.',
productTitle: '제품',
companyTitle: '회사',
links: {
features: '기능 소개',
pricing: '요금제',
webLogin: '웹앱 로그인',
about: '소개',
privacy: '개인정보처리방침',
terms: '이용약관',
},
copyright: '© 2026 VibeRoom. All rights reserved.',
},
},
login: {
title: '다시 오셨군요!',
descriptionFirstLine: '비밀번호를 외울 필요 없이,',
descriptionSecondLine: '사용 중인 계정으로 3초 만에 시작하세요.',
agreementPrefix: '로그인함으로써 VibeRoom의',
agreementAnd: '및',
terms: '이용약관',
privacy: '개인정보처리방침',
agreementSuffix: '에 동의하게 됩니다.',
},
auth: {
social: {
connecting: '연결 중...',
continueWithGoogle: 'Google로 계속하기',
continueWithApple: 'Apple로 계속하기',
continueWithFacebook: 'Facebook으로 계속하기',
},
errors: {
loginFailed: '로그인에 실패했습니다. 다시 시도해 주세요.',
googleFailed: '구글 로그인에 실패했습니다. 팝업 차단 여부를 확인해 주세요.',
appleFailed: '애플 로그인 중 오류가 발생했습니다.',
appleInitFailed: '애플 로그인 초기화 실패',
facebookFailed: '페이스북 로그인에 실패했습니다.',
},
},
modal: {
closeAriaLabel: '모달 닫기',
closeButton: '닫기',
},
media: {
manifestLoadFailed: '미디어 manifest를 불러오지 못했어요.',
},
preferences: {
defaultNotificationIntensity: '기본',
loadFailed: '설정을 불러오지 못했어요.',
saveFailed: '설정을 저장하지 못했어요.',
saved: '저장됨',
saveFailedLabel: '저장 실패',
},
focusSession: {
syncFailed: '세션 엔진과 동기화하지 못했어요.',
startFailed: '세션을 시작하지 못했어요.',
pauseFailed: '세션을 일시정지하지 못했어요.',
resumeFailed: '세션을 다시 시작하지 못했어요.',
restartPhaseFailed: '현재 페이즈를 다시 시작하지 못했어요.',
completeFailed: '세션을 완료 처리하지 못했어요.',
abandonFailed: '세션을 종료하지 못했어요.',
},
soundPlayback: {
loadFailed: '사운드 파일을 불러오지 못했어요.',
browserDeferred: '브라우저가 사운드 재생을 보류했어요.',
},
restart30s: {
button: '숨 고르기 30초',
mode: 'BREATHE',
toast: '잠깐 숨 고르고, 다시 천천히 시작해요.',
complete: '준비됐어요. 집중으로 돌아가요.',
},
} as const;

View File

@@ -0,0 +1,72 @@
export const settings = {
title: 'Settings',
focusPreferencesApi: 'Focus Preferences API',
loading: '저장된 설정을 불러오는 중이에요.',
saving: '변경 사항을 저장하는 중이에요.',
synced: '변경 즉시 서버에 저장합니다.',
reduceMotionTitle: 'Reduce Motion',
reduceMotionDescription: '전환 애니메이션을 최소화합니다. (UI 토글 목업)',
notificationIntensityTitle: '알림 강도',
notificationIntensityDescription: '집중 시작/종료 신호의 존재감을 선택합니다.',
defaultPresetTitle: '기본 프리셋',
defaultPresetDescription: '입장 시 자동 선택될 추천 세트를 고릅니다.',
notificationIntensityOptions: ['조용함', '기본', '강함'],
defaultPresetOptions: [
{ id: 'balanced', label: 'Balanced 25/5 + Rain Focus' },
{ id: 'deep-work', label: 'Deep Work 50/10 + Deep White' },
{ id: 'gentle', label: 'Gentle 25/5 + Silent' },
],
} as const;
export const stats = {
title: 'Stats',
apiLabel: 'API',
mockLabel: 'Mock',
sourceApi: 'API 통계 사용 중',
sourceMock: 'API 실패로 mock 통계 표시 중',
loading: '통계를 불러오는 중이에요.',
loadFailed: '통계를 불러오지 못했어요.',
synced: '화면 진입 시 최신 요약을 동기화합니다.',
refresh: '새로고침',
today: '오늘',
last7Days: '최근 7일',
chartTitle: '집중 흐름 그래프',
chartWithTrend: 'trend 응답으로 간단한 막대 그래프를 렌더링합니다.',
chartWithoutTrend: 'trend 응답이 비어 있어 플레이스홀더 상태입니다.',
todayFocus: '오늘 집중 시간',
completedCycles: '완료한 사이클',
sessionEntries: '입장 횟수',
last7DaysFocus: '최근 7일 집중 시간',
bestDay: '최고 몰입일',
streak: '연속 달성',
syncedApi: '동기화됨',
temporary: '임시값',
actualAggregate: '실집계',
mockAggregate: '목업',
streakActive: '유지 중',
streakStart: '시작 전',
countUnit: '회',
dayUnit: '일',
minuteUnit: '분',
barTitle: (date: string, minutes: number) => `${date} · ${minutes}`,
} as const;
export const plan = {
proFeatureCards: [
{
id: 'scene-packs',
name: 'Scene Packs',
description: '프리미엄 공간 묶음과 장면 변주',
},
{
id: 'sound-packs',
name: 'Sound Packs',
description: '확장 사운드 프리셋 묶음',
},
{
id: 'profiles',
name: 'Profiles',
description: '내 기본 세팅 저장/불러오기',
},
],
} as const;

View File

@@ -0,0 +1,92 @@
export const scenes = [
{
id: 'rain-window',
name: '비 오는 창가',
description: '빗소리 위로 스탠드 조명이 부드럽게 번집니다.',
tags: ['저자극', '감성'],
recommendedSound: 'Rain Focus',
recommendedTime: '밤',
vibeLabel: '잔잔함',
},
{
id: 'dawn-cafe',
name: '새벽 카페',
description: '첫 커피 향처럼 잔잔하고 따뜻한 좌석.',
tags: ['감성', '딥워크'],
recommendedSound: 'Cafe Murmur',
recommendedTime: '새벽',
vibeLabel: '포근함',
},
{
id: 'quiet-library',
name: '도서관',
description: '넘기는 종이 소리만 들리는 정돈된 책상.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Deep White',
recommendedTime: '오후',
vibeLabel: '몰입',
},
{
id: 'wave-sound',
name: '파도 소리',
description: '잔잔한 해변 위로 호흡을 고르는 공간.',
tags: ['움직임 적음', '감성'],
recommendedSound: 'Ocean Breath',
recommendedTime: '밤',
vibeLabel: '차분함',
},
{
id: 'forest',
name: '숲',
description: '바람이 나뭇잎을 스치는 소리로 마음을 낮춥니다.',
tags: ['저자극', '움직임 적음'],
recommendedSound: 'Forest Birds',
recommendedTime: '오전',
vibeLabel: '맑음',
},
{
id: 'fireplace',
name: '벽난로',
description: '작은 불꽃이 주는 리듬으로 집중을 붙잡습니다.',
tags: ['감성', '저자극'],
recommendedSound: 'Fireplace',
recommendedTime: '밤',
vibeLabel: '온기',
},
{
id: 'city-night',
name: '도시 야경',
description: '유리창 너머 야경이 멀리 흐르는 고요한 밤.',
tags: ['딥워크', '감성'],
recommendedSound: 'Night Lo-fi',
recommendedTime: '심야',
vibeLabel: '고요함',
},
{
id: 'snow-mountain',
name: '설산',
description: '차분한 공기와 선명한 수평선이 머리를 맑게 합니다.',
tags: ['움직임 적음', '딥워크'],
recommendedSound: 'Cold Wind',
recommendedTime: '새벽',
vibeLabel: '선명함',
},
{
id: 'sun-window',
name: '창가',
description: '햇살이 들어오는 간결한 책상, 부담 없는 시작.',
tags: ['저자극', '딥워크'],
recommendedSound: 'Soft Daylight',
recommendedTime: '오후',
vibeLabel: '가벼움',
},
{
id: 'outer-space',
name: '우주',
description: '별빛만 남긴 어둠 속에서 깊게 잠수합니다.',
tags: ['딥워크', '감성'],
recommendedSound: 'Deep Drone',
recommendedTime: '심야',
vibeLabel: '깊음',
},
] as const;

View File

@@ -0,0 +1,77 @@
export const session = {
todayOneLiner: '오늘의 한 줄: 완벽보다 시작, 한 조각이면 충분해요.',
goalChips: [
{ id: 'mail-3', label: '메일 3개' },
{ id: 'doc-1p', label: '문서 1p' },
{ id: 'code-1-function', label: '코딩 1함수' },
{ id: 'tidy-10m', label: '정리 10분' },
{ id: 'reading-15m', label: '독서 15분' },
{ id: 'resume-1paragraph', label: '이력서 1문단' },
],
checkInPhrases: [
{ id: 'arrived', text: '지금 들어왔어요' },
{ id: 'sprint-25', text: '25분만 달릴게요' },
{ id: 'on-break', text: '휴식 중' },
{ id: 'back-focus', text: '다시 집중!' },
{ id: 'slow-day', text: '오늘은 천천히' },
],
reactionOptions: [
{ id: 'thumbs-up', emoji: '👍', label: '응원해요' },
{ id: 'fire', emoji: '🔥', label: '집중 모드' },
{ id: 'clap', emoji: '👏', label: '잘하고 있어요' },
{ id: 'heart-hands', emoji: '🫶', label: '연결되어 있어요' },
],
soundPresets: [
{ id: 'deep-white', label: 'Deep White' },
{ id: 'rain-focus', label: 'Rain Focus' },
{ id: 'forest-birds', label: 'Forest Birds' },
{ id: 'cafe-work', label: 'Cafe Work' },
{ id: 'ocean-calm', label: 'Ocean Calm' },
{ id: 'fireplace', label: 'Fireplace' },
{ id: 'silent', label: 'Silent' },
],
timerPresets: [
{ id: '25-5', label: '25/5', focusMinutes: 25, breakMinutes: 5 },
{ id: '50-10', label: '50/10', focusMinutes: 50, breakMinutes: 10 },
{ id: '90-20', label: '90/20', focusMinutes: 90, breakMinutes: 20 },
{ id: 'custom', label: '커스텀' },
],
distractionDumpPlaceholder: ['디자인 QA 요청 확인', '세금계산서 발행 메모', '오후 미팅 질문 1개 정리'],
todayStats: [
{ id: 'today-focus', label: '오늘 집중 시간', value: '2h 40m', delta: '+35m' },
{ id: 'today-cycles', label: '완료한 사이클', value: '5회', delta: '+1' },
{ id: 'today-entry', label: '입장 횟수', value: '3회', delta: '유지' },
],
weeklyStats: [
{ id: 'week-focus', label: '최근 7일 집중 시간', value: '14h 20m', delta: '+2h 10m' },
{ id: 'week-best-day', label: '최고 몰입일', value: '수요일', delta: '3h 30m' },
{ id: 'week-consistency', label: '연속 달성', value: '4일', delta: '+1일' },
],
recentThoughts: [
{
id: 'thought-1',
text: '내일 미팅 전에 제안서 첫 문단만 다시 다듬기',
sceneName: '도서관',
capturedAt: '방금 전',
},
{
id: 'thought-2',
text: '기획 문서의 핵심 흐름을 한 문장으로 정리해두기',
sceneName: '비 오는 창가',
capturedAt: '24분 전',
},
{
id: 'thought-3',
text: '오후에 확인할 이슈 번호만 메모하고 지금 작업 복귀',
sceneName: '숲',
capturedAt: '1시간 전',
},
{
id: 'thought-4',
text: '리뷰 코멘트는 오늘 17시 이후에 한 번에 처리',
sceneName: '벽난로',
capturedAt: '어제',
},
],
justNow: '방금 전',
} as const;

View File

@@ -0,0 +1,184 @@
export const space = {
sessionGoal: {
label: '이번 25분, 딱 한 가지',
required: '(필수)',
placeholder: '예: 계약서 1페이지 정리',
hint: '크게 말고, 바로 다음 한 조각.',
},
setup: {
panelAriaLabel: '집중 시작 패널',
eyebrow: 'Ritual',
title: '이번 한 조각을 정하고 시작해요.',
description: '목표를 정한 뒤 HUD의 시작 버튼으로 실제 세션을 시작해요.',
resumeTitle: '지난 한 조각 이어서',
startFresh: '새로 시작',
resumePrepare: '이어서 준비',
sceneLabel: '배경',
timerLabel: '타이머',
soundLabel: '사운드',
readyHint: '목표를 적으면 시작할 수 있어요.',
openFocusScreen: '집중 화면 열기',
},
timerHud: {
actions: [
{ id: 'start', label: '시작', icon: '▶' },
{ id: 'pause', label: '일시정지', icon: '⏸' },
{ id: 'reset', label: '리셋', icon: '↺' },
],
readyMode: 'Ready',
focusMode: 'Focus',
breakMode: 'Break',
goalFallback: '이번 한 조각을 설정해 주세요.',
goalPrefix: '이번 한 조각 · ',
completeButton: '완료',
},
focusHud: {
goalFallback: '집중을 시작해요.',
goalToast: (goal: string) => `이번 한 조각 · ${goal}`,
restReminder: '5분이 지났어요. 다음 한 조각으로 돌아와요.',
},
goalComplete: {
suggestions: ['리뷰 코멘트 2개 처리', '문서 1문단 다듬기', '이슈 1개 정리', '메일 2개 회신'],
placeholderFallback: '다음 한 조각을 적어보세요',
placeholderExample: (goal: string) => `예: ${goal}`,
title: '좋아요. 다음 한 조각은?',
description: '너무 크게 잡지 말고, 바로 다음 한 조각만.',
closeAriaLabel: '닫기',
restButton: '잠깐 쉬기',
confirmButton: '바로 다음 조각 시작',
},
controlCenter: {
sectionTitles: {
background: 'Background',
time: 'Time',
sound: 'Sound',
packs: 'Packs',
},
packsDescription: '확장/개인화',
recommendation: (soundLabel: string, timerLabel: string) => `추천: ${soundLabel} · ${timerLabel}`,
recommendationHint: '추천 조합은 참고 정보로만 제공돼요.',
autoHideTitle: '컨트롤 자동 숨김',
autoHideDescription: '입력이 없으면 잠시 후 패널을 닫아요.',
autoHideAriaLabel: '컨트롤 자동 숨김',
sideSheetSubtitle: '배경 · 타이머 · 사운드를 그 자리에서 바꿔요.',
quickControlsTitle: 'Quick Controls',
},
toolsDock: {
notesButton: 'Notes',
popoverCloseAria: '팝오버 닫기',
planPro: 'PRO',
planNormal: 'Normal',
inboxSaved: '인박스에 저장됨',
undo: '실행취소',
inboxSaveUndone: '저장 취소됨',
deleted: '삭제됨',
deleteUndone: '삭제를 취소했어요.',
emptyToClear: '비울 항목이 없어요.',
clearedAll: '모두 비워짐',
restored: '복원했어요.',
normalPlanInfo: 'NORMAL 플랜 사용 중 · 잠금 항목에서만 업그레이드할 수 있어요.',
proFeatureLocked: (source: string) => `${source}은(는) PRO 기능이에요.`,
proFeaturePending: (label: string) => `${label} 준비 중(더미)`,
purchaseMock: '결제(더미)',
manageSubscriptionMock: '구독 관리(더미)',
restorePurchaseMock: '구매 복원(더미)',
featureLabels: {
scenePacks: 'Scene Packs',
soundPacks: 'Sound Packs',
profiles: 'Profiles',
},
utilityPanelTitle: {
'control-center': 'Quick Controls',
inbox: '인박스',
paywall: 'PRO',
'manage-plan': '플랜 관리',
},
},
quickNotes: {
title: '떠오른 생각을 잠깐 주차해요',
placeholder: '떠오른 생각을 잠깐 주차…',
submit: '저장',
hint: '나중에 인박스에서 정리해요.',
},
quickSound: {
currentSound: '현재 사운드',
muteAriaLabel: '음소거',
unmuteAriaLabel: '음소거 해제',
volumeAriaLabel: '사운드 볼륨',
quickSwitch: '빠른 전환',
},
soundPresetControls: {
preset: 'Preset',
mixerOpen: 'Mixer 펼치기',
mixerClose: 'Mixer 접기',
mock: '더미',
masterVolume: '마스터 볼륨',
mute: '뮤트',
muteToggleAriaLabel: '마스터 뮤트 토글',
trackLabels: {
white: 'White',
rain: 'Rain',
cafe: 'Cafe',
wave: 'Wave',
fan: 'Fan',
},
},
inbox: {
empty: '지금은 비어 있어요. 집중 중 떠오른 생각을 여기로 주차할 수 있어요.',
complete: '완료',
completed: '완료됨',
delete: '삭제',
readOnly: '나중에 모아보는 읽기 전용 인박스',
clearAll: '모두 비우기',
clearConfirmTitle: '정말 인박스를 비울까요?',
clearConfirmDescription: '실수라면 토스트에서 실행취소할 수 있어요.',
clearButton: '비우기',
openInboxAriaLabel: '인박스 열기',
openInboxTitle: '인박스',
},
rightRail: {
openQuickControlsAriaLabel: 'Quick Controls 열기',
openQuickControlsTitle: 'Quick Controls',
},
paywall: {
points: ['프리미엄 Scene Packs', '확장 Sound Packs', '프로필 저장 / 불러오기'],
title: 'PRO에서 더 많은 공간과 사운드를 열어둘 수 있어요.',
description: '잠금 항목을 누른 순간에만 열리는 더미 결제 시트입니다.',
later: '나중에',
startPro: 'PRO 시작하기',
manageTitle: 'PRO 관리',
manageDescription: '결제/복원은 더미 동작이며 실제 연동은 하지 않아요.',
openSubscription: '구독 관리 열기',
restorePurchase: '구매 복원',
},
statsPanel: {
description: '오늘 흐름과 최근 7일 리듬을 가볍게 확인하세요.',
graphPlaceholder: '그래프 플레이스홀더',
},
settingsPanel: {
reduceMotion: 'Reduce Motion',
reduceMotionDescription: '화면 전환을 조금 더 차분하게 표시합니다.',
background: '배경',
backgroundDescription: '몰입 중에도 배경 scene을 바꿀 수 있어요.',
timerPreset: '타이머 프리셋',
timerPresetDescription: '기본 프리셋만 빠르게 고를 수 있어요.',
defaultPreset: '기본 프리셋',
},
workspace: {
readyToStart: '준비 완료 · 시작 버튼을 눌러 집중을 시작해요.',
startFailed: '세션을 시작하지 못했어요. 잠시 후 다시 시도해 주세요.',
resumeFailed: '세션을 다시 시작하지 못했어요.',
abandonFailed: '세션 종료를 완료하지 못했어요.',
pauseFailed: '세션을 일시정지하지 못했어요.',
restartFailed: '현재 페이즈를 다시 시작하지 못했어요.',
restarted: '현재 페이즈를 처음부터 다시 시작했어요.',
goalCompleteSyncFailed: '현재 세션 완료를 서버에 반영하지 못했어요.',
nextGoalReady: '다음 한 조각 준비 완료 · 시작 버튼을 눌러 이어가요.',
selectionPreferenceSaveFailed: '배경/사운드 기본 설정을 저장하지 못했어요.',
selectionSessionSyncFailed: '현재 세션의 배경/사운드 선택을 동기화하지 못했어요.',
},
exitHold: {
holdToExitAriaLabel: '길게 눌러 나가기',
exit: '나가기',
},
} as const;

View File

@@ -7,11 +7,10 @@
*/ */
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import { TOKEN_COOKIE_KEY } from '@/shared/config/authTokens';
import { copy } from '@/shared/i18n'; import { copy } from '@/shared/i18n';
import { useAuthStore } from '@/store/useAuthStore';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080'; const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
const TOKEN_COOKIE_KEY = 'vr_access_token';
interface ApiEnvelope<T> { interface ApiEnvelope<T> {
data: T; data: T;
@@ -44,12 +43,6 @@ const isRecord = (value: unknown): value is Record<string, unknown> => {
}; };
const readAccessToken = () => { const readAccessToken = () => {
const storeToken = useAuthStore.getState().accessToken;
if (storeToken) {
return storeToken;
}
return Cookies.get(TOKEN_COOKIE_KEY) ?? null; return Cookies.get(TOKEN_COOKIE_KEY) ?? null;
}; };

View File

@@ -1,7 +1,7 @@
import { create } from 'zustand'; import { create } from 'zustand';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import { AuthResponse } from '@/features/auth/types'; import type { AuthResponse } from '@/entities/auth';
import { REFRESH_TOKEN_COOKIE_KEY, TOKEN_COOKIE_KEY } from '@/features/auth/model/constants'; import { REFRESH_TOKEN_COOKIE_KEY, TOKEN_COOKIE_KEY } from '@/shared/config/authTokens';
interface AuthState { interface AuthState {
accessToken: string | null; accessToken: string | null;

View File

@@ -0,0 +1 @@
export * from './ui/AdminConsoleWidget';

View File

@@ -0,0 +1,35 @@
import type { AuthResponse } from '@/entities/auth';
const ADMIN_STORAGE_KEY = 'vr_admin_session';
export const readStoredSession = (): AuthResponse | null => {
if (typeof window === 'undefined') {
return null;
}
const rawValue = window.localStorage.getItem(ADMIN_STORAGE_KEY);
if (!rawValue) {
return null;
}
try {
return JSON.parse(rawValue) as AuthResponse;
} catch {
window.localStorage.removeItem(ADMIN_STORAGE_KEY);
return null;
}
};
export const storeSession = (session: AuthResponse | null) => {
if (typeof window === 'undefined') {
return;
}
if (!session) {
window.localStorage.removeItem(ADMIN_STORAGE_KEY);
return;
}
window.localStorage.setItem(ADMIN_STORAGE_KEY, JSON.stringify(session));
};

View File

@@ -0,0 +1,14 @@
import type { SceneMediaAssetUploadResponse, SoundMediaAssetUploadResponse } from '@/features/admin/api/adminApi';
export type AdminView = 'scene' | 'sound';
export type UploadResult =
| { type: 'scene'; payload: SceneMediaAssetUploadResponse }
| { type: 'sound'; payload: SoundMediaAssetUploadResponse };
export type NavItem = {
id: AdminView;
title: string;
subtitle: string;
section: string;
};

View File

@@ -0,0 +1,208 @@
'use client';
import { useEffect, useMemo, useState, type FormEvent } from 'react';
import type { AuthResponse } from '@/entities/auth';
import { adminApi } from '@/features/admin/api/adminApi';
import { copy } from '@/shared/i18n';
import { readStoredSession, storeSession } from './sessionStorage';
import type { AdminView, UploadResult } from './types';
const getViewMeta = (view: AdminView) => {
return copy.admin.views[view];
};
const formatResultSummary = (uploadResult: UploadResult | null) => {
if (!uploadResult) {
return copy.admin.inspector.noUploadSummary;
}
if (uploadResult.type === 'scene') {
return copy.admin.messages.sceneSummary(uploadResult.payload.sceneId, uploadResult.payload.assetVersion);
}
return copy.admin.messages.soundSummary(uploadResult.payload.presetId, uploadResult.payload.assetVersion);
};
export const useAdminConsole = () => {
const [session, setSession] = useState<AuthResponse | null>(null);
const [activeView, setActiveView] = useState<AdminView>('scene');
const [isDurationOverrideEnabled, setIsDurationOverrideEnabled] = useState(false);
const [loginId, setLoginId] = useState<string>(copy.admin.defaultLoginId);
const [password, setPassword] = useState<string>(copy.admin.defaultPassword);
const [loginError, setLoginError] = useState<string | null>(null);
const [loginPending, setLoginPending] = useState(false);
const [scenePending, setScenePending] = useState(false);
const [soundPending, setSoundPending] = useState(false);
const [sceneMessage, setSceneMessage] = useState<string | null>(null);
const [soundMessage, setSoundMessage] = useState<string | null>(null);
const [uploadResult, setUploadResult] = useState<UploadResult | null>(null);
useEffect(() => {
setSession(readStoredSession());
}, []);
const handleLogin = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoginPending(true);
setLoginError(null);
try {
const response = await adminApi.login({
loginId: loginId.trim(),
password,
});
if (response.user?.grade !== 'ADMIN') {
throw new Error(copy.admin.messages.nonAdmin);
}
setSession(response);
storeSession(response);
} catch (error) {
setLoginError(error instanceof Error ? error.message : copy.admin.messages.loginFailed);
} finally {
setLoginPending(false);
}
};
const handleLogout = () => {
setSession(null);
setActiveView('scene');
setIsDurationOverrideEnabled(false);
setSceneMessage(null);
setSoundMessage(null);
setUploadResult(null);
storeSession(null);
};
const handleSceneUpload = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!session?.accessToken) {
setSceneMessage(copy.admin.messages.loginRequired);
return;
}
setScenePending(true);
setSceneMessage(null);
try {
const form = event.currentTarget;
const source = new FormData(form);
const sceneId = String(source.get('sceneId') ?? '').trim();
if (!sceneId) {
throw new Error(copy.admin.messages.sceneIdRequired);
}
const formData = new FormData();
const sourceImageFile = source.get('sourceImageFile');
if (sourceImageFile instanceof File && sourceImageFile.size > 0) {
formData.append('sourceImageFile', sourceImageFile);
}
const blurDataUrl = String(source.get('blurDataUrl') ?? '').trim();
if (blurDataUrl) {
formData.append('blurDataUrl', blurDataUrl);
}
const response = await adminApi.uploadScene(sceneId, formData, session.accessToken);
setUploadResult({ type: 'scene', payload: response });
setSceneMessage(copy.admin.messages.sceneUploadDone(sceneId));
form.reset();
} catch (error) {
setSceneMessage(error instanceof Error ? error.message : copy.admin.messages.sceneUploadFailed);
} finally {
setScenePending(false);
}
};
const handleSoundUpload = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!session?.accessToken) {
setSoundMessage(copy.admin.messages.loginRequired);
return;
}
setSoundPending(true);
setSoundMessage(null);
try {
const form = event.currentTarget;
const source = new FormData(form);
const presetId = String(source.get('presetId') ?? '').trim();
if (!presetId) {
throw new Error(copy.admin.messages.presetIdRequired);
}
const formData = new FormData();
for (const fieldName of ['loopFile', 'previewFile', 'fallbackLoopFile']) {
const file = source.get(fieldName);
if (file instanceof File && file.size > 0) {
formData.append(fieldName, file);
}
}
const defaultVolume = String(source.get('defaultVolume') ?? '').trim();
if (defaultVolume) {
formData.append('defaultVolume', defaultVolume);
}
if (isDurationOverrideEnabled) {
const durationSec = String(source.get('durationSec') ?? '').trim();
if (durationSec) {
formData.append('durationSec', durationSec);
}
}
const response = await adminApi.uploadSound(presetId, formData, session.accessToken);
setUploadResult({ type: 'sound', payload: response });
setSoundMessage(copy.admin.messages.soundUploadDone(presetId));
form.reset();
setIsDurationOverrideEnabled(false);
} catch (error) {
setSoundMessage(error instanceof Error ? error.message : copy.admin.messages.soundUploadFailed);
} finally {
setSoundPending(false);
}
};
const activeMeta = useMemo(() => getViewMeta(activeView), [activeView]);
const currentMessage = activeView === 'scene' ? sceneMessage : soundMessage;
const lastExtractedDurationSec =
uploadResult?.type === 'sound' ? uploadResult.payload.durationSec ?? null : null;
const resultSummary = useMemo(() => formatResultSummary(uploadResult), [uploadResult]);
return {
session,
activeView,
setActiveView,
activeMeta,
isDurationOverrideEnabled,
setIsDurationOverrideEnabled,
loginId,
setLoginId,
password,
setPassword,
loginError,
loginPending,
scenePending,
soundPending,
currentMessage,
uploadResult,
resultSummary,
lastExtractedDurationSec,
handleLogin,
handleLogout,
handleSceneUpload,
handleSoundUpload,
};
};

View File

@@ -0,0 +1,41 @@
'use client';
import { useAdminConsole } from '../model/useAdminConsole';
import { AdminLoginView } from './AdminLoginView';
export const AdminConsoleWidget = () => {
const {
session,
loginId,
password,
loginError,
loginPending,
setLoginId,
setPassword,
handleLogin,
} = useAdminConsole();
if (!session) {
return (
<AdminLoginView
loginId={loginId}
password={password}
loginError={loginError}
loginPending={loginPending}
onLoginIdChange={setLoginId}
onPasswordChange={setPassword}
onSubmit={handleLogin}
/>
);
}
return (
<div className="flex min-h-screen items-center justify-center bg-[#f3f4f8] text-slate-900">
<div className="text-center">
<h1 className="text-2xl font-bold">Admin Dashboard</h1>
<p className="mt-2 text-slate-500">Welcome, {session.user?.name}!</p>
<p className="mt-4 text-sm text-slate-400">Dashboard is under construction.</p>
</div>
</div>
);
};

View File

@@ -0,0 +1,127 @@
import { copy } from '@/shared/i18n';
import { Button } from '@/shared/ui';
import { fieldClassName } from './constants';
interface AdminLoginViewProps {
loginId: string;
password: string;
loginError: string | null;
loginPending: boolean;
onLoginIdChange: (value: string) => void;
onPasswordChange: (value: string) => void;
onSubmit: React.FormEventHandler<HTMLFormElement>;
}
export const AdminLoginView = ({
loginId,
password,
loginError,
loginPending,
onLoginIdChange,
onPasswordChange,
onSubmit,
}: AdminLoginViewProps) => {
return (
<main className="min-h-screen bg-[#f3f4f8] text-slate-900">
<div className="grid min-h-screen lg:grid-cols-[280px_minmax(0,1fr)]">
<aside className="flex flex-col justify-between bg-[#171821] px-8 py-8 text-white">
<div>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-fuchsia-500 to-sky-500 text-lg font-bold">
V
</div>
<div>
<p className="text-xl font-semibold tracking-tight">{copy.appName}</p>
<p className="text-xs uppercase tracking-[0.28em] text-slate-400">{copy.admin.consoleLabel}</p>
</div>
</div>
<div className="mt-12 space-y-8">
<div>
<p className="mb-4 text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">
{copy.admin.mediaOperations}
</p>
<div className="space-y-2">
{copy.admin.navItems.map((item, index) => (
<div
key={item.id}
className={`flex items-center gap-3 rounded-xl px-4 py-3 ${
index === 0 ? 'bg-white/10 text-white' : 'text-slate-400'
}`}
>
<span className="h-2 w-2 rounded-full bg-sky-400" />
<div>
<p className="text-sm font-medium">{item.title}</p>
<p className="text-xs text-slate-500">{item.subtitle}</p>
</div>
</div>
))}
</div>
</div>
<div className="rounded-2xl border border-white/8 bg-white/5 p-5">
<p className="text-xs uppercase tracking-[0.24em] text-slate-500">{copy.admin.access}</p>
<p className="mt-3 text-2xl font-semibold">{copy.admin.accessTitle}</p>
<p className="mt-2 text-sm leading-6 text-slate-400">{copy.admin.accessDescription}</p>
</div>
</div>
</div>
<p className="text-xs uppercase tracking-[0.24em] text-slate-500">
{copy.admin.localCredentialsHint}
</p>
</aside>
<section className="flex items-center justify-center px-6 py-10">
<div className="w-full max-w-md rounded-[28px] border border-slate-200 bg-white px-8 py-8 shadow-[0_30px_80px_rgba(15,23,42,0.08)]">
<div className="mb-8">
<p className="text-xs font-semibold uppercase tracking-[0.28em] text-sky-600">{copy.admin.signInEyebrow}</p>
<h1 className="mt-3 text-3xl font-semibold tracking-tight text-slate-950">
{copy.admin.loginTitle}
</h1>
<p className="mt-3 text-sm leading-6 text-slate-500">{copy.admin.loginDescription}</p>
</div>
<form className="space-y-4" onSubmit={onSubmit}>
<div>
<label htmlFor="admin-login-id" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.loginIdLabel}
</label>
<input
id="admin-login-id"
className={fieldClassName}
value={loginId}
onChange={(event) => onLoginIdChange(event.target.value)}
autoComplete="username"
placeholder={copy.admin.defaultLoginId}
/>
</div>
<div>
<label htmlFor="admin-login-password" className="mb-2 block text-sm font-medium text-slate-700">
{copy.admin.loginPasswordLabel}
</label>
<input
id="admin-login-password"
type="password"
className={fieldClassName}
value={password}
onChange={(event) => onPasswordChange(event.target.value)}
autoComplete="current-password"
placeholder={copy.admin.defaultPassword}
/>
</div>
{loginError ? (
<div className="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">
{loginError}
</div>
) : null}
<Button type="submit" size="full" className="h-12 rounded-xl" disabled={loginPending}>
{loginPending ? copy.admin.loggingIn : copy.admin.openDashboard}
</Button>
</form>
</div>
</section>
</div>
</main>
);
};

View File

@@ -0,0 +1,13 @@
import { copy } from '@/shared/i18n';
import type { NavItem } from '../model/types';
export const navItems: NavItem[] = [...copy.admin.navItems];
export const fieldClassName =
'h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-100';
export const fileClassName =
'block w-full rounded-xl border border-dashed border-slate-200 bg-slate-50 px-3 py-3 text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-slate-900 file:px-3 file:py-2 file:text-sm file:font-medium file:text-white hover:file:bg-slate-800';
export const textareaClassName =
'min-h-32 w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-sky-400 focus:ring-2 focus:ring-sky-100';

View File

@@ -0,0 +1,206 @@
'use client';
import { useCallback, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import type { RecentThought } from '@/entities/session';
import { copy } from '@/shared/i18n';
import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import type { SpaceAnchorPopoverId, SpaceUtilityPanelId } from './types';
import type { PlanTier } from '@/entities/plan';
interface UseSpaceToolsDockHandlersParams {
setIdle: (idle: boolean) => void;
setOpenPopover: (popover: SpaceAnchorPopoverId | null) => void;
setUtilityPanel: (panel: SpaceUtilityPanelId | null) => void;
onCaptureThought: (note: string) => RecentThought | null;
onDeleteThought: (thoughtId: string) => RecentThought | null;
onSetThoughtCompleted: (thoughtId: string, isCompleted: boolean) => RecentThought | null;
onRestoreThought: (thought: RecentThought) => void;
onRestoreThoughts: (thoughts: RecentThought[]) => void;
onClearInbox: () => RecentThought[];
onStatusMessage: (payload: HudStatusLinePayload) => void;
onSetSoundVolume: (volume: number) => void;
onSetSoundMuted: (muted: boolean) => void;
soundVolume: number;
isSoundMuted: boolean;
showVolumeFeedback: (volume: number) => void;
}
export const useSpaceToolsDockHandlers = ({
setIdle,
setOpenPopover,
setUtilityPanel,
onCaptureThought,
onDeleteThought,
onSetThoughtCompleted,
onRestoreThought,
onRestoreThoughts,
onClearInbox,
onStatusMessage,
onSetSoundVolume,
onSetSoundMuted,
soundVolume,
isSoundMuted,
showVolumeFeedback,
}: UseSpaceToolsDockHandlersParams) => {
const { toolsDock } = copy.space;
const [noteDraft, setNoteDraft] = useState('');
const [plan, setPlan] = useState<PlanTier>('normal');
const openUtilityPanel = useCallback((panel: SpaceUtilityPanelId) => {
setIdle(false);
setOpenPopover(null);
setUtilityPanel(panel);
}, [setIdle, setOpenPopover, setUtilityPanel]);
const handleNoteSubmit = useCallback(() => {
const trimmedNote = noteDraft.trim();
if (!trimmedNote) {
return;
}
const addedThought = onCaptureThought(trimmedNote);
if (!addedThought) {
return;
}
setNoteDraft('');
onStatusMessage({
message: toolsDock.inboxSaved,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
const removed = onDeleteThought(addedThought.id);
if (!removed) {
return;
}
onStatusMessage({ message: toolsDock.inboxSaveUndone });
},
},
});
}, [noteDraft, onCaptureThought, onDeleteThought, onStatusMessage, toolsDock.inboxSaved, toolsDock.inboxSaveUndone, toolsDock.undo]);
const handleInboxComplete = useCallback((thought: RecentThought) => {
onSetThoughtCompleted(thought.id, !thought.isCompleted);
}, [onSetThoughtCompleted]);
const handleInboxDelete = useCallback((thought: RecentThought) => {
const removedThought = onDeleteThought(thought.id);
if (!removedThought) {
return;
}
onStatusMessage({
message: toolsDock.deleted,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
onRestoreThought(removedThought);
onStatusMessage({ message: toolsDock.deleteUndone });
},
},
});
}, [onDeleteThought, onRestoreThought, onStatusMessage, toolsDock.deleted, toolsDock.deleteUndone, toolsDock.undo]);
const handleInboxClear = useCallback(() => {
const snapshot = onClearInbox();
if (snapshot.length === 0) {
onStatusMessage({ message: toolsDock.emptyToClear });
return;
}
onStatusMessage({
message: toolsDock.clearedAll,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
onRestoreThoughts(snapshot);
onStatusMessage({ message: toolsDock.restored });
},
},
});
}, [onClearInbox, onRestoreThoughts, onStatusMessage, toolsDock.clearedAll, toolsDock.emptyToClear, toolsDock.restored, toolsDock.undo]);
const handlePlanPillClick = useCallback(() => {
if (plan === 'pro') {
openUtilityPanel('manage-plan');
return;
}
onStatusMessage({ message: toolsDock.normalPlanInfo });
}, [openUtilityPanel, onStatusMessage, plan, toolsDock.normalPlanInfo]);
const handleLockedClick = useCallback((source: string) => {
onStatusMessage({ message: toolsDock.proFeatureLocked(source) });
openUtilityPanel('paywall');
}, [onStatusMessage, openUtilityPanel, toolsDock]);
const handleSelectProFeature = useCallback((featureId: string) => {
const label =
featureId === 'scene-packs'
? toolsDock.featureLabels.scenePacks
: featureId === 'sound-packs'
? toolsDock.featureLabels.soundPacks
: toolsDock.featureLabels.profiles;
onStatusMessage({ message: toolsDock.proFeaturePending(label) });
}, [onStatusMessage, toolsDock.featureLabels]);
const handleStartPro = useCallback(() => {
setPlan('pro');
onStatusMessage({ message: toolsDock.purchaseMock });
openUtilityPanel('control-center');
}, [onStatusMessage, openUtilityPanel, toolsDock.purchaseMock]);
const handleVolumeChange = useCallback((nextVolume: number) => {
const clamped = Math.min(100, Math.max(0, nextVolume));
onSetSoundVolume(clamped);
if (isSoundMuted && clamped > 0) {
onSetSoundMuted(false);
}
showVolumeFeedback(clamped);
}, [isSoundMuted, onSetSoundMuted, onSetSoundVolume, showVolumeFeedback]);
const handleVolumeKeyDown = useCallback((event: ReactKeyboardEvent<HTMLInputElement>) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') {
return;
}
event.preventDefault();
const step = event.shiftKey ? 10 : 5;
const delta = event.key === 'ArrowRight' ? step : -step;
handleVolumeChange(soundVolume + delta);
}, [handleVolumeChange, soundVolume]);
return {
noteDraft,
setNoteDraft,
plan,
setPlan,
openUtilityPanel,
handleNoteSubmit,
handleInboxComplete,
handleInboxDelete,
handleInboxClear,
handlePlanPillClick,
handleLockedClick,
handleSelectProFeature,
handleStartPro,
handleVolumeChange,
handleVolumeKeyDown,
};
};

View File

@@ -0,0 +1,143 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import type { SpaceAnchorPopoverId, SpaceUtilityPanelId } from './types';
interface UseSpaceToolsDockStateParams {
isFocusMode: boolean;
}
export const useSpaceToolsDockState = ({ isFocusMode }: UseSpaceToolsDockStateParams) => {
const [openPopover, setOpenPopover] = useState<SpaceAnchorPopoverId | null>(null);
const [utilityPanel, setUtilityPanel] = useState<SpaceUtilityPanelId | null>(null);
const [autoHideControls, setAutoHideControls] = useState(true);
const [isIdle, setIdle] = useState(false);
const [volumeFeedback, setVolumeFeedback] = useState<string | null>(null);
const volumeFeedbackTimerRef = useRef<number | null>(null);
useEffect(() => {
return () => {
if (volumeFeedbackTimerRef.current) {
window.clearTimeout(volumeFeedbackTimerRef.current);
volumeFeedbackTimerRef.current = null;
}
};
}, []);
useEffect(() => {
if (isFocusMode) {
return;
}
const rafId = window.requestAnimationFrame(() => {
setOpenPopover(null);
setUtilityPanel(null);
setIdle(false);
});
return () => {
window.cancelAnimationFrame(rafId);
};
}, [isFocusMode]);
useEffect(() => {
if (!isFocusMode || openPopover || utilityPanel) {
return;
}
let timerId: number | null = null;
const armIdleTimer = () => {
if (timerId) {
window.clearTimeout(timerId);
}
timerId = window.setTimeout(() => {
setIdle(true);
}, 3500);
};
const wake = () => {
setIdle(false);
armIdleTimer();
};
armIdleTimer();
window.addEventListener('pointermove', wake);
window.addEventListener('keydown', wake);
window.addEventListener('pointerdown', wake);
return () => {
if (timerId) {
window.clearTimeout(timerId);
}
window.removeEventListener('pointermove', wake);
window.removeEventListener('keydown', wake);
window.removeEventListener('pointerdown', wake);
};
}, [isFocusMode, openPopover, utilityPanel]);
useEffect(() => {
if (utilityPanel !== 'control-center' || !autoHideControls) {
return;
}
let timerId: number | null = null;
const closeDelayMs = 8000;
const armCloseTimer = () => {
if (timerId) {
window.clearTimeout(timerId);
}
timerId = window.setTimeout(() => {
setUtilityPanel((current) => (current === 'control-center' ? null : current));
}, closeDelayMs);
};
const resetTimer = () => {
armCloseTimer();
};
armCloseTimer();
window.addEventListener('pointermove', resetTimer);
window.addEventListener('pointerdown', resetTimer);
window.addEventListener('keydown', resetTimer);
return () => {
if (timerId) {
window.clearTimeout(timerId);
}
window.removeEventListener('pointermove', resetTimer);
window.removeEventListener('pointerdown', resetTimer);
window.removeEventListener('keydown', resetTimer);
};
}, [autoHideControls, utilityPanel]);
const showVolumeFeedback = (nextVolume: number) => {
setVolumeFeedback(`${nextVolume}%`);
if (volumeFeedbackTimerRef.current) {
window.clearTimeout(volumeFeedbackTimerRef.current);
}
volumeFeedbackTimerRef.current = window.setTimeout(() => {
setVolumeFeedback(null);
volumeFeedbackTimerRef.current = null;
}, 900);
};
return {
openPopover,
setOpenPopover,
utilityPanel,
setUtilityPanel,
autoHideControls,
setAutoHideControls,
isIdle,
setIdle,
volumeFeedback,
showVolumeFeedback,
};
};

View File

@@ -0,0 +1,160 @@
'use client';
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
import type { SoundPreset } from '@/entities/session';
import { copy } from '@/shared/i18n';
import { cn } from '@/shared/lib/cn';
import type { SpaceAnchorPopoverId } from '../model/types';
import { ANCHOR_ICON, formatThoughtCount } from './constants';
import { FocusRightRail } from './FocusRightRail';
import { QuickNotesPopover } from './popovers/QuickNotesPopover';
import { QuickSoundPopover } from './popovers/QuickSoundPopover';
interface FocusModeAnchorsProps {
isFocusMode: boolean;
isIdle: boolean;
openPopover: SpaceAnchorPopoverId | null;
thoughtCount: number;
noteDraft: string;
selectedSoundLabel: string;
isSoundMuted: boolean;
soundVolume: number;
volumeFeedback: string | null;
quickSoundPresets: SoundPreset[];
selectedPresetId: string;
onClosePopover: () => void;
onOpenInbox: () => void;
onOpenControlCenter: () => void;
onToggleNotes: () => void;
onToggleSound: () => void;
onNoteDraftChange: (value: string) => void;
onNoteSubmit: () => void;
onToggleMute: () => void;
onVolumeChange: (nextVolume: number) => void;
onVolumeKeyDown: (event: ReactKeyboardEvent<HTMLInputElement>) => void;
onSelectPreset: (presetId: string) => void;
}
const anchorContainerClassName =
'fixed z-30 transition-opacity bottom-[calc(env(safe-area-inset-bottom,0px)+5.25rem)] sm:bottom-[calc(env(safe-area-inset-bottom,0px)+0.75rem)]';
const anchorHaloClassName =
'pointer-events-none absolute -inset-x-5 -inset-y-4 -z-10 rounded-[999px] bg-[radial-gradient(ellipse_at_center,rgba(2,6,23,0.18)_0%,rgba(2,6,23,0.11)_48%,rgba(2,6,23,0)_78%)]';
const anchorButtonClassName =
'inline-flex items-center gap-1.5 rounded-full border border-white/14 bg-black/24 px-2.5 py-1.5 text-[11px] text-white/88 backdrop-blur-md transition-opacity hover:opacity-100';
export const FocusModeAnchors = ({
isFocusMode,
isIdle,
openPopover,
thoughtCount,
noteDraft,
selectedSoundLabel,
isSoundMuted,
soundVolume,
volumeFeedback,
quickSoundPresets,
selectedPresetId,
onClosePopover,
onOpenInbox,
onOpenControlCenter,
onToggleNotes,
onToggleSound,
onNoteDraftChange,
onNoteSubmit,
onToggleMute,
onVolumeChange,
onVolumeKeyDown,
onSelectPreset,
}: FocusModeAnchorsProps) => {
if (!isFocusMode) {
return null;
}
return (
<>
{openPopover ? (
<button
type="button"
aria-label={copy.space.toolsDock.popoverCloseAria}
onClick={onClosePopover}
className="fixed inset-0 z-30"
/>
) : null}
<FocusRightRail
isIdle={isIdle}
thoughtCount={thoughtCount}
onOpenInbox={onOpenInbox}
onOpenControlCenter={onOpenControlCenter}
/>
<div
className={cn(
anchorContainerClassName,
'left-[calc(env(safe-area-inset-left,0px)+0.75rem)]',
isIdle ? 'opacity-34' : 'opacity-82',
)}
>
<div className="relative">
<div aria-hidden className={anchorHaloClassName} />
<button
type="button"
onClick={onToggleNotes}
className={anchorButtonClassName}
>
<span aria-hidden className="text-white/82">{ANCHOR_ICON.notes}</span>
<span>{copy.space.toolsDock.notesButton} {formatThoughtCount(thoughtCount)}</span>
<span aria-hidden className="text-white/60"></span>
</button>
{openPopover === 'notes' ? (
<QuickNotesPopover
noteDraft={noteDraft}
onDraftChange={onNoteDraftChange}
onDraftEnter={onNoteSubmit}
onSubmit={onNoteSubmit}
/>
) : null}
</div>
</div>
<div
className={cn(
anchorContainerClassName,
'right-[calc(env(safe-area-inset-right,0px)+0.75rem)]',
isIdle ? 'opacity-34' : 'opacity-82',
)}
>
<div className="relative">
<div aria-hidden className={anchorHaloClassName} />
<button
type="button"
onClick={onToggleSound}
className={anchorButtonClassName}
>
<span aria-hidden className="text-white/82">{ANCHOR_ICON.sound}</span>
<span className="max-w-[132px] truncate">{selectedSoundLabel}</span>
<span aria-hidden className="text-white/60"></span>
</button>
{openPopover === 'sound' ? (
<QuickSoundPopover
selectedSoundLabel={selectedSoundLabel}
isSoundMuted={isSoundMuted}
soundVolume={soundVolume}
volumeFeedback={volumeFeedback}
quickSoundPresets={quickSoundPresets}
selectedPresetId={selectedPresetId}
onToggleMute={onToggleMute}
onVolumeChange={onVolumeChange}
onVolumeKeyDown={onVolumeKeyDown}
onSelectPreset={onSelectPreset}
/>
) : null}
</div>
</div>
</>
);
};

View File

@@ -1,7 +1,6 @@
'use client'; 'use client';
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; import { useEffect, useMemo } from 'react';
import type { SceneAssetMap } from '@/entities/media'; import type { SceneAssetMap } from '@/entities/media';
import type { PlanTier } from '@/entities/plan';
import type { SceneTheme } from '@/entities/scene'; import type { SceneTheme } from '@/entities/scene';
import { SOUND_PRESETS, type RecentThought, type TimerPreset } from '@/entities/session'; import { SOUND_PRESETS, type RecentThought, type TimerPreset } from '@/entities/session';
import { copy } from '@/shared/i18n'; import { copy } from '@/shared/i18n';
@@ -12,13 +11,13 @@ import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import { cn } from '@/shared/lib/cn'; import { cn } from '@/shared/lib/cn';
import { ControlCenterSheetWidget } from '@/widgets/control-center-sheet'; import { ControlCenterSheetWidget } from '@/widgets/control-center-sheet';
import { SpaceSideSheet } from '@/widgets/space-sheet-shell'; import { SpaceSideSheet } from '@/widgets/space-sheet-shell';
import type { SpaceAnchorPopoverId, SpaceUtilityPanelId } from '../model/types';
import { getQuickSoundPresets } from '../model/getQuickSoundPresets'; import { getQuickSoundPresets } from '../model/getQuickSoundPresets';
import { ANCHOR_ICON, formatThoughtCount, UTILITY_PANEL_TITLE } from './constants'; import { UTILITY_PANEL_TITLE } from './constants';
import { FocusRightRail } from './FocusRightRail'; import { FocusModeAnchors } from './FocusModeAnchors';
import { QuickNotesPopover } from './popovers/QuickNotesPopover';
import { QuickSoundPopover } from './popovers/QuickSoundPopover';
import { InboxToolPanel } from './panels/InboxToolPanel'; import { InboxToolPanel } from './panels/InboxToolPanel';
import { useSpaceToolsDockState } from '../model/useSpaceToolsDockState';
import { useSpaceToolsDockHandlers } from '../model/useSpaceToolsDockHandlers';
interface SpaceToolsDockWidgetProps { interface SpaceToolsDockWidgetProps {
isFocusMode: boolean; isFocusMode: boolean;
scenes: SceneTheme[]; scenes: SceneTheme[];
@@ -76,15 +75,53 @@ export const SpaceToolsDockWidget = ({
onStatusMessage, onStatusMessage,
onExitRequested, onExitRequested,
}: SpaceToolsDockWidgetProps) => { }: SpaceToolsDockWidgetProps) => {
const { toolsDock, controlCenter } = copy.space; const { controlCenter } = copy.space;
const [openPopover, setOpenPopover] = useState<SpaceAnchorPopoverId | null>(null);
const [utilityPanel, setUtilityPanel] = useState<SpaceUtilityPanelId | null>(null); const {
const [autoHideControls, setAutoHideControls] = useState(true); openPopover,
const [noteDraft, setNoteDraft] = useState(''); setOpenPopover,
const [volumeFeedback, setVolumeFeedback] = useState<string | null>(null); utilityPanel,
const [plan, setPlan] = useState<PlanTier>('normal'); setUtilityPanel,
const [isIdle, setIdle] = useState(false); autoHideControls,
const volumeFeedbackTimerRef = useRef<number | null>(null); setAutoHideControls,
isIdle,
setIdle,
volumeFeedback,
showVolumeFeedback,
} = useSpaceToolsDockState({ isFocusMode });
const {
noteDraft,
setNoteDraft,
plan,
openUtilityPanel,
handleNoteSubmit,
handleInboxComplete,
handleInboxDelete,
handleInboxClear,
handlePlanPillClick,
handleLockedClick,
handleSelectProFeature,
handleStartPro,
handleVolumeChange,
handleVolumeKeyDown,
} = useSpaceToolsDockHandlers({
setIdle,
setOpenPopover,
setUtilityPanel,
onCaptureThought,
onDeleteThought,
onSetThoughtCompleted,
onRestoreThought,
onRestoreThoughts,
onClearInbox,
onStatusMessage,
onSetSoundVolume,
onSetSoundMuted,
soundVolume,
isSoundMuted,
showVolumeFeedback,
});
const selectedSoundLabel = useMemo(() => { const selectedSoundLabel = useMemo(() => {
return ( return (
@@ -96,15 +133,6 @@ export const SpaceToolsDockWidget = ({
return getQuickSoundPresets(SOUND_PRESETS); return getQuickSoundPresets(SOUND_PRESETS);
}, []); }, []);
useEffect(() => {
return () => {
if (volumeFeedbackTimerRef.current) {
window.clearTimeout(volumeFeedbackTimerRef.current);
volumeFeedbackTimerRef.current = null;
}
};
}, []);
useEffect(() => { useEffect(() => {
if (!openPopover) { if (!openPopover) {
return; return;
@@ -121,263 +149,10 @@ export const SpaceToolsDockWidget = ({
return () => { return () => {
document.removeEventListener('keydown', handleEscape); document.removeEventListener('keydown', handleEscape);
}; };
}, [openPopover]); }, [openPopover, setOpenPopover]);
useEffect(() => {
if (isFocusMode) {
return;
}
const rafId = window.requestAnimationFrame(() => {
setOpenPopover(null);
setUtilityPanel(null);
setIdle(false);
});
return () => {
window.cancelAnimationFrame(rafId);
};
}, [isFocusMode]);
useEffect(() => {
if (!isFocusMode || openPopover || utilityPanel) {
return;
}
let timerId: number | null = null;
const armIdleTimer = () => {
if (timerId) {
window.clearTimeout(timerId);
}
timerId = window.setTimeout(() => {
setIdle(true);
}, 3500);
};
const wake = () => {
setIdle(false);
armIdleTimer();
};
armIdleTimer();
window.addEventListener('pointermove', wake);
window.addEventListener('keydown', wake);
window.addEventListener('pointerdown', wake);
return () => {
if (timerId) {
window.clearTimeout(timerId);
}
window.removeEventListener('pointermove', wake);
window.removeEventListener('keydown', wake);
window.removeEventListener('pointerdown', wake);
};
}, [isFocusMode, openPopover, utilityPanel]);
useEffect(() => {
if (utilityPanel !== 'control-center' || !autoHideControls) {
return;
}
let timerId: number | null = null;
const closeDelayMs = 8000;
const armCloseTimer = () => {
if (timerId) {
window.clearTimeout(timerId);
}
timerId = window.setTimeout(() => {
setUtilityPanel((current) => (current === 'control-center' ? null : current));
}, closeDelayMs);
};
const resetTimer = () => {
armCloseTimer();
};
armCloseTimer();
window.addEventListener('pointermove', resetTimer);
window.addEventListener('pointerdown', resetTimer);
window.addEventListener('keydown', resetTimer);
return () => {
if (timerId) {
window.clearTimeout(timerId);
}
window.removeEventListener('pointermove', resetTimer);
window.removeEventListener('pointerdown', resetTimer);
window.removeEventListener('keydown', resetTimer);
};
}, [autoHideControls, utilityPanel]);
const openUtilityPanel = (panel: SpaceUtilityPanelId) => {
setIdle(false);
setOpenPopover(null);
setUtilityPanel(panel);
};
const handleNoteSubmit = () => {
const trimmedNote = noteDraft.trim();
if (!trimmedNote) {
return;
}
const addedThought = onCaptureThought(trimmedNote);
if (!addedThought) {
return;
}
setNoteDraft('');
onStatusMessage({
message: toolsDock.inboxSaved,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
const removed = onDeleteThought(addedThought.id);
if (!removed) {
return;
}
onStatusMessage({ message: toolsDock.inboxSaveUndone });
},
},
});
};
const handleInboxComplete = (thought: RecentThought) => {
onSetThoughtCompleted(thought.id, !thought.isCompleted);
};
const handleInboxDelete = (thought: RecentThought) => {
const removedThought = onDeleteThought(thought.id);
if (!removedThought) {
return;
}
onStatusMessage({
message: toolsDock.deleted,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
onRestoreThought(removedThought);
onStatusMessage({ message: toolsDock.deleteUndone });
},
},
});
};
const handleInboxClear = () => {
const snapshot = onClearInbox();
if (snapshot.length === 0) {
onStatusMessage({ message: toolsDock.emptyToClear });
return;
}
onStatusMessage({
message: toolsDock.clearedAll,
durationMs: 4200,
priority: 'undo',
action: {
label: toolsDock.undo,
onClick: () => {
onRestoreThoughts(snapshot);
onStatusMessage({ message: toolsDock.restored });
},
},
});
};
const handlePlanPillClick = () => {
if (plan === 'pro') {
openUtilityPanel('manage-plan');
return;
}
onStatusMessage({ message: toolsDock.normalPlanInfo });
};
const handleLockedClick = (source: string) => {
onStatusMessage({ message: toolsDock.proFeatureLocked(source) });
openUtilityPanel('paywall');
};
const handleSelectProFeature = (featureId: string) => {
const label =
featureId === 'scene-packs'
? toolsDock.featureLabels.scenePacks
: featureId === 'sound-packs'
? toolsDock.featureLabels.soundPacks
: toolsDock.featureLabels.profiles;
onStatusMessage({ message: toolsDock.proFeaturePending(label) });
};
const handleStartPro = () => {
setPlan('pro');
onStatusMessage({ message: toolsDock.purchaseMock });
openUtilityPanel('control-center');
};
const showVolumeFeedback = (nextVolume: number) => {
setVolumeFeedback(`${nextVolume}%`);
if (volumeFeedbackTimerRef.current) {
window.clearTimeout(volumeFeedbackTimerRef.current);
}
volumeFeedbackTimerRef.current = window.setTimeout(() => {
setVolumeFeedback(null);
volumeFeedbackTimerRef.current = null;
}, 900);
};
const handleVolumeChange = (nextVolume: number) => {
const clamped = Math.min(100, Math.max(0, nextVolume));
onSetSoundVolume(clamped);
if (isSoundMuted && clamped > 0) {
onSetSoundMuted(false);
}
showVolumeFeedback(clamped);
};
const handleVolumeKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') {
return;
}
event.preventDefault();
const step = event.shiftKey ? 10 : 5;
const delta = event.key === 'ArrowRight' ? step : -step;
handleVolumeChange(soundVolume + delta);
};
return ( return (
<> <>
{isFocusMode && openPopover ? (
<button
type="button"
aria-label={toolsDock.popoverCloseAria}
onClick={() => setOpenPopover(null)}
className="fixed inset-0 z-30"
/>
) : null}
<div <div
className={cn( className={cn(
'fixed z-30 transition-opacity right-[calc(env(safe-area-inset-right,0px)+0.75rem)] top-[calc(env(safe-area-inset-top,0px)+0.75rem)]', 'fixed z-30 transition-opacity right-[calc(env(safe-area-inset-right,0px)+0.75rem)] top-[calc(env(safe-area-inset-top,0px)+0.75rem)]',
@@ -390,99 +165,43 @@ export const SpaceToolsDockWidget = ({
/> />
</div> </div>
{isFocusMode ? ( <FocusModeAnchors
<> isFocusMode={isFocusMode}
<FocusRightRail isIdle={isIdle}
isIdle={isIdle} openPopover={openPopover}
thoughtCount={thoughtCount} thoughtCount={thoughtCount}
onOpenInbox={() => openUtilityPanel('inbox')} noteDraft={noteDraft}
onOpenControlCenter={() => openUtilityPanel('control-center')} selectedSoundLabel={selectedSoundLabel}
/> isSoundMuted={isSoundMuted}
soundVolume={soundVolume}
<div volumeFeedback={volumeFeedback}
className={cn( quickSoundPresets={quickSoundPresets}
'fixed z-30 transition-opacity left-[calc(env(safe-area-inset-left,0px)+0.75rem)] bottom-[calc(env(safe-area-inset-bottom,0px)+5.25rem)] sm:bottom-[calc(env(safe-area-inset-bottom,0px)+0.75rem)]', selectedPresetId={selectedPresetId}
isIdle ? 'opacity-34' : 'opacity-82', onClosePopover={() => setOpenPopover(null)}
)} onOpenInbox={() => openUtilityPanel('inbox')}
> onOpenControlCenter={() => openUtilityPanel('control-center')}
<div className="relative"> onToggleNotes={() => {
<div setIdle(false);
aria-hidden setOpenPopover((current) => (current === 'notes' ? null : 'notes'));
className="pointer-events-none absolute -inset-x-5 -inset-y-4 -z-10 rounded-[999px] bg-[radial-gradient(ellipse_at_center,rgba(2,6,23,0.18)_0%,rgba(2,6,23,0.11)_48%,rgba(2,6,23,0)_78%)]" }}
/> onToggleSound={() => {
<button setIdle(false);
type="button" setOpenPopover((current) => (current === 'sound' ? null : 'sound'));
onClick={() => { }}
setIdle(false); onNoteDraftChange={setNoteDraft}
setOpenPopover((current) => (current === 'notes' ? null : 'notes')); onNoteSubmit={handleNoteSubmit}
}} onToggleMute={() => {
className="inline-flex items-center gap-1.5 rounded-full border border-white/14 bg-black/24 px-2.5 py-1.5 text-[11px] text-white/88 backdrop-blur-md transition-opacity hover:opacity-100" const nextMuted = !isSoundMuted;
> onSetSoundMuted(nextMuted);
<span aria-hidden className="text-white/82">{ANCHOR_ICON.notes}</span> showVolumeFeedback(nextMuted ? 0 : soundVolume);
<span>{toolsDock.notesButton} {formatThoughtCount(thoughtCount)}</span> }}
<span aria-hidden className="text-white/60"></span> onVolumeChange={handleVolumeChange}
</button> onVolumeKeyDown={handleVolumeKeyDown}
onSelectPreset={(presetId) => {
{openPopover === 'notes' ? ( onQuickSoundSelect(presetId);
<QuickNotesPopover setOpenPopover(null);
noteDraft={noteDraft} }}
onDraftChange={setNoteDraft} />
onDraftEnter={handleNoteSubmit}
onSubmit={handleNoteSubmit}
/>
) : null}
</div>
</div>
<div
className={cn(
'fixed z-30 transition-opacity right-[calc(env(safe-area-inset-right,0px)+0.75rem)] bottom-[calc(env(safe-area-inset-bottom,0px)+5.25rem)] sm:bottom-[calc(env(safe-area-inset-bottom,0px)+0.75rem)]',
isIdle ? 'opacity-34' : 'opacity-82',
)}
>
<div className="relative">
<div
aria-hidden
className="pointer-events-none absolute -inset-x-5 -inset-y-4 -z-10 rounded-[999px] bg-[radial-gradient(ellipse_at_center,rgba(2,6,23,0.18)_0%,rgba(2,6,23,0.11)_48%,rgba(2,6,23,0)_78%)]"
/>
<button
type="button"
onClick={() => {
setIdle(false);
setOpenPopover((current) => (current === 'sound' ? null : 'sound'));
}}
className="inline-flex items-center gap-1.5 rounded-full border border-white/14 bg-black/24 px-2.5 py-1.5 text-[11px] text-white/88 backdrop-blur-md transition-opacity hover:opacity-100"
>
<span aria-hidden className="text-white/82">{ANCHOR_ICON.sound}</span>
<span className="max-w-[132px] truncate">{selectedSoundLabel}</span>
<span aria-hidden className="text-white/60"></span>
</button>
{openPopover === 'sound' ? (
<QuickSoundPopover
selectedSoundLabel={selectedSoundLabel}
isSoundMuted={isSoundMuted}
soundVolume={soundVolume}
volumeFeedback={volumeFeedback}
quickSoundPresets={quickSoundPresets}
selectedPresetId={selectedPresetId}
onToggleMute={() => {
const nextMuted = !isSoundMuted;
onSetSoundMuted(nextMuted);
showVolumeFeedback(nextMuted ? 0 : soundVolume);
}}
onVolumeChange={handleVolumeChange}
onVolumeKeyDown={handleVolumeKeyDown}
onSelectPreset={(presetId) => {
onQuickSoundSelect(presetId);
setOpenPopover(null);
}}
/>
) : null}
</div>
</div>
</>
) : null}
<SpaceSideSheet <SpaceSideSheet
open={isFocusMode && utilityPanel !== null} open={isFocusMode && utilityPanel !== null}
@@ -541,8 +260,8 @@ export const SpaceToolsDockWidget = ({
{utilityPanel === 'manage-plan' ? ( {utilityPanel === 'manage-plan' ? (
<ManagePlanSheetContent <ManagePlanSheetContent
onClose={() => setUtilityPanel(null)} onClose={() => setUtilityPanel(null)}
onManage={() => onStatusMessage({ message: toolsDock.manageSubscriptionMock })} onManage={() => onStatusMessage({ message: copy.space.toolsDock.manageSubscriptionMock })}
onRestore={() => onStatusMessage({ message: toolsDock.restorePurchaseMock })} onRestore={() => onStatusMessage({ message: copy.space.toolsDock.restorePurchaseMock })}
/> />
) : null} ) : null}
</SpaceSideSheet> </SpaceSideSheet>

View File

@@ -0,0 +1,15 @@
export type WorkspaceMode = 'setup' | 'focus';
export type SessionEntryPoint = 'space-setup' | 'goal-complete' | 'resume-restore';
export type SelectionOverride = {
sound: boolean;
timer: boolean;
};
export interface StoredWorkspaceSelection {
sceneId?: string;
timerPresetId?: string;
soundPresetId?: string;
goal?: string;
override?: Partial<SelectionOverride>;
}

View File

@@ -0,0 +1,440 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { SceneAssetMap } from '@/entities/media';
import {
getSceneById,
normalizeSceneId,
SCENE_THEMES,
type SceneTheme,
} from '@/entities/scene';
import {
SOUND_PRESETS,
type GoalChip,
} from '@/entities/session';
import type { FocusSession } from '@/features/focus-session';
import { preferencesApi } from '@/features/preferences/api/preferencesApi';
import { copy } from '@/shared/i18n';
import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import type { SelectionOverride } from './types';
import {
readStoredWorkspaceSelection,
resolveTimerLabelFromPresetId,
resolveTimerPresetIdFromLabel,
} from './workspaceSelection';
import { useWorkspacePersistence } from './useWorkspacePersistence';
import { useWorkspaceMediaDiagnostics } from './useWorkspaceMediaDiagnostics';
interface UseSpaceWorkspaceSelectionParams {
initialSceneId: string;
initialGoal: string;
initialTimerLabel: string;
sceneQuery: string | null;
goalQuery: string;
soundQuery: string | null;
timerQuery: string | null;
hasQueryOverrides: boolean;
currentSession: FocusSession | null;
sceneAssetMap: SceneAssetMap;
selectedPresetId: string;
setSelectedPresetId: (presetId: string) => void;
shouldPlaySound: boolean;
unlockPlayback: (requestedUrl?: string | null) => Promise<boolean>;
resolveSoundPlaybackUrl: (presetId: string) => string | null;
pushStatusLine: (payload: HudStatusLinePayload) => void;
updateCurrentSelection: (payload: {
sceneId?: string;
soundPresetId?: string | null;
}) => Promise<FocusSession | null>;
mediaCatalogError: string | null;
usedFallbackManifest: boolean;
hasResolvedManifest: boolean;
}
const getVisibleSetupScenes = (selectedScene: SceneTheme) => {
const visibleScenes = SCENE_THEMES.slice(0, 6);
if (visibleScenes.some((scene) => scene.id === selectedScene.id)) {
return visibleScenes;
}
return [selectedScene, ...visibleScenes].slice(0, 6);
};
export const useSpaceWorkspaceSelection = ({
initialSceneId,
initialGoal,
initialTimerLabel,
sceneQuery,
goalQuery,
soundQuery,
timerQuery,
hasQueryOverrides,
currentSession,
sceneAssetMap,
selectedPresetId,
setSelectedPresetId,
shouldPlaySound,
unlockPlayback,
resolveSoundPlaybackUrl,
pushStatusLine,
updateCurrentSelection,
mediaCatalogError,
usedFallbackManifest,
hasResolvedManifest,
}: UseSpaceWorkspaceSelectionParams) => {
const [selectedSceneId, setSelectedSceneId] = useState(initialSceneId);
const [selectedTimerLabel, setSelectedTimerLabel] = useState(initialTimerLabel);
const [goalInput, setGoalInput] = useState(initialGoal);
const [selectedGoalId, setSelectedGoalId] = useState<string | null>(null);
const [resumeGoal, setResumeGoal] = useState('');
const [showResumePrompt, setShowResumePrompt] = useState(false);
const [hasHydratedSelection, setHasHydratedSelection] = useState(false);
const [selectionOverride, setSelectionOverride] = useState<SelectionOverride>({
sound: false,
timer: false,
});
const didHydrateServerPreferencesRef = useRef(false);
const selectedScene = useMemo(() => {
return getSceneById(selectedSceneId) ?? SCENE_THEMES[0];
}, [selectedSceneId]);
const selectedSceneAsset = sceneAssetMap[selectedScene.id];
const setupScenes = useMemo(() => {
return getVisibleSetupScenes(selectedScene);
}, [selectedScene]);
const canStart = goalInput.trim().length > 0;
const applyRecommendedSelections = useCallback((
sceneId: string,
overrideState: SelectionOverride = selectionOverride,
) => {
const scene = getSceneById(sceneId);
if (!scene) {
return;
}
if (!overrideState.timer) {
const recommendedTimerLabel = resolveTimerLabelFromPresetId(scene.recommendedTimerPresetId);
if (recommendedTimerLabel) {
setSelectedTimerLabel(recommendedTimerLabel);
}
}
if (
!overrideState.sound &&
SOUND_PRESETS.some((preset) => preset.id === scene.recommendedSoundPresetId)
) {
setSelectedPresetId(scene.recommendedSoundPresetId);
}
}, [selectionOverride, setSelectedPresetId]);
const persistSpaceSelection = useCallback((selection: {
sceneId?: string;
soundPresetId?: string | null;
}) => {
const preferencePayload: {
defaultSceneId?: string | null;
defaultSoundPresetId?: string | null;
} = {};
const currentSessionPayload: {
sceneId?: string;
soundPresetId?: string | null;
} = {};
if (selection.sceneId !== undefined) {
preferencePayload.defaultSceneId = selection.sceneId;
currentSessionPayload.sceneId = selection.sceneId;
}
if (selection.soundPresetId !== undefined) {
preferencePayload.defaultSoundPresetId = selection.soundPresetId;
currentSessionPayload.soundPresetId = selection.soundPresetId;
}
void (async () => {
const [preferencesResult, sessionResult] = await Promise.allSettled([
preferencesApi.updateFocusPreferences(preferencePayload),
currentSession ? updateCurrentSelection(currentSessionPayload) : Promise.resolve(null),
]);
if (preferencesResult.status === 'rejected') {
pushStatusLine({
message: copy.space.workspace.selectionPreferenceSaveFailed,
});
}
if (
currentSession &&
(sessionResult.status === 'rejected' || sessionResult.value === null)
) {
pushStatusLine({
message: copy.space.workspace.selectionSessionSyncFailed,
});
}
})();
}, [currentSession, pushStatusLine, updateCurrentSelection]);
const handleSelectScene = useCallback((sceneId: string) => {
void (async () => {
const normalizedSceneId = normalizeSceneId(sceneId) ?? sceneId;
const recommendedScene = getSceneById(normalizedSceneId);
const nextSoundPresetId =
recommendedScene &&
!selectionOverride.sound &&
SOUND_PRESETS.some((preset) => preset.id === recommendedScene.recommendedSoundPresetId)
? recommendedScene.recommendedSoundPresetId
: selectedPresetId;
if (shouldPlaySound) {
await unlockPlayback(resolveSoundPlaybackUrl(nextSoundPresetId));
}
setSelectedSceneId(normalizedSceneId);
applyRecommendedSelections(normalizedSceneId);
persistSpaceSelection({
sceneId: normalizedSceneId,
soundPresetId: nextSoundPresetId,
});
})();
}, [
applyRecommendedSelections,
persistSpaceSelection,
resolveSoundPlaybackUrl,
selectedPresetId,
selectionOverride.sound,
shouldPlaySound,
unlockPlayback,
]);
const handleSelectTimer = useCallback((timerLabel: string, markOverride = false) => {
setSelectedTimerLabel(timerLabel);
if (!markOverride) {
return;
}
setSelectionOverride((current) => {
if (current.timer) {
return current;
}
return { ...current, timer: true };
});
}, []);
const handleSelectSound = useCallback((presetId: string, markOverride = false) => {
void (async () => {
if (shouldPlaySound) {
await unlockPlayback(resolveSoundPlaybackUrl(presetId));
}
setSelectedPresetId(presetId);
if (!markOverride) {
return;
}
setSelectionOverride((current) => {
if (current.sound) {
return current;
}
return { ...current, sound: true };
});
persistSpaceSelection({
soundPresetId: presetId,
});
})();
}, [
persistSpaceSelection,
resolveSoundPlaybackUrl,
setSelectedPresetId,
shouldPlaySound,
unlockPlayback,
]);
const handleGoalChipSelect = useCallback((chip: GoalChip) => {
setShowResumePrompt(false);
setSelectedGoalId(chip.id);
setGoalInput(chip.label);
}, []);
const handleGoalChange = useCallback((value: string) => {
if (showResumePrompt) {
setShowResumePrompt(false);
}
setGoalInput(value);
if (value.trim().length === 0) {
setSelectedGoalId(null);
}
}, [showResumePrompt]);
useEffect(() => {
const storedSelection = readStoredWorkspaceSelection();
const restoredSelectionOverride: SelectionOverride = {
sound: Boolean(storedSelection.override?.sound),
timer: Boolean(storedSelection.override?.timer),
};
const restoredSceneId =
!sceneQuery && storedSelection.sceneId && getSceneById(storedSelection.sceneId)
? normalizeSceneId(storedSelection.sceneId)
: null;
const restoredTimerLabel = !timerQuery
? resolveTimerLabelFromPresetId(storedSelection.timerPresetId)
: null;
const restoredSoundPresetId =
!soundQuery && storedSelection.soundPresetId && SOUND_PRESETS.some((preset) => preset.id === storedSelection.soundPresetId)
? storedSelection.soundPresetId
: null;
const restoredGoal = storedSelection.goal?.trim() ?? '';
const rafId = window.requestAnimationFrame(() => {
setSelectionOverride(restoredSelectionOverride);
if (restoredSceneId) {
setSelectedSceneId(restoredSceneId);
}
if (restoredTimerLabel) {
setSelectedTimerLabel(restoredTimerLabel);
}
if (restoredSoundPresetId) {
setSelectedPresetId(restoredSoundPresetId);
}
if (!goalQuery && restoredGoal.length > 0 && !hasQueryOverrides) {
setResumeGoal(restoredGoal);
setShowResumePrompt(true);
}
setHasHydratedSelection(true);
});
return () => {
window.cancelAnimationFrame(rafId);
};
}, [goalQuery, hasQueryOverrides, sceneQuery, setSelectedPresetId, soundQuery, timerQuery]);
useEffect(() => {
if (!hasHydratedSelection || didHydrateServerPreferencesRef.current) {
return;
}
didHydrateServerPreferencesRef.current = true;
let cancelled = false;
void preferencesApi
.getFocusPreferences()
.then((preferences) => {
if (cancelled || currentSession || hasQueryOverrides) {
return;
}
const normalizedPreferredSceneId = normalizeSceneId(preferences.defaultSceneId);
const nextSceneId =
normalizedPreferredSceneId && getSceneById(normalizedPreferredSceneId)
? normalizedPreferredSceneId
: null;
const nextSoundPresetId =
preferences.defaultSoundPresetId &&
SOUND_PRESETS.some((preset) => preset.id === preferences.defaultSoundPresetId)
? preferences.defaultSoundPresetId
: null;
if (nextSceneId) {
setSelectedSceneId(nextSceneId);
}
if (nextSoundPresetId) {
setSelectedPresetId(nextSoundPresetId);
setSelectionOverride((current) => ({ ...current, sound: true }));
}
})
.catch(() => {
// Focus preference load failure should not block entering the space.
});
return () => {
cancelled = true;
};
}, [currentSession, hasHydratedSelection, hasQueryOverrides, setSelectedPresetId]);
useEffect(() => {
if (!currentSession) {
return;
}
const nextTimerLabel =
resolveTimerLabelFromPresetId(currentSession.timerPresetId) ?? selectedTimerLabel;
const nextSoundPresetId =
currentSession.soundPresetId &&
SOUND_PRESETS.some((preset) => preset.id === currentSession.soundPresetId)
? currentSession.soundPresetId
: selectedPresetId;
const rafId = window.requestAnimationFrame(() => {
setSelectedSceneId(normalizeSceneId(currentSession.sceneId) ?? currentSession.sceneId);
setSelectedTimerLabel(nextTimerLabel);
setSelectedPresetId(nextSoundPresetId);
setGoalInput(currentSession.goal);
setSelectedGoalId(null);
setShowResumePrompt(false);
});
return () => {
window.cancelAnimationFrame(rafId);
};
}, [currentSession, selectedPresetId, selectedTimerLabel, setSelectedPresetId]);
useWorkspacePersistence({
hasHydratedSelection,
selectedScene,
selectedTimerPresetId: resolveTimerPresetIdFromLabel(selectedTimerLabel),
selectedPresetId,
goalInput,
showResumePrompt,
resumeGoal,
selectionOverride,
});
useWorkspaceMediaDiagnostics({
mediaCatalogError,
pushStatusLine,
selectedScene,
hasResolvedManifest,
usedFallbackManifest,
selectedSceneAsset,
});
return {
selectedSceneId,
selectedTimerLabel,
goalInput,
selectedGoalId,
resumeGoal,
showResumePrompt,
hasHydratedSelection,
selectionOverride,
selectedScene,
selectedSceneAsset,
setupScenes,
canStart,
setGoalInput,
setSelectedGoalId,
setShowResumePrompt,
setResumeGoal,
handleSelectScene,
handleSelectTimer,
handleSelectSound,
handleGoalChipSelect,
handleGoalChange,
};
};

View File

@@ -0,0 +1,316 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import type { FocusSession } from '@/features/focus-session';
import { copy } from '@/shared/i18n';
import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import { resolveTimerPresetIdFromLabel } from './workspaceSelection';
import type { SessionEntryPoint, WorkspaceMode } from './types';
interface UseSpaceWorkspaceSessionControlsParams {
canStart: boolean;
currentSession: FocusSession | null;
goalInput: string;
selectedSceneId: string;
selectedTimerLabel: string;
selectedPresetId: string;
soundPlaybackError: string | null;
pushStatusLine: (payload: HudStatusLinePayload) => void;
unlockPlayback: (requestedUrl?: string | null) => Promise<boolean>;
resolveSoundPlaybackUrl: (presetId: string) => string | null;
startSession: (input: {
sceneId: string;
goal: string;
timerPresetId: string;
soundPresetId: string;
entryPoint: SessionEntryPoint;
}) => Promise<FocusSession | null>;
pauseSession: () => Promise<FocusSession | null>;
resumeSession: () => Promise<FocusSession | null>;
restartCurrentPhase: () => Promise<FocusSession | null>;
completeSession: (input: {
completionType: 'goal-complete';
completedGoal: string;
}) => Promise<FocusSession | null>;
abandonSession: () => Promise<boolean>;
setGoalInput: (value: string) => void;
setSelectedGoalId: (value: string | null) => void;
setShowResumePrompt: (value: boolean) => void;
}
export const useSpaceWorkspaceSessionControls = ({
canStart,
currentSession,
goalInput,
selectedSceneId,
selectedTimerLabel,
selectedPresetId,
soundPlaybackError,
pushStatusLine,
unlockPlayback,
resolveSoundPlaybackUrl,
startSession,
pauseSession,
resumeSession,
restartCurrentPhase,
completeSession,
abandonSession,
setGoalInput,
setSelectedGoalId,
setShowResumePrompt,
}: UseSpaceWorkspaceSessionControlsParams) => {
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>('setup');
const [previewPlaybackState, setPreviewPlaybackState] = useState<'running' | 'paused'>('paused');
const [pendingSessionEntryPoint, setPendingSessionEntryPoint] =
useState<SessionEntryPoint>('space-setup');
const queuedFocusStatusMessageRef = useRef<string | null>(null);
const lastSoundPlaybackErrorRef = useRef<string | null>(null);
const resolvedPlaybackState = currentSession?.state ?? previewPlaybackState;
const isFocusMode = workspaceMode === 'focus';
const canStartSession = canStart && (!currentSession || resolvedPlaybackState !== 'running');
const canPauseSession = Boolean(currentSession && resolvedPlaybackState === 'running');
const canRestartSession = Boolean(currentSession);
const openFocusMode = useCallback((
nextGoal: string,
entryPoint: SessionEntryPoint = 'space-setup',
) => {
const trimmedGoal = nextGoal.trim();
if (!trimmedGoal) {
return;
}
setShowResumePrompt(false);
setPendingSessionEntryPoint(entryPoint);
setPreviewPlaybackState('paused');
setWorkspaceMode('focus');
queuedFocusStatusMessageRef.current = copy.space.workspace.readyToStart;
}, [setShowResumePrompt]);
const startFocusFlow = useCallback(async () => {
const trimmedGoal = goalInput.trim();
const timerPresetId = resolveTimerPresetIdFromLabel(selectedTimerLabel);
if (!trimmedGoal || !timerPresetId) {
return;
}
const startedSession = await startSession({
sceneId: selectedSceneId,
goal: trimmedGoal,
timerPresetId,
soundPresetId: selectedPresetId,
entryPoint: pendingSessionEntryPoint,
});
if (startedSession) {
setPreviewPlaybackState('running');
return;
}
setPreviewPlaybackState('paused');
pushStatusLine({
message: copy.space.workspace.startFailed,
});
}, [
goalInput,
pendingSessionEntryPoint,
pushStatusLine,
selectedPresetId,
selectedSceneId,
selectedTimerLabel,
startSession,
]);
const handleSetupFocusOpen = useCallback(() => {
if (!canStart) {
return;
}
openFocusMode(goalInput, 'space-setup');
}, [canStart, goalInput, openFocusMode]);
const handleStartRequested = useCallback(async () => {
if (!canStartSession) {
return;
}
await unlockPlayback(resolveSoundPlaybackUrl(selectedPresetId));
if (!currentSession) {
await startFocusFlow();
return;
}
const resumedSession = await resumeSession();
if (!resumedSession) {
pushStatusLine({
message: copy.space.workspace.resumeFailed,
});
}
}, [
canStartSession,
currentSession,
pushStatusLine,
resolveSoundPlaybackUrl,
resumeSession,
selectedPresetId,
startFocusFlow,
unlockPlayback,
]);
const handleExitRequested = useCallback(async () => {
const didAbandon = await abandonSession();
if (!didAbandon) {
pushStatusLine({
message: copy.space.workspace.abandonFailed,
});
return;
}
setPreviewPlaybackState('paused');
setPendingSessionEntryPoint('space-setup');
setWorkspaceMode('setup');
}, [abandonSession, pushStatusLine]);
const handlePauseRequested = useCallback(async () => {
if (!currentSession) {
setPreviewPlaybackState('paused');
return;
}
const pausedSession = await pauseSession();
if (!pausedSession) {
pushStatusLine({
message: copy.space.workspace.pauseFailed,
});
}
}, [currentSession, pauseSession, pushStatusLine]);
const handleRestartRequested = useCallback(async () => {
if (!currentSession) {
return;
}
const restartedSession = await restartCurrentPhase();
if (!restartedSession) {
pushStatusLine({
message: copy.space.workspace.restartFailed,
});
return;
}
pushStatusLine({
message: copy.space.workspace.restarted,
});
}, [currentSession, pushStatusLine, restartCurrentPhase]);
const handleGoalAdvance = useCallback(async (nextGoal: string) => {
const trimmedNextGoal = nextGoal.trim();
if (!trimmedNextGoal) {
return;
}
if (currentSession) {
const completedSession = await completeSession({
completionType: 'goal-complete',
completedGoal: goalInput.trim(),
});
if (!completedSession) {
pushStatusLine({
message: copy.space.workspace.goalCompleteSyncFailed,
});
return;
}
}
setGoalInput(trimmedNextGoal);
setSelectedGoalId(null);
setPendingSessionEntryPoint('goal-complete');
setPreviewPlaybackState('paused');
pushStatusLine({
message: copy.space.workspace.nextGoalReady,
});
}, [completeSession, currentSession, goalInput, pushStatusLine, setGoalInput, setSelectedGoalId]);
useEffect(() => {
const previousBodyOverflow = document.body.style.overflow;
const previousHtmlOverflow = document.documentElement.style.overflow;
document.body.style.overflow = 'hidden';
document.documentElement.style.overflow = 'hidden';
return () => {
document.body.style.overflow = previousBodyOverflow;
document.documentElement.style.overflow = previousHtmlOverflow;
};
}, []);
useEffect(() => {
if (!currentSession) {
return;
}
const rafId = window.requestAnimationFrame(() => {
setPreviewPlaybackState(currentSession.state);
setWorkspaceMode('focus');
});
return () => {
window.cancelAnimationFrame(rafId);
};
}, [currentSession]);
useEffect(() => {
if (!isFocusMode || !queuedFocusStatusMessageRef.current) {
return;
}
const message = queuedFocusStatusMessageRef.current;
queuedFocusStatusMessageRef.current = null;
pushStatusLine({
message,
});
}, [isFocusMode, pushStatusLine]);
useEffect(() => {
if (!soundPlaybackError) {
lastSoundPlaybackErrorRef.current = null;
return;
}
if (soundPlaybackError === lastSoundPlaybackErrorRef.current) {
return;
}
lastSoundPlaybackErrorRef.current = soundPlaybackError;
pushStatusLine({
message: soundPlaybackError,
});
}, [pushStatusLine, soundPlaybackError]);
return {
workspaceMode,
isFocusMode,
previewPlaybackState,
resolvedPlaybackState,
canStartSession,
canPauseSession,
canRestartSession,
openFocusMode,
handleSetupFocusOpen,
handleStartRequested,
handleExitRequested,
handlePauseRequested,
handleRestartRequested,
handleGoalAdvance,
};
};

View File

@@ -0,0 +1,70 @@
'use client';
import { useEffect, useRef } from 'react';
import type { HudStatusLinePayload } from '@/shared/lib/useHudStatusLine';
import type { SceneTheme } from '@/entities/scene';
import type { SceneAssetManifestItem } from '@/entities/media';
interface UseWorkspaceMediaDiagnosticsParams {
mediaCatalogError: string | null;
pushStatusLine: (payload: HudStatusLinePayload) => void;
selectedScene: SceneTheme;
hasResolvedManifest: boolean;
usedFallbackManifest: boolean;
selectedSceneAsset: SceneAssetManifestItem | undefined;
}
export const useWorkspaceMediaDiagnostics = ({
mediaCatalogError,
pushStatusLine,
selectedScene,
hasResolvedManifest,
usedFallbackManifest,
selectedSceneAsset,
}: UseWorkspaceMediaDiagnosticsParams) => {
const lastMediaManifestErrorRef = useRef<string | null>(null);
const lastFallbackSceneDiagnosticRef = useRef<string | null>(null);
useEffect(() => {
if (!mediaCatalogError) {
lastMediaManifestErrorRef.current = null;
return;
}
if (mediaCatalogError === lastMediaManifestErrorRef.current) {
return;
}
lastMediaManifestErrorRef.current = mediaCatalogError;
console.error('[media] Failed to load remote media manifest.', {
error: mediaCatalogError,
sceneId: selectedScene.id,
});
pushStatusLine({
message: mediaCatalogError,
});
}, [mediaCatalogError, pushStatusLine, selectedScene.id]);
useEffect(() => {
if (!hasResolvedManifest || usedFallbackManifest) {
return;
}
const isUsingFallbackSceneAsset = !selectedSceneAsset || selectedSceneAsset.source === 'fallback';
if (!isUsingFallbackSceneAsset) {
lastFallbackSceneDiagnosticRef.current = null;
return;
}
if (lastFallbackSceneDiagnosticRef.current === selectedScene.id) {
return;
}
lastFallbackSceneDiagnosticRef.current = selectedScene.id;
console.warn('[space] Selected scene is using fallback asset data.', {
sceneId: selectedScene.id,
asset: selectedSceneAsset ?? null,
});
}, [hasResolvedManifest, selectedScene.id, selectedSceneAsset, usedFallbackManifest]);
};

View File

@@ -0,0 +1,60 @@
'use client';
import { useEffect } from 'react';
import { WORKSPACE_SELECTION_STORAGE_KEY } from './workspaceSelection';
import type { SelectionOverride } from './types';
import type { SceneTheme } from '@/entities/scene';
interface UseWorkspacePersistenceParams {
hasHydratedSelection: boolean;
selectedScene: SceneTheme;
selectedTimerPresetId: string | undefined;
selectedPresetId: string;
goalInput: string;
showResumePrompt: boolean;
resumeGoal: string;
selectionOverride: SelectionOverride;
}
export const useWorkspacePersistence = ({
hasHydratedSelection,
selectedScene,
selectedTimerPresetId,
selectedPresetId,
goalInput,
showResumePrompt,
resumeGoal,
selectionOverride,
}: UseWorkspacePersistenceParams) => {
useEffect(() => {
if (typeof window === 'undefined' || !hasHydratedSelection) {
return;
}
const normalizedGoal = goalInput.trim().length > 0
? goalInput.trim()
: showResumePrompt
? resumeGoal
: '';
window.localStorage.setItem(
WORKSPACE_SELECTION_STORAGE_KEY,
JSON.stringify({
sceneId: selectedScene.id,
timerPresetId: selectedTimerPresetId,
soundPresetId: selectedPresetId,
goal: normalizedGoal,
override: selectionOverride,
}),
);
}, [
goalInput,
hasHydratedSelection,
resumeGoal,
selectedPresetId,
selectedScene.id,
selectedTimerPresetId,
selectionOverride,
showResumePrompt,
]);
};

View File

@@ -0,0 +1,140 @@
import {
getSceneById,
normalizeSceneId,
SCENE_THEMES,
} from '@/entities/scene';
import {
SOUND_PRESETS,
TIMER_PRESETS,
type TimerPreset,
} from '@/entities/session';
export type SelectionOverride = {
sound: boolean;
timer: boolean;
};
export interface StoredWorkspaceSelection {
sceneId?: string;
timerPresetId?: string;
soundPresetId?: string;
goal?: string;
override?: Partial<SelectionOverride>;
}
export const WORKSPACE_SELECTION_STORAGE_KEY = 'viberoom:workspace-selection:v1';
export const readStoredWorkspaceSelection = (): StoredWorkspaceSelection => {
if (typeof window === 'undefined') {
return {};
}
const raw = window.localStorage.getItem(WORKSPACE_SELECTION_STORAGE_KEY);
if (!raw) {
return {};
}
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') {
return {};
}
return parsed as StoredWorkspaceSelection;
} catch {
return {};
}
};
export const resolveInitialSceneId = (
sceneIdFromQuery: string | null,
storedSceneId?: string,
) => {
const normalizedQuerySceneId = normalizeSceneId(sceneIdFromQuery);
if (normalizedQuerySceneId && getSceneById(normalizedQuerySceneId)) {
return normalizedQuerySceneId;
}
const normalizedStoredSceneId = normalizeSceneId(storedSceneId);
if (normalizedStoredSceneId && getSceneById(normalizedStoredSceneId)) {
return normalizedStoredSceneId;
}
return SCENE_THEMES[0].id;
};
export const resolveInitialSoundPreset = (
presetIdFromQuery: string | null,
storedPresetId: string | undefined,
recommendedPresetId?: string,
) => {
if (presetIdFromQuery && SOUND_PRESETS.some((preset) => preset.id === presetIdFromQuery)) {
return presetIdFromQuery;
}
if (storedPresetId && SOUND_PRESETS.some((preset) => preset.id === storedPresetId)) {
return storedPresetId;
}
if (recommendedPresetId && SOUND_PRESETS.some((preset) => preset.id === recommendedPresetId)) {
return recommendedPresetId;
}
return SOUND_PRESETS[0].id;
};
export const TIMER_SELECTION_PRESETS = TIMER_PRESETS.filter(
(preset): preset is TimerPreset & { focusMinutes: number; breakMinutes: number } =>
typeof preset.focusMinutes === 'number' && typeof preset.breakMinutes === 'number',
).slice(0, 3);
export const resolveTimerLabelFromPresetId = (presetId?: string) => {
if (!presetId) {
return null;
}
const preset = TIMER_SELECTION_PRESETS.find((candidate) => candidate.id === presetId);
if (!preset) {
return null;
}
return preset.label;
};
export const resolveTimerPresetIdFromLabel = (timerLabel: string) => {
const preset = TIMER_SELECTION_PRESETS.find((candidate) => candidate.label === timerLabel);
return preset?.id;
};
export const resolveInitialTimerLabel = (
timerLabelFromQuery: string | null,
storedPresetId?: string,
recommendedPresetId?: string,
) => {
if (timerLabelFromQuery && TIMER_SELECTION_PRESETS.some((preset) => preset.label === timerLabelFromQuery)) {
return timerLabelFromQuery;
}
const storedLabel = resolveTimerLabelFromPresetId(storedPresetId);
if (storedLabel) {
return storedLabel;
}
const recommendedLabel = resolveTimerLabelFromPresetId(recommendedPresetId);
if (recommendedLabel) {
return recommendedLabel;
}
return TIMER_SELECTION_PRESETS[0]?.label ?? '25/5';
};
export const resolveFocusTimeDisplayFromTimerLabel = (timerLabel: string) => {
const preset = TIMER_SELECTION_PRESETS.find((candidate) => candidate.label === timerLabel);
const focusMinutes = preset?.focusMinutes ?? 25;
return `${String(focusMinutes).padStart(2, '0')}:00`;
};

File diff suppressed because it is too large Load Diff