diff --git a/assets/flags/cambodia.svg b/assets/flags/cambodia.svg new file mode 100644 index 0000000..828e54a --- /dev/null +++ b/assets/flags/cambodia.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/indonesia.svg b/assets/flags/indonesia.svg new file mode 100644 index 0000000..08c1098 --- /dev/null +++ b/assets/flags/indonesia.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/malaysia.svg b/assets/flags/malaysia.svg new file mode 100644 index 0000000..bb160fd --- /dev/null +++ b/assets/flags/malaysia.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/myanmar.svg b/assets/flags/myanmar.svg new file mode 100644 index 0000000..4509bb3 --- /dev/null +++ b/assets/flags/myanmar.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/philippines.svg b/assets/flags/philippines.svg new file mode 100644 index 0000000..be4ac14 --- /dev/null +++ b/assets/flags/philippines.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/singapore.svg b/assets/flags/singapore.svg new file mode 100644 index 0000000..4d4a817 --- /dev/null +++ b/assets/flags/singapore.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/thailand.svg b/assets/flags/thailand.svg new file mode 100644 index 0000000..3f22b44 --- /dev/null +++ b/assets/flags/thailand.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/flags/vietnam.svg b/assets/flags/vietnam.svg new file mode 100644 index 0000000..691cd96 --- /dev/null +++ b/assets/flags/vietnam.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/App.tsx b/src/App.tsx index 2712454..26dab91 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,6 +3,7 @@ import { BrowserRouter } from 'react-router-dom'; import { useEffect } from 'react'; import { AppRouter } from './navigation/AppRouter'; +import { withTimeout } from './lib/asyncTimeout'; import { supabase } from './lib/supabase'; import { removeKey, STORAGE_KEYS } from './lib/storage'; import { useAuthStore } from './stores/authStore'; @@ -18,7 +19,11 @@ export default function App() { const { data: { session: nextSession }, error, - } = await supabase.auth.getSession(); + } = await withTimeout( + supabase.auth.getSession(), + 8000, + 'Timed out while initialising session.', + ); if (error) { throw error; @@ -55,7 +60,7 @@ export default function App() { return ( - + diff --git a/src/components/LearningLanguageBadge.css b/src/components/LearningLanguageBadge.css index a6b7fab..9d33b6d 100644 --- a/src/components/LearningLanguageBadge.css +++ b/src/components/LearningLanguageBadge.css @@ -1,19 +1,18 @@ .learning-language-badge { align-items: center; - background: rgba(255, 249, 233, 0.86); - border: 1px solid rgba(96, 72, 40, 0.1); + background: rgba(255, 249, 233, 0.9); + border: 1px solid rgba(96, 72, 40, 0.08); border-radius: 999px; box-shadow: - 0 6px 16px rgba(68, 46, 24, 0.14), - inset 0 1px 0 rgba(255, 255, 255, 0.78); + 0 5px 14px rgba(68, 46, 24, 0.15), + inset 0 1px 0 rgba(255, 255, 255, 0.68); color: #604828; cursor: pointer; display: inline-flex; font-family: 'Satoshi', 'Poppins', ui-sans-serif, system-ui, sans-serif; - font-weight: 700; - gap: 5px; - justify-content: center; - line-height: 1; + gap: 8px; + justify-content: flex-start; + line-height: 1.1; max-width: 100%; min-width: 0; -webkit-tap-highlight-color: transparent; @@ -28,46 +27,105 @@ outline-offset: 2px; } -.learning-language-badge span { +.learning-language-badge-copy { + display: grid; + gap: 1px; + justify-items: start; min-width: 0; +} + +.learning-language-badge-name, +.learning-language-badge-country { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.learning-language-badge-icon { +.learning-language-badge-name { + color: #3d291c; + font-weight: 800; + line-height: 1.18; +} + +.learning-language-badge-country { + color: rgba(61, 41, 28, 0.72); + font-weight: 500; + line-height: 1.2; +} + +.learning-language-badge-flag { + align-items: center; + border-radius: 999px; + box-shadow: 0 1px 4px rgba(68, 46, 24, 0.12); + display: inline-flex; flex-shrink: 0; + justify-content: center; + overflow: hidden; +} + +.learning-language-badge-flag img { + border-radius: 999px; + display: block; + height: 100%; + object-fit: cover; + width: 100%; } .learning-language-badge-chevron { flex-shrink: 0; - opacity: 0.72; + margin-left: auto; + opacity: 0.9; } .learning-language-badge--home { + align-items: center; font-size: 12px; - min-height: 30px; - padding: 0 10px; + min-height: 48px; + padding: 0 12px 0 8px; + width: 148px; } -.learning-language-badge--home .learning-language-badge-icon { - font-size: 14px; +.learning-language-badge--home .learning-language-badge-copy { + align-content: center; + min-height: 32px; +} + +.learning-language-badge--home .learning-language-badge-flag { + height: 32px; + width: 32px; +} + +.learning-language-badge--home .learning-language-badge-country { + font-size: 11px; } .learning-language-badge--home .learning-language-badge-chevron { - font-size: 13px; + color: #3d291c; + font-size: 19px; } .learning-language-badge--compact { - font-size: 12px; - min-height: 28px; + font-size: 11px; + gap: 7px; + min-height: 38px; padding: 0 9px; + width: 130px; +} + +.learning-language-badge--compact .learning-language-badge-flag { + height: 24px; + width: 24px; } -.learning-language-badge--compact .learning-language-badge-icon { - font-size: 13px; +.learning-language-badge--compact .learning-language-badge-copy { + align-content: center; + min-height: 24px; +} + +.learning-language-badge--compact .learning-language-badge-country { + font-size: 10px; } .learning-language-badge--compact .learning-language-badge-chevron { - font-size: 12px; + font-size: 14px; } diff --git a/src/components/LearningLanguageBadge.tsx b/src/components/LearningLanguageBadge.tsx index 6820133..1c37150 100644 --- a/src/components/LearningLanguageBadge.tsx +++ b/src/components/LearningLanguageBadge.tsx @@ -1,6 +1,8 @@ -import { chevronDownOutline, globeOutline } from 'ionicons/icons'; +import { chevronDownOutline } from 'ionicons/icons'; import { IonIcon } from '@ionic/react'; +import { getLearningLanguageMetadata } from '../lib/learningLanguages'; + import './LearningLanguageBadge.css'; type LearningLanguageBadgeVariant = 'home' | 'compact'; @@ -18,7 +20,7 @@ export function LearningLanguageBadge({ onClick, className, }: LearningLanguageBadgeProps) { - const label = language; + const metadata = getLearningLanguageMetadata(language); const classes = ['learning-language-badge', `learning-language-badge--${variant}`, className] .filter(Boolean) .join(' '); @@ -28,10 +30,15 @@ export function LearningLanguageBadge({ type="button" className={classes} onClick={onClick} - aria-label={`Learning language: ${language}`} + aria-label={`Learning language: ${metadata.language}, ${metadata.country}`} > - - {label} + + + + + {metadata.language} + {metadata.country} + ; @@ -10,7 +11,7 @@ type AppButtonProps = IonButtonProps & { export function AppButton({ loading = false, disabled, children, ...props }: AppButtonProps) { return ( - {loading ? : children} + {loading ? : children} ); } diff --git a/src/lib/asyncTimeout.ts b/src/lib/asyncTimeout.ts new file mode 100644 index 0000000..86aa333 --- /dev/null +++ b/src/lib/asyncTimeout.ts @@ -0,0 +1,21 @@ +export const withTimeout = async ( + promise: PromiseLike, + timeoutMs: number, + message: string, +): Promise => { + let timeoutId: ReturnType | undefined; + + const timeout = new Promise((_, reject) => { + timeoutId = setTimeout(() => { + reject(new Error(message)); + }, timeoutMs); + }); + + try { + return await Promise.race([promise, timeout]); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + } +}; diff --git a/src/lib/learningLanguages.ts b/src/lib/learningLanguages.ts index a518ef1..e99a724 100644 --- a/src/lib/learningLanguages.ts +++ b/src/lib/learningLanguages.ts @@ -1,3 +1,12 @@ +import cambodiaFlag from '../../assets/flags/cambodia.svg'; +import indonesiaFlag from '../../assets/flags/indonesia.svg'; +import malaysiaFlag from '../../assets/flags/malaysia.svg'; +import myanmarFlag from '../../assets/flags/myanmar.svg'; +import philippinesFlag from '../../assets/flags/philippines.svg'; +import singaporeFlag from '../../assets/flags/singapore.svg'; +import thailandFlag from '../../assets/flags/thailand.svg'; +import vietnamFlag from '../../assets/flags/vietnam.svg'; + export const LEARNING_LANGUAGE_OPTIONS = [ 'Tandia', 'Semai', @@ -13,7 +22,28 @@ export type LearningLanguage = (typeof LEARNING_LANGUAGE_OPTIONS)[number]; export const DEFAULT_LEARNING_LANGUAGE: LearningLanguage = 'Semai'; +export type LearningLanguageMetadata = { + language: LearningLanguage; + country: string; + flagSrc: string; +}; + +export const LEARNING_LANGUAGE_METADATA: Record = { + Tandia: { language: 'Tandia', country: 'Indonesia', flagSrc: indonesiaFlag }, + Semai: { language: 'Semai', country: 'Malaysia', flagSrc: malaysiaFlag }, + Mlabri: { language: 'Mlabri', country: 'Thailand', flagSrc: thailandFlag }, + Chong: { language: 'Chong', country: 'Cambodia', flagSrc: cambodiaFlag }, + Arta: { language: 'Arta', country: 'Philippines', flagSrc: philippinesFlag }, + Arem: { language: 'Arem', country: 'Vietnam', flagSrc: vietnamFlag }, + Kristang: { language: 'Kristang', country: 'Singapore', flagSrc: singaporeFlag }, + Moken: { language: 'Moken', country: 'Myanmar', flagSrc: myanmarFlag }, +}; + export const resolveLearningLanguage = (value: string | null | undefined): LearningLanguage => { const matched = LEARNING_LANGUAGE_OPTIONS.find((language) => language === value); return matched ?? DEFAULT_LEARNING_LANGUAGE; }; + +export const getLearningLanguageMetadata = ( + value: string | null | undefined, +): LearningLanguageMetadata => LEARNING_LANGUAGE_METADATA[resolveLearningLanguage(value)]; diff --git a/src/lib/storage.ts b/src/lib/storage.ts index f7395d9..5e28452 100644 --- a/src/lib/storage.ts +++ b/src/lib/storage.ts @@ -9,6 +9,7 @@ export const STORAGE_KEYS = { PENDING_SYNC: 'pending-sync', SETTINGS: 'settings', STREAK: 'streak', + STORY_PROGRESS: 'story-progress', AUTH_TRANSIENT_SESSION: 'auth-transient-session', } as const; diff --git a/src/lib/storyProgress.test.ts b/src/lib/storyProgress.test.ts new file mode 100644 index 0000000..0089a1b --- /dev/null +++ b/src/lib/storyProgress.test.ts @@ -0,0 +1,108 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Story } from './storyData'; +import { + applyStoryProgress, + getLastReadStory, + saveStoryProgress, + type StoryProgressEntry, +} from './storyProgress'; + +vi.mock('@capacitor/preferences', () => { + const store = new Map(); + return { + Preferences: { + get: vi.fn(async ({ key }: { key: string }) => ({ value: store.get(key) ?? null })), + set: vi.fn(async ({ key, value }: { key: string; value: string }) => { + store.set(key, value); + }), + remove: vi.fn(async ({ key }: { key: string }) => { + store.delete(key); + }), + __store: store, + }, + }; +}); + +const story: Story = { + id: 'kancil', + title: 'Kancil & Buaya', + author: 'Cerite Rakyat', + cover: '/cover.png', + bg: '/bg.png', + duration: '15 min', + pages: 8, + genre: 'Fable', + synopsis: 'A story', + lastChapter: 'Satu Cerite', + lastPage: 0, + totalPages: 8, + progress: 0, + scenes: Array.from({ length: 8 }, (_, index) => ({ + image: `/scene-${index}.png`, + text: `Scene ${index + 1}`, + })), +}; + +describe('storyProgress', () => { + beforeEach(async () => { + const { Preferences } = await import('@capacitor/preferences'); + (Preferences as unknown as { __store: Map }).__store.clear(); + }); + + it('saves scene position as percentage progress', async () => { + const progress = await saveStoryProgress(story, 3); + + expect(progress).toMatchObject({ + storyId: 'kancil', + currentScene: 3, + lastPage: 4, + totalPages: 8, + progress: 50, + }); + }); + + it('applies stored progress without using catalog placeholder values', () => { + const progress: StoryProgressEntry = { + storyId: 'kancil', + currentScene: 4, + totalScenes: 8, + lastPage: 5, + totalPages: 8, + progress: 63, + lastChapter: 'Satu Cerite', + updatedAt: '2026-05-10T01:00:00.000Z', + }; + + expect(applyStoryProgress({ ...story, progress: 99 }, progress)).toMatchObject({ + progress: 63, + lastPage: 5, + totalPages: 8, + }); + }); + + it('selects the most recently updated story as last read', () => { + const older = { + storyId: 'kancil', + currentScene: 0, + totalScenes: 8, + lastPage: 1, + totalPages: 8, + progress: 13, + lastChapter: 'Satu Cerite', + updatedAt: '2026-05-10T01:00:00.000Z', + }; + const newer = { + ...older, + storyId: 'sunbe', + updatedAt: '2026-05-10T02:00:00.000Z', + }; + + expect( + getLastReadStory([{ ...story, id: 'sunbe', title: 'Sunbe & Fenyi' }, story], { + kancil: older, + sunbe: newer, + })?.id, + ).toBe('sunbe'); + }); +}); diff --git a/src/lib/storyProgress.ts b/src/lib/storyProgress.ts new file mode 100644 index 0000000..0d6d629 --- /dev/null +++ b/src/lib/storyProgress.ts @@ -0,0 +1,84 @@ +import { getJSON, setJSON, STORAGE_KEYS } from './storage'; +import type { Story } from './storyData'; + +export interface StoryProgressEntry { + storyId: string; + currentScene: number; + totalScenes: number; + progress: number; + lastPage: number; + totalPages: number; + lastChapter: string; + updatedAt: string; +} + +type StoryProgressMap = Record; + +const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)); + +const getTotalScenes = (story: Story) => Math.max(1, story.scenes?.length ?? story.totalPages); + +export const getStoryProgress = async (): Promise => + getJSON(STORAGE_KEYS.STORY_PROGRESS, {}); + +export const getStoryProgressEntry = async ( + storyId: string, +): Promise => { + const progress = await getStoryProgress(); + return progress[storyId] ?? null; +}; + +export const saveStoryProgress = async ( + story: Story, + currentScene: number, +): Promise => { + const totalScenes = getTotalScenes(story); + const sceneIndex = clamp(currentScene, 0, totalScenes - 1); + const lastPage = sceneIndex + 1; + const entry: StoryProgressEntry = { + storyId: story.id, + currentScene: sceneIndex, + totalScenes, + progress: Math.round((lastPage / totalScenes) * 100), + lastPage, + totalPages: totalScenes, + lastChapter: story.lastChapter || 'Scene 1', + updatedAt: new Date().toISOString(), + }; + const progress = await getStoryProgress(); + await setJSON(STORAGE_KEYS.STORY_PROGRESS, { ...progress, [story.id]: entry }); + return entry; +}; + +export const applyStoryProgress = ( + story: Story, + progressEntry: StoryProgressEntry | null | undefined, +): Story => { + if (!progressEntry || progressEntry.storyId !== story.id) { + return { ...story, progress: 0, lastPage: 0 }; + } + + const totalPages = getTotalScenes(story); + const lastPage = clamp(progressEntry.lastPage, 1, totalPages); + return { + ...story, + lastChapter: progressEntry.lastChapter, + lastPage, + totalPages, + progress: clamp(progressEntry.progress, 0, 100), + }; +}; + +export const getLastReadStory = (stories: Story[], progress: StoryProgressMap): Story | null => { + const storyById = new Map(stories.map((story) => [story.id, story])); + const latest = Object.values(progress) + .filter((entry) => storyById.has(entry.storyId)) + .sort((first, second) => second.updatedAt.localeCompare(first.updatedAt))[0]; + + if (!latest) { + return null; + } + + const story = storyById.get(latest.storyId); + return story ? applyStoryProgress(story, latest) : null; +}; diff --git a/src/navigation/AppRouter.tsx b/src/navigation/AppRouter.tsx index 0e0744b..6879d10 100644 --- a/src/navigation/AppRouter.tsx +++ b/src/navigation/AppRouter.tsx @@ -5,6 +5,7 @@ import { Capacitor } from '@capacitor/core'; import { SplashScreen } from '@capacitor/splash-screen'; import { AppSplashScreen } from '../components/ui'; +import { withTimeout } from '../lib/asyncTimeout'; import { fetchOnboardingStatus } from '../lib/profile'; import { useAuthStore } from '../stores/authStore'; import { AuthPage } from '../pages/AuthPage'; @@ -112,13 +113,18 @@ export function AppRouter() { completed: current.completed, })); - void fetchOnboardingStatus({ - userId: session.user.id, - fallbackRole: - session.user.user_metadata?.role === 'elder' || session.user.user_metadata?.role === 'admin' - ? session.user.user_metadata.role - : 'learner', - }) + void withTimeout( + fetchOnboardingStatus({ + userId: session.user.id, + fallbackRole: + session.user.user_metadata?.role === 'elder' || + session.user.user_metadata?.role === 'admin' + ? session.user.user_metadata.role + : 'learner', + }), + 8000, + 'Timed out while resolving onboarding status.', + ) .then((status) => { if (!cancelled) { setOnboardingState({ isLoading: false, completed: status.completed }); diff --git a/src/pages/AiHelperPage.css b/src/pages/AiHelperPage.css index 8aa53b7..d3c7bf9 100644 --- a/src/pages/AiHelperPage.css +++ b/src/pages/AiHelperPage.css @@ -286,6 +286,7 @@ } .tavi-thread-drawer-backdrop { + animation: tavi-backdrop-in 180ms cubic-bezier(0.22, 1, 0.36, 1) both; background: rgba(26, 26, 26, 0.22); border: 0; cursor: pointer; @@ -295,6 +296,7 @@ } .tavi-thread-panel { + animation: tavi-drawer-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both; background: #fff9e9; border-left: 1px solid rgba(203, 64, 60, 0.16); bottom: 0; @@ -309,6 +311,28 @@ width: 100%; } +@keyframes tavi-backdrop-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes tavi-drawer-in { + from { + opacity: 0.86; + transform: translateX(18px); + } + + to { + opacity: 1; + transform: translateX(0); + } +} + .tavi-thread-panel-header { align-items: flex-start; display: flex; @@ -398,6 +422,10 @@ padding: 10px; } +.tavi-thread-item--skeleton { + pointer-events: none; +} + .tavi-thread-item.is-active { background: rgba(203, 64, 60, 0.1); border-color: rgba(203, 64, 60, 0.36); @@ -451,10 +479,38 @@ } .tavi-chat-history-loading { - align-items: center; + display: grid; + gap: 12px; + padding: 24px 0 8px; +} + +.tavi-chat-skeleton-row { + align-items: flex-end; display: flex; - justify-content: center; - min-height: 180px; + gap: 8px; +} + +.tavi-chat-skeleton-row--user { + justify-content: flex-end; +} + +.tavi-chat-skeleton-bubble { + display: grid; + gap: 8px; + max-width: 72%; + padding: 14px; +} + +.tavi-chat-skeleton-bubble--tavi { + background: #f5c0be; + border-radius: 18px 18px 18px 4px; + width: min(250px, 72%); +} + +.tavi-chat-skeleton-bubble--user { + background: #cb403c; + border-radius: 18px 18px 4px; + width: min(190px, 62%); } .tavi-chat-greeting-title { @@ -490,11 +546,24 @@ } .tavi-bubble-row { + animation: tavi-message-enter 170ms cubic-bezier(0.22, 1, 0.36, 1) both; display: flex; gap: 8px; margin-bottom: 12px; } +@keyframes tavi-message-enter { + from { + opacity: 0; + transform: translateY(5px) scale(0.99); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + .tavi-bubble-row--user { flex-direction: row-reverse; } @@ -754,40 +823,10 @@ } .tavi-bubble-loading { - align-items: center; - display: flex; - gap: 5px; - height: 20px; - padding: 2px 4px; -} - -.tavi-bubble-loading span { - animation: tavi-dot-bounce 1.2s ease-in-out infinite; - background: #b0a99f; - border-radius: 50%; - display: block; - height: 7px; - width: 7px; -} - -.tavi-bubble-loading span:nth-child(2) { - animation-delay: 0.18s; -} -.tavi-bubble-loading span:nth-child(3) { - animation-delay: 0.36s; -} - -@keyframes tavi-dot-bounce { - 0%, - 80%, - 100% { - transform: translateY(0); - opacity: 0.4; - } - 40% { - transform: translateY(-6px); - opacity: 1; - } + display: grid; + gap: 8px; + min-width: 172px; + padding: 3px 0; } .tavi-chat-inputbar { @@ -1028,3 +1067,13 @@ .tavi-chat-inputbar-send:not(:disabled):active { transform: scale(0.9); } + +@media (prefers-reduced-motion: reduce) { + .tavi-intro-mascot, + .tavi-intro-aura, + .tavi-thread-drawer-backdrop, + .tavi-thread-panel, + .tavi-bubble-row { + animation: none; + } +} diff --git a/src/pages/AiHelperPage.tsx b/src/pages/AiHelperPage.tsx index 42d7037..1139f74 100644 --- a/src/pages/AiHelperPage.tsx +++ b/src/pages/AiHelperPage.tsx @@ -1,4 +1,4 @@ -import { IonAlert, IonSpinner, IonToast } from '@ionic/react'; +import { IonAlert, IonToast } from '@ionic/react'; import type { CSSProperties, ReactNode } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; @@ -31,6 +31,7 @@ import { } from '../lib/taviThreads'; import { useEdgeSwipeBack } from '../lib/useEdgeSwipeBack'; import { useAuthStore } from '../stores/authStore'; +import { AppSkeleton } from '../components/ui'; import './AiHelperPage.css'; @@ -333,10 +334,9 @@ function ChatBubble({ {message.loading ? ( - - - - + + + ) : ( @@ -437,7 +437,7 @@ function ThreadDrawer({ History - x + × @@ -446,7 +446,18 @@ function ThreadDrawer({ - {isLoading ? Loading chats... : null} + {isLoading + ? Array.from({ length: 4 }).map((_, index) => ( + + + + + + + + + )) + : null} {!isLoading && threads.length === 0 ? ( No saved chats yet. ) : null} @@ -479,6 +490,33 @@ function ThreadDrawer({ ); } +function TaviChatSkeleton() { + return ( + + + + + + + + + + + + + + + + + + + + + + + ); +} + export function AiHelperPage() { const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); @@ -1289,11 +1327,7 @@ export function AiHelperPage() { onDidDismiss={() => setThreadPendingRename(null)} /> - {isThreadLoading && messages.length === 0 ? ( - - - - ) : null} + {isThreadLoading && messages.length === 0 ? : null} {!isThreadLoading && messages.length === 0 ? ( @@ -1406,7 +1440,7 @@ export function AiHelperPage() { aria-label="Send message" > {isSending ? ( - + ) : ( { + const { findSemaiDictionaryHints } = await import('../lib/semaiDictionary'); const nextHints = await Promise.all( reviewPagination.items.map(async (recording) => { const transcript = @@ -966,7 +967,7 @@ export function ArchiveReviewPage() { } > {loadingPlaybackRecordingId === recording.id ? ( - 'Loading...' + ) : ( <> - {loading - ? isSignUp - ? 'Creating account...' - : 'Logging in...' - : isSignUp - ? 'Get Started' - : 'Log In'} + {loading ? ( + + ) : isSignUp ? ( + 'Get Started' + ) : ( + 'Log In' + )} diff --git a/src/pages/ElderStudioTab.tsx b/src/pages/ElderStudioTab.tsx index 8c99091..d85c8fc 100644 --- a/src/pages/ElderStudioTab.tsx +++ b/src/pages/ElderStudioTab.tsx @@ -1,4 +1,4 @@ -import { IonIcon, IonSpinner, IonToast } from '@ionic/react'; +import { IonIcon, IonToast } from '@ionic/react'; import { addOutline, arrowBackOutline, @@ -26,6 +26,7 @@ import { } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; +import { AppSkeleton } from '../components/ui'; import { countPendingStudioReview, doesStudioRecordingNeedReview, @@ -1004,7 +1005,7 @@ export function ElderStudioTab() { Studio {isSyncing ? ( - + ) : ( )} @@ -1364,8 +1365,8 @@ export function ElderStudioTab() { > {isSaving ? ( <> - - Saving... + + > ) : ( 'Save to Archive' diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx index d876314..7425c37 100644 --- a/src/pages/HomePage.tsx +++ b/src/pages/HomePage.tsx @@ -375,6 +375,7 @@ function isLearnerOnlyRoute(pathname: string): boolean { function resolveLearnerTab(pathname: string): LearnerTab | null { if (pathname.startsWith('/home/landing')) return 'home'; if (pathname.startsWith('/home/garden')) return 'garden'; + if (pathname.startsWith('/home/translation')) return null; if (pathname.startsWith('/home/stories')) return 'story'; if (pathname.startsWith('/home/archive')) return null; if (pathname.startsWith('/home/ai')) return 'ai'; @@ -435,7 +436,6 @@ export function HomePage() { new URLSearchParams(location.search).get('chat') === '1'; const shouldShowTabMenu = - !isTranslateRoute && !location.pathname.startsWith('/home/profile/') && !isQuizRoute && !isStoryDetailRoute && diff --git a/src/pages/LandingPage.css b/src/pages/LandingPage.css index 74e5d80..5a5ddcb 100644 --- a/src/pages/LandingPage.css +++ b/src/pages/LandingPage.css @@ -98,7 +98,7 @@ justify-items: center; } -.landing-hero img { +.landing-hero > img { height: 110%; left: 0; max-width: none; @@ -143,21 +143,23 @@ pointer-events: auto; position: absolute; right: calc(var(--safe-area-right) + 24px); - top: calc(var(--safe-area-top) + 35px); + top: calc(var(--safe-area-top) + 30px); z-index: 3; } @media (max-width: 374px) { .landing-hero-greeting { - right: calc(var(--safe-area-right) + 150px); + left: calc(var(--safe-area-left) + 18px); } .landing-hero-greeting span { - font-size: 29px; + font-size: 27px; } .landing-learning-language-badge { right: calc(var(--safe-area-right) + 18px); + top: calc(var(--safe-area-top) + 28px); + width: 142px; } } @@ -287,6 +289,7 @@ } .landing-last-read-cover { + background: linear-gradient(135deg, rgba(175, 126, 167, 0.22), rgba(203, 64, 60, 0.18)); border-radius: 10px; flex-shrink: 0; height: 88px; @@ -405,6 +408,7 @@ } .landing-book-cover { + background: linear-gradient(135deg, rgba(175, 126, 167, 0.22), rgba(203, 64, 60, 0.18)); border-radius: 8px; height: 96px; overflow: hidden; @@ -715,6 +719,7 @@ .landing-action-card { align-items: stretch; + background: linear-gradient(135deg, #a8c85b 0%, #cfe590 100%); border: none; border-radius: 20px; cursor: pointer; @@ -730,6 +735,30 @@ box-shadow 120ms ease; } +.landing-action-card:nth-child(2) { + background: linear-gradient(135deg, #78aee8 0%, #a9cfef 100%); +} + +.landing-action-card:nth-child(3) { + background: linear-gradient(135deg, #d196b7 0%, #f2c7d6 100%); +} + +.landing-action-card-fallback { + align-items: center; + color: rgba(54, 38, 24, 0.72); + display: flex; + font-size: 26px; + font-weight: 800; + inset: 0; + justify-content: center; + letter-spacing: 0; + line-height: 1; + padding: 18px; + position: absolute; + text-align: center; + z-index: 0; +} + .landing-action-card:active { transform: scale(0.97); } @@ -739,7 +768,9 @@ height: 100%; object-fit: cover; pointer-events: none; + position: relative; width: 100%; + z-index: 1; } @media (min-width: 768px) { diff --git a/src/pages/LandingPage.tsx b/src/pages/LandingPage.tsx index edddb22..a5d61e1 100644 --- a/src/pages/LandingPage.tsx +++ b/src/pages/LandingPage.tsx @@ -3,11 +3,13 @@ import { useNavigate } from 'react-router-dom'; import { AppSkeleton } from '../components/ui'; import { LearningLanguageBadge } from '../components/LearningLanguageBadge'; +import { withTimeout } from '../lib/asyncTimeout'; import { triggerHapticFeedback } from '../lib/feedback'; import { DEFAULT_LEARNING_LANGUAGE, resolveLearningLanguage } from '../lib/learningLanguages'; import { addExploreEntry } from '../lib/navigationEntry'; import { fetchProfileDashboard } from '../lib/profile'; -import { STORIES } from '../lib/storyData'; +import { STORIES, type Story } from '../lib/storyData'; +import { getLastReadStory, getStoryProgress, type StoryProgressEntry } from '../lib/storyProgress'; import { useAuthStore } from '../stores/authStore'; import aiTaviCardImg from '../../assets/home-revised/ai-tavi.png'; @@ -76,9 +78,6 @@ const BOOKS = STORIES.slice(0, 4).map((story) => ({ img: story.cover, })); -const FEATURED_STORY = - [...STORIES].sort((first, second) => second.progress - first.progress)[0] ?? STORIES[0]; - function LandingPageSkeleton({ isElder }: { isElder: boolean }) { return ( @@ -234,6 +233,9 @@ function ExploreTalekaCards({ onNavigate }: { onNavigate: (href: string) => void className="landing-action-card" onClick={() => onNavigate(addExploreEntry('/home/garden'))} > + + Garden + @@ -242,6 +244,9 @@ function ExploreTalekaCards({ onNavigate }: { onNavigate: (href: string) => void className="landing-action-card" onClick={() => onNavigate(addExploreEntry('/home/ai'))} > + + AI Helper + @@ -250,6 +255,9 @@ function ExploreTalekaCards({ onNavigate }: { onNavigate: (href: string) => void className="landing-action-card" onClick={() => onNavigate(addExploreEntry('/home/translation'))} > + + Translate + @@ -262,17 +270,21 @@ function ExploreTalekaCards({ onNavigate }: { onNavigate: (href: string) => void function LearnerLanding({ firstName, onNavigate, + onOpenLanguageSettings, learningLanguage, leaderName, leaderAvatarSrc, leaderHasCustomPhoto, + lastReadStory, }: { firstName: string; onNavigate: (h: string) => void; + onOpenLanguageSettings: () => void; learningLanguage: string; leaderName: string; leaderAvatarSrc: string; leaderHasCustomPhoto: boolean; + lastReadStory: Story | null; }) { return ( @@ -286,7 +298,7 @@ function LearnerLanding({ language={learningLanguage} variant="home" className="landing-learning-language-badge" - onClick={() => onNavigate('/home/profile/settings/language')} + onClick={onOpenLanguageSettings} /> @@ -295,43 +307,41 @@ function LearnerLanding({ onNavigate('/home/ai')} + onClick={() => onNavigate('/home/stories?focusSearch=1')} aria-label="Search" > - What would you like to explore today? + Search stories by title or author - - Last Read - onNavigate(`/home/stories/${FEATURED_STORY.id}`)} - > - - - - - {FEATURED_STORY.title} - by {FEATURED_STORY.author} - - + {lastReadStory ? ( + + Last Read + onNavigate(`/home/stories/${lastReadStory.id}/read`)} + > + + - - {FEATURED_STORY.progress > 0 - ? `${FEATURED_STORY.progress}% complete` - : `${FEATURED_STORY.totalPages} pages ready`} - - Continue reading - - - + + {lastReadStory.title} + by {lastReadStory.author} + + + + {lastReadStory.progress}% complete + Continue reading + + + + ) : null} >({}); const meta = user?.user_metadata as Record | undefined; const fullName = meta?.full_name as string | undefined; @@ -454,10 +465,14 @@ export function LandingPage() { setIsProfileLoading(true); - void fetchProfileDashboard({ - userId: user.id, - fallbackRole: isElder ? 'elder' : 'learner', - }) + void withTimeout( + fetchProfileDashboard({ + userId: user.id, + fallbackRole: isElder ? 'elder' : 'learner', + }), + 8000, + 'Timed out while loading the landing profile.', + ) .then((dashboard) => { if (cancelled) return; @@ -484,25 +499,50 @@ export function LandingPage() { }; }, [firstName, isElder, meta?.avatar_url, meta?.full_name, user?.id]); + useEffect(() => { + let cancelled = false; + + void getStoryProgress().then((progress) => { + if (!cancelled) { + setStoryProgress(progress); + } + }); + + return () => { + cancelled = true; + }; + }, []); + const onNavigate = (href: string) => { triggerHapticFeedback('light'); navigate(href); }; + const openLanguageSettingsFromHome = () => { + triggerHapticFeedback('light'); + navigate('/home/profile/settings/language', { + state: { languageSettingsEntry: 'home' }, + }); + }; + if (isProfileLoading) { return ; } + const lastReadStory = getLastReadStory(STORIES, storyProgress); + return isElder ? ( ) : ( ); } diff --git a/src/pages/LanguageGardenTab.css b/src/pages/LanguageGardenTab.css index 25bd980..1ae87a0 100644 --- a/src/pages/LanguageGardenTab.css +++ b/src/pages/LanguageGardenTab.css @@ -85,13 +85,16 @@ } .garden-card { + aspect-ratio: 345 / 124; background: transparent; border: none; border-radius: 18px; cursor: pointer; display: block; + min-height: 118px; overflow: hidden; padding: 0; + position: relative; transition: transform 120ms ease, box-shadow 120ms ease; @@ -99,6 +102,38 @@ -webkit-tap-highlight-color: transparent; } +.garden-card-fallback { + align-items: center; + background: + radial-gradient(circle at 18% 42%, rgba(255, 255, 255, 0.28) 0 24%, transparent 25%), + linear-gradient(135deg, #a8c85b 0%, #c6df7d 100%); + border-radius: inherit; + color: rgba(54, 38, 24, 0.72); + display: flex; + font-size: 28px; + font-weight: 800; + inset: 0; + justify-content: center; + letter-spacing: 0; + line-height: 1; + padding: 20px; + position: absolute; + text-align: center; + z-index: 0; +} + +.garden-cards li:nth-child(2) .garden-card-fallback { + background: + radial-gradient(circle at 18% 42%, rgba(255, 255, 255, 0.24) 0 24%, transparent 25%), + linear-gradient(135deg, #ad82b6 0%, #d3a0ce 100%); +} + +.garden-cards li:nth-child(3) .garden-card-fallback { + background: + radial-gradient(circle at 18% 42%, rgba(255, 255, 255, 0.22) 0 24%, transparent 25%), + linear-gradient(135deg, #4e9add 0%, #7eb6e2 100%); +} + .garden-card:active { box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transform: scale(0.97); @@ -106,12 +141,15 @@ .garden-card-image { border-radius: 20px; - display: flex; - height: auto; + display: block; + height: 100%; + inset: 0; object-fit: cover; pointer-events: none; + position: absolute; user-select: none; width: 100%; + z-index: 1; } /* ─── Background Illustration ───────────────────────────────────────────────── */ @@ -162,11 +200,11 @@ .garden-card { height: 100%; + min-height: 180px; } .garden-card-image { height: 100%; - min-height: 180px; } .garden-bg-illustration { diff --git a/src/pages/LanguageGardenTab.tsx b/src/pages/LanguageGardenTab.tsx index fec7114..c2b6c00 100644 --- a/src/pages/LanguageGardenTab.tsx +++ b/src/pages/LanguageGardenTab.tsx @@ -97,6 +97,9 @@ export function LanguageGardenTab() { onClick={() => handleCardTap(card.id)} aria-label={`Play ${card.label}`} > + + {card.label} + span { - color: #604828; - font-size: 14px; - line-height: 1; +.profile-learning-language-flag img { + border-radius: 999px; + display: block; + height: 100%; + object-fit: cover; + width: 100%; } -.profile-learning-language-right { - align-items: center; - display: inline-flex; - gap: 4px; - justify-content: flex-end; +.profile-learning-language-copy { + display: grid; + gap: 2px; min-width: 0; + text-align: left; } -.profile-learning-language-right strong { - color: #604828; - font-size: 14px; - font-weight: 700; - line-height: 1; - max-width: 110px; +.profile-learning-language-copy strong, +.profile-learning-language-copy span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.profile-learning-language-copy strong { + color: #604828; + font-size: 15px; + font-weight: 800; + line-height: 1.22; +} + +.profile-learning-language-copy span { + color: rgba(96, 72, 40, 0.66); + font-size: 12px; + font-weight: 600; + line-height: 1.24; +} + .profile-menu-icon { flex-shrink: 0; height: 16px; @@ -544,11 +667,6 @@ width: 15px; } -.profile-menu-item.profile-learning-language-row .profile-learning-language-icon { - height: 15px; - width: 15px; -} - .profile-menu-chevron { flex-shrink: 0; height: 19.352px; @@ -1028,10 +1146,6 @@ } @media (prefers-reduced-motion: reduce) { - .profile-loading-shimmer::after { - animation: none; - } - .profile-screen-enter { animation: none; } diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx index 8f4e267..d33ec85 100644 --- a/src/pages/ProfilePage.tsx +++ b/src/pages/ProfilePage.tsx @@ -1,4 +1,5 @@ import { IonButton, IonToast } from '@ionic/react'; +import type { User } from '@supabase/supabase-js'; import { useCallback, useEffect, @@ -11,8 +12,9 @@ import { import { Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; import { updatePassword } from '../lib/auth'; +import { withTimeout } from '../lib/asyncTimeout'; import { triggerHapticFeedback } from '../lib/feedback'; -import { LEARNING_LANGUAGE_OPTIONS } from '../lib/learningLanguages'; +import { getLearningLanguageMetadata, LEARNING_LANGUAGE_OPTIONS } from '../lib/learningLanguages'; import { fetchProfileDashboard, type ProfileDashboard, @@ -100,6 +102,10 @@ type ToastState = { color: 'danger' | 'success' | 'warning'; }; +type ProfileRouteState = { + languageSettingsEntry?: 'home'; +}; + type ProfileRole = ProfileDashboard['profile']['role']; type VisualRole = 'learner' | 'elder'; @@ -333,17 +339,38 @@ const BackButton = ({ onBack, tone = 'dark' }: BackButtonProps) => { ); }; -const ProfileLoadingSkeleton = () => ( - +type ProfileSkeletonVariant = 'overview' | 'edit' | 'settings' | 'password' | 'language' | 'info'; + +const resolveProfileSkeletonVariant = (pathname: string): ProfileSkeletonVariant => { + if (pathname.endsWith('/profile/edit')) return 'edit'; + if (pathname.endsWith('/profile/settings/password')) return 'password'; + if (pathname.endsWith('/profile/settings/language')) return 'language'; + if ( + pathname.endsWith('/profile/settings/about') || + pathname.endsWith('/profile/settings/privacy') + ) { + return 'info'; + } + if (pathname.endsWith('/profile/settings')) return 'settings'; + return 'overview'; +}; + +const ProfileLoadingSubHeader = ({ title }: { title: string }) => ( + + + + {title} + +); + +const ProfileOverviewLoadingSkeleton = () => ( + <> - + - - + + @@ -363,6 +390,81 @@ const ProfileLoadingSkeleton = () => ( ))} + > +); + +const ProfileEditLoadingSkeleton = () => ( + <> + + + + + + + {Array.from({ length: 4 }).map((_, index) => ( + + + + + ))} + + + > +); + +const ProfileSettingsLoadingSkeleton = () => ( + <> + + + + + + + {Array.from({ length: 5 }).map((_, index) => ( + + ))} + + + > +); + +const ProfileFormSubpageLoadingSkeleton = ({ title }: { title: string }) => ( + <> + + + {Array.from({ length: title === 'Change Language' ? 2 : 3 }).map((_, index) => ( + + + + + ))} + + + > +); + +const ProfileInfoLoadingSkeleton = () => ( + <> + + + {Array.from({ length: 5 }).map((_, index) => ( + + ))} + + > +); + +const ProfileLoadingSkeleton = ({ variant }: { variant: ProfileSkeletonVariant }) => ( + + {variant === 'overview' ? : null} + {variant === 'edit' ? : null} + {variant === 'settings' ? : null} + {variant === 'password' ? : null} + {variant === 'language' ? : null} + {variant === 'info' ? : null} ); @@ -384,6 +486,7 @@ const ProfileOverviewScreen = ({ onSignOut, isSigningOut, }: OverviewProps) => { + const learningLanguage = getLearningLanguageMetadata(dashboard.profile.indigenousLanguage); const roleLabel = toRoleLabel(dashboard.profile.role); const visualRole = toVisualRole(dashboard.profile.role); const statCards = getStatCards(dashboard); @@ -475,26 +578,23 @@ const ProfileOverviewScreen = ({ type="button" className="profile-menu-item profile-learning-language-row" onClick={onOpenChangeLanguage} - aria-label={`Learning language: ${dashboard.profile.indigenousLanguage}`} + aria-label={`Learning language: ${learningLanguage.language}, ${learningLanguage.country}`} > - - Learning language - - - {dashboard.profile.indigenousLanguage} - + + + + + Learning {learningLanguage.language} + Language from {learningLanguage.country} + + { return undefined; }; +const parseMetadataString = (metadata: Record | undefined, key: string) => { + const value = metadata?.[key]; + return typeof value === 'string' && value.trim() ? value.trim() : null; +}; + +const createFallbackDashboard = ({ + user, + fallbackRole, +}: { + user: User; + fallbackRole?: ProfileRole; +}): ProfileDashboard => { + const metadata = user.user_metadata as Record | undefined; + const role = fallbackRole ?? 'learner'; + const fullName = + parseMetadataString(metadata, 'full_name') ?? + parseMetadataString(metadata, 'name') ?? + user.email?.split('@')[0] ?? + 'Taleka User'; + const avatarUrl = + parseMetadataString(metadata, 'avatar_url') ?? parseMetadataString(metadata, 'picture'); + const metadataLearningLanguage = parseMetadataString(metadata, 'indigenous_language'); + const indigenousLanguage = LEARNING_LANGUAGE_OPTIONS.includes( + metadataLearningLanguage as (typeof LEARNING_LANGUAGE_OPTIONS)[number], + ) + ? metadataLearningLanguage! + : LEARNING_LANGUAGE_OPTIONS[0]; + + return { + profile: { + id: user.id, + fullName, + email: user.email ?? '', + role, + avatarUrl, + bio: null, + village: null, + age: null, + specialty: null, + appLanguage: APP_LANGUAGE_OPTIONS[0], + indigenousLanguage, + onboardingCompleted: true, + onboardingCompletedAt: null, + onboardingResponses: null, + pushNotificationsEnabled: true, + }, + level: { + label: 'Lv. Pending', + progressPercent: 0, + }, + stats: + role === 'elder' + ? { + wordsLearned: 0, + storiesCompleted: 0, + storiesShared: 0, + followerCount: 0, + followingCount: 0, + } + : { + wordsLearned: 0, + storiesCompleted: 0, + storiesShared: 0, + followerCount: 0, + followingCount: 0, + }, + }; +}; + export function ProfilePage() { const navigate = useNavigate(); const location = useLocation(); @@ -1129,6 +1298,15 @@ export function ProfilePage() { () => parseMetadataRole((user?.user_metadata as Record | undefined)?.role), [user?.user_metadata], ); + const profileRouteState = location.state as ProfileRouteState | null; + const languageSettingsReturnPath = + profileRouteState?.languageSettingsEntry === 'home' + ? '/home/landing' + : '/home/profile/settings'; + const loadingSkeletonVariant = useMemo( + () => resolveProfileSkeletonVariant(location.pathname), + [location.pathname], + ); const refreshProfile = useCallback(async () => { if (!user) { @@ -1140,14 +1318,20 @@ export function ProfilePage() { setIsLoading(true); try { - const nextDashboard = await fetchProfileDashboard({ - userId: user.id, - fallbackRole, - }); + const nextDashboard = await withTimeout( + fetchProfileDashboard({ + userId: user.id, + fallbackRole, + }), + 8000, + 'Timed out while loading your profile.', + ); setDashboard(nextDashboard); } catch (error) { - setDashboard(null); - setToast({ message: toAuthErrorMessage(error), color: 'danger' }); + setDashboard( + (currentDashboard) => currentDashboard ?? createFallbackDashboard({ user, fallbackRole }), + ); + setToast({ message: toAuthErrorMessage(error), color: 'warning' }); } finally { setIsLoading(false); } @@ -1207,7 +1391,7 @@ export function ProfilePage() { } if (isLoading && !dashboard) { - return ; + return ; } if (!dashboard) { @@ -1318,7 +1502,7 @@ export function ProfilePage() { dashboard={dashboard} onBack={() => { triggerHapticFeedback('light'); - navigate('/home/profile/settings'); + navigate(languageSettingsReturnPath); }} onSaved={async (appLanguage, indigenousLanguage) => { await updateProfilePreferences({ @@ -1328,7 +1512,7 @@ export function ProfilePage() { pushNotificationsEnabled: dashboard.profile.pushNotificationsEnabled, }); await refreshProfile(); - navigate('/home/profile/settings', { replace: true }); + navigate(languageSettingsReturnPath, { replace: true }); }} onToast={setToast} /> diff --git a/src/pages/ResetPasswordPage.tsx b/src/pages/ResetPasswordPage.tsx index e2c7bf3..c105671 100644 --- a/src/pages/ResetPasswordPage.tsx +++ b/src/pages/ResetPasswordPage.tsx @@ -10,6 +10,7 @@ import { supabase } from '../lib/supabase'; import { useAuthStore } from '../stores/authStore'; import { toAuthErrorMessage } from '../utils/authErrors'; import { validatePassword } from '../utils/authValidation'; +import { AppSkeleton } from '../components/ui'; import './AuthPage.css'; @@ -164,7 +165,11 @@ export function ResetPasswordPage() { - {isSubmitting ? 'Updating password...' : 'Update Password'} + {isSubmitting ? ( + + ) : ( + 'Update Password' + )} diff --git a/src/pages/SoundArchiveTab.tsx b/src/pages/SoundArchiveTab.tsx index 07b4c60..eab029e 100644 --- a/src/pages/SoundArchiveTab.tsx +++ b/src/pages/SoundArchiveTab.tsx @@ -1,4 +1,4 @@ -import { IonIcon, IonSpinner, IonToast } from '@ionic/react'; +import { IonIcon, IonToast } from '@ionic/react'; import { arrowBackOutline, cloudDoneOutline, @@ -500,7 +500,7 @@ export function SoundArchiveTab() { Sound Archive {isSyncing ? ( - + ) : ( )} @@ -623,7 +623,7 @@ export function SoundArchiveTab() { disabled={Boolean(loadingPlaybackRecordingId)} > {loadingPlaybackRecordingId === recording.id ? ( - 'Loading...' + ) : ( <> {isGeneratingCover || isGeneratingBg ? ( <> - - Generating… + + > ) : !generatedCoverUrl ? ( 'Generate Cover' @@ -783,8 +783,8 @@ export function SoundArchiveTab() { > {isPublishing ? ( <> - - Publishing… + + > ) : ( 'Publish Story' diff --git a/src/pages/StoryDetailPage.css b/src/pages/StoryDetailPage.css index 6e1ccc6..4acad15 100644 --- a/src/pages/StoryDetailPage.css +++ b/src/pages/StoryDetailPage.css @@ -31,6 +31,11 @@ display: block; } +.story-detail-hero-blur--skeleton { + background: #e0d4c4; + filter: blur(5px); +} + /* Gradient fade from hero into cream background */ .story-detail-hero-fade { position: absolute; @@ -113,6 +118,10 @@ display: block; } +.story-detail-cover--skeleton { + background: var(--app-skeleton-base); +} + .story-detail-cover-meta { position: relative; z-index: 1; @@ -204,6 +213,16 @@ box-shadow: 0 4px 4px rgba(0, 0, 0, 0.1); } +.story-detail-skeleton-centered { + margin: 0 auto 10px; +} + +.story-detail-skeleton-copy { + display: grid; + gap: 9px; + padding-top: 14px; +} + .story-detail-progress-chapter { display: block; font-family: 'Satoshi', sans-serif; diff --git a/src/pages/StoryDetailPage.tsx b/src/pages/StoryDetailPage.tsx index f1718e8..2ac4410 100644 --- a/src/pages/StoryDetailPage.tsx +++ b/src/pages/StoryDetailPage.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; +import { AppSkeleton } from '../components/ui'; import { triggerHapticFeedback } from '../lib/feedback'; import { PUBLISHED_STORY_SELECT, @@ -8,6 +9,7 @@ import { } from '../lib/publishedStory'; import { supabase } from '../lib/supabase'; import { STORIES, type Story } from '../lib/storyData'; +import { applyStoryProgress, getStoryProgressEntry } from '../lib/storyProgress'; import './StoryDetailPage.css'; @@ -68,6 +70,60 @@ function GenreIcon() { // ── Page ───────────────────────────────────────────────────────────────────── +function StoryDetailSkeleton({ onBack }: { onBack: () => void }) { + return ( + + + + + + + + + + + + + + + + + + {Array.from({ length: 3 }).map((_, index) => ( + + + + + ))} + + + + + + + + + + + + + + + + + + + + + + + ); +} + export function StoryDetailPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); @@ -75,6 +131,7 @@ export function StoryDetailPage() { const staticStory = STORIES.find((s) => s.id === id); const [story, setStory] = useState(staticStory ?? null); const [isLoading, setIsLoading] = useState(!staticStory); + const storyId = story?.id; useEffect(() => { if (staticStory || !id) return; @@ -102,15 +159,27 @@ export function StoryDetailPage() { })(); }, [id, staticStory]); + useEffect(() => { + if (!storyId) return; + let cancelled = false; + + void getStoryProgressEntry(storyId).then((progress) => { + if (!cancelled) { + setStory((currentStory) => + currentStory && currentStory.id === storyId + ? applyStoryProgress(currentStory, progress) + : currentStory, + ); + } + }); + + return () => { + cancelled = true; + }; + }, [storyId]); + if (isLoading) { - return ( - - navigate(-1)}> - - - Loading… - - ); + return navigate(-1)} />; } if (!story) { diff --git a/src/pages/StoryPage.css b/src/pages/StoryPage.css index d278311..8072e03 100644 --- a/src/pages/StoryPage.css +++ b/src/pages/StoryPage.css @@ -160,6 +160,7 @@ } .story-card-cover { + background: linear-gradient(135deg, rgba(175, 126, 167, 0.2), rgba(203, 64, 60, 0.16)); width: 100%; aspect-ratio: 2 / 3; border-radius: 8px; diff --git a/src/pages/StoryPage.tsx b/src/pages/StoryPage.tsx index afef7d6..2e55476 100644 --- a/src/pages/StoryPage.tsx +++ b/src/pages/StoryPage.tsx @@ -1,5 +1,5 @@ -import { useEffect, useState } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { useEffect, useRef, useState } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; import { triggerHapticFeedback } from '../lib/feedback'; import { PUBLISHED_STORY_SELECT, @@ -24,6 +24,8 @@ function SearchIcon() { export function StoryPage() { const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const searchInputRef = useRef(null); const [query, setQuery] = useState(''); const [publishedStories, setPublishedStories] = useState([]); const [publishedStoryError, setPublishedStoryError] = useState(null); @@ -50,6 +52,11 @@ export function StoryPage() { }); }, []); + useEffect(() => { + if (searchParams.get('focusSearch') !== '1') return; + window.requestAnimationFrame(() => searchInputRef.current?.focus()); + }, [searchParams]); + const allStories = [...STORIES, ...publishedStories]; const filtered = allStories.filter( @@ -76,6 +83,7 @@ export function StoryPage() { void }) { + return ( + + + + + + + + + + + + + + + + + + + + + + + + ); +} + export function StoryReadPage() { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); @@ -107,6 +137,8 @@ export function StoryReadPage() { const staticStory = STORIES.find((s) => s.id === id); const [story, setStory] = useState(staticStory ?? null); const [isLoading, setIsLoading] = useState(!staticStory); + const [currentScene, setCurrentScene] = useState(0); + const [hasLoadedProgress, setHasLoadedProgress] = useState(false); useEffect(() => { if (staticStory || !id) return; @@ -134,7 +166,34 @@ export function StoryReadPage() { })(); }, [id, staticStory]); - const [currentScene, setCurrentScene] = useState(0); + useEffect(() => { + if (!story) return; + let cancelled = false; + setHasLoadedProgress(false); + + void getStoryProgressEntry(story.id).then((progress) => { + if (cancelled) return; + + if (progress) { + setCurrentScene( + Math.min(progress.currentScene, Math.max(0, (story.scenes?.length ?? 1) - 1)), + ); + } else { + setCurrentScene(0); + } + + setHasLoadedProgress(true); + }); + + return () => { + cancelled = true; + }; + }, [story]); + + useEffect(() => { + if (!story || !hasLoadedProgress) return; + void saveStoryProgress(story, currentScene); + }, [currentScene, hasLoadedProgress, story]); // Touch swipe state const touchStartX = useRef(null); @@ -153,14 +212,7 @@ export function StoryReadPage() { }, [currentScene, story]); if (isLoading) { - return ( - - navigate(-1)} className="story-read-back-btn"> - - - Loading… - - ); + return navigate(-1)} />; } if (!story || !story.scenes || story.scenes.length === 0) { diff --git a/src/pages/TranslatePage.css b/src/pages/TranslatePage.css index 8560aa4..ff7c227 100644 --- a/src/pages/TranslatePage.css +++ b/src/pages/TranslatePage.css @@ -71,7 +71,7 @@ .translate-panel { margin: 24px auto 0; max-width: 354px; - padding: 0 7px calc(var(--safe-area-bottom) + 28px); + padding: 0 7px calc(var(--safe-area-bottom) + 128px); } .translate-card { diff --git a/src/pages/VocabMaster.css b/src/pages/VocabMaster.css index 70f7cb5..4647f40 100644 --- a/src/pages/VocabMaster.css +++ b/src/pages/VocabMaster.css @@ -165,12 +165,13 @@ /* ─── Deck area ───────────────────────────────────────────────────────────── */ -/* Vertical column — card4 at top, card1 front at bottom */ .vocab-deck-area { align-items: center; display: flex; - flex-direction: column; - padding: 64px 0 8px; + height: 404px; + justify-content: center; + overflow: visible; + padding: 0; position: relative; } @@ -220,96 +221,107 @@ /* ─── Stacked background cards ────────────────────────────────────────────── */ -/* Each back card shows only its top edge peeking above the card in front */ .vocab-card-stack { + background: + linear-gradient(135deg, rgba(255, 255, 255, 0.18), rgba(255, 255, 255, 0)), + linear-gradient(135deg, #d79ed1 0%, #e76573 100%); border-radius: 20px; - flex-shrink: 0; + height: 237px; + left: 50%; overflow: hidden; - will-change: transform, width, height, margin-bottom; + position: absolute; + transform-origin: center center; + width: 267px; + will-change: top, transform, opacity; transition: - transform 380ms cubic-bezier(0.22, 1, 0.36, 1), - width 380ms cubic-bezier(0.22, 1, 0.36, 1), - height 380ms cubic-bezier(0.22, 1, 0.36, 1), - margin-bottom 380ms cubic-bezier(0.22, 1, 0.36, 1), - box-shadow 380ms cubic-bezier(0.22, 1, 0.36, 1); + top 420ms cubic-bezier(0.22, 1, 0.36, 1), + transform 420ms cubic-bezier(0.22, 1, 0.36, 1), + opacity 260ms ease; +} + +.vocab-card-stack::after { + background-image: + linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px), + linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px); + background-size: 28px 28px; + border-radius: inherit; + content: ''; + inset: 0; + opacity: 0.16; + position: absolute; +} + +.vocab-card-stack .vocab-card-bg { + display: none; +} + +.vocab-card-stack.is-resetting { + transition: none !important; } -/* card4 — furthest back, topmost */ .vocab-card-stack--back3 { - box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); - opacity: 0.74; - transform: translateX(-7px); + box-shadow: 0 8px 20px rgba(96, 72, 40, 0.08); + opacity: 0.2; + top: 66px; + transform: translateX(-50%) scale(0.62) rotate(-0.5deg); z-index: 0; - height: 202px; - width: 228px; - margin-bottom: -174px; /* 202 - 28px peek */ } -/* back3 steps into back2's slot */ + .vocab-card-stack--back3.is-promoting { - opacity: 0.84; - height: 216px; - width: 244px; - transform: translateX(-4px) translateY(18px); - margin-bottom: -188px; + opacity: 0.34; + top: 94px; + transform: translateX(-50%) scale(0.7) rotate(0.3deg); } -/* card3 */ .vocab-card-stack--back2 { - box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); - opacity: 0.86; - transform: translateX(-4px); + box-shadow: 0 10px 24px rgba(96, 72, 40, 0.1); + opacity: 0.34; + top: 94px; + transform: translateX(-50%) scale(0.7) rotate(0.3deg); z-index: 1; - height: 216px; - width: 244px; - margin-bottom: -188px; /* 216 - 28px peek */ } -/* back2 steps into back1's slot */ + .vocab-card-stack--back2.is-promoting { - opacity: 0.94; - height: 228px; - width: 258px; - transform: translateX(-2px) translateY(18px); - margin-bottom: -200px; + opacity: 0.5; + top: 122px; + transform: translateX(-50%) scale(0.78) rotate(-0.15deg); } -/* card2 */ .vocab-card-stack--back1 { - box-shadow: 0 6px 20px rgba(0, 0, 0, 0.14); - opacity: 0.94; - transform: translateX(-2px); + box-shadow: 0 12px 28px rgba(96, 72, 40, 0.12); + opacity: 0; + top: 122px; + transform: translateX(-50%) scale(0.78) rotate(-0.15deg); z-index: 2; - width: 258px; - height: 228px; - margin-bottom: -200px; /* 228 - 28px peek */ } -/* back1 steps into the front position */ + .vocab-card-stack--back1.is-promoting { - box-shadow: 0 16px 34px rgba(0, 0, 0, 0.18); - height: 237px; - margin-bottom: -209px; + box-shadow: 0 18px 36px rgba(96, 72, 40, 0.17); opacity: 1; - transform: translateX(0px) translateY(18px) scale(1.02); - width: 267px; + top: 146px; + transform: translateX(-50%) scale(1) rotate(4.277deg); z-index: 4; } /* ─── Front card (flipper) ────────────────────────────────────────────────── */ .vocab-card-flipper { - transform: translateX(-6px); cursor: pointer; - flex-shrink: 0; + height: 237px; + left: 50%; perspective: 1000px; - position: relative; + position: absolute; + top: 146px; + transform: translateX(-50%) rotate(4.277deg); + transform-origin: center center; + transform-style: preserve-3d; transition: transform 220ms ease, opacity 300ms ease; touch-action: pan-y; user-select: none; - z-index: 3; width: 267px; - height: 237px; - will-change: transform, opacity; + z-index: 5; will-change: transform, opacity; } @@ -332,6 +344,7 @@ /* ─── Card faces ──────────────────────────────────────────────────────────── */ .vocab-card-face { + -webkit-backface-visibility: hidden; backface-visibility: hidden; border-radius: 20px; bottom: 0; @@ -345,19 +358,29 @@ } .vocab-card-face--front { + opacity: 1; transform: rotateY(0deg); + visibility: visible; z-index: 2; } .vocab-card-face--back { + opacity: 0; + pointer-events: none; transform: rotateY(180deg); + visibility: hidden; z-index: 1; } .vocab-card-flipper.is-flipped .vocab-card-face--front { + opacity: 0; transform: rotateY(-180deg); + visibility: hidden; } .vocab-card-flipper.is-flipped .vocab-card-face--back { + opacity: 1; + pointer-events: auto; transform: rotateY(0deg); + visibility: visible; } /* ─── Card bg image ───────────────────────────────────────────────────────── */ @@ -371,6 +394,10 @@ width: 100%; } +.vocab-card-face .vocab-card-bg { + transform: scale(1.015); +} + .vocab-card-bg--back { filter: brightness(0.88) saturate(0.8); } diff --git a/src/pages/VocabMaster.tsx b/src/pages/VocabMaster.tsx index 9a61fe3..4bb3056 100644 --- a/src/pages/VocabMaster.tsx +++ b/src/pages/VocabMaster.tsx @@ -18,6 +18,7 @@ const CARDS_PER_ROUND = 10; const SWIPE_THRESHOLD = 80; const CARD_TIMER = 20; const SWIPE_ANIMATION_MS = 380; +const SWIPE_COOLDOWN_MS = 900; // card1 = front of deck, card4 = furthest back const CARD_ARTS = [card1Svg, card2Svg, card3Svg, card4Svg]; @@ -87,6 +88,8 @@ export function VocabMaster() { const mouseDownX = useRef(0); const mouseDown = useRef(false); const dragXRef = useRef(0); + const advancingRef = useRef(false); + const lastAdvanceAtRef = useRef(0); // Load deck useEffect(() => { @@ -134,6 +137,11 @@ export function VocabMaster() { const advance = useCallback( (dir: 'left' | 'right') => { + const now = Date.now(); + if (now - lastAdvanceAtRef.current < SWIPE_COOLDOWN_MS) return; + if (advancingRef.current) return; + advancingRef.current = true; + lastAdvanceAtRef.current = now; if (timerRef.current) clearInterval(timerRef.current); triggerHapticFeedback(dir === 'right' ? 'medium' : 'light'); setDragging(false); @@ -156,19 +164,26 @@ export function VocabMaster() { if (index + 1 >= deck.length) { if (timerRef.current) clearInterval(timerRef.current); void updateStreak(); - void refreshLevel().then((newLevel) => { - if (newLevel) { - navigate(`/home/levelup`, { replace: true, state: { level: newLevel } }); - } else { - setFinished(true); - } - }); + void refreshLevel() + .then((newLevel) => { + if (newLevel) { + navigate(`/home/levelup`, { replace: true, state: { level: newLevel } }); + } else { + setFinished(true); + } + }) + .finally(() => { + advancingRef.current = false; + }); setResetting(false); } else { setIndex((i) => i + 1); // Re-enable transitions on the next frame so future drags/swipes animate requestAnimationFrame(() => { setResetting(false); + setTimeout(() => { + advancingRef.current = false; + }, 260); }); } }, SWIPE_ANIMATION_MS); @@ -389,7 +404,7 @@ export function VocabMaster() { .filter(Boolean) .join(' ')} style={{ - transform: `translateX(${flyX}px) rotate(${baseRotate + flyRotate}deg)`, + transform: `translateX(calc(-50% + ${flyX}px)) rotate(${baseRotate + flyRotate}deg)`, }} onTouchStart={onTouchStart} onTouchMove={onTouchMove} @@ -438,12 +453,12 @@ export function VocabMaster() { 30 ? 'is-visible' : ''}`} > - Know it ✓ + Got it - Review ✗ + Practice > )} @@ -491,8 +506,8 @@ export function VocabMaster() { Quick guide Tap the card to flip and reveal the meaning. - Swipe right if you know it. - Swipe left if you want to review it again. + Swipe right when you remember the word. + Swipe left when you want more practice.
Loading chats...
No saved chats yet.
Loading…
Quick guide