Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion apps/next/src/app/layout-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,14 @@ function GlobalSnackbar() {
}, [showSnackbar]);

return (
<Snackbar open={open} autoHideDuration={4000} onClose={closeSnackbar}>
<Snackbar
open={open}
autoHideDuration={4000}
onClose={(_, reason) => {
if (reason === "clickaway") return;
closeSnackbar();
}}
>
<Alert onClose={closeSnackbar} severity={severity} variant="filled">
{message}
</Alert>
Expand Down
206 changes: 140 additions & 66 deletions apps/next/src/components/ui/nutrition-goals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import EditIcon from "@mui/icons-material/Edit";
import { Button, Drawer } from "@mui/material";
import { NutritionGoalsSchema } from "@peterplate/validators";
import { useEffect, useRef, useState } from "react";
import { useSnackbarStore } from "@/context/useSnackbar";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { trpc } from "@/utils/trpc";

Expand All @@ -12,6 +14,29 @@ interface Props {
tourId?: string;
}

/* Macros scaling so that macros and calories add up when changed */
const calculateCalories = (carbs: number, protein: number, fat: number) =>
carbs * 4 + protein * 4 + fat * 9;

const scaleMacros = (
targetCalories: number,
carbs: number,
protein: number,
fat: number,
) => {
const currentCalories = calculateCalories(carbs, protein, fat);

if (currentCalories <= 0) return null;

const ratio = targetCalories / currentCalories;

return {
carbGoal: Math.round(carbs * ratio),
proteinGoal: Math.round(protein * ratio),
fatGoal: Math.round(fat * ratio),
};
};

export default function NutritionGoals({ userId, date, tourId }: Props) {
const isMobile = useMediaQuery("(max-width: 768px)");
const utils = trpc.useUtils();
Expand All @@ -37,18 +62,85 @@ export default function NutritionGoals({ userId, date, tourId }: Props) {
const [carbGoal, setCarbGoal] = useState(250);
const [fatGoal, setFatGoal] = useState(50);
const containerRef = useRef<HTMLDivElement>(null);
const { showSnackbar } = useSnackbarStore();

const handleUpdate = (
field: "calorieGoal" | "proteinGoal" | "carbGoal" | "fatGoal",
value: number,
) => {
const updated = {
calorieGoal,
proteinGoal,
carbGoal,
fatGoal,
[field]: value,
};

// Validate the user's input before recalculating
const fieldResult = NutritionGoalsSchema.shape[field].safeParse(value);
if (!fieldResult.success) {
showSnackbar(fieldResult.error.issues[0].message, "error");
return false;
}

// Scaling calories/macros so all values add up correctly
if (field === "calorieGoal") {
const macros = scaleMacros(value, carbGoal, proteinGoal, fatGoal);

if (!macros) return false;

Object.assign(updated, macros);
} else {
updated.calorieGoal = calculateCalories(
updated.carbGoal,
updated.proteinGoal,
updated.fatGoal,
);
}

// Confirm if values are still in range - the only error possible here is if recalculating results in Calories < 100
const result = NutritionGoalsSchema.safeParse(updated);
if (!result.success) {
if (field !== "calorieGoal" && updated.calorieGoal < 100) {
showSnackbar(
`Changing ${field.replace("Goal", "").toUpperCase()} results in ${updated.calorieGoal} Calories. Calories must be at least 100.`,
"error",
);
} else {
showSnackbar(result.error.issues[0].message, "error");
}

return false;
}

// Update React state
setCalorieGoal(updated.calorieGoal);
setProteinGoal(updated.proteinGoal);
setCarbGoal(updated.carbGoal);
setFatGoal(updated.fatGoal);

// Save to database
if (date) {
upsertGoalsByDay.mutate({ userId, date, ...updated });
} else {
upsertGoals.mutate({ userId, ...updated });
}

return true;
};

useEffect(() => {
if (goals) {
if (goals && !open) {
setCalorieGoal(goals.calorieGoal);
setProteinGoal(goals.proteinGoal);
setCarbGoal(goals.carbGoal);
setFatGoal(goals.fatGoal);
}
}, [goals]);
}, [goals, open]);

useEffect(() => {
if (isMobile || !open) return;

const handleClickOutside = (e: MouseEvent) => {
if (
containerRef.current &&
Expand All @@ -57,53 +149,34 @@ export default function NutritionGoals({ userId, date, tourId }: Props) {
setOpen(false);
}
};

document.addEventListener("click", handleClickOutside);
return () => document.removeEventListener("click", handleClickOutside);
}, [open, isMobile]);

const handleUpdate = (updates: {
calorieGoal?: number;
proteinGoal?: number;
carbGoal?: number;
fatGoal?: number;
}) => {
const merged = {
calorieGoal,
proteinGoal,
carbGoal,
fatGoal,
...updates,
};
if (date) {
upsertGoalsByDay.mutate({ userId, date, ...merged });
} else {
upsertGoals.mutate({ userId, ...merged });
}
};

const inputs = (
<>
<label className="flex items-center justify-between gap-4 text-sm font-medium text-zinc-900 dark:text-white">
Calorie Goal
<input
key={calorieGoal}
type="number"
value={calorieGoal === 0 ? "" : calorieGoal}
defaultValue={calorieGoal}
min={100}
max={10000}
onChange={(e) => {
const raw = e.target.value;
onBlur={(e) => {
const input = e.currentTarget;
const raw = input.value;

if (raw === "") {
setCalorieGoal(0);
input.value = String(calorieGoal);
return;
}
const val = Number(raw);
setCalorieGoal(val);
}}
onBlur={(e) => {
if (e.target.value === "") {
setCalorieGoal(calorieGoal);
if (Number(raw) === calorieGoal) return;

if (!handleUpdate("calorieGoal", Number(raw))) {
input.value = String(calorieGoal);
}
handleUpdate({ calorieGoal: Number(e.target.value) });
}}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
Expand All @@ -114,24 +187,24 @@ export default function NutritionGoals({ userId, date, tourId }: Props) {
<label className="flex items-center justify-between gap-4 text-sm font-medium text-zinc-900 dark:text-white">
Protein Goal
<input
key={proteinGoal}
type="number"
value={proteinGoal === 0 ? "" : proteinGoal}
defaultValue={proteinGoal}
min={1}
max={500}
onChange={(e) => {
const raw = e.target.value;
onBlur={(e) => {
const input = e.currentTarget;
const raw = input.value;

if (raw === "") {
setProteinGoal(0);
input.value = String(proteinGoal);
return;
}
const val = Number(raw);
setProteinGoal(val);
}}
onBlur={(e) => {
if (e.target.value === "") {
setProteinGoal(proteinGoal);
if (Number(raw) === proteinGoal) return;

if (!handleUpdate("proteinGoal", Number(raw))) {
input.value = String(proteinGoal);
}
handleUpdate({ proteinGoal: Number(e.target.value) });
}}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
Expand All @@ -142,24 +215,24 @@ export default function NutritionGoals({ userId, date, tourId }: Props) {
<label className="flex items-center justify-between gap-4 text-sm font-medium text-zinc-900 dark:text-white">
Carb Goal
<input
key={carbGoal}
type="number"
value={carbGoal === 0 ? "" : carbGoal}
defaultValue={carbGoal}
min={1}
max={1000}
onChange={(e) => {
const raw = e.target.value;
onBlur={(e) => {
const input = e.currentTarget;
const raw = input.value;

if (raw === "") {
setCarbGoal(0);
input.value = String(carbGoal);
return;
}
const val = Number(raw);
setCarbGoal(val);
}}
onBlur={(e) => {
if (e.target.value === "") {
setCarbGoal(carbGoal);
if (Number(raw) === carbGoal) return;

if (!handleUpdate("carbGoal", Number(raw))) {
input.value = String(carbGoal);
}
handleUpdate({ carbGoal: Number(e.target.value) });
}}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
Expand All @@ -170,24 +243,25 @@ export default function NutritionGoals({ userId, date, tourId }: Props) {
<label className="flex items-center justify-between gap-4 text-sm font-medium text-zinc-900 dark:text-white">
Fat Goal
<input
key={fatGoal}
type="number"
value={fatGoal === 0 ? "" : fatGoal}
defaultValue={fatGoal}
min={1}
max={500}
onChange={(e) => {
const raw = e.target.value;
onBlur={(e) => {
const input = e.currentTarget;
const raw = input.value;

if (raw === "") {
setFatGoal(0);
input.value = String(fatGoal);
return;
}
const val = Number(raw);
setFatGoal(val);
}}
onBlur={(e) => {
if (e.target.value === "") {
setFatGoal(fatGoal);

if (Number(raw) === fatGoal) return;

if (!handleUpdate("fatGoal", Number(raw))) {
input.value = String(fatGoal);
}
handleUpdate({ fatGoal: Number(e.target.value) });
}}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
Expand Down
13 changes: 3 additions & 10 deletions packages/api/src/nutrition/router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getDishes } from "@api/dishes/services";
import { createTRPCRouter, publicProcedure } from "@api/trpc";
import { loggedMeals, userGoals, userGoalsByDay } from "@peterplate/db";
import { NutritionGoalsSchema } from "@peterplate/validators";
import { TRPCError } from "@trpc/server";
import { and, desc, eq, gt, gte, lt } from "drizzle-orm";
import { z } from "zod";
Expand Down Expand Up @@ -190,12 +191,8 @@ export const nutritionRouter = createTRPCRouter({

upsertGoals: publicProcedure
.input(
z.object({
NutritionGoalsSchema.extend({
userId: z.string(),
calorieGoal: z.number().min(100).max(10000),
proteinGoal: z.number().min(1).max(500),
carbGoal: z.number().min(1).max(1000),
fatGoal: z.number().min(1).max(500),
}),
)
.mutation(async ({ ctx, input }) => {
Expand Down Expand Up @@ -243,13 +240,9 @@ export const nutritionRouter = createTRPCRouter({

upsertGoalsByDay: publicProcedure
.input(
z.object({
NutritionGoalsSchema.extend({
userId: z.string(),
date: z.string(),
calorieGoal: z.number().min(100).max(10000),
proteinGoal: z.number().min(1).max(500),
carbGoal: z.number().min(1).max(1000),
fatGoal: z.number().min(1).max(500),
}),
)
.mutation(async ({ ctx, input }) => {
Expand Down
1 change: 1 addition & 0 deletions packages/validators/src/peterplate/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./date";
export * from "./feedback";
export * from "./nutrition";
27 changes: 27 additions & 0 deletions packages/validators/src/peterplate/nutrition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { z } from "zod";

export const NutritionGoalsSchema = z.object({
calorieGoal: z
.number()
.int()
.min(100, "Calories must be at least 100")
.max(10000, "Calories cannot exceed 10,000"),

proteinGoal: z
.number()
.int()
.min(1, "Protein must be at least 1")
.max(500, "Protein cannot exceed 500"),

carbGoal: z
.number()
.int()
.min(1, "Carbs must be at least 1")
.max(1000, "Carbs cannot exceed 1,000"),

fatGoal: z
.number()
.int()
.min(1, "Fat must be at least 1")
.max(500, "Fat cannot exceed 500"),
});
Loading