build: 55712324-398e-4334-a254-fc30c84b2e47
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonItem,
|
||||
IonLabel,
|
||||
IonPage,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
waterOutline,
|
||||
fitnessOutline,
|
||||
shieldCheckmarkOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { Redirect as RedirectRR, useHistory } from 'react-router-dom';
|
||||
import { supabase } from '../supabase';
|
||||
import {
|
||||
Style,
|
||||
setStatusBarBackground,
|
||||
setStatusBarStyle,
|
||||
} from '../utils/statusBar';
|
||||
import { useIonViewWillEnter } from '@ionic/react';
|
||||
import runnerDrinkingWaterImage from '../assets/runner-drinking-water-photorealistic.png';
|
||||
|
||||
const RedirectAny = RedirectRR as any;
|
||||
|
||||
const Account: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const [sessionChecked, setSessionChecked] = useState(false);
|
||||
const [email, setEmail] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setStatusBarStyle(Style.Dark);
|
||||
setStatusBarBackground('#ffffff');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
supabase.auth.getSession().then(({ data }) => {
|
||||
setEmail(data.session?.user.email ?? null);
|
||||
setSessionChecked(true);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await supabase.auth.signOut();
|
||||
history.replace('/auth');
|
||||
};
|
||||
|
||||
if (sessionChecked && !email) {
|
||||
return <RedirectAny to="/auth" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<IonPage>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar>
|
||||
<IonTitle>Account</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
<IonContent fullscreen>
|
||||
<div className="dashboard-shell ion-padding account-shell">
|
||||
<section className="account-hero-card">
|
||||
<div className="account-hero-image-wrap">
|
||||
<img
|
||||
src={runnerDrinkingWaterImage}
|
||||
alt="Runner drinking water after a run"
|
||||
className="account-hero-image"
|
||||
/>
|
||||
<div className="account-hero-overlay" />
|
||||
</div>
|
||||
|
||||
<div className="account-hero-content">
|
||||
<span className="eyebrow">Recovery & account</span>
|
||||
<h1>{email ?? 'Loading...'}</h1>
|
||||
<p>
|
||||
Stay hydrated, stay consistent, and keep your habit history
|
||||
safely synced across sessions.
|
||||
</p>
|
||||
|
||||
<div className="account-highlight-row">
|
||||
<div className="account-highlight-chip">
|
||||
<IonIcon icon={waterOutline} />
|
||||
<span>Recovery mindset</span>
|
||||
</div>
|
||||
<div className="account-highlight-chip subtle">
|
||||
<IonIcon icon={fitnessOutline} />
|
||||
<span>Built for routines</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="stats-card account-details-card">
|
||||
<IonItem lines="none" className="account-info-item">
|
||||
<IonLabel>
|
||||
<h2>Email</h2>
|
||||
<p>{email ?? '—'}</p>
|
||||
</IonLabel>
|
||||
</IonItem>
|
||||
|
||||
<div className="account-trust-row">
|
||||
<div className="account-trust-icon">
|
||||
<IonIcon icon={shieldCheckmarkOutline} />
|
||||
</div>
|
||||
<div>
|
||||
<h3>Your data is synced</h3>
|
||||
<p>
|
||||
Sign in to keep your streaks and progress available whenever
|
||||
you come back.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IonButton
|
||||
expand="block"
|
||||
className="account-primary-button"
|
||||
routerLink="/home"
|
||||
>
|
||||
Back to Habits
|
||||
</IonButton>
|
||||
<IonButton
|
||||
expand="block"
|
||||
fill="outline"
|
||||
color="danger"
|
||||
className="account-secondary-button"
|
||||
onClick={handleSignOut}
|
||||
>
|
||||
Sign Out
|
||||
</IonButton>
|
||||
</div>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default Account;
|
||||
@@ -0,0 +1,215 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonCard,
|
||||
IonCardContent,
|
||||
IonContent,
|
||||
IonInput,
|
||||
IonItem,
|
||||
IonLabel,
|
||||
IonPage,
|
||||
IonSegment,
|
||||
IonSegmentButton,
|
||||
IonText,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import { Redirect, useHistory } from 'react-router-dom';
|
||||
import {
|
||||
Style,
|
||||
setStatusBarBackground,
|
||||
setStatusBarStyle,
|
||||
} from '../utils/statusBar';
|
||||
import { supabase } from '../supabase';
|
||||
|
||||
const Auth: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [info, setInfo] = useState('');
|
||||
const [verificationMessage, setVerificationMessage] = useState('');
|
||||
const [sessionChecked, setSessionChecked] = useState(false);
|
||||
const [hasSession, setHasSession] = useState(false);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setStatusBarStyle(Style.Dark);
|
||||
setStatusBarBackground('#f6f7fb');
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
let mounted = true;
|
||||
|
||||
supabase.auth.getSession().then(({ data }) => {
|
||||
if (!mounted) return;
|
||||
setHasSession(Boolean(data.session));
|
||||
setSessionChecked(true);
|
||||
});
|
||||
|
||||
const {
|
||||
data: { subscription },
|
||||
} = supabase.auth.onAuthStateChange((_event, session) => {
|
||||
if (!mounted) return;
|
||||
setHasSession(Boolean(session));
|
||||
setSessionChecked(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
subscription.unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const formValid = useMemo(() => {
|
||||
return email.trim().length > 3 && password.length >= 6;
|
||||
}, [email, password]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError('');
|
||||
setInfo('');
|
||||
setVerificationMessage('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
if (mode === 'login') {
|
||||
const { error: signInError } = await supabase.auth.signInWithPassword({
|
||||
email: email.trim(),
|
||||
password,
|
||||
});
|
||||
|
||||
if (signInError) {
|
||||
setError(signInError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
history.replace('/home');
|
||||
return;
|
||||
}
|
||||
|
||||
const { data, error: signUpError } = await supabase.auth.signUp({
|
||||
email: email.trim(),
|
||||
password,
|
||||
});
|
||||
|
||||
if (signUpError) {
|
||||
setError(signUpError.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.session) {
|
||||
history.replace('/home');
|
||||
return;
|
||||
}
|
||||
|
||||
setVerificationMessage(
|
||||
'Account created! Check your email for a verification link.',
|
||||
);
|
||||
setInfo('Once verified, come back and sign in.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (sessionChecked && hasSession) {
|
||||
return <Redirect to="/home" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<IonPage>
|
||||
<IonContent fullscreen style={{ '--background': '#f6f7fb' }}>
|
||||
<div className="auth-shell">
|
||||
<div className="auth-hero">
|
||||
<span className="eyebrow">Protect your streaks</span>
|
||||
<h1>Build habits that actually stick.</h1>
|
||||
<p>
|
||||
Track daily wins, recover faster from misses, and see which habits
|
||||
are getting real momentum.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<IonCard className="auth-card">
|
||||
<IonCardContent>
|
||||
<IonSegment
|
||||
value={mode}
|
||||
onIonChange={(e) =>
|
||||
setMode(e.detail.value as 'login' | 'signup')
|
||||
}
|
||||
>
|
||||
<IonSegmentButton value="login">
|
||||
<IonLabel>Login</IonLabel>
|
||||
</IonSegmentButton>
|
||||
<IonSegmentButton value="signup">
|
||||
<IonLabel>Sign Up</IonLabel>
|
||||
</IonSegmentButton>
|
||||
</IonSegment>
|
||||
|
||||
{verificationMessage ? (
|
||||
<div className="auth-message-block">
|
||||
<h2>Check your inbox</h2>
|
||||
<p>{verificationMessage}</p>
|
||||
<IonText color="medium">
|
||||
<p>{info}</p>
|
||||
</IonText>
|
||||
<IonButton fill="clear" onClick={() => setMode('login')}>
|
||||
Back to Login
|
||||
</IonButton>
|
||||
</div>
|
||||
) : (
|
||||
<div className="auth-form">
|
||||
<IonItem lines="none" className="auth-input-item">
|
||||
<IonInput
|
||||
type="email"
|
||||
label="Email"
|
||||
labelPlacement="stacked"
|
||||
value={email}
|
||||
placeholder="you@example.com"
|
||||
onIonInput={(e) => setEmail(e.detail.value ?? '')}
|
||||
/>
|
||||
</IonItem>
|
||||
|
||||
<IonItem lines="none" className="auth-input-item">
|
||||
<IonInput
|
||||
type="password"
|
||||
label="Password"
|
||||
labelPlacement="stacked"
|
||||
value={password}
|
||||
placeholder="At least 6 characters"
|
||||
onIonInput={(e) => setPassword(e.detail.value ?? '')}
|
||||
/>
|
||||
</IonItem>
|
||||
|
||||
{error ? (
|
||||
<IonText color="danger">
|
||||
<p className="auth-feedback">{error}</p>
|
||||
</IonText>
|
||||
) : null}
|
||||
|
||||
{info ? (
|
||||
<IonText color="medium">
|
||||
<p className="auth-feedback">{info}</p>
|
||||
</IonText>
|
||||
) : null}
|
||||
|
||||
<IonButton
|
||||
expand="block"
|
||||
disabled={!formValid || loading}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
{loading
|
||||
? 'Please wait…'
|
||||
: mode === 'login'
|
||||
? 'Log In'
|
||||
: 'Create Account'}
|
||||
</IonButton>
|
||||
</div>
|
||||
)}
|
||||
</IonCardContent>
|
||||
</IonCard>
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default Auth;
|
||||
@@ -0,0 +1,405 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonRefresher,
|
||||
IonRefresherContent,
|
||||
IonSkeletonText,
|
||||
IonToolbar,
|
||||
useIonViewWillEnter,
|
||||
} from '@ionic/react';
|
||||
import {
|
||||
addOutline,
|
||||
analyticsOutline,
|
||||
checkmarkCircle,
|
||||
personCircleOutline,
|
||||
sparklesOutline,
|
||||
} from 'ionicons/icons';
|
||||
import { Redirect, useHistory } from 'react-router-dom';
|
||||
import type { Tables } from '../database.types';
|
||||
import { supabase } from '../supabase';
|
||||
import EmptyState from '../components/EmptyState';
|
||||
import HabitCard from '../components/HabitCard';
|
||||
import HabitFormModal from '../components/HabitFormModal';
|
||||
import {
|
||||
Style,
|
||||
setStatusBarBackground,
|
||||
setStatusBarStyle,
|
||||
} from '../utils/statusBar';
|
||||
|
||||
interface HabitWithMeta extends Tables<'habits'> {
|
||||
completions: Tables<'habit_completions'>[];
|
||||
}
|
||||
|
||||
const formatDate = (date: Date) => date.toISOString().slice(0, 10);
|
||||
|
||||
const calculateCurrentStreak = (dates: string[]) => {
|
||||
const unique = Array.from(new Set(dates)).sort((a, b) => b.localeCompare(a));
|
||||
let streak = 0;
|
||||
let cursor = new Date();
|
||||
|
||||
if (!unique.includes(formatDate(cursor))) {
|
||||
cursor.setDate(cursor.getDate() - 1);
|
||||
}
|
||||
|
||||
while (unique.includes(formatDate(cursor))) {
|
||||
streak += 1;
|
||||
cursor.setDate(cursor.getDate() - 1);
|
||||
}
|
||||
|
||||
return streak;
|
||||
};
|
||||
|
||||
const Home: React.FC = () => {
|
||||
const history = useHistory();
|
||||
const [sessionChecked, setSessionChecked] = useState(false);
|
||||
const [userId, setUserId] = useState<string | null>(null);
|
||||
const [habits, setHabits] = useState<HabitWithMeta[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||
const [busyHabitId, setBusyHabitId] = useState<string | null>(null);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setStatusBarStyle(Style.Dark);
|
||||
setStatusBarBackground('#ffffff');
|
||||
});
|
||||
|
||||
const loadDashboard = useCallback(async () => {
|
||||
setError('');
|
||||
|
||||
const {
|
||||
data: { session },
|
||||
error: sessionError,
|
||||
} = await supabase.auth.getSession();
|
||||
|
||||
if (sessionError) {
|
||||
setError(sessionError.message);
|
||||
setSessionChecked(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session?.user) {
|
||||
setUserId(null);
|
||||
setSessionChecked(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setUserId(session.user.id);
|
||||
setSessionChecked(true);
|
||||
|
||||
const { data, error: habitsError } = await supabase
|
||||
.from('habits')
|
||||
.select('*, completions:habit_completions(*)')
|
||||
.order('created_at', { ascending: true });
|
||||
|
||||
if (habitsError) {
|
||||
setError(habitsError.message);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setHabits((data ?? []) as HabitWithMeta[]);
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadDashboard();
|
||||
}, [loadDashboard]);
|
||||
|
||||
const today = formatDate(new Date());
|
||||
|
||||
const habitStats = useMemo(() => {
|
||||
const last7Days = Array.from({ length: 7 }, (_, index) => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - index);
|
||||
return formatDate(date);
|
||||
});
|
||||
|
||||
return habits.reduce<
|
||||
Record<string, { streak: number; weekRate: number; doneToday: boolean }>
|
||||
>((acc, habit) => {
|
||||
const completionDates = habit.completions.map(
|
||||
(entry) => entry.completed_on
|
||||
);
|
||||
const completedInWeek = completionDates.filter((date) =>
|
||||
last7Days.includes(date)
|
||||
).length;
|
||||
|
||||
acc[habit.id] = {
|
||||
streak: calculateCurrentStreak(completionDates),
|
||||
weekRate: Math.round((completedInWeek / last7Days.length) * 100),
|
||||
doneToday: completionDates.includes(today),
|
||||
};
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
}, [habits, today]);
|
||||
|
||||
const totalCompletedToday = habits.filter(
|
||||
(habit) => habitStats[habit.id]?.doneToday
|
||||
).length;
|
||||
const longestStreak = habits.reduce(
|
||||
(max, habit) => Math.max(max, habitStats[habit.id]?.streak ?? 0),
|
||||
0
|
||||
);
|
||||
const completionRatio = habits.length
|
||||
? totalCompletedToday / habits.length
|
||||
: 0;
|
||||
const pendingCount = Math.max(habits.length - totalCompletedToday, 0);
|
||||
|
||||
const createHabit = async (values: {
|
||||
name: string;
|
||||
targetDescription: string;
|
||||
color: string;
|
||||
}) => {
|
||||
if (!userId) throw new Error('You need to be logged in.');
|
||||
|
||||
const { error: insertError } = await supabase.from('habits').insert({
|
||||
user_id: userId,
|
||||
name: values.name,
|
||||
target_description: values.targetDescription || null,
|
||||
color: values.color,
|
||||
});
|
||||
|
||||
if (insertError) throw insertError;
|
||||
await loadDashboard();
|
||||
};
|
||||
|
||||
const toggleHabit = async (habit: HabitWithMeta) => {
|
||||
if (!userId) return;
|
||||
setBusyHabitId(habit.id);
|
||||
|
||||
const existing = habit.completions.find(
|
||||
(entry) => entry.completed_on === today
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
const { error: deleteError } = await supabase
|
||||
.from('habit_completions')
|
||||
.delete()
|
||||
.eq('id', existing.id);
|
||||
if (deleteError) setError(deleteError.message);
|
||||
} else {
|
||||
const { error: insertError } = await supabase
|
||||
.from('habit_completions')
|
||||
.insert({
|
||||
habit_id: habit.id,
|
||||
user_id: userId,
|
||||
completed_on: today,
|
||||
});
|
||||
if (insertError) setError(insertError.message);
|
||||
}
|
||||
|
||||
await loadDashboard();
|
||||
setBusyHabitId(null);
|
||||
};
|
||||
|
||||
const deleteHabit = async (habitId: string) => {
|
||||
setBusyHabitId(habitId);
|
||||
const { error: deleteError } = await supabase
|
||||
.from('habits')
|
||||
.delete()
|
||||
.eq('id', habitId);
|
||||
if (deleteError) {
|
||||
setError(deleteError.message);
|
||||
}
|
||||
await loadDashboard();
|
||||
setBusyHabitId(null);
|
||||
};
|
||||
|
||||
if (sessionChecked && !userId) {
|
||||
return <Redirect to="/auth" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<IonPage>
|
||||
<IonHeader className="ion-no-border home-header">
|
||||
<IonToolbar>
|
||||
<IonButtons slot="end">
|
||||
<IonButton
|
||||
className="soft-icon-button"
|
||||
onClick={() => history.push('/stats')}
|
||||
>
|
||||
<IonIcon icon={analyticsOutline} />
|
||||
</IonButton>
|
||||
<IonButton
|
||||
className="soft-icon-button"
|
||||
onClick={() => history.push('/account')}
|
||||
>
|
||||
<IonIcon icon={personCircleOutline} />
|
||||
</IonButton>
|
||||
</IonButtons>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
|
||||
<IonContent fullscreen className="home-content">
|
||||
<IonRefresher
|
||||
slot="fixed"
|
||||
onIonRefresh={async (e) => {
|
||||
await loadDashboard();
|
||||
e.detail.complete();
|
||||
}}
|
||||
>
|
||||
<IonRefresherContent />
|
||||
</IonRefresher>
|
||||
|
||||
<div className="dashboard-shell home-shell ion-padding">
|
||||
<section className="habits-hero">
|
||||
<div className="habits-hero-top">
|
||||
<div>
|
||||
<p className="hero-kicker">Habits ({habits.length})</p>
|
||||
<div className="hero-title-wrap">
|
||||
<h1>Daily</h1>
|
||||
<span>Weekly</span>
|
||||
</div>
|
||||
</div>
|
||||
<IonButton
|
||||
className="hero-add-button"
|
||||
fill="clear"
|
||||
onClick={() => setShowCreateModal(true)}
|
||||
>
|
||||
<IonIcon icon={addOutline} />
|
||||
</IonButton>
|
||||
</div>
|
||||
|
||||
<div className="hero-progress-track" aria-hidden="true">
|
||||
<div
|
||||
className="hero-progress-fill"
|
||||
style={{ width: `${Math.max(completionRatio * 100, 6)}%` }}
|
||||
>
|
||||
<span className="hero-progress-dot" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="hero-progress-meta">
|
||||
<span>{totalCompletedToday} completed today</span>
|
||||
<span>{Math.round(completionRatio * 100)}% completed</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{loading ? (
|
||||
<div className="home-routine-panel">
|
||||
<div className="stack-list home-habit-stack">
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '82px',
|
||||
borderRadius: '24px',
|
||||
}}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '82px',
|
||||
borderRadius: '24px',
|
||||
}}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '82px',
|
||||
borderRadius: '24px',
|
||||
}}
|
||||
/>
|
||||
<IonSkeletonText
|
||||
animated
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '82px',
|
||||
borderRadius: '24px',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="inline-message error-card home-inline-card">
|
||||
<h3>Couldn't load your habits</h3>
|
||||
<p>{error}</p>
|
||||
<IonButton onClick={loadDashboard}>Try Again</IonButton>
|
||||
</div>
|
||||
) : habits.length === 0 ? (
|
||||
<div className="home-routine-panel">
|
||||
<EmptyState
|
||||
title="Start your first routine"
|
||||
message="Create one small daily habit and begin building your streak story today."
|
||||
actionLabel="Create First Habit"
|
||||
onAction={() => setShowCreateModal(true)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<section className="home-routine-panel">
|
||||
<div className="stack-list home-habit-stack">
|
||||
{habits.map((habit) => (
|
||||
<HabitCard
|
||||
key={habit.id}
|
||||
habit={habit}
|
||||
completedToday={habitStats[habit.id]?.doneToday ?? false}
|
||||
currentStreak={habitStats[habit.id]?.streak ?? 0}
|
||||
completionRate={habitStats[habit.id]?.weekRate ?? 0}
|
||||
onToggle={() => toggleHabit(habit)}
|
||||
onDelete={() => deleteHabit(habit.id)}
|
||||
busy={busyHabitId === habit.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="home-complete-section">
|
||||
<p className="home-section-label">Momentum</p>
|
||||
<div className="home-summary-card">
|
||||
<div
|
||||
className="summary-ring"
|
||||
style={{
|
||||
background: `conic-gradient(#7c3aed 0deg, #a855f7 ${completionRatio * 360}deg, rgba(109, 40, 217, 0.08) ${completionRatio * 360}deg 360deg)`,
|
||||
}}
|
||||
>
|
||||
<div className="summary-ring-inner">
|
||||
{Math.round(completionRatio * 100)}%
|
||||
</div>
|
||||
</div>
|
||||
<div className="summary-copy">
|
||||
<h3>Keep your rhythm</h3>
|
||||
<p>
|
||||
{pendingCount === 0
|
||||
? 'Everything is complete today. Enjoy the streak.'
|
||||
: `${pendingCount} habit${pendingCount === 1 ? '' : 's'} left to protect today's routine.`}
|
||||
</p>
|
||||
<div className="summary-metrics">
|
||||
<span>
|
||||
<IonIcon icon={sparklesOutline} /> {totalCompletedToday}{' '}
|
||||
done
|
||||
</span>
|
||||
<span>
|
||||
<IonIcon icon={checkmarkCircle} /> {longestStreak} day
|
||||
best streak
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<HabitFormModal
|
||||
isOpen={showCreateModal}
|
||||
onDismiss={() => setShowCreateModal(false)}
|
||||
onSubmit={createHabit}
|
||||
/>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
||||
@@ -0,0 +1,179 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
IonButton,
|
||||
IonButtons,
|
||||
IonContent,
|
||||
IonHeader,
|
||||
IonIcon,
|
||||
IonPage,
|
||||
IonSegment,
|
||||
IonSegmentButton,
|
||||
IonTitle,
|
||||
IonToolbar,
|
||||
} from '@ionic/react';
|
||||
import { IonBackButton } from '@ionic/react';
|
||||
import { calendarOutline } from 'ionicons/icons';
|
||||
import { Redirect } from 'react-router-dom';
|
||||
import type { Tables } from '../database.types';
|
||||
import StatsHabitCard from '../components/StatsHabitCard';
|
||||
import { supabase } from '../supabase';
|
||||
import {
|
||||
Style,
|
||||
setStatusBarBackground,
|
||||
setStatusBarStyle,
|
||||
} from '../utils/statusBar';
|
||||
import { useIonViewWillEnter } from '@ionic/react';
|
||||
|
||||
interface HabitWithMeta extends Tables<'habits'> {
|
||||
completions: Tables<'habit_completions'>[];
|
||||
}
|
||||
|
||||
const formatDate = (date: Date) => date.toISOString().slice(0, 10);
|
||||
|
||||
const calculateCurrentStreak = (dates: string[]) => {
|
||||
const unique = Array.from(new Set(dates)).sort((a, b) => b.localeCompare(a));
|
||||
let streak = 0;
|
||||
let cursor = new Date();
|
||||
|
||||
if (!unique.includes(formatDate(cursor))) {
|
||||
cursor.setDate(cursor.getDate() - 1);
|
||||
}
|
||||
|
||||
while (unique.includes(formatDate(cursor))) {
|
||||
streak += 1;
|
||||
cursor.setDate(cursor.getDate() - 1);
|
||||
}
|
||||
|
||||
return streak;
|
||||
};
|
||||
|
||||
const Stats: React.FC = () => {
|
||||
const [period, setPeriod] = useState<'7' | '30'>('7');
|
||||
const [sessionChecked, setSessionChecked] = useState(false);
|
||||
const [userId, setUserId] = useState<string | null>(null);
|
||||
const [habits, setHabits] = useState<HabitWithMeta[]>([]);
|
||||
|
||||
useIonViewWillEnter(() => {
|
||||
setStatusBarStyle(Style.Dark);
|
||||
setStatusBarBackground('#ffffff');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
const {
|
||||
data: { session },
|
||||
} = await supabase.auth.getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
setSessionChecked(true);
|
||||
setUserId(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setUserId(session.user.id);
|
||||
setSessionChecked(true);
|
||||
|
||||
const { data } = await supabase
|
||||
.from('habits')
|
||||
.select('*, completions:habit_completions(*)')
|
||||
.order('created_at', { ascending: true });
|
||||
|
||||
setHabits((data ?? []) as HabitWithMeta[]);
|
||||
};
|
||||
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const days = Number(period);
|
||||
const visibleDates = useMemo(() => {
|
||||
return Array.from({ length: days }, (_, index) => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - index);
|
||||
return formatDate(date);
|
||||
});
|
||||
}, [days]);
|
||||
|
||||
const summary = useMemo(() => {
|
||||
return habits.map((habit) => {
|
||||
const completionDates = habit.completions.map(
|
||||
(entry) => entry.completed_on
|
||||
);
|
||||
const completedCount = completionDates.filter((date) =>
|
||||
visibleDates.includes(date)
|
||||
).length;
|
||||
return {
|
||||
id: habit.id,
|
||||
name: habit.name,
|
||||
color: habit.color,
|
||||
completedCount,
|
||||
streak: calculateCurrentStreak(completionDates),
|
||||
};
|
||||
});
|
||||
}, [habits, visibleDates]);
|
||||
|
||||
if (sessionChecked && !userId) {
|
||||
return <Redirect to="/auth" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<IonPage>
|
||||
<IonHeader className="ion-no-border">
|
||||
<IonToolbar>
|
||||
<IonButtons slot="start">
|
||||
<IonBackButton defaultHref="/home" />
|
||||
</IonButtons>
|
||||
<IonTitle>Stats</IonTitle>
|
||||
</IonToolbar>
|
||||
</IonHeader>
|
||||
<IonContent fullscreen>
|
||||
<div className="dashboard-shell ion-padding">
|
||||
<section className="hero-card compact">
|
||||
<span className="eyebrow">Consistency view</span>
|
||||
<h1>See which habits you're actually keeping.</h1>
|
||||
<p>
|
||||
Flip between the last week and month to spot patterns before a
|
||||
streak disappears.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div className="stats-filter-row">
|
||||
<IonIcon icon={calendarOutline} />
|
||||
<IonSegment
|
||||
value={period}
|
||||
onIonChange={(e) => setPeriod(e.detail.value as '7' | '30')}
|
||||
>
|
||||
<IonSegmentButton value="7">Last 7 days</IonSegmentButton>
|
||||
<IonSegmentButton value="30">Last 30 days</IonSegmentButton>
|
||||
</IonSegment>
|
||||
</div>
|
||||
|
||||
{summary.length === 0 ? (
|
||||
<div className="inline-message">
|
||||
<h3>No stats yet</h3>
|
||||
<p>
|
||||
Create a habit and start checking it off daily to unlock
|
||||
consistency insights.
|
||||
</p>
|
||||
<IonButton routerLink="/home">Go to dashboard</IonButton>
|
||||
</div>
|
||||
) : (
|
||||
<div className="stack-list">
|
||||
{summary.map((habit) => (
|
||||
<StatsHabitCard
|
||||
key={habit.id}
|
||||
name={habit.name}
|
||||
color={habit.color}
|
||||
completedCount={habit.completedCount}
|
||||
totalDays={days}
|
||||
streak={habit.streak}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</IonContent>
|
||||
</IonPage>
|
||||
);
|
||||
};
|
||||
|
||||
export default Stats;
|
||||
Reference in New Issue
Block a user