setting up test functionality
This commit is contained in:
9
lib/app-events.ts
Normal file
9
lib/app-events.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export const HABIT_PET_DATA_UPDATED_EVENT = "habit-pet-data-updated";
|
||||
|
||||
export function notifyHabitPetDataUpdated() {
|
||||
if (typeof window === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
window.dispatchEvent(new Event(HABIT_PET_DATA_UPDATED_EVENT));
|
||||
}
|
||||
97
lib/avatar-state.ts
Normal file
97
lib/avatar-state.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
export type AvatarMood = "happy" | "neutral" | "tired";
|
||||
|
||||
export type DailyQuizAnswers = {
|
||||
feeling: number;
|
||||
stress: number;
|
||||
energy: number;
|
||||
sleepLength: number;
|
||||
sleepQuality: number;
|
||||
journal: string;
|
||||
};
|
||||
|
||||
export type AvatarCondition = {
|
||||
mood: AvatarMood;
|
||||
energy: number;
|
||||
health: number;
|
||||
};
|
||||
|
||||
export type DailyQuizSubmission = {
|
||||
date: string;
|
||||
answers: DailyQuizAnswers;
|
||||
condition: AvatarCondition;
|
||||
};
|
||||
|
||||
export const WELLNESS_SCALE_MAX = 5;
|
||||
|
||||
export const defaultDailyQuizAnswers: DailyQuizAnswers = {
|
||||
feeling: 3,
|
||||
stress: 3,
|
||||
energy: 3,
|
||||
sleepLength: 3,
|
||||
sleepQuality: 3,
|
||||
journal: "",
|
||||
};
|
||||
|
||||
export function computeAvatarCondition(
|
||||
answers: DailyQuizAnswers,
|
||||
): AvatarCondition {
|
||||
const { feeling, stress, energy, sleepLength, sleepQuality } = answers;
|
||||
|
||||
const wellnessAverage = (feeling + energy + (WELLNESS_SCALE_MAX + 1 - stress)) / 3;
|
||||
const sleepAverage = (sleepLength + sleepQuality) / 2;
|
||||
const health = Math.round((wellnessAverage + sleepAverage) / 2);
|
||||
const energyLevel = Math.round((energy + sleepQuality) / 2);
|
||||
|
||||
let avatarMood: AvatarMood = "neutral";
|
||||
|
||||
if (energyLevel >= 4 && feeling >= 4 && health >= 4) {
|
||||
avatarMood = "happy";
|
||||
} else if (energy <= 2 || sleepLength <= 2 || sleepQuality <= 2) {
|
||||
avatarMood = "tired";
|
||||
}
|
||||
|
||||
return {
|
||||
mood: avatarMood,
|
||||
energy: clampStat(energyLevel),
|
||||
health: clampStat(health),
|
||||
};
|
||||
}
|
||||
|
||||
function clampStat(value: number) {
|
||||
return Math.min(WELLNESS_SCALE_MAX, Math.max(1, value));
|
||||
}
|
||||
|
||||
export const defaultAvatarCondition: AvatarCondition = {
|
||||
mood: "neutral",
|
||||
energy: 3,
|
||||
health: 3,
|
||||
};
|
||||
|
||||
// Backward compatibility for older saved submissions.
|
||||
export function normalizeDailyQuizAnswers(
|
||||
answers: Partial<DailyQuizAnswers> & {
|
||||
mood?: number;
|
||||
},
|
||||
): DailyQuizAnswers {
|
||||
const scaleValue = (value: number | undefined, fallback: number) => {
|
||||
if (value === undefined) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return value > WELLNESS_SCALE_MAX
|
||||
? Math.max(1, Math.round(value / 2))
|
||||
: value;
|
||||
};
|
||||
|
||||
return {
|
||||
feeling: scaleValue(answers.feeling ?? answers.mood, defaultDailyQuizAnswers.feeling),
|
||||
stress: scaleValue(answers.stress, defaultDailyQuizAnswers.stress),
|
||||
energy: scaleValue(answers.energy, defaultDailyQuizAnswers.energy),
|
||||
sleepLength: scaleValue(answers.sleepLength, defaultDailyQuizAnswers.sleepLength),
|
||||
sleepQuality: scaleValue(
|
||||
answers.sleepQuality,
|
||||
defaultDailyQuizAnswers.sleepQuality,
|
||||
),
|
||||
journal: answers.journal ?? "",
|
||||
};
|
||||
}
|
||||
74
lib/daily-quiz-storage.ts
Normal file
74
lib/daily-quiz-storage.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
computeAvatarCondition,
|
||||
normalizeDailyQuizAnswers,
|
||||
type AvatarCondition,
|
||||
type DailyQuizAnswers,
|
||||
type DailyQuizSubmission,
|
||||
} from "@/lib/avatar-state";
|
||||
import { notifyHabitPetDataUpdated } from "@/lib/app-events";
|
||||
const STORAGE_KEY = "habit-pet-daily-quiz";
|
||||
|
||||
export function getTodayDateKey(date = new Date()) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function normalizeSubmission(
|
||||
submission: DailyQuizSubmission,
|
||||
): DailyQuizSubmission {
|
||||
const answers = normalizeDailyQuizAnswers(submission.answers);
|
||||
|
||||
return {
|
||||
...submission,
|
||||
answers,
|
||||
condition: computeAvatarCondition(answers),
|
||||
};
|
||||
}
|
||||
|
||||
export function getDailyQuizSubmission(): DailyQuizSubmission | null {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeSubmission(JSON.parse(raw) as DailyQuizSubmission);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function hasCompletedDailyQuizToday() {
|
||||
const submission = getDailyQuizSubmission();
|
||||
return submission?.date === getTodayDateKey();
|
||||
}
|
||||
|
||||
export function saveDailyQuizSubmission(
|
||||
answers: DailyQuizAnswers,
|
||||
): DailyQuizSubmission {
|
||||
const submission: DailyQuizSubmission = {
|
||||
date: getTodayDateKey(),
|
||||
answers,
|
||||
condition: computeAvatarCondition(answers),
|
||||
};
|
||||
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(submission));
|
||||
|
||||
notifyHabitPetDataUpdated();
|
||||
|
||||
return submission;
|
||||
}
|
||||
|
||||
export function getAvatarConditionForToday(): AvatarCondition | null {
|
||||
const submission = getDailyQuizSubmission();
|
||||
|
||||
if (!submission || submission.date !== getTodayDateKey()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return submission.condition;
|
||||
}
|
||||
111
lib/daily-tasks.ts
Normal file
111
lib/daily-tasks.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import type { DailyQuizAnswers } from "@/lib/avatar-state";
|
||||
import { getDailyQuizSubmission, getTodayDateKey } from "@/lib/daily-quiz-storage";
|
||||
import {
|
||||
catalogHabitIds,
|
||||
getCatalogEntry,
|
||||
habitCatalog,
|
||||
matchesFocusTopics,
|
||||
matchesQuizAnswers,
|
||||
} from "@/lib/habit-catalog";
|
||||
import { getHabits, saveHabits, type Habit } from "@/lib/habits-storage";
|
||||
import {
|
||||
getProfilePreferences,
|
||||
type ProfilePreferences,
|
||||
} from "@/lib/profile-preferences-storage";
|
||||
|
||||
export type DailyTaskReason = "custom" | "focus" | "quiz";
|
||||
|
||||
export type DailyTask = Habit & {
|
||||
reason: DailyTaskReason;
|
||||
};
|
||||
|
||||
function getQuizAnswersForToday(): DailyQuizAnswers | null {
|
||||
const submission = getDailyQuizSubmission();
|
||||
|
||||
if (!submission || submission.date !== getTodayDateKey()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return submission.answers;
|
||||
}
|
||||
|
||||
function ensureCatalogHabit(entryId: string, habits: Habit[]) {
|
||||
const entry = getCatalogEntry(entryId);
|
||||
|
||||
if (!entry) {
|
||||
return habits;
|
||||
}
|
||||
|
||||
if (habits.some((habit) => habit.id === entry.id)) {
|
||||
return habits;
|
||||
}
|
||||
|
||||
return [
|
||||
...habits,
|
||||
{
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
streak: 0,
|
||||
lastCompletedDate: null,
|
||||
isCustom: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function getCatalogTaskReason(
|
||||
entry: NonNullable<ReturnType<typeof getCatalogEntry>>,
|
||||
preferences: ProfilePreferences,
|
||||
quizAnswers: DailyQuizAnswers | null,
|
||||
): DailyTaskReason | null {
|
||||
const fromQuiz = quizAnswers ? matchesQuizAnswers(entry, quizAnswers) : false;
|
||||
const fromFocus = matchesFocusTopics(entry, preferences);
|
||||
|
||||
if (fromQuiz) {
|
||||
return "quiz";
|
||||
}
|
||||
|
||||
if (fromFocus) {
|
||||
return "focus";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getDailyTasks(): DailyTask[] {
|
||||
let habits = getHabits();
|
||||
const preferences = getProfilePreferences();
|
||||
const quizAnswers = getQuizAnswersForToday();
|
||||
const initialHabitCount = habits.length;
|
||||
|
||||
const selectedCatalogIds = habitCatalog
|
||||
.map((entry) => {
|
||||
const reason = getCatalogTaskReason(entry, preferences, quizAnswers);
|
||||
return reason ? { id: entry.id, reason } : null;
|
||||
})
|
||||
.filter((item): item is { id: string; reason: DailyTaskReason } => item !== null);
|
||||
|
||||
for (const { id } of selectedCatalogIds) {
|
||||
habits = ensureCatalogHabit(id, habits);
|
||||
}
|
||||
|
||||
if (habits.length !== initialHabitCount) {
|
||||
saveHabits(habits, { notify: false });
|
||||
}
|
||||
|
||||
const customTasks: DailyTask[] = habits
|
||||
.filter((habit) => habit.isCustom)
|
||||
.map((habit) => ({ ...habit, reason: "custom" as const }));
|
||||
|
||||
const catalogTasks: DailyTask[] = selectedCatalogIds
|
||||
.map(({ id, reason }) => {
|
||||
const habit = habits.find((item) => item.id === id);
|
||||
return habit ? { ...habit, reason } : null;
|
||||
})
|
||||
.filter((task): task is DailyTask => task !== null);
|
||||
|
||||
return [...customTasks, ...catalogTasks];
|
||||
}
|
||||
|
||||
export function isCatalogHabitId(habitId: string) {
|
||||
return catalogHabitIds.has(habitId);
|
||||
}
|
||||
77
lib/habit-catalog.ts
Normal file
77
lib/habit-catalog.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import type { DailyQuizAnswers } from "@/lib/avatar-state";
|
||||
import type { ProfilePreferences } from "@/lib/profile-preferences-storage";
|
||||
|
||||
export type HabitCatalogEntry = {
|
||||
id: string;
|
||||
label: string;
|
||||
focusTopics: string[];
|
||||
suggestedByQuiz: (answers: DailyQuizAnswers) => boolean;
|
||||
};
|
||||
|
||||
export const habitCatalog: HabitCatalogEntry[] = [
|
||||
{
|
||||
id: "walk",
|
||||
label: "Went for a walk",
|
||||
focusTopics: ["Movement"],
|
||||
suggestedByQuiz: (answers) => answers.energy <= 2 || answers.feeling <= 2,
|
||||
},
|
||||
{
|
||||
id: "water",
|
||||
label: "Drank enough water",
|
||||
focusTopics: ["Hydration"],
|
||||
suggestedByQuiz: (answers) => answers.energy <= 3,
|
||||
},
|
||||
{
|
||||
id: "meal",
|
||||
label: "Ate a proper meal",
|
||||
focusTopics: ["Hydration"],
|
||||
suggestedByQuiz: (answers) => answers.feeling <= 2,
|
||||
},
|
||||
{
|
||||
id: "study",
|
||||
label: "Studied",
|
||||
focusTopics: ["Mindfulness"],
|
||||
suggestedByQuiz: () => false,
|
||||
},
|
||||
{
|
||||
id: "clean",
|
||||
label: "Cleaned room",
|
||||
focusTopics: ["Mindfulness"],
|
||||
suggestedByQuiz: (answers) => answers.stress >= 4,
|
||||
},
|
||||
{
|
||||
id: "screen-break",
|
||||
label: "Took a screen break",
|
||||
focusTopics: ["Mindfulness", "Movement"],
|
||||
suggestedByQuiz: (answers) => answers.stress >= 4 || answers.energy <= 2,
|
||||
},
|
||||
{
|
||||
id: "wind-down",
|
||||
label: "Wind down before bed",
|
||||
focusTopics: ["Sleep"],
|
||||
suggestedByQuiz: (answers) =>
|
||||
answers.sleepLength <= 2 || answers.sleepQuality <= 2,
|
||||
},
|
||||
];
|
||||
|
||||
export const catalogHabitIds = new Set(habitCatalog.map((habit) => habit.id));
|
||||
|
||||
export function getCatalogEntry(habitId: string) {
|
||||
return habitCatalog.find((habit) => habit.id === habitId);
|
||||
}
|
||||
|
||||
export function matchesFocusTopics(
|
||||
entry: HabitCatalogEntry,
|
||||
preferences: ProfilePreferences,
|
||||
) {
|
||||
return entry.focusTopics.some((topic) =>
|
||||
preferences.focusTopics.includes(topic),
|
||||
);
|
||||
}
|
||||
|
||||
export function matchesQuizAnswers(
|
||||
entry: HabitCatalogEntry,
|
||||
answers: DailyQuizAnswers,
|
||||
) {
|
||||
return entry.suggestedByQuiz(answers);
|
||||
}
|
||||
135
lib/habits-storage.ts
Normal file
135
lib/habits-storage.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { catalogHabitIds, habitCatalog } from "@/lib/habit-catalog";
|
||||
import { notifyHabitPetDataUpdated } from "@/lib/app-events";
|
||||
|
||||
export type Habit = {
|
||||
id: string;
|
||||
label: string;
|
||||
streak: number;
|
||||
lastCompletedDate: string | null;
|
||||
isCustom: boolean;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "habit-pet-habits";
|
||||
|
||||
export const defaultHabits: Habit[] = habitCatalog.map((entry) => ({
|
||||
id: entry.id,
|
||||
label: entry.label,
|
||||
streak: 0,
|
||||
lastCompletedDate: null,
|
||||
isCustom: false,
|
||||
}));
|
||||
|
||||
export function getTodayDateKey(date = new Date()) {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function getYesterdayDateKey(date = new Date()) {
|
||||
const yesterday = new Date(date);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
return getTodayDateKey(yesterday);
|
||||
}
|
||||
|
||||
function normalizeHabit(habit: Partial<Habit> & { id: string; label: string }): Habit {
|
||||
return {
|
||||
id: habit.id,
|
||||
label: habit.label,
|
||||
streak: habit.streak ?? 0,
|
||||
lastCompletedDate: habit.lastCompletedDate ?? null,
|
||||
isCustom: habit.isCustom ?? !catalogHabitIds.has(habit.id),
|
||||
};
|
||||
}
|
||||
|
||||
export function isHabitCompletedToday(habit: Habit, today = getTodayDateKey()) {
|
||||
return habit.lastCompletedDate === today;
|
||||
}
|
||||
|
||||
export function getHabits(): Habit[] {
|
||||
if (typeof window === "undefined") {
|
||||
return defaultHabits;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return defaultHabits;
|
||||
}
|
||||
|
||||
try {
|
||||
const habits = (JSON.parse(raw) as Habit[]).map(normalizeHabit);
|
||||
return habits.length > 0 ? habits : defaultHabits;
|
||||
} catch {
|
||||
return defaultHabits;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveHabits(habits: Habit[], options?: { notify?: boolean }) {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(habits));
|
||||
|
||||
if (options?.notify !== false) {
|
||||
notifyHabitPetDataUpdated();
|
||||
}
|
||||
}
|
||||
|
||||
export function toggleHabitCompletion(habitId: string): Habit[] {
|
||||
const today = getTodayDateKey();
|
||||
const yesterday = getYesterdayDateKey();
|
||||
const habits = getHabits().map((habit) => {
|
||||
if (habit.id !== habitId) {
|
||||
return habit;
|
||||
}
|
||||
|
||||
if (isHabitCompletedToday(habit, today)) {
|
||||
return {
|
||||
...habit,
|
||||
lastCompletedDate: null,
|
||||
streak: Math.max(0, habit.streak - 1),
|
||||
};
|
||||
}
|
||||
|
||||
const nextStreak =
|
||||
habit.lastCompletedDate === yesterday ? habit.streak + 1 : 1;
|
||||
|
||||
return {
|
||||
...habit,
|
||||
lastCompletedDate: today,
|
||||
streak: nextStreak,
|
||||
};
|
||||
});
|
||||
|
||||
saveHabits(habits);
|
||||
return habits;
|
||||
}
|
||||
|
||||
export function addHabit(label: string): Habit[] {
|
||||
const trimmedLabel = label.trim();
|
||||
|
||||
if (!trimmedLabel) {
|
||||
return getHabits();
|
||||
}
|
||||
|
||||
const habits = [
|
||||
...getHabits(),
|
||||
normalizeHabit({
|
||||
id: crypto.randomUUID(),
|
||||
label: trimmedLabel,
|
||||
streak: 0,
|
||||
lastCompletedDate: null,
|
||||
isCustom: true,
|
||||
}),
|
||||
];
|
||||
|
||||
saveHabits(habits);
|
||||
return habits;
|
||||
}
|
||||
|
||||
export function removeHabit(habitId: string): Habit[] {
|
||||
const habits = getHabits().filter(
|
||||
(habit) => habit.id !== habitId || !habit.isCustom,
|
||||
);
|
||||
saveHabits(habits);
|
||||
return habits;
|
||||
}
|
||||
|
||||
export function getCustomHabits() {
|
||||
return getHabits().filter((habit) => habit.isCustom);
|
||||
}
|
||||
52
lib/profile-preferences-storage.ts
Normal file
52
lib/profile-preferences-storage.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { notifyHabitPetDataUpdated } from "@/lib/app-events";
|
||||
|
||||
export type ProfilePreferences = {
|
||||
focusTopics: string[];
|
||||
avatarVibe: string;
|
||||
dailyReminderEnabled: boolean;
|
||||
dailyReminderTime: string;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "habit-pet-profile-preferences";
|
||||
|
||||
export const focusTopicOptions = [
|
||||
"Sleep",
|
||||
"Movement",
|
||||
"Hydration",
|
||||
"Mindfulness",
|
||||
] as const;
|
||||
|
||||
export const avatarVibeOptions = ["Calm", "Energetic", "Curious", "Cozy"] as const;
|
||||
|
||||
export const defaultProfilePreferences: ProfilePreferences = {
|
||||
focusTopics: ["Movement"],
|
||||
avatarVibe: "Calm",
|
||||
dailyReminderEnabled: false,
|
||||
dailyReminderTime: "20:00",
|
||||
};
|
||||
|
||||
export function getProfilePreferences(): ProfilePreferences {
|
||||
if (typeof window === "undefined") {
|
||||
return defaultProfilePreferences;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (!raw) {
|
||||
return defaultProfilePreferences;
|
||||
}
|
||||
|
||||
try {
|
||||
return {
|
||||
...defaultProfilePreferences,
|
||||
...(JSON.parse(raw) as Partial<ProfilePreferences>),
|
||||
};
|
||||
} catch {
|
||||
return defaultProfilePreferences;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveProfilePreferences(preferences: ProfilePreferences) {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
|
||||
notifyHabitPetDataUpdated();
|
||||
}
|
||||
@@ -5,6 +5,7 @@ export const routes = {
|
||||
signUpSuccess: "/auth/sign-up-success",
|
||||
onboardingQuiz: "/onboarding/quiz",
|
||||
avatar: "/avatar",
|
||||
habits: "/habits",
|
||||
dailyQuiz: "/daily/quiz",
|
||||
shop: "/shop",
|
||||
profile: "/profile",
|
||||
@@ -14,15 +15,33 @@ export type AppRoute = (typeof routes)[keyof typeof routes];
|
||||
|
||||
export const appNavItems = [
|
||||
{ href: routes.avatar, label: "Pet", shortLabel: "Pet" },
|
||||
{ href: routes.habits, label: "Habits", shortLabel: "Habits" },
|
||||
{ href: routes.dailyQuiz, label: "Daily Quiz", shortLabel: "Quiz" },
|
||||
{ href: routes.shop, label: "Shop", shortLabel: "Shop" },
|
||||
{ href: routes.profile, label: "Profile", shortLabel: "Profile" },
|
||||
] as const;
|
||||
|
||||
export type NavItem = (typeof appNavItems)[number];
|
||||
|
||||
const appPaths = [
|
||||
routes.avatar,
|
||||
routes.habits,
|
||||
routes.dailyQuiz,
|
||||
routes.shop,
|
||||
routes.profile,
|
||||
routes.onboardingQuiz,
|
||||
] as const;
|
||||
|
||||
export function isAuthPath(pathname: string) {
|
||||
return pathname.startsWith("/auth");
|
||||
}
|
||||
|
||||
export function isPublicPath(pathname: string) {
|
||||
return pathname === routes.home || isAuthPath(pathname);
|
||||
return (
|
||||
pathname === routes.home ||
|
||||
isAuthPath(pathname) ||
|
||||
appPaths.some(
|
||||
(path) => pathname === path || pathname.startsWith(`${path}/`),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user